badpacket/proto/codec/decoder.go

51 lines
927 B
Go

package codec
import (
"bufio"
"io"
"net"
"tpack/proto/packet"
)
type Decoder struct {
underlying io.Reader
}
func NewDecoder(c net.Conn) *Decoder {
out := &Decoder{
underlying: &fullReader{bufio.NewReader(c)},
}
return out
}
type fullReader struct{ io.Reader }
func (fr *fullReader) Read(p []byte) (int, error) { return io.ReadFull(fr.Reader, p) }
func (D *Decoder) ReadPacket() (*packet.Packet, error) {
pkt := &packet.Packet{}
pkt.Head = &packet.Header{}
err := pkt.Head.Decode(D.underlying)
if err != nil {
return pkt, err
}
if pkt.Head.Length < 9 {
return pkt, err
}
pkt.Data = make([]byte, pkt.Head.Length-9)
err = D.DecryptTo(pkt.Data)
if err != nil {
return nil, err
}
return pkt, err
}
func (D *Decoder) DecryptTo(b []byte) error {
_, err := D.underlying.Read(b)
if err != nil {
return err
}
// you would decrypt the buffer here, since b now holds encrypted data
return err
}