forked from p4gefau1t/trojan-go
-
Notifications
You must be signed in to change notification settings - Fork 1
/
chuck.go
88 lines (70 loc) · 1.41 KB
/
chuck.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
package vmess
import (
"encoding/binary"
"io"
)
const (
lenSize = 2
chunkSize = 1 << 14 // 16384
)
type chunkedWriter struct {
io.Writer
}
// ChunkedWriter returns a chunked writer
func ChunkedWriter(w io.Writer) io.Writer {
return &chunkedWriter{Writer: w}
}
func (w *chunkedWriter) Write(b []byte) (n int, err error) {
buf := GetBuffer(lenSize + chunkSize)
defer PutBuffer(buf)
left := len(b)
for left != 0 {
writeLen := left
if writeLen > chunkSize {
writeLen = chunkSize
}
copy(buf[lenSize:], b[n:n+writeLen])
binary.BigEndian.PutUint16(buf[:lenSize], uint16(writeLen))
_, err = w.Writer.Write(buf[:lenSize+writeLen])
if err != nil {
break
}
n += writeLen
left -= writeLen
}
return
}
type chunkedReader struct {
io.Reader
left int
}
// ChunkedReader returns a chunked reader
func ChunkedReader(r io.Reader) io.Reader {
return &chunkedReader{Reader: r}
}
func (r *chunkedReader) Read(b []byte) (int, error) {
if r.left == 0 {
// get length
buf := GetBuffer(lenSize)
_, err := io.ReadFull(r.Reader, buf[:lenSize])
if err != nil {
return 0, err
}
r.left = int(binary.BigEndian.Uint16(buf[:lenSize]))
PutBuffer(buf)
// if left == 0, then this is the end
if r.left == 0 {
return 0, nil
}
}
readLen := len(b)
if readLen > r.left {
readLen = r.left
}
n, err := r.Reader.Read(b[:readLen])
if err != nil {
return 0, err
}
r.left -= n
return n, err
}