2017-02-07 20:11:47 +00:00
|
|
|
package mux
|
|
|
|
|
2017-04-02 07:48:30 +00:00
|
|
|
import (
|
|
|
|
"io"
|
2017-02-07 20:11:47 +00:00
|
|
|
|
2017-04-02 07:48:30 +00:00
|
|
|
"v2ray.com/core/common/buf"
|
2017-04-03 10:55:46 +00:00
|
|
|
"v2ray.com/core/common/errors"
|
2017-04-02 07:48:30 +00:00
|
|
|
"v2ray.com/core/common/serial"
|
|
|
|
)
|
|
|
|
|
2017-04-02 11:43:24 +00:00
|
|
|
type Reader struct {
|
2017-02-07 20:11:47 +00:00
|
|
|
reader io.Reader
|
|
|
|
remainingLength int
|
|
|
|
buffer *buf.Buffer
|
|
|
|
}
|
|
|
|
|
2017-04-02 11:43:24 +00:00
|
|
|
func NewReader(reader buf.Reader) *Reader {
|
|
|
|
return &Reader{
|
2017-02-15 21:51:01 +00:00
|
|
|
reader: buf.ToBytesReader(reader),
|
2017-02-07 20:11:47 +00:00
|
|
|
buffer: buf.NewLocal(1024),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-04-02 11:43:24 +00:00
|
|
|
func (r *Reader) ReadMetadata() (*FrameMetadata, error) {
|
2017-02-07 20:11:47 +00:00
|
|
|
b := r.buffer
|
|
|
|
b.Clear()
|
|
|
|
|
|
|
|
if err := b.AppendSupplier(buf.ReadFullFrom(r.reader, 2)); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
metaLen := serial.BytesToUint16(b.Bytes())
|
2017-04-03 10:55:46 +00:00
|
|
|
if metaLen > 512 {
|
|
|
|
return nil, errors.New("Proxyman|Mux|Reader: Invalid metalen ", metaLen)
|
|
|
|
}
|
2017-02-07 20:11:47 +00:00
|
|
|
b.Clear()
|
|
|
|
if err := b.AppendSupplier(buf.ReadFullFrom(r.reader, int(metaLen))); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return ReadFrameFrom(b.Bytes())
|
|
|
|
}
|
|
|
|
|
2017-04-02 11:43:24 +00:00
|
|
|
func (r *Reader) Read() (*buf.Buffer, bool, error) {
|
2017-02-07 20:11:47 +00:00
|
|
|
b := buf.New()
|
|
|
|
var dataLen int
|
|
|
|
if r.remainingLength > 0 {
|
|
|
|
dataLen = r.remainingLength
|
|
|
|
r.remainingLength = 0
|
|
|
|
} else {
|
|
|
|
if err := b.AppendSupplier(buf.ReadFullFrom(r.reader, 2)); err != nil {
|
|
|
|
return nil, false, err
|
|
|
|
}
|
|
|
|
dataLen = int(serial.BytesToUint16(b.Bytes()))
|
|
|
|
b.Clear()
|
|
|
|
}
|
|
|
|
|
|
|
|
if dataLen > buf.Size {
|
|
|
|
r.remainingLength = dataLen - buf.Size
|
|
|
|
dataLen = buf.Size
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := b.AppendSupplier(buf.ReadFullFrom(r.reader, dataLen)); err != nil {
|
|
|
|
return nil, false, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return b, (r.remainingLength > 0), nil
|
|
|
|
}
|