Repository navigation
Expand file tree
/
Copy pathstack_go_dial.go
More file actions
344 lines (329 loc) · 10.1 KB
/
Copy pathstack_go_dial.go
File metadata and controls
344 lines (329 loc) · 10.1 KB
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
package tun
import (
"context"
"hash/maphash"
"math/rand/v2"
"net"
"net/netip"
"syscall"
"time"
"github.com/sagernet/sing-tun/gtcpip/header"
E "github.com/sagernet/sing/common/exceptions"
M "github.com/sagernet/sing/common/metadata"
)
const (
goSynRetransmit = time.Second
goSynAttempts = 6
goEphemeralPortBase = 32768
goEphemeralPortSpan = 60999 - goEphemeralPortBase + 1
goEphemeralAttempts = 1024
)
var errGoInvalidAddress = E.New("go: invalid address")
func (s *Go) DialTCP(ctx context.Context, source netip.Addr, destination netip.AddrPort) (*GoConn, error) {
source = source.Unmap()
destination = netip.AddrPortFrom(destination.Addr().Unmap(), destination.Port())
if !source.IsValid() || !destination.IsValid() || destination.Port() == 0 || source.Is4() != destination.Addr().Is4() {
return nil, errGoInvalidAddress
}
engine, err := s.selectEngine(destination)
if err != nil {
return nil, err
}
conn := new(GoConn)
conn.initialize(engine, flowKey{}, M.SocksaddrFromNetIP(destination), M.SocksaddrFrom(source, 0))
conn.socket = true
conn.ipVersion = goIPVersion(source)
conn.state = goTCPSynSent
conn.phase = goPhaseEngaged
conn.localWindowShift = goLocalWindowShift
conn.timestampsEnabled = true
conn.sackPermitted = true
conn.receiveCapacity = min(goReceiveCapacityBase, conn.receiveWindowBound())
conn.dialMessage = goMessage{kind: goMessageConnDial, conn: conn}
engine.postMessage(&conn.dialMessage)
err = conn.awaitHandshake(ctx, nil)
if err != nil {
return nil, err
}
return conn, nil
}
func goIPVersion(addr netip.Addr) uint8 {
if addr.Is4() {
return 4
}
return 6
}
func (s *Go) selectEngine(destination netip.AddrPort) (*goEngine, error) {
s.access.Lock()
defer s.access.Unlock()
if s.closed.Load() {
return nil, net.ErrClosed
}
return s.engines[maphash.Comparable(s.engines[0].sequenceSeed, destination)%uint64(len(s.engines))], nil
}
func goAllocatePort(available func(port uint16) bool) (uint16, bool) {
offset := rand.IntN(goEphemeralPortSpan)
for attempt := range goEphemeralAttempts {
port := uint16(goEphemeralPortBase + (offset+attempt)%goEphemeralPortSpan)
if available(port) {
return port, true
}
}
return 0, false
}
func (e *goEngine) handleDial(conn *GoConn) {
if conn.dead {
return
}
if len(e.flows) >= e.flowCapacity && !e.evictFlow() {
e.detachConn(conn, E.Cause(syscall.ENOBUFS, "go: flow table full"), goDeathImmediate)
return
}
directory := &e.stack.directory
key := flowKey{protocol: uint8(header.TCPProtocolNumber), source: conn.peer.AddrPort()}
directory.access.Lock()
port, allocated := goAllocatePort(func(port uint16) bool {
key.destination = netip.AddrPortFrom(conn.local.Addr, port)
return directory.flows[key] == nil && directory.listeners[key.destination] == nil && !directory.reservedLocked(uint8(header.TCPProtocolNumber), key.destination)
})
if allocated {
conn.key = key
conn.keyed = true
directory.insertLocked(key, conn)
}
directory.access.Unlock()
if !allocated {
e.detachConn(conn, E.Cause(syscall.EADDRINUSE, "go: ephemeral ports exhausted"), goDeathImmediate)
return
}
now := e.coarseTime.Load()
conn.local.Port = port
conn.sendISN = e.initialSequence(key, now)
conn.lastActivity = now
conn.buildHandshake(e.localMSS(conn.ipVersion), true, true, header.TCPFlagSyn, 0)
err := goIgnoreDropped(conn.engine.platformIO.writePacket(conn.handshakeImage[:conn.handshakeLength], ForwardFrameMeta{}))
if err != nil {
e.detachConn(conn, E.Cause(err, "go: send SYN"), goDeathImmediate)
return
}
conn.handshakeAttempts = 0
conn.handshakeStamp = now
conn.handshakeDeadline = now + int64(goSynRetransmit)
e.rearmTimer(conn)
}
func (e *goEngine) retransmitSyn(conn *GoConn, now int64) {
conn.handshakeAttempts++
if conn.handshakeAttempts >= goSynAttempts {
conn.handshakeDeadline = 0
e.detachConn(conn, E.Cause(syscall.ETIMEDOUT, "go: connect timeout"), goDeathImmediate)
return
}
conn.buildHandshake(e.localMSS(conn.ipVersion), true, true, header.TCPFlagSyn, 0)
err := goIgnoreDropped(conn.engine.platformIO.writePacket(conn.handshakeImage[:conn.handshakeLength], ForwardFrameMeta{}))
if err != nil {
e.stack.logger.Trace(E.Cause(err, "go: resend SYN"))
}
conn.handshakeDeadline = now + int64(goSynRetransmit)<<conn.handshakeAttempts
e.rearmTimer(conn)
}
func (e *goEngine) inputSynSent(conn *GoConn, parsed *forwardPacket, tcpHdr header.TCP, dataOffset int) {
flags := tcpHdr.Flags()
ackAcceptable := false
if flags&header.TCPFlagAck != 0 {
if tcpHdr.AckNumber() != conn.sendISN+1 {
if flags&header.TCPFlagRst == 0 {
e.answerNoFlow(parsed)
}
return
}
ackAcceptable = true
}
if flags&header.TCPFlagRst != 0 {
if ackAcceptable {
e.detachConn(conn, E.Cause(syscall.ECONNREFUSED, "go: connection refused"), goDeathImmediate)
}
return
}
if flags&header.TCPFlagSyn == 0 || !ackAcceptable {
return
}
synOptions := header.ParseSynOptions(tcpHdr[header.TCPMinimumSize:dataOffset], true)
now := e.coarseTime.Load()
conn.clientISN = tcpHdr.SequenceNumber()
conn.peerMSS = synOptions.MSS
effectiveMSS := min(synOptions.MSS, e.localMSS(conn.ipVersion))
conn.sackPermitted = synOptions.SACKPermitted
if synOptions.WS >= 0 {
conn.peerWindowShift = uint8(synOptions.WS)
} else {
conn.localWindowShift = 0
}
if synOptions.TS {
conn.tsRecent.Store(synOptions.TSVal)
effectiveMSS -= goTimestampOptionLength
} else {
conn.timestampsEnabled = false
}
conn.effectiveMSS.Store(uint32(effectiveMSS))
e.initializeSession(conn, now, tcpHdr.WindowSize())
if conn.handshakeAttempts == 0 {
roundTrip := max((now-conn.handshakeStamp)/int64(time.Microsecond), 1)
e.ackUpdateRoundTrip(conn, 0, roundTrip, -1, roundTrip, &e.rateSample, 0, false, now)
}
e.establishConn(conn)
e.rearmTimer(conn)
e.sendAck(conn)
}
func (e *goEngine) inputICMPError(parsed *forwardPacket) {
inner, ok := parsed.icmpErrorInner()
if !ok {
return
}
embedded, ok := parseEmbedded(inner)
if !ok {
return
}
mtu, tooBig := goICMPPacketTooBig(parsed)
if tooBig {
e.inputPacketTooBig(&embedded, mtu)
return
}
err := goICMPError(parsed)
if err == nil {
return
}
switch embedded.protocol {
case uint8(header.TCPProtocolNumber):
conn := e.flows[embedded.flowKey().reversed()]
if conn == nil || conn.dead || conn.state != goTCPSynSent {
return
}
if len(embedded.payload) < header.TCPAckNumOffset || header.TCP(embedded.payload).SequenceNumber() != conn.sendISN {
return
}
e.detachConn(conn, E.Cause(err, "go: connect"), goDeathImmediate)
case uint8(header.UDPProtocolNumber):
socket := e.udpSockets[embedded.source]
if socket == nil || !socket.connected || socket.remote != embedded.destination {
return
}
socket.deliverError(err)
}
}
func goICMPError(parsed *forwardPacket) error {
switch parsed.protocol {
case uint8(header.ICMPv4ProtocolNumber):
icmpHdr := header.ICMPv4(parsed.transport)
switch icmpHdr.Type() {
case header.ICMPv4DstUnreachable:
switch icmpHdr.Code() {
case header.ICMPv4NetUnreachable, header.ICMPv4NetUnreachableForTos:
return syscall.ENETUNREACH
case header.ICMPv4HostUnreachable, header.ICMPv4HostUnreachableForTos:
return syscall.EHOSTUNREACH
case header.ICMPv4ProtoUnreachable:
return syscall.EPROTO
case header.ICMPv4PortUnreachable:
return syscall.ECONNREFUSED
case header.ICMPv4NetProhibited, header.ICMPv4HostProhibited:
return syscall.EACCES
default:
return syscall.EHOSTUNREACH
}
case header.ICMPv4TimeExceeded:
return syscall.EHOSTUNREACH
case header.ICMPv4ParamProblem:
return syscall.EPROTO
default:
return nil
}
case uint8(header.ICMPv6ProtocolNumber):
icmpHdr := header.ICMPv6(parsed.transport)
switch icmpHdr.Type() {
case header.ICMPv6DstUnreachable:
switch icmpHdr.Code() {
case header.ICMPv6NetworkUnreachable:
return syscall.ENETUNREACH
case header.ICMPv6Prohibited:
return syscall.EACCES
case header.ICMPv6PortUnreachable:
return syscall.ECONNREFUSED
default:
return syscall.EHOSTUNREACH
}
case header.ICMPv6TimeExceeded:
return syscall.EHOSTUNREACH
case header.ICMPv6ParamProblem:
return syscall.EPROTO
default:
return nil
}
default:
return nil
}
}
func goICMPPacketTooBig(parsed *forwardPacket) (int, bool) {
switch parsed.protocol {
case uint8(header.ICMPv4ProtocolNumber):
icmpHdr := header.ICMPv4(parsed.transport)
if icmpHdr.Type() != header.ICMPv4DstUnreachable || icmpHdr.Code() != header.ICMPv4FragmentationNeeded {
return 0, false
}
return int(icmpHdr.MTU()), true
case uint8(header.ICMPv6ProtocolNumber):
icmpHdr := header.ICMPv6(parsed.transport)
if icmpHdr.Type() != header.ICMPv6PacketTooBig {
return 0, false
}
return int(icmpHdr.MTU()), true
default:
return 0, false
}
}
func (e *goEngine) inputPacketTooBig(embedded *embeddedPacket, mtu int) {
if embedded.protocol != uint8(header.TCPProtocolNumber) || mtu == 0 {
return
}
conn := e.flows[embedded.flowKey().reversed()]
if conn == nil || conn.dead || conn.state < goTCPEstablished || len(embedded.payload) < header.TCPAckNumOffset {
return
}
offset := conn.sendOffset(header.TCP(embedded.payload).SequenceNumber())
if offset < int64(conn.sendUnacked.Load()) || offset >= int64(conn.sendNext()) {
return
}
if conn.ipVersion == 4 {
mtu = max(mtu, header.IPv4MinimumProcessableDatagramSize)
} else {
mtu = max(mtu, header.IPv6MinimumMTU)
}
mss := mtu - goNetworkHeaderLength(conn.ipVersion) - header.TCPMinimumSize
if conn.timestampsEnabled {
mss -= goTimestampOptionLength
}
if mss >= int(conn.effectiveMSS.Load()) {
return
}
e.drainDescriptors(conn)
lost := false
start := conn.sendUnacked.Load()
for index := range conn.scoreboard.entries {
descriptor := &conn.scoreboard.entries[index]
if descriptor.endOffset-start > uint64(mss) && descriptor.flags&(goDescriptorSacked|goDescriptorLost) == 0 {
e.markLost(conn, descriptor)
lost = true
}
start = descriptor.endOffset
}
conn.effectiveMSS.Store(uint32(mss))
e.refreshPacketsOut(conn)
if lost {
e.enterCWR(conn)
if conn.congestionState < goCongestionRecovery {
e.enterRecovery(conn)
}
e.xmitRetransmitQueue(conn)
}
e.rearmRetransmit(conn)
conn.publishPermit(conn.sendUnacked.Load())
}