1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-11-07 18:57:44 -05:00
v2fly/common/mux/reader.go

53 lines
1.1 KiB
Go
Raw Normal View History

2017-02-07 15:11:47 -05:00
package mux
2017-04-02 03:48:30 -04:00
import (
"io"
2017-02-07 15:11:47 -05:00
"github.com/v2fly/v2ray-core/v5/common/buf"
"github.com/v2fly/v2ray-core/v5/common/crypto"
"github.com/v2fly/v2ray-core/v5/common/serial"
2017-04-02 03:48:30 -04:00
)
2017-10-30 07:36:31 -04:00
// PacketReader is an io.Reader that reads whole chunk of Mux frames every time.
2017-05-02 16:23:07 -04:00
type PacketReader struct {
reader io.Reader
eof bool
2017-02-07 15:11:47 -05:00
}
2017-10-30 07:36:31 -04:00
// NewPacketReader creates a new PacketReader.
2017-05-02 16:23:07 -04:00
func NewPacketReader(reader io.Reader) *PacketReader {
return &PacketReader{
reader: reader,
eof: false,
2017-04-27 16:20:29 -04:00
}
}
2017-11-09 16:33:15 -05:00
// ReadMultiBuffer implements buf.Reader.
func (r *PacketReader) ReadMultiBuffer() (buf.MultiBuffer, error) {
2017-05-02 16:23:07 -04:00
if r.eof {
return nil, io.EOF
}
2018-11-03 08:03:02 -04:00
size, err := serial.ReadUint16(r.reader)
2017-05-02 16:23:07 -04:00
if err != nil {
return nil, err
}
2018-08-16 06:05:33 -04:00
if size > buf.Size {
return nil, newError("packet size too large: ", size)
}
b := buf.New()
2018-11-02 10:01:33 -04:00
if _, err := b.ReadFullFrom(r.reader, int32(size)); err != nil {
2017-05-02 16:23:07 -04:00
b.Release()
return nil, err
}
r.eof = true
2018-11-16 05:08:12 -05:00
return buf.MultiBuffer{b}, nil
2017-05-02 16:23:07 -04:00
}
2017-10-30 07:36:31 -04:00
// NewStreamReader creates a new StreamReader.
2018-08-23 04:39:53 -04:00
func NewStreamReader(reader *buf.BufferedReader) buf.Reader {
return crypto.NewChunkStreamReaderWithChunkCount(crypto.PlainChunkSizeParser{}, reader, 1)
2017-02-07 15:11:47 -05:00
}