forked from SagerNet/sing-vmess
-
Notifications
You must be signed in to change notification settings - Fork 9
/
chunk_stream.go
70 lines (58 loc) · 1.5 KB
/
chunk_stream.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
package vmess
import (
"crypto/cipher"
"io"
"github.com/sagernet/sing/common/buf"
"github.com/sagernet/sing/common/bufio"
N "github.com/sagernet/sing/common/network"
)
type StreamReader struct {
upstream N.ExtendedReader
cipher cipher.Stream
}
func NewStreamReader(upstream io.Reader, key []byte, iv []byte) *StreamReader {
return &StreamReader{
upstream: bufio.NewExtendedReader(upstream),
cipher: newAesStream(key, iv, cipher.NewCFBDecrypter),
}
}
func (r *StreamReader) Read(p []byte) (n int, err error) {
n, err = r.upstream.Read(p)
if err != nil {
return
}
r.cipher.XORKeyStream(p[:n], p[:n])
return
}
func (r *StreamReader) ReadBuffer(buffer *buf.Buffer) error {
err := r.upstream.ReadBuffer(buffer)
if err != nil {
return err
}
r.cipher.XORKeyStream(buffer.Bytes(), buffer.Bytes())
return nil
}
func (r *StreamReader) Upstream() any {
return r.upstream
}
type StreamWriter struct {
upstream N.ExtendedWriter
cipher cipher.Stream
}
func NewStreamWriter(upstream io.Writer, key []byte, iv []byte) *StreamWriter {
return &StreamWriter{
upstream: bufio.NewExtendedWriter(upstream),
cipher: newAesStream(key, iv, cipher.NewCFBEncrypter),
}
}
func (w *StreamWriter) Write(p []byte) (n int, err error) {
w.cipher.XORKeyStream(p, p)
return w.upstream.Write(p)
}
func (w *StreamWriter) WriteBuffer(buffer *buf.Buffer) error {
w.cipher.XORKeyStream(buffer.Bytes(), buffer.Bytes())
return w.upstream.WriteBuffer(buffer)
}
func (w *StreamWriter) Upstream() any {
return w.upstream
}