forked from v2fly/v2ray-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
reader.go
94 lines (79 loc) · 1.92 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
package mux
import (
"io"
"v2ray.com/core/common/buf"
"v2ray.com/core/common/serial"
)
// ReadMetadata reads FrameMetadata from the given reader.
func ReadMetadata(reader io.Reader) (*FrameMetadata, error) {
metaLen, err := serial.ReadUint16(reader)
if err != nil {
return nil, err
}
if metaLen > 512 {
return nil, newError("invalid metalen ", metaLen).AtError()
}
b := buf.NewSize(int32(metaLen))
defer b.Release()
if err := b.Reset(buf.ReadFullFrom(reader, int32(metaLen))); err != nil {
return nil, err
}
return ReadFrameFrom(b)
}
// PacketReader is an io.Reader that reads whole chunk of Mux frames every time.
type PacketReader struct {
reader io.Reader
eof bool
}
// NewPacketReader creates a new PacketReader.
func NewPacketReader(reader io.Reader) *PacketReader {
return &PacketReader{
reader: reader,
eof: false,
}
}
// ReadMultiBuffer implements buf.Reader.
func (r *PacketReader) ReadMultiBuffer() (buf.MultiBuffer, error) {
if r.eof {
return nil, io.EOF
}
size, err := serial.ReadUint16(r.reader)
if err != nil {
return nil, err
}
b := buf.NewSize(int32(size))
if err := b.Reset(buf.ReadFullFrom(r.reader, int32(size))); err != nil {
b.Release()
return nil, err
}
r.eof = true
return buf.NewMultiBufferValue(b), nil
}
// StreamReader reads Mux frame as a stream.
type StreamReader struct {
reader *buf.BufferedReader
leftOver int32
}
// NewStreamReader creates a new StreamReader.
func NewStreamReader(reader *buf.BufferedReader) *StreamReader {
return &StreamReader{
reader: reader,
leftOver: -1,
}
}
// ReadMultiBuffer implmenets buf.Reader.
func (r *StreamReader) ReadMultiBuffer() (buf.MultiBuffer, error) {
if r.leftOver == 0 {
return nil, io.EOF
}
if r.leftOver == -1 {
size, err := serial.ReadUint16(r.reader)
if err != nil {
return nil, err
}
r.leftOver = int32(size)
}
mb, err := r.reader.ReadAtMost(r.leftOver)
r.leftOver -= mb.Len()
return mb, err
}