-
Notifications
You must be signed in to change notification settings - Fork 9
/
v2_server.go
58 lines (55 loc) · 1.52 KB
/
v2_server.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 shadowtls
import (
"bytes"
"context"
"encoding/binary"
"io"
"net"
"os"
"github.com/sagernet/sing/common/buf"
"github.com/sagernet/sing/common/logger"
)
func copyUntilHandshakeFinishedV2(ctx context.Context, logger logger.ContextLogger, dst net.Conn, src io.Reader, hash *hashWriteConn, fallbackAfter int) (*buf.Buffer, error) {
var tlsHdr [tlsHeaderSize]byte
var applicationDataCount int
for {
_, err := io.ReadFull(src, tlsHdr[:])
if err != nil {
return nil, err
}
length := binary.BigEndian.Uint16(tlsHdr[3:])
if tlsHdr[0] == applicationData {
data := buf.NewSize(int(length))
_, err = data.ReadFullFrom(src, int(length))
if err != nil {
data.Release()
return nil, err
}
if hash.HasContent() && length >= 8 {
checksum := hash.Sum()
if bytes.Equal(data.To(8), checksum) {
logger.TraceContext(ctx, "match current hashcode")
data.Advance(8)
return data, nil
} else if hash.LastSum() != nil && bytes.Equal(data.To(8), hash.LastSum()) {
logger.TraceContext(ctx, "match last hashcode")
data.Advance(8)
return data, nil
} else {
logger.TraceContext(ctx, "hashcode mismatch")
}
}
_, err = io.Copy(dst, io.MultiReader(bytes.NewReader(tlsHdr[:]), data))
data.Release()
applicationDataCount++
} else {
_, err = io.Copy(dst, io.MultiReader(bytes.NewReader(tlsHdr[:]), io.LimitReader(src, int64(length))))
}
if err != nil {
return nil, err
}
if applicationDataCount > fallbackAfter {
return nil, os.ErrPermission
}
}
}