forked from v2fly/v2ray-core
-
Notifications
You must be signed in to change notification settings - Fork 30
/
reader.go
58 lines (50 loc) · 1.26 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
package io
import (
"hash/fnv"
"io"
"github.com/v2ray/v2ray-core/common/alloc"
"github.com/v2ray/v2ray-core/common/serial"
"github.com/v2ray/v2ray-core/transport"
)
type AuthChunkReader struct {
reader io.Reader
}
func NewAuthChunkReader(reader io.Reader) *AuthChunkReader {
return &AuthChunkReader{
reader: reader,
}
}
func (this *AuthChunkReader) Read() (*alloc.Buffer, error) {
buffer := alloc.NewBuffer()
if _, err := io.ReadFull(this.reader, buffer.Value[:2]); err != nil {
buffer.Release()
return nil, err
}
length := serial.BytesLiteral(buffer.Value[:2]).Uint16Value()
if length <= 4 { // Length of authentication bytes.
return nil, io.EOF
}
if length > 8*1024 {
buffer.Release()
buffer = alloc.NewLargeBuffer()
}
buffer.SliceBack(16)
if _, err := io.ReadFull(this.reader, buffer.Value[:length]); err != nil {
buffer.Release()
return nil, err
}
buffer.Slice(0, int(length))
fnvHash := fnv.New32a()
fnvHash.Write(buffer.Value[4:])
expAuth := serial.BytesLiteral(fnvHash.Sum(nil))
actualAuth := serial.BytesLiteral(buffer.Value[:4])
if !actualAuth.Equals(expAuth) {
buffer.Release()
return nil, transport.ErrorCorruptedPacket
}
buffer.SliceFrom(4)
return buffer, nil
}
func (this *AuthChunkReader) Release() {
this.reader = nil
}