-
Notifications
You must be signed in to change notification settings - Fork 28
/
chunk_stream_checksum.go
81 lines (68 loc) · 1.81 KB
/
chunk_stream_checksum.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
package vmess
import (
"encoding/binary"
"hash/fnv"
"io"
"github.com/sagernet/sing/common"
"github.com/sagernet/sing/common/buf"
"github.com/sagernet/sing/common/bufio"
N "github.com/sagernet/sing/common/network"
)
type StreamChecksumReader struct {
upstream N.ExtendedReader
}
func NewStreamChecksumReader(reader io.Reader) *StreamChecksumReader {
return &StreamChecksumReader{bufio.NewExtendedReader(reader)}
}
func (r *StreamChecksumReader) Read(p []byte) (n int, err error) {
n, err = r.upstream.Read(p)
if err != nil {
return
}
hash := fnv.New32a()
common.Must1(hash.Write(p[4:n]))
if hash.Sum32() != binary.BigEndian.Uint32(p) {
return 0, ErrInvalidChecksum
}
n = copy(p, p[4:n])
return
}
func (r *StreamChecksumReader) ReadBuffer(buffer *buf.Buffer) error {
err := r.upstream.ReadBuffer(buffer)
if err != nil {
return err
}
hash := fnv.New32a()
common.Must1(hash.Write(buffer.From(4)))
if hash.Sum32() != binary.BigEndian.Uint32(buffer.To(4)) {
return ErrInvalidChecksum
}
buffer.Advance(4)
return nil
}
func (r *StreamChecksumReader) Upstream() any {
return r.upstream
}
type StreamChecksumWriter struct {
upstream *StreamChunkWriter
}
func NewStreamChecksumWriter(upstream *StreamChunkWriter) *StreamChecksumWriter {
return &StreamChecksumWriter{upstream}
}
func (w *StreamChecksumWriter) Write(p []byte) (n int, err error) {
hash := fnv.New32a()
common.Must1(hash.Write(p))
return w.upstream.WriteWithChecksum(hash.Sum32(), p)
}
func (w *StreamChecksumWriter) WriteBuffer(buffer *buf.Buffer) error {
hash := fnv.New32a()
common.Must1(hash.Write(buffer.Bytes()))
hash.Sum(buffer.ExtendHeader(4)[:0])
return common.Error(w.upstream.Write(buffer.Bytes()))
}
func (w *StreamChecksumWriter) FrontHeadroom() int {
return 4
}
func (w *StreamChecksumWriter) Upstream() any {
return w.upstream
}