1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-11-17 18:06:15 -05:00
v2fly/app/proxyman/mux/reader.go

63 lines
1.2 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
2017-04-02 03:48:30 -04:00
"v2ray.com/core/common/buf"
"v2ray.com/core/common/serial"
)
2017-04-02 07:43:24 -04:00
type Reader struct {
2017-04-15 15:07:23 -04:00
reader io.Reader
buffer *buf.Buffer
2017-02-07 15:11:47 -05:00
}
2017-04-02 07:43:24 -04:00
func NewReader(reader buf.Reader) *Reader {
return &Reader{
2017-02-15 16:51:01 -05:00
reader: buf.ToBytesReader(reader),
2017-02-07 15:11:47 -05:00
buffer: buf.NewLocal(1024),
}
}
2017-04-02 07:43:24 -04:00
func (r *Reader) ReadMetadata() (*FrameMetadata, error) {
2017-02-07 15:11:47 -05: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 06:55:46 -04:00
if metaLen > 512 {
return nil, newError("invalid metalen ", metaLen).AtWarning()
2017-04-03 06:55:46 -04:00
}
2017-02-07 15:11:47 -05:00
b.Clear()
if err := b.AppendSupplier(buf.ReadFullFrom(r.reader, int(metaLen))); err != nil {
return nil, err
}
return ReadFrameFrom(b.Bytes())
}
2017-04-15 15:07:23 -04:00
func (r *Reader) Read() (buf.MultiBuffer, error) {
2017-04-19 10:29:36 -04:00
if err := r.buffer.Reset(buf.ReadFullFrom(r.reader, 2)); err != nil {
2017-04-15 15:07:23 -04:00
return nil, err
2017-02-07 15:11:47 -05:00
}
2017-04-15 15:07:23 -04:00
dataLen := int(serial.BytesToUint16(r.buffer.Bytes()))
mb := buf.NewMultiBuffer()
for dataLen > 0 {
readLen := buf.Size
if dataLen < readLen {
readLen = dataLen
}
2017-04-19 10:29:36 -04:00
b := buf.New()
2017-04-15 15:07:23 -04:00
if err := b.AppendSupplier(buf.ReadFullFrom(r.reader, readLen)); err != nil {
mb.Release()
return nil, err
}
dataLen -= readLen
mb.Append(b)
2017-02-07 15:11:47 -05:00
}
2017-04-15 15:07:23 -04:00
return mb, nil
2017-02-07 15:11:47 -05:00
}