Repository navigation
Expand file tree
/
Copy pathtfo_connect_generic.go
More file actions
369 lines (334 loc) · 9.37 KB
/
Copy pathtfo_connect_generic.go
File metadata and controls
369 lines (334 loc) · 9.37 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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
//go:build darwin || freebsd || linux || (windows && tfogo_checklinkname0)
package tfo
import (
"context"
"net"
"net/netip"
"os"
"syscall"
"time"
)
const comptimeDialNoTFO = false
// Boolean to int.
func boolint(b bool) int {
if b {
return 1
}
return 0
}
// wrapSyscallError takes an error and a syscall name. If the error is
// a syscall.Errno, it wraps it in a os.SyscallError using the syscall name.
func wrapSyscallError(name string, err error) error {
if _, ok := err.(syscall.Errno); ok {
err = os.NewSyscallError(name, err)
}
return err
}
// Modified from favoriteAddrFamily in src/net/ipsock_posix.go
func favoriteDialAddrFamily(network string, laddr, raddr netip.AddrPort) (family int, ipv6only bool) {
switch network {
case "tcp4":
return syscall.AF_INET, false
case "tcp6":
return syscall.AF_INET6, true
}
if laddr.Addr().Is4() || laddr.Addr().Is4In6() || raddr.Addr().Is4() || raddr.Addr().Is4In6() {
return syscall.AF_INET, false
}
return syscall.AF_INET6, false
}
func ctrlNetwork(network string, family int) string {
if network == "tcp4" || family == syscall.AF_INET {
return "tcp4"
}
return "tcp6"
}
func (d *Dialer) dialCtx(ctx context.Context) (context.Context, context.CancelFunc) {
if ctx == nil {
panic("nil context")
}
deadline := d.deadline(ctx, time.Now())
var cancel1, cancel2 context.CancelFunc
if !deadline.IsZero() {
if d, ok := ctx.Deadline(); !ok || deadline.Before(d) {
var subCtx context.Context
subCtx, cancel1 = context.WithDeadline(ctx, deadline)
ctx = subCtx
}
}
if oldCancel := d.Cancel; oldCancel != nil {
var subCtx context.Context
subCtx, cancel2 = context.WithCancel(ctx)
go func() {
select {
case <-oldCancel:
cancel2()
case <-subCtx.Done():
}
}()
ctx = subCtx
}
return ctx, func() {
if cancel1 != nil {
cancel1()
}
if cancel2 != nil {
cancel2()
}
}
}
func (d *Dialer) dialTCPFromSocket(ctx context.Context, network string, laddr, raddr netip.AddrPort, b []byte) (*net.TCPConn, error) {
ctx, cancel := d.dialCtx(ctx)
defer cancel()
c, err := d.dialSingle(ctx, network, laddr, raddr, b)
if err != nil {
return nil, &net.OpError{Op: "dial", Net: network, Source: opAddrPort(laddr), Addr: opAddrPort(raddr), Err: err}
}
return c, nil
}
func (d *Dialer) dialFromSocket(ctx context.Context, network, address string, b []byte) (net.Conn, error) {
ctx, cancel := d.dialCtx(ctx)
defer cancel()
var laddr netip.AddrPort
if d.LocalAddr != nil {
la, ok := d.LocalAddr.(*net.TCPAddr)
if !ok {
return nil, &net.OpError{
Op: "dial",
Net: network,
Source: nil,
Addr: nil,
Err: &net.AddrError{
Err: "mismatched local address type",
Addr: d.LocalAddr.String(),
},
}
}
laddr = la.AddrPort()
laddrIs4 := laddr.Addr().Is4() || laddr.Addr().Is4In6()
switch {
case network == "tcp":
if laddrIs4 {
network = "tcp4"
} else {
network = "tcp6"
}
case network == "tcp4" && !laddrIs4 || network == "tcp6" && laddrIs4:
return nil, &net.OpError{
Op: "dial",
Net: network,
Source: nil,
Addr: nil,
Err: &net.AddrError{
Err: "no suitable address found",
Addr: laddr.String(),
},
}
}
}
host, port, err := net.SplitHostPort(address)
if err != nil {
return nil, &net.OpError{Op: "dial", Net: network, Source: nil, Addr: nil, Err: err}
}
portNum, err := d.Resolver.LookupPort(ctx, network, port)
if err != nil {
return nil, &net.OpError{Op: "dial", Net: network, Source: nil, Addr: nil, Err: err}
}
ips, err := d.Resolver.LookupNetIP(ctx, ipNetwork(network), host)
if err != nil {
return nil, &net.OpError{Op: "dial", Net: network, Source: nil, Addr: nil, Err: err}
}
var primaries, fallbacks []netip.AddrPort
if d.FallbackDelay >= 0 && network == "tcp" {
var primaryLabel bool
for i, ip := range ips {
label := ip.Is4() || ip.Is4In6()
addr := netip.AddrPortFrom(ip, uint16(portNum))
if i == 0 || label == primaryLabel {
primaryLabel = label
primaries = append(primaries, addr)
} else {
fallbacks = append(fallbacks, addr)
}
}
} else {
primaries = make([]netip.AddrPort, len(ips))
for i, ip := range ips {
primaries[i] = netip.AddrPortFrom(ip, uint16(portNum))
}
}
return d.dialParallel(ctx, network, laddr, primaries, fallbacks, b)
}
// dialParallel races two copies of dialSerial, giving the first a
// head start. It returns the first established connection and
// closes the others. Otherwise it returns an error from the first
// primary address.
func (d *Dialer) dialParallel(ctx context.Context, network string, laddr netip.AddrPort, primaries, fallbacks []netip.AddrPort, b []byte) (net.Conn, error) {
if len(fallbacks) == 0 {
return d.dialSerial(ctx, network, laddr, primaries, b)
}
returned := make(chan struct{})
defer close(returned)
type dialResult struct {
net.Conn
error
primary bool
done bool
}
results := make(chan dialResult) // unbuffered
startRacer := func(ctx context.Context, primary bool) {
ras := primaries
if !primary {
ras = fallbacks
}
c, err := d.dialSerial(ctx, network, laddr, ras, b)
select {
case results <- dialResult{Conn: c, error: err, primary: primary, done: true}:
case <-returned:
if c != nil {
c.Close()
}
}
}
var primary, fallback dialResult
// Start the main racer.
primaryCtx, primaryCancel := context.WithCancel(ctx)
defer primaryCancel()
go startRacer(primaryCtx, true)
// Start the timer for the fallback racer.
fallbackDelay := d.FallbackDelay
if fallbackDelay == 0 {
const defaultFallbackDelay = 300 * time.Millisecond
fallbackDelay = defaultFallbackDelay
}
fallbackTimer := time.NewTimer(fallbackDelay)
defer fallbackTimer.Stop()
for {
select {
case <-fallbackTimer.C:
fallbackCtx, fallbackCancel := context.WithCancel(ctx)
defer fallbackCancel()
go startRacer(fallbackCtx, false)
case res := <-results:
if res.error == nil {
return res.Conn, nil
}
if res.primary {
primary = res
} else {
fallback = res
}
if primary.done && fallback.done {
return nil, primary.error
}
if res.primary && fallbackTimer.Stop() {
// If we were able to stop the timer, that means it
// was running (hadn't yet started the fallback), but
// we just got an error on the primary path, so start
// the fallback immediately (in 0 nanoseconds).
fallbackTimer.Reset(0)
}
}
}
}
// dialSerial connects to a list of addresses in sequence, returning
// either the first successful connection, or the first error.
func (d *Dialer) dialSerial(ctx context.Context, network string, laddr netip.AddrPort, ras []netip.AddrPort, b []byte) (net.Conn, error) {
var firstErr error // The error from the first address is most relevant.
for i, ra := range ras {
select {
case <-ctx.Done():
return nil, &net.OpError{Op: "dial", Net: network, Source: opAddrPort(laddr), Addr: opAddrPort(ra), Err: ctx.Err()}
default:
}
dialCtx := ctx
if deadline, hasDeadline := ctx.Deadline(); hasDeadline {
partialDeadline, err := partialDeadline(time.Now(), deadline, len(ras)-i)
if err != nil {
// Ran out of time.
if firstErr == nil {
firstErr = &net.OpError{Op: "dial", Net: network, Source: opAddrPort(laddr), Addr: opAddrPort(ra), Err: err}
}
break
}
if partialDeadline.Before(deadline) {
var cancel context.CancelFunc
dialCtx, cancel = context.WithDeadline(ctx, partialDeadline)
defer cancel()
}
}
c, err := d.dialSingle(dialCtx, network, laddr, ra, b)
if err == nil {
return c, nil
}
if firstErr == nil {
// err is *net.OpError when TFO fallback happens.
var ok bool
firstErr, ok = err.(*net.OpError)
if !ok {
firstErr = &net.OpError{Op: "dial", Net: network, Source: opAddrPort(laddr), Addr: opAddrPort(ra), Err: err}
}
}
}
if firstErr == nil {
firstErr = &net.OpError{Op: "dial", Net: network, Source: nil, Addr: nil, Err: errMissingAddress}
}
return nil, firstErr
}
func ipNetwork(network string) string {
switch network {
case "tcp4":
return "ip4"
case "tcp6":
return "ip6"
default:
return "ip"
}
}
func minNonzeroTime(a, b time.Time) time.Time {
if a.IsZero() {
return b
}
if b.IsZero() || a.Before(b) {
return a
}
return b
}
// deadline returns the earliest of:
// - now+Timeout
// - d.Deadline
// - the context's deadline
//
// Or zero, if none of Timeout, Deadline, or context's deadline is set.
func (d *Dialer) deadline(ctx context.Context, now time.Time) (earliest time.Time) {
if d.Timeout != 0 { // including negative, for historical reasons
earliest = now.Add(d.Timeout)
}
if d, ok := ctx.Deadline(); ok {
earliest = minNonzeroTime(earliest, d)
}
return minNonzeroTime(earliest, d.Deadline)
}
// partialDeadline returns the deadline to use for a single address,
// when multiple addresses are pending.
func partialDeadline(now, deadline time.Time, addrsRemaining int) (time.Time, error) {
if deadline.IsZero() {
return deadline, nil
}
timeRemaining := deadline.Sub(now)
if timeRemaining <= 0 {
return time.Time{}, os.ErrDeadlineExceeded
}
// Tentatively allocate equal time to each remaining address.
timeout := timeRemaining / time.Duration(addrsRemaining)
// If the time per address is too short, steal from the end of the list.
const saneMinimum = 2 * time.Second
if timeout < saneMinimum {
if timeRemaining < saneMinimum {
timeout = timeRemaining
} else {
timeout = saneMinimum
}
}
return now.Add(timeout), nil
}