github.com/xmplusdev/xray-core@v1.8.10/common/mux/reader.go (about) 1 package mux 2 3 import ( 4 "io" 5 6 "github.com/xmplusdev/xray-core/common/buf" 7 "github.com/xmplusdev/xray-core/common/crypto" 8 "github.com/xmplusdev/xray-core/common/net" 9 "github.com/xmplusdev/xray-core/common/serial" 10 ) 11 12 // PacketReader is an io.Reader that reads whole chunk of Mux frames every time. 13 type PacketReader struct { 14 reader io.Reader 15 eof bool 16 dest *net.Destination 17 } 18 19 // NewPacketReader creates a new PacketReader. 20 func NewPacketReader(reader io.Reader, dest *net.Destination) *PacketReader { 21 return &PacketReader{ 22 reader: reader, 23 eof: false, 24 dest: dest, 25 } 26 } 27 28 // ReadMultiBuffer implements buf.Reader. 29 func (r *PacketReader) ReadMultiBuffer() (buf.MultiBuffer, error) { 30 if r.eof { 31 return nil, io.EOF 32 } 33 34 size, err := serial.ReadUint16(r.reader) 35 if err != nil { 36 return nil, err 37 } 38 39 if size > buf.Size { 40 return nil, newError("packet size too large: ", size) 41 } 42 43 b := buf.New() 44 if _, err := b.ReadFullFrom(r.reader, int32(size)); err != nil { 45 b.Release() 46 return nil, err 47 } 48 r.eof = true 49 if r.dest != nil && r.dest.Network == net.Network_UDP { 50 b.UDP = r.dest 51 } 52 return buf.MultiBuffer{b}, nil 53 } 54 55 // NewStreamReader creates a new StreamReader. 56 func NewStreamReader(reader *buf.BufferedReader) buf.Reader { 57 return crypto.NewChunkStreamReaderWithChunkCount(crypto.PlainChunkSizeParser{}, reader, 1) 58 }