-
Notifications
You must be signed in to change notification settings - Fork 9
/
v2_conn.go
95 lines (86 loc) · 2.13 KB
/
v2_conn.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
89
90
91
92
93
94
95
package shadowtls
import (
"crypto/tls"
"encoding/binary"
"io"
"net"
"github.com/sagernet/sing/common/buf"
"github.com/sagernet/sing/common/bufio"
E "github.com/sagernet/sing/common/exceptions"
N "github.com/sagernet/sing/common/network"
)
type shadowConn struct {
net.Conn
writer N.VectorisedWriter
readRemaining int
}
func newConn(conn net.Conn) *shadowConn {
return &shadowConn{
Conn: conn,
writer: bufio.NewVectorisedWriter(conn),
}
}
func (c *shadowConn) Read(p []byte) (n int, err error) {
if c.readRemaining > 0 {
if len(p) > c.readRemaining {
p = p[:c.readRemaining]
}
n, err = c.Conn.Read(p)
c.readRemaining -= n
return
}
var tlsHeader [5]byte
_, err = io.ReadFull(c.Conn, tlsHeader[:])
if err != nil {
return
}
length := int(binary.BigEndian.Uint16(tlsHeader[3:5]))
if tlsHeader[0] != 23 {
return 0, E.New("unexpected TLS record type: ", tlsHeader[0])
}
readLen := len(p)
if readLen > length {
readLen = length
}
n, err = c.Conn.Read(p[:readLen])
if err != nil {
return
}
c.readRemaining = length - n
return
}
func (c *shadowConn) Write(p []byte) (n int, err error) {
var header [tlsHeaderSize]byte
header[0] = 23
for len(p) > 16384 {
binary.BigEndian.PutUint16(header[1:3], tls.VersionTLS12)
binary.BigEndian.PutUint16(header[3:5], uint16(16384))
_, err = bufio.WriteVectorised(c.writer, [][]byte{header[:], p[:16384]})
if err != nil {
return
}
n += 16384
p = p[16384:]
}
binary.BigEndian.PutUint16(header[1:3], tls.VersionTLS12)
binary.BigEndian.PutUint16(header[3:5], uint16(len(p)))
_, err = bufio.WriteVectorised(c.writer, [][]byte{header[:], p})
if err == nil {
n += len(p)
}
return
}
func (c *shadowConn) WriteVectorised(buffers []*buf.Buffer) error {
var header [tlsHeaderSize]byte
header[0] = 23
dataLen := buf.LenMulti(buffers)
binary.BigEndian.PutUint16(header[1:3], tls.VersionTLS12)
binary.BigEndian.PutUint16(header[3:5], uint16(dataLen))
return c.writer.WriteVectorised(append([]*buf.Buffer{buf.As(header[:])}, buffers...))
}
func (c *shadowConn) NeedAdditionalReadDeadline() bool {
return true
}
func (c *shadowConn) Upstream() any {
return c.Conn
}