forked from v2fly/v2ray-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
reader.go
119 lines (103 loc) · 2.07 KB
/
reader.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package mux
import (
"io"
"v2ray.com/core/common/buf"
"v2ray.com/core/common/serial"
)
type MetadataReader struct {
reader io.Reader
buffer []byte
}
func NewMetadataReader(reader io.Reader) *MetadataReader {
return &MetadataReader{
reader: reader,
buffer: make([]byte, 1024),
}
}
func (r *MetadataReader) Read() (*FrameMetadata, error) {
metaLen, err := serial.ReadUint16(r.reader)
if err != nil {
return nil, err
}
if metaLen > 512 {
return nil, newError("invalid metalen ", metaLen).AtWarning()
}
if _, err := io.ReadFull(r.reader, r.buffer[:metaLen]); err != nil {
return nil, err
}
return ReadFrameFrom(r.buffer)
}
type PacketReader struct {
reader io.Reader
eof bool
}
func NewPacketReader(reader io.Reader) *PacketReader {
return &PacketReader{
reader: reader,
eof: false,
}
}
func (r *PacketReader) Read() (buf.MultiBuffer, error) {
if r.eof {
return nil, io.EOF
}
size, err := serial.ReadUint16(r.reader)
if err != nil {
return nil, err
}
var b *buf.Buffer
if size <= buf.Size {
b = buf.New()
} else {
b = buf.NewLocal(int(size))
}
if err := b.AppendSupplier(buf.ReadFullFrom(r.reader, int(size))); err != nil {
b.Release()
return nil, err
}
r.eof = true
return buf.NewMultiBufferValue(b), nil
}
type StreamReader struct {
reader io.Reader
leftOver int
}
func NewStreamReader(reader io.Reader) *StreamReader {
return &StreamReader{
reader: reader,
leftOver: -1,
}
}
func (r *StreamReader) Read() (buf.MultiBuffer, error) {
if r.leftOver == 0 {
r.leftOver = -1
return nil, io.EOF
}
if r.leftOver == -1 {
size, err := serial.ReadUint16(r.reader)
if err != nil {
return nil, err
}
r.leftOver = int(size)
}
mb := buf.NewMultiBuffer()
for r.leftOver > 0 {
readLen := buf.Size
if r.leftOver < readLen {
readLen = r.leftOver
}
b := buf.New()
if err := b.AppendSupplier(func(bb []byte) (int, error) {
return r.reader.Read(bb[:readLen])
}); err != nil {
mb.Release()
return nil, err
}
r.leftOver -= b.Len()
mb.Append(b)
if b.Len() < readLen {
break
}
}
return mb, nil
}