-
Notifications
You must be signed in to change notification settings - Fork 9
/
tfo_connect_generic.go
359 lines (322 loc) · 9.22 KB
/
tfo_connect_generic.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
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
//go:build darwin || freebsd || linux || (windows && (!go1.23 || (go1.23 && tfogo_checklinkname0)))
package tfo
import (
"context"
"net"
"os"
"syscall"
"time"
_ "unsafe"
)
const comptimeDialNoTFO = false
const (
defaultTCPKeepAlive = 15 * time.Second
defaultFallbackDelay = 300 * time.Millisecond
)
// 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 *net.TCPAddr) (family int, ipv6only bool) {
switch network {
case "tcp4":
return syscall.AF_INET, false
case "tcp6":
return syscall.AF_INET6, true
}
if tcpAddrIs4(laddr) || tcpAddrIs4(raddr) {
return syscall.AF_INET, false
}
return syscall.AF_INET6, false
}
func tcpAddrIs4(a *net.TCPAddr) bool {
return a != nil && a.IP.To4() != nil
}
func (d *Dialer) dialTFOFromSocket(ctx context.Context, network, address string, b []byte) (*net.TCPConn, error) {
if ctx == nil {
panic("nil context")
}
deadline := d.deadline(ctx, time.Now())
if !deadline.IsZero() {
if d, ok := ctx.Deadline(); !ok || deadline.Before(d) {
subCtx, cancel := context.WithDeadline(ctx, deadline)
defer cancel()
ctx = subCtx
}
}
if oldCancel := d.Cancel; oldCancel != nil {
subCtx, cancel := context.WithCancel(ctx)
defer cancel()
go func() {
select {
case <-oldCancel:
cancel()
case <-subCtx.Done():
}
}()
ctx = subCtx
}
var laddr *net.TCPAddr
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
}
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}
}
ipaddrs, err := d.Resolver.LookupIPAddr(ctx, host)
if err != nil {
return nil, &net.OpError{Op: "dial", Net: network, Source: nil, Addr: nil, Err: err}
}
var addrs []*net.TCPAddr
for _, ipaddr := range ipaddrs {
if laddr != nil && !laddr.IP.IsUnspecified() && !matchAddrFamily(laddr.IP, ipaddr.IP) {
continue
}
addrs = append(addrs, &net.TCPAddr{
IP: ipaddr.IP,
Port: portNum,
Zone: ipaddr.Zone,
})
}
var primaries, fallbacks []*net.TCPAddr
if d.FallbackDelay >= 0 && network == "tcp" {
primaries, fallbacks = partition(addrs, func(a *net.TCPAddr) bool {
return a.IP.To4() != nil
})
} else {
primaries = addrs
}
var c *net.TCPConn
if len(fallbacks) > 0 {
c, err = d.dialParallel(ctx, network, laddr, primaries, fallbacks, b)
} else {
c, err = d.dialSerial(ctx, network, laddr, primaries, b)
}
if err != nil {
return nil, err
}
if d.KeepAlive >= 0 {
c.SetKeepAlive(true)
ka := d.KeepAlive
if d.KeepAlive == 0 {
ka = defaultTCPKeepAlive
}
c.SetKeepAlivePeriod(ka)
}
return c, nil
}
// 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 *net.TCPAddr, primaries, fallbacks []*net.TCPAddr, b []byte) (*net.TCPConn, error) {
if len(fallbacks) == 0 {
return d.dialSerial(ctx, network, laddr, primaries, b)
}
returned := make(chan struct{})
defer close(returned)
type dialResult struct {
*net.TCPConn
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{TCPConn: 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 {
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.TCPConn, 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 *net.TCPAddr, ras []*net.TCPAddr, b []byte) (*net.TCPConn, 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: d.LocalAddr, Addr: 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: d.LocalAddr, Addr: ra, Err: err}
}
break
}
if partialDeadline.Before(deadline) {
var cancel context.CancelFunc
dialCtx, cancel = context.WithDeadline(ctx, partialDeadline)
defer cancel()
}
}
ctrlCtxFn := d.ControlContext
if ctrlCtxFn == nil && d.Control != nil {
ctrlCtxFn = func(ctx context.Context, network, address string, c syscall.RawConn) error {
return d.Control(network, address, c)
}
}
c, err := d.dialSingle(dialCtx, network, laddr, ra, b, ctrlCtxFn)
if err == nil {
return c, nil
}
if firstErr == nil {
firstErr = &net.OpError{Op: "dial", Net: network, Source: d.LocalAddr, Addr: ra, Err: err}
}
}
if firstErr == nil {
firstErr = &net.OpError{Op: "dial", Net: network, Source: nil, Addr: nil, Err: errMissingAddress}
}
return nil, firstErr
}
func matchAddrFamily(x, y net.IP) bool {
return x.To4() != nil && y.To4() != nil || x.To16() != nil && x.To4() == nil && y.To16() != nil && y.To4() == nil
}
// partition divides an address list into two categories, using a
// strategy function to assign a boolean label to each address.
// The first address, and any with a matching label, are returned as
// primaries, while addresses with the opposite label are returned
// as fallbacks. For non-empty inputs, primaries is guaranteed to be
// non-empty.
func partition(addrs []*net.TCPAddr, strategy func(*net.TCPAddr) bool) (primaries, fallbacks []*net.TCPAddr) {
var primaryLabel bool
for i, addr := range addrs {
label := strategy(addr)
if i == 0 || label == primaryLabel {
primaryLabel = label
primaries = append(primaries, addr)
} else {
fallbacks = append(fallbacks, addr)
}
}
return
}
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
}