codekingpro commited on
Commit
9adc280
·
verified ·
1 Parent(s): bd21366

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. go/src/net/resolverdialfunc_test.go +325 -0
  2. go/src/net/rlimit_js.go +13 -0
  3. go/src/net/rlimit_unix.go +33 -0
  4. go/src/net/sendfile.go +62 -0
  5. go/src/net/sendfile_nonwindows.go +12 -0
  6. go/src/net/sendfile_stub.go +19 -0
  7. go/src/net/sendfile_test.go +634 -0
  8. go/src/net/sendfile_unix_test.go +86 -0
  9. go/src/net/sendfile_windows.go +19 -0
  10. go/src/net/server_test.go +410 -0
  11. go/src/net/sock_bsd.go +39 -0
  12. go/src/net/sock_cloexec.go +25 -0
  13. go/src/net/sock_cloexec_solaris.go +47 -0
  14. go/src/net/sock_linux.go +53 -0
  15. go/src/net/sock_linux_test.go +22 -0
  16. go/src/net/sock_plan9.go +10 -0
  17. go/src/net/sock_posix.go +226 -0
  18. go/src/net/sock_stub.go +15 -0
  19. go/src/net/sock_windows.go +27 -0
  20. go/src/net/sockaddr_posix.go +58 -0
  21. go/src/net/sockopt_aix.go +39 -0
  22. go/src/net/sockopt_bsd.go +57 -0
  23. go/src/net/sockopt_fake.go +46 -0
  24. go/src/net/sockopt_linux.go +35 -0
  25. go/src/net/sockopt_plan9.go +19 -0
  26. go/src/net/sockopt_posix.go +75 -0
  27. go/src/net/sockopt_solaris.go +35 -0
  28. go/src/net/sockopt_windows.go +40 -0
  29. go/src/net/sockoptip4_bsdvar.go +30 -0
  30. go/src/net/sockoptip4_linux.go +37 -0
  31. go/src/net/sockoptip4_posix_nonlinux.go +52 -0
  32. go/src/net/sockoptip4_windows.go +29 -0
  33. go/src/net/sockoptip6_posix.go +39 -0
  34. go/src/net/sockoptip_stub.go +33 -0
  35. go/src/net/splice_linux.go +64 -0
  36. go/src/net/splice_linux_test.go +541 -0
  37. go/src/net/splice_stub.go +17 -0
  38. go/src/net/sys_cloexec.go +36 -0
  39. go/src/net/tcpconn_keepalive_conf_darwin_test.go +22 -0
  40. go/src/net/tcpconn_keepalive_conf_posix_test.go +102 -0
  41. go/src/net/tcpconn_keepalive_conf_solaris_test.go +115 -0
  42. go/src/net/tcpconn_keepalive_conf_unix_test.go +22 -0
  43. go/src/net/tcpconn_keepalive_conf_windows_test.go +31 -0
  44. go/src/net/tcpconn_keepalive_illumos_test.go +120 -0
  45. go/src/net/tcpconn_keepalive_posix_test.go +92 -0
  46. go/src/net/tcpconn_keepalive_solaris_test.go +170 -0
  47. go/src/net/tcpconn_keepalive_test.go +190 -0
  48. go/src/net/tcpsock.go +478 -0
  49. go/src/net/tcpsock_plan9.go +90 -0
  50. go/src/net/tcpsock_posix.go +194 -0
go/src/net/resolverdialfunc_test.go ADDED
@@ -0,0 +1,325 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2022 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ // Test that Resolver.Dial can be a func returning an in-memory net.Conn
6
+ // speaking DNS.
7
+
8
+ package net
9
+
10
+ import (
11
+ "bytes"
12
+ "context"
13
+ "errors"
14
+ "fmt"
15
+ "reflect"
16
+ "slices"
17
+ "testing"
18
+ "time"
19
+
20
+ "golang.org/x/net/dns/dnsmessage"
21
+ )
22
+
23
+ func TestResolverDialFunc(t *testing.T) {
24
+ r := &Resolver{
25
+ PreferGo: true,
26
+ Dial: newResolverDialFunc(&resolverDialHandler{
27
+ StartDial: func(network, address string) error {
28
+ t.Logf("StartDial(%q, %q) ...", network, address)
29
+ return nil
30
+ },
31
+ Question: func(h dnsmessage.Header, q dnsmessage.Question) {
32
+ t.Logf("Header: %+v for %q (type=%v, class=%v)", h,
33
+ q.Name.String(), q.Type, q.Class)
34
+ },
35
+ // TODO: add test without HandleA* hooks specified at all, that Go
36
+ // doesn't issue retries; map to something terminal.
37
+ HandleA: func(w AWriter, name string) error {
38
+ w.AddIP([4]byte{1, 2, 3, 4})
39
+ w.AddIP([4]byte{5, 6, 7, 8})
40
+ return nil
41
+ },
42
+ HandleAAAA: func(w AAAAWriter, name string) error {
43
+ w.AddIP([16]byte{1: 1, 15: 15})
44
+ w.AddIP([16]byte{2: 2, 14: 14})
45
+ return nil
46
+ },
47
+ HandleSRV: func(w SRVWriter, name string) error {
48
+ w.AddSRV(1, 2, 80, "foo.bar.")
49
+ w.AddSRV(2, 3, 81, "bar.baz.")
50
+ return nil
51
+ },
52
+ }),
53
+ }
54
+ ctx := context.Background()
55
+ const fakeDomain = "something-that-is-a-not-a-real-domain.fake-tld."
56
+
57
+ t.Run("LookupIP", func(t *testing.T) {
58
+ ips, err := r.LookupIP(ctx, "ip", fakeDomain)
59
+ if err != nil {
60
+ t.Fatal(err)
61
+ }
62
+ if got, want := sortedIPStrings(ips), []string{"0:200::e00", "1.2.3.4", "1::f", "5.6.7.8"}; !slices.Equal(got, want) {
63
+ t.Errorf("LookupIP wrong.\n got: %q\nwant: %q\n", got, want)
64
+ }
65
+ })
66
+
67
+ t.Run("LookupSRV", func(t *testing.T) {
68
+ _, got, err := r.LookupSRV(ctx, "some-service", "tcp", fakeDomain)
69
+ if err != nil {
70
+ t.Fatal(err)
71
+ }
72
+ want := []*SRV{
73
+ {
74
+ Target: "foo.bar.",
75
+ Port: 80,
76
+ Priority: 1,
77
+ Weight: 2,
78
+ },
79
+ {
80
+ Target: "bar.baz.",
81
+ Port: 81,
82
+ Priority: 2,
83
+ Weight: 3,
84
+ },
85
+ }
86
+ if !reflect.DeepEqual(got, want) {
87
+ t.Errorf("wrong result. got:")
88
+ for _, r := range got {
89
+ t.Logf(" - %+v", r)
90
+ }
91
+ }
92
+ })
93
+ }
94
+
95
+ func sortedIPStrings(ips []IP) []string {
96
+ ret := make([]string, len(ips))
97
+ for i, ip := range ips {
98
+ ret[i] = ip.String()
99
+ }
100
+ slices.Sort(ret)
101
+ return ret
102
+ }
103
+
104
+ func newResolverDialFunc(h *resolverDialHandler) func(ctx context.Context, network, address string) (Conn, error) {
105
+ return func(ctx context.Context, network, address string) (Conn, error) {
106
+ a := &resolverFuncConn{
107
+ h: h,
108
+ network: network,
109
+ address: address,
110
+ ttl: 10, // 10 second default if unset
111
+ }
112
+ if h.StartDial != nil {
113
+ if err := h.StartDial(network, address); err != nil {
114
+ return nil, err
115
+ }
116
+ }
117
+ return a, nil
118
+ }
119
+ }
120
+
121
+ type resolverDialHandler struct {
122
+ // StartDial, if non-nil, is called when Go first calls Resolver.Dial.
123
+ // Any error returned aborts the dial and is returned unwrapped.
124
+ StartDial func(network, address string) error
125
+
126
+ Question func(dnsmessage.Header, dnsmessage.Question)
127
+
128
+ // err may be ErrNotExist or ErrRefused; others map to SERVFAIL (RCode2).
129
+ // A nil error means success.
130
+ HandleA func(w AWriter, name string) error
131
+ HandleAAAA func(w AAAAWriter, name string) error
132
+ HandleSRV func(w SRVWriter, name string) error
133
+ }
134
+
135
+ type ResponseWriter struct{ a *resolverFuncConn }
136
+
137
+ func (w ResponseWriter) header() dnsmessage.ResourceHeader {
138
+ q := w.a.q
139
+ return dnsmessage.ResourceHeader{
140
+ Name: q.Name,
141
+ Type: q.Type,
142
+ Class: q.Class,
143
+ TTL: w.a.ttl,
144
+ }
145
+ }
146
+
147
+ // SetTTL sets the TTL for subsequent written resources.
148
+ // Once a resource has been written, SetTTL calls are no-ops.
149
+ // That is, it can only be called at most once, before anything
150
+ // else is written.
151
+ func (w ResponseWriter) SetTTL(seconds uint32) {
152
+ // ... intention is last one wins and mutates all previously
153
+ // written records too, but that's a little annoying.
154
+ // But it's also annoying if the requirement is it needs to be set
155
+ // last.
156
+ // And it's also annoying if it's possible for users to set
157
+ // different TTLs per Answer.
158
+ if w.a.wrote {
159
+ return
160
+ }
161
+ w.a.ttl = seconds
162
+
163
+ }
164
+
165
+ type AWriter struct{ ResponseWriter }
166
+
167
+ func (w AWriter) AddIP(v4 [4]byte) {
168
+ w.a.wrote = true
169
+ err := w.a.builder.AResource(w.header(), dnsmessage.AResource{A: v4})
170
+ if err != nil {
171
+ panic(err)
172
+ }
173
+ }
174
+
175
+ type AAAAWriter struct{ ResponseWriter }
176
+
177
+ func (w AAAAWriter) AddIP(v6 [16]byte) {
178
+ w.a.wrote = true
179
+ err := w.a.builder.AAAAResource(w.header(), dnsmessage.AAAAResource{AAAA: v6})
180
+ if err != nil {
181
+ panic(err)
182
+ }
183
+ }
184
+
185
+ type SRVWriter struct{ ResponseWriter }
186
+
187
+ // AddSRV adds a SRV record. The target name must end in a period and
188
+ // be 63 bytes or fewer.
189
+ func (w SRVWriter) AddSRV(priority, weight, port uint16, target string) error {
190
+ targetName, err := dnsmessage.NewName(target)
191
+ if err != nil {
192
+ return err
193
+ }
194
+ w.a.wrote = true
195
+ err = w.a.builder.SRVResource(w.header(), dnsmessage.SRVResource{
196
+ Priority: priority,
197
+ Weight: weight,
198
+ Port: port,
199
+ Target: targetName,
200
+ })
201
+ if err != nil {
202
+ panic(err) // internal fault, not user
203
+ }
204
+ return nil
205
+ }
206
+
207
+ var (
208
+ ErrNotExist = errors.New("name does not exist") // maps to RCode3, NXDOMAIN
209
+ ErrRefused = errors.New("refused") // maps to RCode5, REFUSED
210
+ )
211
+
212
+ type resolverFuncConn struct {
213
+ h *resolverDialHandler
214
+ network string
215
+ address string
216
+ builder *dnsmessage.Builder
217
+ q dnsmessage.Question
218
+ ttl uint32
219
+ wrote bool
220
+
221
+ rbuf bytes.Buffer
222
+ }
223
+
224
+ func (*resolverFuncConn) Close() error { return nil }
225
+ func (*resolverFuncConn) LocalAddr() Addr { return someaddr{} }
226
+ func (*resolverFuncConn) RemoteAddr() Addr { return someaddr{} }
227
+ func (*resolverFuncConn) SetDeadline(t time.Time) error { return nil }
228
+ func (*resolverFuncConn) SetReadDeadline(t time.Time) error { return nil }
229
+ func (*resolverFuncConn) SetWriteDeadline(t time.Time) error { return nil }
230
+
231
+ func (a *resolverFuncConn) Read(p []byte) (n int, err error) {
232
+ return a.rbuf.Read(p)
233
+ }
234
+
235
+ func (a *resolverFuncConn) Write(packet []byte) (n int, err error) {
236
+ if len(packet) < 2 {
237
+ return 0, fmt.Errorf("short write of %d bytes; want 2+", len(packet))
238
+ }
239
+ reqLen := int(packet[0])<<8 | int(packet[1])
240
+ req := packet[2:]
241
+ if len(req) != reqLen {
242
+ return 0, fmt.Errorf("packet declared length %d doesn't match body length %d", reqLen, len(req))
243
+ }
244
+
245
+ var parser dnsmessage.Parser
246
+ h, err := parser.Start(req)
247
+ if err != nil {
248
+ // TODO: hook
249
+ return 0, err
250
+ }
251
+ q, err := parser.Question()
252
+ hadQ := (err == nil)
253
+ if err == nil && a.h.Question != nil {
254
+ a.h.Question(h, q)
255
+ }
256
+ if err != nil && err != dnsmessage.ErrSectionDone {
257
+ return 0, err
258
+ }
259
+
260
+ resh := h
261
+ resh.Response = true
262
+ resh.Authoritative = true
263
+ if hadQ {
264
+ resh.RCode = dnsmessage.RCodeSuccess
265
+ } else {
266
+ resh.RCode = dnsmessage.RCodeNotImplemented
267
+ }
268
+ a.rbuf.Grow(514)
269
+ a.rbuf.WriteByte('X') // reserved header for beu16 length
270
+ a.rbuf.WriteByte('Y') // reserved header for beu16 length
271
+ builder := dnsmessage.NewBuilder(a.rbuf.Bytes(), resh)
272
+ a.builder = &builder
273
+ if hadQ {
274
+ a.q = q
275
+ a.builder.StartQuestions()
276
+ err := a.builder.Question(q)
277
+ if err != nil {
278
+ return 0, fmt.Errorf("Question: %w", err)
279
+ }
280
+ a.builder.StartAnswers()
281
+ switch q.Type {
282
+ case dnsmessage.TypeA:
283
+ if a.h.HandleA != nil {
284
+ resh.RCode = mapRCode(a.h.HandleA(AWriter{ResponseWriter{a}}, q.Name.String()))
285
+ }
286
+ case dnsmessage.TypeAAAA:
287
+ if a.h.HandleAAAA != nil {
288
+ resh.RCode = mapRCode(a.h.HandleAAAA(AAAAWriter{ResponseWriter{a}}, q.Name.String()))
289
+ }
290
+ case dnsmessage.TypeSRV:
291
+ if a.h.HandleSRV != nil {
292
+ resh.RCode = mapRCode(a.h.HandleSRV(SRVWriter{ResponseWriter{a}}, q.Name.String()))
293
+ }
294
+ }
295
+ }
296
+ tcpRes, err := builder.Finish()
297
+ if err != nil {
298
+ return 0, fmt.Errorf("Finish: %w", err)
299
+ }
300
+
301
+ n = len(tcpRes) - 2
302
+ tcpRes[0] = byte(n >> 8)
303
+ tcpRes[1] = byte(n)
304
+ a.rbuf.Write(tcpRes[2:])
305
+
306
+ return len(packet), nil
307
+ }
308
+
309
+ type someaddr struct{}
310
+
311
+ func (someaddr) Network() string { return "unused" }
312
+ func (someaddr) String() string { return "unused-someaddr" }
313
+
314
+ func mapRCode(err error) dnsmessage.RCode {
315
+ switch err {
316
+ case nil:
317
+ return dnsmessage.RCodeSuccess
318
+ case ErrNotExist:
319
+ return dnsmessage.RCodeNameError
320
+ case ErrRefused:
321
+ return dnsmessage.RCodeRefused
322
+ default:
323
+ return dnsmessage.RCodeServerFailure
324
+ }
325
+ }
go/src/net/rlimit_js.go ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2023 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build js
6
+
7
+ package net
8
+
9
+ // concurrentThreadsLimit returns the number of threads we permit to
10
+ // run concurrently doing DNS lookups.
11
+ func concurrentThreadsLimit() int {
12
+ return 500
13
+ }
go/src/net/rlimit_unix.go ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2023 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build unix || wasip1
6
+
7
+ package net
8
+
9
+ import "syscall"
10
+
11
+ // concurrentThreadsLimit returns the number of threads we permit to
12
+ // run concurrently doing DNS lookups via cgo. A DNS lookup may use a
13
+ // file descriptor so we limit this to less than the number of
14
+ // permitted open files. On some systems, notably Darwin, if
15
+ // getaddrinfo is unable to open a file descriptor it simply returns
16
+ // EAI_NONAME rather than a useful error. Limiting the number of
17
+ // concurrent getaddrinfo calls to less than the permitted number of
18
+ // file descriptors makes that error less likely. We don't bother to
19
+ // apply the same limit to DNS lookups run directly from Go, because
20
+ // there we will return a meaningful "too many open files" error.
21
+ func concurrentThreadsLimit() int {
22
+ var rlim syscall.Rlimit
23
+ if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rlim); err != nil {
24
+ return 500
25
+ }
26
+ r := rlim.Cur
27
+ if r > 500 {
28
+ r = 500
29
+ } else if r > 30 {
30
+ r -= 30
31
+ }
32
+ return int(r)
33
+ }
go/src/net/sendfile.go ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2011 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build linux || (darwin && !ios) || dragonfly || freebsd || solaris || windows
6
+
7
+ package net
8
+
9
+ import (
10
+ "internal/poll"
11
+ "io"
12
+ "syscall"
13
+ )
14
+
15
+ var testHookSupportsSendfile func() bool
16
+
17
+ // sendFile copies the contents of r to c using the sendfile
18
+ // system call to minimize copies.
19
+ //
20
+ // if handled == true, sendFile returns the number (potentially zero) of bytes
21
+ // copied and any non-EOF error.
22
+ //
23
+ // if handled == false, sendFile performed no work.
24
+ func sendFile(c *netFD, r io.Reader) (written int64, err error, handled bool) {
25
+ if !supportsSendfile() {
26
+ return 0, nil, false
27
+ }
28
+ var remain int64 = 0 // 0 writes the entire file
29
+ lr, ok := r.(*io.LimitedReader)
30
+ if ok {
31
+ remain, r = lr.N, lr.R
32
+ if remain <= 0 {
33
+ return 0, nil, true
34
+ }
35
+ }
36
+ // r might be an *os.File or an os.fileWithoutWriteTo.
37
+ // Type assert to an interface rather than *os.File directly to handle the latter case.
38
+ f, ok := r.(syscall.Conn)
39
+ if !ok {
40
+ return 0, nil, false
41
+ }
42
+
43
+ sc, err := f.SyscallConn()
44
+ if err != nil {
45
+ return 0, nil, false
46
+ }
47
+
48
+ var werr error
49
+ err = sc.Read(func(fd uintptr) bool {
50
+ written, werr, handled = poll.SendFile(&c.pfd, fd, remain)
51
+ return true
52
+ })
53
+ if err == nil {
54
+ err = werr
55
+ }
56
+
57
+ if lr != nil {
58
+ lr.N = remain - written
59
+ }
60
+
61
+ return written, wrapSyscallError("sendfile", err), handled
62
+ }
go/src/net/sendfile_nonwindows.go ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2025 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build linux || (darwin && !ios) || dragonfly || freebsd || solaris
6
+
7
+ package net
8
+
9
+ // Always true except for workstation and client versions of Windows
10
+ func supportsSendfile() bool {
11
+ return true
12
+ }
go/src/net/sendfile_stub.go ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2011 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build !(linux || (darwin && !ios) || dragonfly || freebsd || solaris || windows)
6
+
7
+ package net
8
+
9
+ import "io"
10
+
11
+ var testHookSupportsSendfile func() bool
12
+
13
+ func supportsSendfile() bool {
14
+ return false
15
+ }
16
+
17
+ func sendFile(c *netFD, r io.Reader) (n int64, err error, handled bool) {
18
+ return 0, nil, false
19
+ }
go/src/net/sendfile_test.go ADDED
@@ -0,0 +1,634 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2016 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package net
6
+
7
+ import (
8
+ "bytes"
9
+ "context"
10
+ "crypto/sha256"
11
+ "encoding/hex"
12
+ "errors"
13
+ "fmt"
14
+ "internal/poll"
15
+ "io"
16
+ "math/rand"
17
+ "os"
18
+ "runtime"
19
+ "strconv"
20
+ "sync"
21
+ "testing"
22
+ "time"
23
+ )
24
+
25
+ const (
26
+ newton = "../testdata/Isaac.Newton-Opticks.txt"
27
+ newtonLen = 567198
28
+ newtonSHA256 = "d4a9ac22462b35e7821a4f2706c211093da678620a8f9997989ee7cf8d507bbd"
29
+ )
30
+
31
+ func hookSupportsSendfile(t *testing.T) {
32
+ if runtime.GOOS == "windows" {
33
+ origHook := testHookSupportsSendfile
34
+ testHookSupportsSendfile = func() bool { return true }
35
+ t.Cleanup(func() {
36
+ testHookSupportsSendfile = origHook
37
+ })
38
+ }
39
+ }
40
+
41
+ // expectSendfile runs f, and verifies that internal/poll.SendFile successfully handles
42
+ // a write to wantConn during f's execution.
43
+ //
44
+ // On platforms where supportsSendfile() is false, expectSendfile runs f but does not
45
+ // expect a call to SendFile.
46
+ func expectSendfile(t *testing.T, wantConn Conn, f func()) {
47
+ t.Helper()
48
+ hookSupportsSendfile(t)
49
+ if !supportsSendfile() {
50
+ f()
51
+ return
52
+ }
53
+ orig := poll.TestHookDidSendFile
54
+ defer func() {
55
+ poll.TestHookDidSendFile = orig
56
+ }()
57
+ var (
58
+ called bool
59
+ gotHandled bool
60
+ gotFD *poll.FD
61
+ gotErr error
62
+ )
63
+ poll.TestHookDidSendFile = func(dstFD *poll.FD, src uintptr, written int64, err error, handled bool) {
64
+ if called {
65
+ t.Error("internal/poll.SendFile called multiple times, want one call")
66
+ }
67
+ called = true
68
+ gotHandled = handled
69
+ gotFD = dstFD
70
+ gotErr = err
71
+ }
72
+ f()
73
+ if !called {
74
+ t.Error("internal/poll.SendFile was not called, want it to be")
75
+ return
76
+ }
77
+ if !gotHandled {
78
+ t.Error("internal/poll.SendFile did not handle the write, want it to, error:", gotErr)
79
+ return
80
+ }
81
+ if &wantConn.(*TCPConn).fd.pfd != gotFD {
82
+ t.Error("internal.poll.SendFile called with unexpected FD")
83
+ }
84
+ }
85
+
86
+ func TestSendfile(t *testing.T) { testSendfile(t, newton, newtonSHA256, newtonLen, 0) }
87
+ func TestSendfileWithExactLimit(t *testing.T) {
88
+ testSendfile(t, newton, newtonSHA256, newtonLen, newtonLen)
89
+ }
90
+ func TestSendfileWithLimitLargerThanFile(t *testing.T) {
91
+ testSendfile(t, newton, newtonSHA256, newtonLen, newtonLen*2)
92
+ }
93
+ func TestSendfileWithLargeFile(t *testing.T) {
94
+ // Some platforms are not capable of handling large files with sendfile
95
+ // due to limited system resource, so we only run this test on amd64 and
96
+ // arm64 for the moment.
97
+ if runtime.GOARCH != "amd64" && runtime.GOARCH != "arm64" {
98
+ t.Skip("skipping on non-amd64 and non-arm64 platforms")
99
+ }
100
+ // Also skip it during short testing.
101
+ if testing.Short() {
102
+ t.Skip("Skip it during short testing")
103
+ }
104
+
105
+ // We're using 1<<31 - 1 as the chunk size for sendfile currently,
106
+ // make an edge case file that is 1 byte bigger than that.
107
+ f := createTempFile(t, 1<<31)
108
+ // For big file like this, only verify the transmission of the file,
109
+ // skip the content check.
110
+ testSendfile(t, f.Name(), "", 1<<31, 0)
111
+ }
112
+ func testSendfile(t *testing.T, filePath, fileHash string, size, limit int64) {
113
+ ln := newLocalListener(t, "tcp")
114
+ defer ln.Close()
115
+
116
+ errc := make(chan error, 1)
117
+ go func(ln Listener) {
118
+ // Wait for a connection.
119
+ conn, err := ln.Accept()
120
+ if err != nil {
121
+ errc <- err
122
+ close(errc)
123
+ return
124
+ }
125
+
126
+ go func() {
127
+ defer close(errc)
128
+ defer conn.Close()
129
+
130
+ f, err := os.Open(filePath)
131
+ if err != nil {
132
+ errc <- err
133
+ return
134
+ }
135
+ defer f.Close()
136
+
137
+ // Return file data using io.Copy, which should use
138
+ // sendFile if available.
139
+ var sbytes int64
140
+ expectSendfile(t, conn, func() {
141
+ if limit > 0 {
142
+ sbytes, err = io.CopyN(conn, f, limit)
143
+ if err == io.EOF && limit > size {
144
+ err = nil
145
+ }
146
+ } else {
147
+ sbytes, err = io.Copy(conn, f)
148
+ }
149
+ })
150
+ if err != nil {
151
+ errc <- err
152
+ return
153
+ }
154
+
155
+ if sbytes != size {
156
+ errc <- fmt.Errorf("sent %d bytes; expected %d", sbytes, size)
157
+ return
158
+ }
159
+ }()
160
+ }(ln)
161
+
162
+ // Connect to listener to retrieve file and verify digest matches
163
+ // expected.
164
+ c, err := Dial("tcp", ln.Addr().String())
165
+ if err != nil {
166
+ t.Fatal(err)
167
+ }
168
+ defer c.Close()
169
+
170
+ h := sha256.New()
171
+ rbytes, err := io.Copy(h, c)
172
+ if err != nil {
173
+ t.Error(err)
174
+ }
175
+
176
+ if rbytes != size {
177
+ t.Errorf("received %d bytes; expected %d", rbytes, size)
178
+ }
179
+
180
+ if len(fileHash) > 0 && hex.EncodeToString(h.Sum(nil)) != newtonSHA256 {
181
+ t.Error("retrieved data hash did not match")
182
+ }
183
+
184
+ for err := range errc {
185
+ t.Error(err)
186
+ }
187
+ }
188
+
189
+ func TestSendfileParts(t *testing.T) {
190
+ ln := newLocalListener(t, "tcp")
191
+ defer ln.Close()
192
+
193
+ errc := make(chan error, 1)
194
+ go func(ln Listener) {
195
+ // Wait for a connection.
196
+ conn, err := ln.Accept()
197
+ if err != nil {
198
+ errc <- err
199
+ close(errc)
200
+ return
201
+ }
202
+
203
+ go func() {
204
+ defer close(errc)
205
+ defer conn.Close()
206
+
207
+ f, err := os.Open(newton)
208
+ if err != nil {
209
+ errc <- err
210
+ return
211
+ }
212
+ defer f.Close()
213
+
214
+ for i := 0; i < 3; i++ {
215
+ // Return file data using io.CopyN, which should use
216
+ // sendFile if available.
217
+ expectSendfile(t, conn, func() {
218
+ _, err = io.CopyN(conn, f, 3)
219
+ })
220
+ if err != nil {
221
+ errc <- err
222
+ return
223
+ }
224
+ }
225
+ }()
226
+ }(ln)
227
+
228
+ c, err := Dial("tcp", ln.Addr().String())
229
+ if err != nil {
230
+ t.Fatal(err)
231
+ }
232
+ defer c.Close()
233
+
234
+ buf := new(bytes.Buffer)
235
+ buf.ReadFrom(c)
236
+
237
+ if want, have := "Produced ", buf.String(); have != want {
238
+ t.Errorf("unexpected server reply %q, want %q", have, want)
239
+ }
240
+
241
+ for err := range errc {
242
+ t.Error(err)
243
+ }
244
+ }
245
+
246
+ func TestSendfileSeeked(t *testing.T) {
247
+ ln := newLocalListener(t, "tcp")
248
+ defer ln.Close()
249
+
250
+ const seekTo = 65 << 10
251
+ const sendSize = 10 << 10
252
+
253
+ errc := make(chan error, 1)
254
+ go func(ln Listener) {
255
+ // Wait for a connection.
256
+ conn, err := ln.Accept()
257
+ if err != nil {
258
+ errc <- err
259
+ close(errc)
260
+ return
261
+ }
262
+
263
+ go func() {
264
+ defer close(errc)
265
+ defer conn.Close()
266
+
267
+ f, err := os.Open(newton)
268
+ if err != nil {
269
+ errc <- err
270
+ return
271
+ }
272
+ defer f.Close()
273
+ if _, err := f.Seek(seekTo, io.SeekStart); err != nil {
274
+ errc <- err
275
+ return
276
+ }
277
+
278
+ expectSendfile(t, conn, func() {
279
+ _, err = io.CopyN(conn, f, sendSize)
280
+ })
281
+ if err != nil {
282
+ errc <- err
283
+ return
284
+ }
285
+ }()
286
+ }(ln)
287
+
288
+ c, err := Dial("tcp", ln.Addr().String())
289
+ if err != nil {
290
+ t.Fatal(err)
291
+ }
292
+ defer c.Close()
293
+
294
+ buf := new(bytes.Buffer)
295
+ buf.ReadFrom(c)
296
+
297
+ if buf.Len() != sendSize {
298
+ t.Errorf("Got %d bytes; want %d", buf.Len(), sendSize)
299
+ }
300
+
301
+ for err := range errc {
302
+ t.Error(err)
303
+ }
304
+ }
305
+
306
+ // Test that sendfile doesn't put a pipe into blocking mode.
307
+ func TestSendfilePipe(t *testing.T) {
308
+ switch runtime.GOOS {
309
+ case "plan9", "windows", "js", "wasip1":
310
+ // These systems don't support deadlines on pipes.
311
+ t.Skipf("skipping on %s", runtime.GOOS)
312
+ }
313
+
314
+ t.Parallel()
315
+
316
+ ln := newLocalListener(t, "tcp")
317
+ defer ln.Close()
318
+
319
+ r, w, err := os.Pipe()
320
+ if err != nil {
321
+ t.Fatal(err)
322
+ }
323
+ defer w.Close()
324
+ defer r.Close()
325
+
326
+ copied := make(chan bool)
327
+
328
+ var wg sync.WaitGroup
329
+ wg.Add(1)
330
+ go func() {
331
+ // Accept a connection and copy 1 byte from the read end of
332
+ // the pipe to the connection. This will call into sendfile.
333
+ defer wg.Done()
334
+ conn, err := ln.Accept()
335
+ if err != nil {
336
+ t.Error(err)
337
+ return
338
+ }
339
+ defer conn.Close()
340
+ // The comment above states that this should call into sendfile,
341
+ // but empirically it doesn't seem to do so at this time.
342
+ // If it does, or does on some platforms, this CopyN should be wrapped
343
+ // in expectSendfile.
344
+ _, err = io.CopyN(conn, r, 1)
345
+ if err != nil {
346
+ t.Error(err)
347
+ return
348
+ }
349
+ // Signal the main goroutine that we've copied the byte.
350
+ close(copied)
351
+ }()
352
+
353
+ wg.Add(1)
354
+ go func() {
355
+ // Write 1 byte to the write end of the pipe.
356
+ defer wg.Done()
357
+ _, err := w.Write([]byte{'a'})
358
+ if err != nil {
359
+ t.Error(err)
360
+ }
361
+ }()
362
+
363
+ wg.Add(1)
364
+ go func() {
365
+ // Connect to the server started two goroutines up and
366
+ // discard any data that it writes.
367
+ defer wg.Done()
368
+ conn, err := Dial("tcp", ln.Addr().String())
369
+ if err != nil {
370
+ t.Error(err)
371
+ return
372
+ }
373
+ defer conn.Close()
374
+ io.Copy(io.Discard, conn)
375
+ }()
376
+
377
+ // Wait for the byte to be copied, meaning that sendfile has
378
+ // been called on the pipe.
379
+ <-copied
380
+
381
+ // Set a very short deadline on the read end of the pipe.
382
+ if err := r.SetDeadline(time.Now().Add(time.Microsecond)); err != nil {
383
+ t.Fatal(err)
384
+ }
385
+
386
+ wg.Add(1)
387
+ go func() {
388
+ // Wait for much longer than the deadline and write a byte
389
+ // to the pipe.
390
+ defer wg.Done()
391
+ time.Sleep(50 * time.Millisecond)
392
+ w.Write([]byte{'b'})
393
+ }()
394
+
395
+ // If this read does not time out, the pipe was incorrectly
396
+ // put into blocking mode.
397
+ _, err = r.Read(make([]byte, 1))
398
+ if err == nil {
399
+ t.Error("Read did not time out")
400
+ } else if !os.IsTimeout(err) {
401
+ t.Errorf("got error %v, expected a time out", err)
402
+ }
403
+
404
+ wg.Wait()
405
+ }
406
+
407
+ // Issue 43822: tests that returns EOF when conn write timeout.
408
+ func TestSendfileOnWriteTimeoutExceeded(t *testing.T) {
409
+ ln := newLocalListener(t, "tcp")
410
+ defer ln.Close()
411
+
412
+ errc := make(chan error, 1)
413
+ go func(ln Listener) (retErr error) {
414
+ defer func() {
415
+ errc <- retErr
416
+ close(errc)
417
+ }()
418
+
419
+ conn, err := ln.Accept()
420
+ if err != nil {
421
+ return err
422
+ }
423
+ defer conn.Close()
424
+
425
+ // Set the write deadline in the past(1h ago). It makes
426
+ // sure that it is always write timeout.
427
+ if err := conn.SetWriteDeadline(time.Now().Add(-1 * time.Hour)); err != nil {
428
+ return err
429
+ }
430
+
431
+ f, err := os.Open(newton)
432
+ if err != nil {
433
+ return err
434
+ }
435
+ defer f.Close()
436
+
437
+ // We expect this to use sendfile, but as of the time this comment was written
438
+ // poll.SendFile on an FD past its timeout can return an error indicating that
439
+ // it didn't handle the operation, resulting in a non-sendfile retry.
440
+ // So don't use expectSendfile here.
441
+ _, err = io.Copy(conn, f)
442
+ if errors.Is(err, os.ErrDeadlineExceeded) {
443
+ return nil
444
+ }
445
+
446
+ if err == nil {
447
+ err = fmt.Errorf("expected ErrDeadlineExceeded, but got nil")
448
+ }
449
+ return err
450
+ }(ln)
451
+
452
+ conn, err := Dial("tcp", ln.Addr().String())
453
+ if err != nil {
454
+ t.Fatal(err)
455
+ }
456
+ defer conn.Close()
457
+
458
+ n, err := io.Copy(io.Discard, conn)
459
+ if err != nil {
460
+ t.Fatalf("expected nil error, but got %v", err)
461
+ }
462
+ if n != 0 {
463
+ t.Fatalf("expected receive zero, but got %d byte(s)", n)
464
+ }
465
+
466
+ if err := <-errc; err != nil {
467
+ t.Fatal(err)
468
+ }
469
+ }
470
+
471
+ func BenchmarkSendfileZeroBytes(b *testing.B) {
472
+ var (
473
+ wg sync.WaitGroup
474
+ ctx, cancel = context.WithCancel(context.Background())
475
+ )
476
+
477
+ defer wg.Wait()
478
+
479
+ ln := newLocalListener(b, "tcp")
480
+ defer ln.Close()
481
+
482
+ tempFile, err := os.CreateTemp(b.TempDir(), "test.txt")
483
+ if err != nil {
484
+ b.Fatalf("failed to create temp file: %v", err)
485
+ }
486
+ defer tempFile.Close()
487
+
488
+ fileName := tempFile.Name()
489
+
490
+ dataSize := b.N
491
+ wg.Add(1)
492
+ go func(f *os.File) {
493
+ defer wg.Done()
494
+
495
+ for i := 0; i < dataSize; i++ {
496
+ if _, err := f.Write([]byte{1}); err != nil {
497
+ b.Errorf("failed to write: %v", err)
498
+ return
499
+ }
500
+ if i%1000 == 0 {
501
+ f.Sync()
502
+ }
503
+ }
504
+ }(tempFile)
505
+
506
+ b.ResetTimer()
507
+ b.ReportAllocs()
508
+
509
+ wg.Add(1)
510
+ go func(ln Listener, fileName string) {
511
+ defer wg.Done()
512
+
513
+ conn, err := ln.Accept()
514
+ if err != nil {
515
+ b.Errorf("failed to accept: %v", err)
516
+ return
517
+ }
518
+ defer conn.Close()
519
+
520
+ f, err := os.OpenFile(fileName, os.O_RDONLY, 0660)
521
+ if err != nil {
522
+ b.Errorf("failed to open file: %v", err)
523
+ return
524
+ }
525
+ defer f.Close()
526
+
527
+ for {
528
+ if ctx.Err() != nil {
529
+ return
530
+ }
531
+
532
+ if _, err := io.Copy(conn, f); err != nil {
533
+ b.Errorf("failed to copy: %v", err)
534
+ return
535
+ }
536
+ }
537
+ }(ln, fileName)
538
+
539
+ conn, err := Dial("tcp", ln.Addr().String())
540
+ if err != nil {
541
+ b.Fatalf("failed to dial: %v", err)
542
+ }
543
+ defer conn.Close()
544
+
545
+ n, err := io.CopyN(io.Discard, conn, int64(dataSize))
546
+ if err != nil {
547
+ b.Fatalf("failed to copy: %v", err)
548
+ }
549
+ if n != int64(dataSize) {
550
+ b.Fatalf("expected %d copied bytes, but got %d", dataSize, n)
551
+ }
552
+
553
+ cancel()
554
+ }
555
+
556
+ func BenchmarkSendFile(b *testing.B) {
557
+ if runtime.GOOS == "windows" {
558
+ // TODO(panjf2000): Windows has not yet implemented FileConn,
559
+ // remove this when it's implemented in https://go.dev/issues/9503.
560
+ b.Skipf("skipping on %s", runtime.GOOS)
561
+ }
562
+
563
+ b.Run("file-to-tcp", func(b *testing.B) { benchmarkSendFile(b, "tcp") })
564
+ b.Run("file-to-unix", func(b *testing.B) { benchmarkSendFile(b, "unix") })
565
+ }
566
+
567
+ func benchmarkSendFile(b *testing.B, proto string) {
568
+ for i := 0; i <= 10; i++ {
569
+ size := 1 << (i + 10)
570
+ bench := sendFileBench{
571
+ proto: proto,
572
+ chunkSize: size,
573
+ }
574
+ b.Run(strconv.Itoa(size), bench.benchSendFile)
575
+ }
576
+ }
577
+
578
+ type sendFileBench struct {
579
+ proto string
580
+ chunkSize int
581
+ }
582
+
583
+ func (bench sendFileBench) benchSendFile(b *testing.B) {
584
+ fileSize := b.N * bench.chunkSize
585
+ f := createTempFile(b, int64(fileSize))
586
+
587
+ client, server := spawnTestSocketPair(b, bench.proto)
588
+ defer server.Close()
589
+
590
+ cleanUp, err := startTestSocketPeer(b, client, "r", bench.chunkSize, fileSize)
591
+ if err != nil {
592
+ client.Close()
593
+ b.Fatal(err)
594
+ }
595
+ defer cleanUp(b)
596
+
597
+ b.ReportAllocs()
598
+ b.SetBytes(int64(bench.chunkSize))
599
+ b.ResetTimer()
600
+
601
+ // Data go from file to socket via sendfile(2).
602
+ sent, err := io.Copy(server, f)
603
+ if err != nil {
604
+ b.Fatalf("failed to copy data with sendfile, error: %v", err)
605
+ }
606
+ if sent != int64(fileSize) {
607
+ b.Fatalf("bytes sent mismatch, got: %d, want: %d", sent, fileSize)
608
+ }
609
+ }
610
+
611
+ func createTempFile(tb testing.TB, size int64) *os.File {
612
+ f, err := os.CreateTemp(tb.TempDir(), "sendfile-bench")
613
+ if err != nil {
614
+ tb.Fatalf("failed to create temporary file: %v", err)
615
+ }
616
+ tb.Cleanup(func() {
617
+ f.Close()
618
+ })
619
+
620
+ if _, err := io.CopyN(f, newRandReader(tb), size); err != nil {
621
+ tb.Fatalf("failed to fill the file with random data: %v", err)
622
+ }
623
+ if _, err := f.Seek(0, io.SeekStart); err != nil {
624
+ tb.Fatalf("failed to rewind the file: %v", err)
625
+ }
626
+
627
+ return f
628
+ }
629
+
630
+ func newRandReader(tb testing.TB) io.Reader {
631
+ seed := time.Now().UnixNano()
632
+ tb.Logf("Deterministic RNG seed based on timestamp: 0x%x", seed)
633
+ return rand.New(rand.NewSource(seed))
634
+ }
go/src/net/sendfile_unix_test.go ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2024 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build unix
6
+
7
+ package net
8
+
9
+ import (
10
+ "internal/testpty"
11
+ "io"
12
+ "os"
13
+ "sync"
14
+ "syscall"
15
+ "testing"
16
+ )
17
+
18
+ // Issue 70763: test that we don't fail on sendfile from a tty.
19
+ func TestCopyFromTTY(t *testing.T) {
20
+ pty, ttyName, err := testpty.Open()
21
+ if err != nil {
22
+ t.Skipf("skipping test because pty open failed: %v", err)
23
+ }
24
+ defer pty.Close()
25
+
26
+ // Use syscall.Open so that the tty is blocking.
27
+ ttyFD, err := syscall.Open(ttyName, syscall.O_RDWR, 0)
28
+ if err != nil {
29
+ t.Skipf("skipping test because tty open failed: %v", err)
30
+ }
31
+ defer syscall.Close(ttyFD)
32
+
33
+ tty := os.NewFile(uintptr(ttyFD), "tty")
34
+ defer tty.Close()
35
+
36
+ ln := newLocalListener(t, "tcp")
37
+ defer ln.Close()
38
+
39
+ ch := make(chan bool)
40
+
41
+ const data = "data\n"
42
+
43
+ var wg sync.WaitGroup
44
+ defer wg.Wait()
45
+
46
+ wg.Add(1)
47
+ go func() {
48
+ defer wg.Done()
49
+ conn, err := ln.Accept()
50
+ if err != nil {
51
+ t.Error(err)
52
+ return
53
+ }
54
+ defer conn.Close()
55
+
56
+ buf := make([]byte, len(data))
57
+ if _, err := io.ReadFull(conn, buf); err != nil {
58
+ t.Error(err)
59
+ }
60
+
61
+ ch <- true
62
+ }()
63
+
64
+ conn, err := Dial("tcp", ln.Addr().String())
65
+ if err != nil {
66
+ t.Fatal(err)
67
+ }
68
+ defer conn.Close()
69
+
70
+ wg.Add(1)
71
+ go func() {
72
+ defer wg.Done()
73
+ if _, err := pty.Write([]byte(data)); err != nil {
74
+ t.Error(err)
75
+ }
76
+ <-ch
77
+ if err := pty.Close(); err != nil {
78
+ t.Error(err)
79
+ }
80
+ }()
81
+
82
+ lr := io.LimitReader(tty, int64(len(data)))
83
+ if _, err := io.Copy(conn, lr); err != nil {
84
+ t.Error(err)
85
+ }
86
+ }
go/src/net/sendfile_windows.go ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2025 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package net
6
+
7
+ import "internal/syscall/windows"
8
+
9
+ // Workstation and client versions of Windows limit the number
10
+ // of concurrent TransmitFile operations allowed on the system
11
+ // to a maximum of two. Please see:
12
+ // https://learn.microsoft.com/en-us/windows/win32/api/mswsock/nf-mswsock-transmitfile
13
+ // https://golang.org/issue/73746
14
+ func supportsSendfile() bool {
15
+ if testHookSupportsSendfile != nil {
16
+ return testHookSupportsSendfile()
17
+ }
18
+ return windows.SupportUnlimitedTransmitFile()
19
+ }
go/src/net/server_test.go ADDED
@@ -0,0 +1,410 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2009 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package net
6
+
7
+ import (
8
+ "fmt"
9
+ "os"
10
+ "testing"
11
+ )
12
+
13
+ var tcpServerTests = []struct {
14
+ snet, saddr string // server endpoint
15
+ tnet, taddr string // target endpoint for client
16
+ }{
17
+ {snet: "tcp", saddr: ":0", tnet: "tcp", taddr: "127.0.0.1"},
18
+ {snet: "tcp", saddr: "0.0.0.0:0", tnet: "tcp", taddr: "127.0.0.1"},
19
+ {snet: "tcp", saddr: "[::ffff:0.0.0.0]:0", tnet: "tcp", taddr: "127.0.0.1"},
20
+ {snet: "tcp", saddr: "[::]:0", tnet: "tcp", taddr: "::1"},
21
+
22
+ {snet: "tcp", saddr: ":0", tnet: "tcp", taddr: "::1"},
23
+ {snet: "tcp", saddr: "0.0.0.0:0", tnet: "tcp", taddr: "::1"},
24
+ {snet: "tcp", saddr: "[::ffff:0.0.0.0]:0", tnet: "tcp", taddr: "::1"},
25
+ {snet: "tcp", saddr: "[::]:0", tnet: "tcp", taddr: "127.0.0.1"},
26
+
27
+ {snet: "tcp", saddr: ":0", tnet: "tcp4", taddr: "127.0.0.1"},
28
+ {snet: "tcp", saddr: "0.0.0.0:0", tnet: "tcp4", taddr: "127.0.0.1"},
29
+ {snet: "tcp", saddr: "[::ffff:0.0.0.0]:0", tnet: "tcp4", taddr: "127.0.0.1"},
30
+ {snet: "tcp", saddr: "[::]:0", tnet: "tcp6", taddr: "::1"},
31
+
32
+ {snet: "tcp", saddr: ":0", tnet: "tcp6", taddr: "::1"},
33
+ {snet: "tcp", saddr: "0.0.0.0:0", tnet: "tcp6", taddr: "::1"},
34
+ {snet: "tcp", saddr: "[::ffff:0.0.0.0]:0", tnet: "tcp6", taddr: "::1"},
35
+ {snet: "tcp", saddr: "[::]:0", tnet: "tcp4", taddr: "127.0.0.1"},
36
+
37
+ {snet: "tcp", saddr: "127.0.0.1:0", tnet: "tcp", taddr: "127.0.0.1"},
38
+ {snet: "tcp", saddr: "[::ffff:127.0.0.1]:0", tnet: "tcp", taddr: "127.0.0.1"},
39
+ {snet: "tcp", saddr: "[::1]:0", tnet: "tcp", taddr: "::1"},
40
+
41
+ {snet: "tcp4", saddr: ":0", tnet: "tcp4", taddr: "127.0.0.1"},
42
+ {snet: "tcp4", saddr: "0.0.0.0:0", tnet: "tcp4", taddr: "127.0.0.1"},
43
+ {snet: "tcp4", saddr: "[::ffff:0.0.0.0]:0", tnet: "tcp4", taddr: "127.0.0.1"},
44
+
45
+ {snet: "tcp4", saddr: "127.0.0.1:0", tnet: "tcp4", taddr: "127.0.0.1"},
46
+
47
+ {snet: "tcp6", saddr: ":0", tnet: "tcp6", taddr: "::1"},
48
+ {snet: "tcp6", saddr: "[::]:0", tnet: "tcp6", taddr: "::1"},
49
+
50
+ {snet: "tcp6", saddr: "[::1]:0", tnet: "tcp6", taddr: "::1"},
51
+ }
52
+
53
+ // TestTCPServer tests concurrent accept-read-write servers.
54
+ func TestTCPServer(t *testing.T) {
55
+ const N = 3
56
+
57
+ for i, tt := range tcpServerTests {
58
+ t.Run(tt.snet+" "+tt.saddr+"<-"+tt.taddr, func(t *testing.T) {
59
+ if !testableListenArgs(tt.snet, tt.saddr, tt.taddr) {
60
+ t.Skip("not testable")
61
+ }
62
+
63
+ ln, err := Listen(tt.snet, tt.saddr)
64
+ if err != nil {
65
+ if perr := parseDialError(err); perr != nil {
66
+ t.Error(perr)
67
+ }
68
+ t.Fatal(err)
69
+ }
70
+
71
+ var lss []*localServer
72
+ var tpchs []chan error
73
+ defer func() {
74
+ for _, ls := range lss {
75
+ ls.teardown()
76
+ }
77
+ }()
78
+ for i := 0; i < N; i++ {
79
+ ls := (&streamListener{Listener: ln}).newLocalServer()
80
+ lss = append(lss, ls)
81
+ tpchs = append(tpchs, make(chan error, 1))
82
+ }
83
+ for i := 0; i < N; i++ {
84
+ ch := tpchs[i]
85
+ handler := func(ls *localServer, ln Listener) { ls.transponder(ln, ch) }
86
+ if err := lss[i].buildup(handler); err != nil {
87
+ t.Fatal(err)
88
+ }
89
+ }
90
+
91
+ var trchs []chan error
92
+ for i := 0; i < N; i++ {
93
+ _, port, err := SplitHostPort(lss[i].Listener.Addr().String())
94
+ if err != nil {
95
+ t.Fatal(err)
96
+ }
97
+ d := Dialer{Timeout: someTimeout}
98
+ c, err := d.Dial(tt.tnet, JoinHostPort(tt.taddr, port))
99
+ if err != nil {
100
+ if perr := parseDialError(err); perr != nil {
101
+ t.Error(perr)
102
+ }
103
+ t.Fatal(err)
104
+ }
105
+ defer c.Close()
106
+ trchs = append(trchs, make(chan error, 1))
107
+ go transceiver(c, []byte("TCP SERVER TEST"), trchs[i])
108
+ }
109
+
110
+ for _, ch := range trchs {
111
+ for err := range ch {
112
+ t.Errorf("#%d: %v", i, err)
113
+ }
114
+ }
115
+ for _, ch := range tpchs {
116
+ for err := range ch {
117
+ t.Errorf("#%d: %v", i, err)
118
+ }
119
+ }
120
+ })
121
+ }
122
+ }
123
+
124
+ // TestUnixAndUnixpacketServer tests concurrent accept-read-write
125
+ // servers
126
+ func TestUnixAndUnixpacketServer(t *testing.T) {
127
+ var unixAndUnixpacketServerTests = []struct {
128
+ network, address string
129
+ }{
130
+ {"unix", testUnixAddr(t)},
131
+ {"unix", "@nettest/go/unix"},
132
+
133
+ {"unixpacket", testUnixAddr(t)},
134
+ {"unixpacket", "@nettest/go/unixpacket"},
135
+ }
136
+
137
+ const N = 3
138
+
139
+ for i, tt := range unixAndUnixpacketServerTests {
140
+ if !testableListenArgs(tt.network, tt.address, "") {
141
+ t.Logf("skipping %s test", tt.network+" "+tt.address)
142
+ continue
143
+ }
144
+
145
+ ln, err := Listen(tt.network, tt.address)
146
+ if err != nil {
147
+ if perr := parseDialError(err); perr != nil {
148
+ t.Error(perr)
149
+ }
150
+ t.Fatal(err)
151
+ }
152
+
153
+ var lss []*localServer
154
+ var tpchs []chan error
155
+ defer func() {
156
+ for _, ls := range lss {
157
+ ls.teardown()
158
+ }
159
+ }()
160
+ for i := 0; i < N; i++ {
161
+ ls := (&streamListener{Listener: ln}).newLocalServer()
162
+ lss = append(lss, ls)
163
+ tpchs = append(tpchs, make(chan error, 1))
164
+ }
165
+ for i := 0; i < N; i++ {
166
+ ch := tpchs[i]
167
+ handler := func(ls *localServer, ln Listener) { ls.transponder(ln, ch) }
168
+ if err := lss[i].buildup(handler); err != nil {
169
+ t.Fatal(err)
170
+ }
171
+ }
172
+
173
+ var trchs []chan error
174
+ for i := 0; i < N; i++ {
175
+ d := Dialer{Timeout: someTimeout}
176
+ c, err := d.Dial(lss[i].Listener.Addr().Network(), lss[i].Listener.Addr().String())
177
+ if err != nil {
178
+ if perr := parseDialError(err); perr != nil {
179
+ t.Error(perr)
180
+ }
181
+ t.Fatal(err)
182
+ }
183
+
184
+ if addr := c.LocalAddr(); addr != nil {
185
+ t.Logf("connected %s->%s", addr, lss[i].Listener.Addr())
186
+ }
187
+
188
+ defer c.Close()
189
+ trchs = append(trchs, make(chan error, 1))
190
+ go transceiver(c, []byte("UNIX AND UNIXPACKET SERVER TEST"), trchs[i])
191
+ }
192
+
193
+ for _, ch := range trchs {
194
+ for err := range ch {
195
+ t.Errorf("#%d: %v", i, err)
196
+ }
197
+ }
198
+ for _, ch := range tpchs {
199
+ for err := range ch {
200
+ t.Errorf("#%d: %v", i, err)
201
+ }
202
+ }
203
+ }
204
+ }
205
+
206
+ var udpServerTests = []struct {
207
+ snet, saddr string // server endpoint
208
+ tnet, taddr string // target endpoint for client
209
+ dial bool // test with Dial
210
+ }{
211
+ {snet: "udp", saddr: ":0", tnet: "udp", taddr: "127.0.0.1"},
212
+ {snet: "udp", saddr: "0.0.0.0:0", tnet: "udp", taddr: "127.0.0.1"},
213
+ {snet: "udp", saddr: "[::ffff:0.0.0.0]:0", tnet: "udp", taddr: "127.0.0.1"},
214
+ {snet: "udp", saddr: "[::]:0", tnet: "udp", taddr: "::1"},
215
+
216
+ {snet: "udp", saddr: ":0", tnet: "udp", taddr: "::1"},
217
+ {snet: "udp", saddr: "0.0.0.0:0", tnet: "udp", taddr: "::1"},
218
+ {snet: "udp", saddr: "[::ffff:0.0.0.0]:0", tnet: "udp", taddr: "::1"},
219
+ {snet: "udp", saddr: "[::]:0", tnet: "udp", taddr: "127.0.0.1"},
220
+
221
+ {snet: "udp", saddr: ":0", tnet: "udp4", taddr: "127.0.0.1"},
222
+ {snet: "udp", saddr: "0.0.0.0:0", tnet: "udp4", taddr: "127.0.0.1"},
223
+ {snet: "udp", saddr: "[::ffff:0.0.0.0]:0", tnet: "udp4", taddr: "127.0.0.1"},
224
+ {snet: "udp", saddr: "[::]:0", tnet: "udp6", taddr: "::1"},
225
+
226
+ {snet: "udp", saddr: ":0", tnet: "udp6", taddr: "::1"},
227
+ {snet: "udp", saddr: "0.0.0.0:0", tnet: "udp6", taddr: "::1"},
228
+ {snet: "udp", saddr: "[::ffff:0.0.0.0]:0", tnet: "udp6", taddr: "::1"},
229
+ {snet: "udp", saddr: "[::]:0", tnet: "udp4", taddr: "127.0.0.1"},
230
+
231
+ {snet: "udp", saddr: "127.0.0.1:0", tnet: "udp", taddr: "127.0.0.1"},
232
+ {snet: "udp", saddr: "[::ffff:127.0.0.1]:0", tnet: "udp", taddr: "127.0.0.1"},
233
+ {snet: "udp", saddr: "[::1]:0", tnet: "udp", taddr: "::1"},
234
+
235
+ {snet: "udp4", saddr: ":0", tnet: "udp4", taddr: "127.0.0.1"},
236
+ {snet: "udp4", saddr: "0.0.0.0:0", tnet: "udp4", taddr: "127.0.0.1"},
237
+ {snet: "udp4", saddr: "[::ffff:0.0.0.0]:0", tnet: "udp4", taddr: "127.0.0.1"},
238
+
239
+ {snet: "udp4", saddr: "127.0.0.1:0", tnet: "udp4", taddr: "127.0.0.1"},
240
+
241
+ {snet: "udp6", saddr: ":0", tnet: "udp6", taddr: "::1"},
242
+ {snet: "udp6", saddr: "[::]:0", tnet: "udp6", taddr: "::1"},
243
+
244
+ {snet: "udp6", saddr: "[::1]:0", tnet: "udp6", taddr: "::1"},
245
+
246
+ {snet: "udp", saddr: "127.0.0.1:0", tnet: "udp", taddr: "127.0.0.1", dial: true},
247
+
248
+ {snet: "udp", saddr: "[::1]:0", tnet: "udp", taddr: "::1", dial: true},
249
+ }
250
+
251
+ func TestUDPServer(t *testing.T) {
252
+ for i, tt := range udpServerTests {
253
+ t.Run(fmt.Sprint(i), func(t *testing.T) {
254
+ if !testableListenArgs(tt.snet, tt.saddr, tt.taddr) {
255
+ t.Skipf("skipping %s %s<-%s test", tt.snet, tt.saddr, tt.taddr)
256
+ }
257
+ t.Logf("%s %s<-%s", tt.snet, tt.saddr, tt.taddr)
258
+
259
+ c1, err := ListenPacket(tt.snet, tt.saddr)
260
+ if err != nil {
261
+ if perr := parseDialError(err); perr != nil {
262
+ t.Error(perr)
263
+ }
264
+ t.Fatal(err)
265
+ }
266
+
267
+ ls := (&packetListener{PacketConn: c1}).newLocalServer()
268
+ defer ls.teardown()
269
+ tpch := make(chan error, 1)
270
+ handler := func(ls *localPacketServer, c PacketConn) { packetTransponder(c, tpch) }
271
+ if err := ls.buildup(handler); err != nil {
272
+ t.Fatal(err)
273
+ }
274
+
275
+ trch := make(chan error, 1)
276
+ _, port, err := SplitHostPort(ls.PacketConn.LocalAddr().String())
277
+ if err != nil {
278
+ t.Fatal(err)
279
+ }
280
+ if tt.dial {
281
+ d := Dialer{Timeout: someTimeout}
282
+ c2, err := d.Dial(tt.tnet, JoinHostPort(tt.taddr, port))
283
+ if err != nil {
284
+ if perr := parseDialError(err); perr != nil {
285
+ t.Error(perr)
286
+ }
287
+ t.Fatal(err)
288
+ }
289
+ defer c2.Close()
290
+ go transceiver(c2, []byte("UDP SERVER TEST"), trch)
291
+ } else {
292
+ c2, err := ListenPacket(tt.tnet, JoinHostPort(tt.taddr, "0"))
293
+ if err != nil {
294
+ if perr := parseDialError(err); perr != nil {
295
+ t.Error(perr)
296
+ }
297
+ t.Fatal(err)
298
+ }
299
+ defer c2.Close()
300
+ dst, err := ResolveUDPAddr(tt.tnet, JoinHostPort(tt.taddr, port))
301
+ if err != nil {
302
+ t.Fatal(err)
303
+ }
304
+ go packetTransceiver(c2, []byte("UDP SERVER TEST"), dst, trch)
305
+ }
306
+
307
+ for trch != nil || tpch != nil {
308
+ select {
309
+ case err, ok := <-trch:
310
+ if !ok {
311
+ trch = nil
312
+ }
313
+ if err != nil {
314
+ t.Errorf("client: %v", err)
315
+ }
316
+ case err, ok := <-tpch:
317
+ if !ok {
318
+ tpch = nil
319
+ }
320
+ if err != nil {
321
+ t.Errorf("server: %v", err)
322
+ }
323
+ }
324
+ }
325
+ })
326
+ }
327
+ }
328
+
329
+ func TestUnixgramServer(t *testing.T) {
330
+ var unixgramServerTests = []struct {
331
+ saddr string // server endpoint
332
+ caddr string // client endpoint
333
+ dial bool // test with Dial
334
+ }{
335
+ {saddr: testUnixAddr(t), caddr: testUnixAddr(t)},
336
+ {saddr: testUnixAddr(t), caddr: testUnixAddr(t), dial: true},
337
+
338
+ {saddr: "@nettest/go/unixgram/server", caddr: "@nettest/go/unixgram/client"},
339
+ }
340
+
341
+ for i, tt := range unixgramServerTests {
342
+ t.Run(fmt.Sprint(i), func(t *testing.T) {
343
+ if !testableListenArgs("unixgram", tt.saddr, "") {
344
+ t.Skipf("skipping unixgram %s<-%s test", tt.saddr, tt.caddr)
345
+ }
346
+ t.Logf("unixgram %s<-%s", tt.saddr, tt.caddr)
347
+
348
+ c1, err := ListenPacket("unixgram", tt.saddr)
349
+ if err != nil {
350
+ if perr := parseDialError(err); perr != nil {
351
+ t.Error(perr)
352
+ }
353
+ t.Fatal(err)
354
+ }
355
+
356
+ ls := (&packetListener{PacketConn: c1}).newLocalServer()
357
+ defer ls.teardown()
358
+ tpch := make(chan error, 1)
359
+ handler := func(ls *localPacketServer, c PacketConn) { packetTransponder(c, tpch) }
360
+ if err := ls.buildup(handler); err != nil {
361
+ t.Fatal(err)
362
+ }
363
+
364
+ trch := make(chan error, 1)
365
+ if tt.dial {
366
+ d := Dialer{Timeout: someTimeout, LocalAddr: &UnixAddr{Net: "unixgram", Name: tt.caddr}}
367
+ c2, err := d.Dial("unixgram", ls.PacketConn.LocalAddr().String())
368
+ if err != nil {
369
+ if perr := parseDialError(err); perr != nil {
370
+ t.Error(perr)
371
+ }
372
+ t.Fatal(err)
373
+ }
374
+ defer os.Remove(c2.LocalAddr().String())
375
+ defer c2.Close()
376
+ go transceiver(c2, []byte(c2.LocalAddr().String()), trch)
377
+ } else {
378
+ c2, err := ListenPacket("unixgram", tt.caddr)
379
+ if err != nil {
380
+ if perr := parseDialError(err); perr != nil {
381
+ t.Error(perr)
382
+ }
383
+ t.Fatal(err)
384
+ }
385
+ defer os.Remove(c2.LocalAddr().String())
386
+ defer c2.Close()
387
+ go packetTransceiver(c2, []byte("UNIXGRAM SERVER TEST"), ls.PacketConn.LocalAddr(), trch)
388
+ }
389
+
390
+ for trch != nil || tpch != nil {
391
+ select {
392
+ case err, ok := <-trch:
393
+ if !ok {
394
+ trch = nil
395
+ }
396
+ if err != nil {
397
+ t.Errorf("client: %v", err)
398
+ }
399
+ case err, ok := <-tpch:
400
+ if !ok {
401
+ tpch = nil
402
+ }
403
+ if err != nil {
404
+ t.Errorf("server: %v", err)
405
+ }
406
+ }
407
+ }
408
+ })
409
+ }
410
+ }
go/src/net/sock_bsd.go ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2009 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build darwin || dragonfly || freebsd || netbsd || openbsd
6
+
7
+ package net
8
+
9
+ import (
10
+ "runtime"
11
+ "syscall"
12
+ )
13
+
14
+ func maxListenerBacklog() int {
15
+ var (
16
+ n uint32
17
+ err error
18
+ )
19
+ switch runtime.GOOS {
20
+ case "darwin", "ios":
21
+ n, err = syscall.SysctlUint32("kern.ipc.somaxconn")
22
+ case "freebsd":
23
+ n, err = syscall.SysctlUint32("kern.ipc.soacceptqueue")
24
+ case "netbsd":
25
+ // NOTE: NetBSD has no somaxconn-like kernel state so far
26
+ case "openbsd":
27
+ n, err = syscall.SysctlUint32("kern.somaxconn")
28
+ }
29
+ if n == 0 || err != nil {
30
+ return syscall.SOMAXCONN
31
+ }
32
+ // FreeBSD stores the backlog in a uint16, as does Linux.
33
+ // Assume the other BSDs do too. Truncate number to avoid wrapping.
34
+ // See issue 5030.
35
+ if n > 1<<16-1 {
36
+ n = 1<<16 - 1
37
+ }
38
+ return int(n)
39
+ }
go/src/net/sock_cloexec.go ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2013 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ // This file implements sysSocket for platforms that provide a fast path for
6
+ // setting SetNonblock and CloseOnExec.
7
+
8
+ //go:build dragonfly || freebsd || linux || netbsd || openbsd
9
+
10
+ package net
11
+
12
+ import (
13
+ "os"
14
+ "syscall"
15
+ )
16
+
17
+ // Wrapper around the socket system call that marks the returned file
18
+ // descriptor as nonblocking and close-on-exec.
19
+ func sysSocket(family, sotype, proto int) (int, error) {
20
+ s, err := socketFunc(family, sotype|syscall.SOCK_NONBLOCK|syscall.SOCK_CLOEXEC, proto)
21
+ if err != nil {
22
+ return -1, os.NewSyscallError("socket", err)
23
+ }
24
+ return s, nil
25
+ }
go/src/net/sock_cloexec_solaris.go ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2024 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ // This file implements sysSocket for platforms that provide a fast path for
6
+ // setting SetNonblock and CloseOnExec, but don't necessarily support it.
7
+ // Support for SOCK_* flags as part of the type parameter was added to Oracle
8
+ // Solaris in the 11.4 release. Thus, on releases prior to 11.4, we fall back
9
+ // to the combination of socket(3c) and fcntl(2).
10
+
11
+ package net
12
+
13
+ import (
14
+ "internal/poll"
15
+ "internal/syscall/unix"
16
+ "os"
17
+ "syscall"
18
+ )
19
+
20
+ // Wrapper around the socket system call that marks the returned file
21
+ // descriptor as nonblocking and close-on-exec.
22
+ func sysSocket(family, sotype, proto int) (int, error) {
23
+ // Perform a cheap test and try the fast path first.
24
+ if unix.SupportSockNonblockCloexec() {
25
+ s, err := socketFunc(family, sotype|syscall.SOCK_NONBLOCK|syscall.SOCK_CLOEXEC, proto)
26
+ if err != nil {
27
+ return -1, os.NewSyscallError("socket", err)
28
+ }
29
+ return s, nil
30
+ }
31
+
32
+ // See ../syscall/exec_unix.go for description of ForkLock.
33
+ syscall.ForkLock.RLock()
34
+ s, err := socketFunc(family, sotype, proto)
35
+ if err == nil {
36
+ syscall.CloseOnExec(s)
37
+ }
38
+ syscall.ForkLock.RUnlock()
39
+ if err != nil {
40
+ return -1, os.NewSyscallError("socket", err)
41
+ }
42
+ if err = syscall.SetNonblock(s, true); err != nil {
43
+ poll.CloseFunc(s)
44
+ return -1, os.NewSyscallError("setnonblock", err)
45
+ }
46
+ return s, nil
47
+ }
go/src/net/sock_linux.go ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2009 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package net
6
+
7
+ import (
8
+ "internal/syscall/unix"
9
+ "syscall"
10
+ )
11
+
12
+ // Linux stores the backlog as:
13
+ //
14
+ // - uint16 in kernel version < 4.1,
15
+ // - uint32 in kernel version >= 4.1
16
+ //
17
+ // Truncate number to avoid wrapping.
18
+ //
19
+ // See issue 5030 and 41470.
20
+ func maxAckBacklog(n int) int {
21
+ size := 16
22
+ if unix.KernelVersionGE(4, 1) {
23
+ size = 32
24
+ }
25
+
26
+ var max uint = 1<<size - 1
27
+ if uint(n) > max {
28
+ n = int(max)
29
+ }
30
+ return n
31
+ }
32
+
33
+ func maxListenerBacklog() int {
34
+ fd, err := open("/proc/sys/net/core/somaxconn")
35
+ if err != nil {
36
+ return syscall.SOMAXCONN
37
+ }
38
+ defer fd.close()
39
+ l, ok := fd.readLine()
40
+ if !ok {
41
+ return syscall.SOMAXCONN
42
+ }
43
+ f := getFields(l)
44
+ n, _, ok := dtoi(f[0])
45
+ if n == 0 || !ok {
46
+ return syscall.SOMAXCONN
47
+ }
48
+
49
+ if n > 1<<16-1 {
50
+ return maxAckBacklog(n)
51
+ }
52
+ return n
53
+ }
go/src/net/sock_linux_test.go ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2020 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package net
6
+
7
+ import (
8
+ "internal/syscall/unix"
9
+ "testing"
10
+ )
11
+
12
+ func TestMaxAckBacklog(t *testing.T) {
13
+ n := 196602
14
+ backlog := maxAckBacklog(n)
15
+ expected := 1<<16 - 1
16
+ if unix.KernelVersionGE(4, 1) {
17
+ expected = n
18
+ }
19
+ if backlog != expected {
20
+ t.Fatalf(`sk_max_ack_backlog mismatch, got %d, want %d`, backlog, expected)
21
+ }
22
+ }
go/src/net/sock_plan9.go ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2013 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package net
6
+
7
+ func maxListenerBacklog() int {
8
+ // /sys/include/ape/sys/socket.h:/SOMAXCONN
9
+ return 5
10
+ }
go/src/net/sock_posix.go ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2009 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build unix || windows
6
+
7
+ package net
8
+
9
+ import (
10
+ "context"
11
+ "internal/poll"
12
+ "os"
13
+ "syscall"
14
+ )
15
+
16
+ // socket returns a network file descriptor that is ready for
17
+ // asynchronous I/O using the network poller.
18
+ func socket(ctx context.Context, net string, family, sotype, proto int, ipv6only bool, laddr, raddr sockaddr, ctrlCtxFn func(context.Context, string, string, syscall.RawConn) error) (fd *netFD, err error) {
19
+ s, err := sysSocket(family, sotype, proto)
20
+ if err != nil {
21
+ return nil, err
22
+ }
23
+ if err = setDefaultSockopts(s, family, sotype, ipv6only); err != nil {
24
+ poll.CloseFunc(s)
25
+ return nil, err
26
+ }
27
+ if fd, err = newFD(s, family, sotype, net); err != nil {
28
+ poll.CloseFunc(s)
29
+ return nil, err
30
+ }
31
+
32
+ // This function makes a network file descriptor for the
33
+ // following applications:
34
+ //
35
+ // - An endpoint holder that opens a passive stream
36
+ // connection, known as a stream listener
37
+ //
38
+ // - An endpoint holder that opens a destination-unspecific
39
+ // datagram connection, known as a datagram listener
40
+ //
41
+ // - An endpoint holder that opens an active stream or a
42
+ // destination-specific datagram connection, known as a
43
+ // dialer
44
+ //
45
+ // - An endpoint holder that opens the other connection, such
46
+ // as talking to the protocol stack inside the kernel
47
+ //
48
+ // For stream and datagram listeners, they will only require
49
+ // named sockets, so we can assume that it's just a request
50
+ // from stream or datagram listeners when laddr is not nil but
51
+ // raddr is nil. Otherwise we assume it's just for dialers or
52
+ // the other connection holders.
53
+
54
+ if laddr != nil && raddr == nil {
55
+ switch sotype {
56
+ case syscall.SOCK_STREAM, syscall.SOCK_SEQPACKET:
57
+ if err := fd.listenStream(ctx, laddr, listenerBacklog(), ctrlCtxFn); err != nil {
58
+ fd.Close()
59
+ return nil, err
60
+ }
61
+ return fd, nil
62
+ case syscall.SOCK_DGRAM:
63
+ if err := fd.listenDatagram(ctx, laddr, ctrlCtxFn); err != nil {
64
+ fd.Close()
65
+ return nil, err
66
+ }
67
+ return fd, nil
68
+ }
69
+ }
70
+ if err := fd.dial(ctx, laddr, raddr, ctrlCtxFn); err != nil {
71
+ fd.Close()
72
+ return nil, err
73
+ }
74
+ return fd, nil
75
+ }
76
+
77
+ func (fd *netFD) ctrlNetwork() string {
78
+ switch fd.net {
79
+ case "unix", "unixgram", "unixpacket":
80
+ return fd.net
81
+ }
82
+ switch fd.net[len(fd.net)-1] {
83
+ case '4', '6':
84
+ return fd.net
85
+ }
86
+ if fd.family == syscall.AF_INET {
87
+ return fd.net + "4"
88
+ }
89
+ return fd.net + "6"
90
+ }
91
+
92
+ func (fd *netFD) dial(ctx context.Context, laddr, raddr sockaddr, ctrlCtxFn func(context.Context, string, string, syscall.RawConn) error) error {
93
+ var c *rawConn
94
+ if ctrlCtxFn != nil {
95
+ c = newRawConn(fd)
96
+ var ctrlAddr string
97
+ if raddr != nil {
98
+ ctrlAddr = raddr.String()
99
+ } else if laddr != nil {
100
+ ctrlAddr = laddr.String()
101
+ }
102
+ if err := ctrlCtxFn(ctx, fd.ctrlNetwork(), ctrlAddr, c); err != nil {
103
+ return err
104
+ }
105
+ }
106
+
107
+ var lsa syscall.Sockaddr
108
+ var err error
109
+ if laddr != nil {
110
+ if lsa, err = laddr.sockaddr(fd.family); err != nil {
111
+ return err
112
+ } else if lsa != nil {
113
+ if err = syscall.Bind(fd.pfd.Sysfd, lsa); err != nil {
114
+ return os.NewSyscallError("bind", err)
115
+ }
116
+ }
117
+ }
118
+ var rsa syscall.Sockaddr // remote address from the user
119
+ var crsa syscall.Sockaddr // remote address we actually connected to
120
+ if raddr != nil {
121
+ if rsa, err = raddr.sockaddr(fd.family); err != nil {
122
+ return err
123
+ }
124
+ if crsa, err = fd.connect(ctx, lsa, rsa); err != nil {
125
+ return err
126
+ }
127
+ fd.isConnected = true
128
+ } else {
129
+ if err := fd.init(); err != nil {
130
+ return err
131
+ }
132
+ }
133
+ // Record the local and remote addresses from the actual socket.
134
+ // Get the local address by calling Getsockname.
135
+ // For the remote address, use
136
+ // 1) the one returned by the connect method, if any; or
137
+ // 2) the one from Getpeername, if it succeeds; or
138
+ // 3) the one passed to us as the raddr parameter.
139
+ lsa, _ = syscall.Getsockname(fd.pfd.Sysfd)
140
+ if crsa != nil {
141
+ fd.setAddr(fd.addrFunc()(lsa), fd.addrFunc()(crsa))
142
+ } else if rsa, _ = syscall.Getpeername(fd.pfd.Sysfd); rsa != nil {
143
+ fd.setAddr(fd.addrFunc()(lsa), fd.addrFunc()(rsa))
144
+ } else {
145
+ fd.setAddr(fd.addrFunc()(lsa), raddr)
146
+ }
147
+ return nil
148
+ }
149
+
150
+ func (fd *netFD) listenStream(ctx context.Context, laddr sockaddr, backlog int, ctrlCtxFn func(context.Context, string, string, syscall.RawConn) error) error {
151
+ var err error
152
+ if err = setDefaultListenerSockopts(fd.pfd.Sysfd); err != nil {
153
+ return err
154
+ }
155
+ var lsa syscall.Sockaddr
156
+ if lsa, err = laddr.sockaddr(fd.family); err != nil {
157
+ return err
158
+ }
159
+
160
+ if ctrlCtxFn != nil {
161
+ c := newRawConn(fd)
162
+ if err := ctrlCtxFn(ctx, fd.ctrlNetwork(), laddr.String(), c); err != nil {
163
+ return err
164
+ }
165
+ }
166
+
167
+ if err = syscall.Bind(fd.pfd.Sysfd, lsa); err != nil {
168
+ return os.NewSyscallError("bind", err)
169
+ }
170
+ if err = listenFunc(fd.pfd.Sysfd, backlog); err != nil {
171
+ return os.NewSyscallError("listen", err)
172
+ }
173
+ if err = fd.init(); err != nil {
174
+ return err
175
+ }
176
+ lsa, _ = syscall.Getsockname(fd.pfd.Sysfd)
177
+ fd.setAddr(fd.addrFunc()(lsa), nil)
178
+ return nil
179
+ }
180
+
181
+ func (fd *netFD) listenDatagram(ctx context.Context, laddr sockaddr, ctrlCtxFn func(context.Context, string, string, syscall.RawConn) error) error {
182
+ switch addr := laddr.(type) {
183
+ case *UDPAddr:
184
+ // We provide a socket that listens to a wildcard
185
+ // address with reusable UDP port when the given laddr
186
+ // is an appropriate UDP multicast address prefix.
187
+ // This makes it possible for a single UDP listener to
188
+ // join multiple different group addresses, for
189
+ // multiple UDP listeners that listen on the same UDP
190
+ // port to join the same group address.
191
+ if addr.IP != nil && addr.IP.IsMulticast() {
192
+ if err := setDefaultMulticastSockopts(fd.pfd.Sysfd); err != nil {
193
+ return err
194
+ }
195
+ addr := *addr
196
+ switch fd.family {
197
+ case syscall.AF_INET:
198
+ addr.IP = IPv4zero
199
+ case syscall.AF_INET6:
200
+ addr.IP = IPv6unspecified
201
+ }
202
+ laddr = &addr
203
+ }
204
+ }
205
+ var err error
206
+ var lsa syscall.Sockaddr
207
+ if lsa, err = laddr.sockaddr(fd.family); err != nil {
208
+ return err
209
+ }
210
+
211
+ if ctrlCtxFn != nil {
212
+ c := newRawConn(fd)
213
+ if err := ctrlCtxFn(ctx, fd.ctrlNetwork(), laddr.String(), c); err != nil {
214
+ return err
215
+ }
216
+ }
217
+ if err = syscall.Bind(fd.pfd.Sysfd, lsa); err != nil {
218
+ return os.NewSyscallError("bind", err)
219
+ }
220
+ if err = fd.init(); err != nil {
221
+ return err
222
+ }
223
+ lsa, _ = syscall.Getsockname(fd.pfd.Sysfd)
224
+ fd.setAddr(fd.addrFunc()(lsa), nil)
225
+ return nil
226
+ }
go/src/net/sock_stub.go ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2009 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build aix || js || solaris || wasip1
6
+
7
+ package net
8
+
9
+ import "syscall"
10
+
11
+ func maxListenerBacklog() int {
12
+ // TODO: Implement this
13
+ // NOTE: Never return a number bigger than 1<<16 - 1. See issue 5030.
14
+ return syscall.SOMAXCONN
15
+ }
go/src/net/sock_windows.go ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2009 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package net
6
+
7
+ import (
8
+ "internal/syscall/windows"
9
+ "os"
10
+ "syscall"
11
+ )
12
+
13
+ func maxListenerBacklog() int {
14
+ // When the socket backlog is SOMAXCONN, Windows will set the backlog to
15
+ // "a reasonable maximum value".
16
+ // See: https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-listen
17
+ return syscall.SOMAXCONN
18
+ }
19
+
20
+ func sysSocket(family, sotype, proto int) (syscall.Handle, error) {
21
+ s, err := wsaSocketFunc(int32(family), int32(sotype), int32(proto),
22
+ nil, 0, windows.WSA_FLAG_OVERLAPPED|windows.WSA_FLAG_NO_HANDLE_INHERIT)
23
+ if err != nil {
24
+ return syscall.InvalidHandle, os.NewSyscallError("socket", err)
25
+ }
26
+ return s, nil
27
+ }
go/src/net/sockaddr_posix.go ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build unix || js || wasip1 || windows
6
+
7
+ package net
8
+
9
+ import (
10
+ "syscall"
11
+ )
12
+
13
+ // A sockaddr represents a TCP, UDP, IP or Unix network endpoint
14
+ // address that can be converted into a syscall.Sockaddr.
15
+ type sockaddr interface {
16
+ Addr
17
+
18
+ // family returns the platform-dependent address family
19
+ // identifier.
20
+ family() int
21
+
22
+ // isWildcard reports whether the address is a wildcard
23
+ // address.
24
+ isWildcard() bool
25
+
26
+ // sockaddr returns the address converted into a syscall
27
+ // sockaddr type that implements syscall.Sockaddr
28
+ // interface. It returns a nil interface when the address is
29
+ // nil.
30
+ sockaddr(family int) (syscall.Sockaddr, error)
31
+
32
+ // toLocal maps the zero address to a local system address (127.0.0.1 or ::1)
33
+ toLocal(net string) sockaddr
34
+ }
35
+
36
+ func (fd *netFD) addrFunc() func(syscall.Sockaddr) Addr {
37
+ switch fd.family {
38
+ case syscall.AF_INET, syscall.AF_INET6:
39
+ switch fd.sotype {
40
+ case syscall.SOCK_STREAM:
41
+ return sockaddrToTCP
42
+ case syscall.SOCK_DGRAM:
43
+ return sockaddrToUDP
44
+ case syscall.SOCK_RAW:
45
+ return sockaddrToIP
46
+ }
47
+ case syscall.AF_UNIX:
48
+ switch fd.sotype {
49
+ case syscall.SOCK_STREAM:
50
+ return sockaddrToUnix
51
+ case syscall.SOCK_DGRAM:
52
+ return sockaddrToUnixgram
53
+ case syscall.SOCK_SEQPACKET:
54
+ return sockaddrToUnixpacket
55
+ }
56
+ }
57
+ return func(syscall.Sockaddr) Addr { return nil }
58
+ }
go/src/net/sockopt_aix.go ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package net
6
+
7
+ import (
8
+ "os"
9
+ "syscall"
10
+ )
11
+
12
+ func setDefaultSockopts(s, family, sotype int, ipv6only bool) error {
13
+ if family == syscall.AF_INET6 && sotype != syscall.SOCK_RAW {
14
+ // Allow both IP versions even if the OS default
15
+ // is otherwise. Note that some operating systems
16
+ // never admit this option.
17
+ syscall.SetsockoptInt(s, syscall.IPPROTO_IPV6, syscall.IPV6_V6ONLY, boolint(ipv6only))
18
+ }
19
+ if (sotype == syscall.SOCK_DGRAM || sotype == syscall.SOCK_RAW) && family != syscall.AF_UNIX {
20
+ // Allow broadcast.
21
+ return os.NewSyscallError("setsockopt", syscall.SetsockoptInt(s, syscall.SOL_SOCKET, syscall.SO_BROADCAST, 1))
22
+ }
23
+ return nil
24
+ }
25
+
26
+ func setDefaultListenerSockopts(s int) error {
27
+ // Allow reuse of recently-used addresses.
28
+ return os.NewSyscallError("setsockopt", syscall.SetsockoptInt(s, syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1))
29
+ }
30
+
31
+ func setDefaultMulticastSockopts(s int) error {
32
+ // Allow multicast UDP and raw IP datagram sockets to listen
33
+ // concurrently across multiple listeners.
34
+ if err := syscall.SetsockoptInt(s, syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1); err != nil {
35
+ return os.NewSyscallError("setsockopt", err)
36
+ }
37
+ // Allow reuse of recently-used ports.
38
+ return os.NewSyscallError("setsockopt", syscall.SetsockoptInt(s, syscall.SOL_SOCKET, syscall.SO_REUSEPORT, 1))
39
+ }
go/src/net/sockopt_bsd.go ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2011 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build darwin || dragonfly || freebsd || netbsd || openbsd
6
+
7
+ package net
8
+
9
+ import (
10
+ "os"
11
+ "runtime"
12
+ "syscall"
13
+ )
14
+
15
+ func setDefaultSockopts(s, family, sotype int, ipv6only bool) error {
16
+ if runtime.GOOS == "dragonfly" && sotype != syscall.SOCK_RAW {
17
+ // On DragonFly BSD, we adjust the ephemeral port
18
+ // range because unlike other BSD systems its default
19
+ // port range doesn't conform to IANA recommendation
20
+ // as described in RFC 6056 and is pretty narrow.
21
+ switch family {
22
+ case syscall.AF_INET:
23
+ syscall.SetsockoptInt(s, syscall.IPPROTO_IP, syscall.IP_PORTRANGE, syscall.IP_PORTRANGE_HIGH)
24
+ case syscall.AF_INET6:
25
+ syscall.SetsockoptInt(s, syscall.IPPROTO_IPV6, syscall.IPV6_PORTRANGE, syscall.IPV6_PORTRANGE_HIGH)
26
+ }
27
+ }
28
+ if family == syscall.AF_INET6 && sotype != syscall.SOCK_RAW && supportsIPv4map() {
29
+ // Allow both IP versions even if the OS default
30
+ // is otherwise. Note that some operating systems
31
+ // never admit this option.
32
+ syscall.SetsockoptInt(s, syscall.IPPROTO_IPV6, syscall.IPV6_V6ONLY, boolint(ipv6only))
33
+ }
34
+ if (sotype == syscall.SOCK_DGRAM || sotype == syscall.SOCK_RAW) && family != syscall.AF_UNIX {
35
+ // Allow broadcast.
36
+ return os.NewSyscallError("setsockopt", syscall.SetsockoptInt(s, syscall.SOL_SOCKET, syscall.SO_BROADCAST, 1))
37
+ }
38
+ return nil
39
+ }
40
+
41
+ func setDefaultListenerSockopts(s int) error {
42
+ // Allow reuse of recently-used addresses.
43
+ return os.NewSyscallError("setsockopt", syscall.SetsockoptInt(s, syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1))
44
+ }
45
+
46
+ func setDefaultMulticastSockopts(s int) error {
47
+ // Allow multicast UDP and raw IP datagram sockets to listen
48
+ // concurrently across multiple listeners.
49
+ if err := syscall.SetsockoptInt(s, syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1); err != nil {
50
+ return os.NewSyscallError("setsockopt", err)
51
+ }
52
+ // Allow reuse of recently-used ports.
53
+ // This option is supported only in descendants of 4.4BSD,
54
+ // to make an effective multicast application that requires
55
+ // quick draw possible.
56
+ return os.NewSyscallError("setsockopt", syscall.SetsockoptInt(s, syscall.SOL_SOCKET, syscall.SO_REUSEPORT, 1))
57
+ }
go/src/net/sockopt_fake.go ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2011 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build js || wasip1
6
+
7
+ package net
8
+
9
+ import "syscall"
10
+
11
+ func setDefaultSockopts(s, family, sotype int, ipv6only bool) error {
12
+ return nil
13
+ }
14
+
15
+ func setDefaultListenerSockopts(s int) error {
16
+ return nil
17
+ }
18
+
19
+ func setDefaultMulticastSockopts(s int) error {
20
+ return nil
21
+ }
22
+
23
+ func setReadBuffer(fd *netFD, bytes int) error {
24
+ if fd.fakeNetFD != nil {
25
+ return fd.fakeNetFD.setReadBuffer(bytes)
26
+ }
27
+ return syscall.ENOPROTOOPT
28
+ }
29
+
30
+ func setWriteBuffer(fd *netFD, bytes int) error {
31
+ if fd.fakeNetFD != nil {
32
+ return fd.fakeNetFD.setWriteBuffer(bytes)
33
+ }
34
+ return syscall.ENOPROTOOPT
35
+ }
36
+
37
+ func setKeepAlive(fd *netFD, keepalive bool) error {
38
+ return syscall.ENOPROTOOPT
39
+ }
40
+
41
+ func setLinger(fd *netFD, sec int) error {
42
+ if fd.fakeNetFD != nil {
43
+ return fd.fakeNetFD.setLinger(sec)
44
+ }
45
+ return syscall.ENOPROTOOPT
46
+ }
go/src/net/sockopt_linux.go ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2011 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package net
6
+
7
+ import (
8
+ "os"
9
+ "syscall"
10
+ )
11
+
12
+ func setDefaultSockopts(s, family, sotype int, ipv6only bool) error {
13
+ if family == syscall.AF_INET6 && sotype != syscall.SOCK_RAW {
14
+ // Allow both IP versions even if the OS default
15
+ // is otherwise. Note that some operating systems
16
+ // never admit this option.
17
+ syscall.SetsockoptInt(s, syscall.IPPROTO_IPV6, syscall.IPV6_V6ONLY, boolint(ipv6only))
18
+ }
19
+ if (sotype == syscall.SOCK_DGRAM || sotype == syscall.SOCK_RAW) && family != syscall.AF_UNIX {
20
+ // Allow broadcast.
21
+ return os.NewSyscallError("setsockopt", syscall.SetsockoptInt(s, syscall.SOL_SOCKET, syscall.SO_BROADCAST, 1))
22
+ }
23
+ return nil
24
+ }
25
+
26
+ func setDefaultListenerSockopts(s int) error {
27
+ // Allow reuse of recently-used addresses.
28
+ return os.NewSyscallError("setsockopt", syscall.SetsockoptInt(s, syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1))
29
+ }
30
+
31
+ func setDefaultMulticastSockopts(s int) error {
32
+ // Allow multicast UDP and raw IP datagram sockets to listen
33
+ // concurrently across multiple listeners.
34
+ return os.NewSyscallError("setsockopt", syscall.SetsockoptInt(s, syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1))
35
+ }
go/src/net/sockopt_plan9.go ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2014 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package net
6
+
7
+ import "syscall"
8
+
9
+ func setKeepAlive(fd *netFD, keepalive bool) error {
10
+ if keepalive {
11
+ _, e := fd.ctl.WriteAt([]byte("keepalive"), 0)
12
+ return e
13
+ }
14
+ return nil
15
+ }
16
+
17
+ func setLinger(fd *netFD, sec int) error {
18
+ return syscall.EPLAN9
19
+ }
go/src/net/sockopt_posix.go ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2009 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build unix || windows
6
+
7
+ package net
8
+
9
+ import (
10
+ "runtime"
11
+ "syscall"
12
+ )
13
+
14
+ // Boolean to int.
15
+ func boolint(b bool) int {
16
+ if b {
17
+ return 1
18
+ }
19
+ return 0
20
+ }
21
+
22
+ func interfaceToIPv4Addr(ifi *Interface) (IP, error) {
23
+ if ifi == nil {
24
+ return IPv4zero, nil
25
+ }
26
+ ifat, err := ifi.Addrs()
27
+ if err != nil {
28
+ return nil, err
29
+ }
30
+ for _, ifa := range ifat {
31
+ switch v := ifa.(type) {
32
+ case *IPAddr:
33
+ if v.IP.To4() != nil {
34
+ return v.IP, nil
35
+ }
36
+ case *IPNet:
37
+ if v.IP.To4() != nil {
38
+ return v.IP, nil
39
+ }
40
+ }
41
+ }
42
+ return nil, errNoSuchInterface
43
+ }
44
+
45
+ func setReadBuffer(fd *netFD, bytes int) error {
46
+ err := fd.pfd.SetsockoptInt(syscall.SOL_SOCKET, syscall.SO_RCVBUF, bytes)
47
+ runtime.KeepAlive(fd)
48
+ return wrapSyscallError("setsockopt", err)
49
+ }
50
+
51
+ func setWriteBuffer(fd *netFD, bytes int) error {
52
+ err := fd.pfd.SetsockoptInt(syscall.SOL_SOCKET, syscall.SO_SNDBUF, bytes)
53
+ runtime.KeepAlive(fd)
54
+ return wrapSyscallError("setsockopt", err)
55
+ }
56
+
57
+ func setKeepAlive(fd *netFD, keepalive bool) error {
58
+ err := fd.pfd.SetsockoptInt(syscall.SOL_SOCKET, syscall.SO_KEEPALIVE, boolint(keepalive))
59
+ runtime.KeepAlive(fd)
60
+ return wrapSyscallError("setsockopt", err)
61
+ }
62
+
63
+ func setLinger(fd *netFD, sec int) error {
64
+ var l syscall.Linger
65
+ if sec >= 0 {
66
+ l.Onoff = 1
67
+ l.Linger = int32(sec)
68
+ } else {
69
+ l.Onoff = 0
70
+ l.Linger = 0
71
+ }
72
+ err := fd.pfd.SetsockoptLinger(syscall.SOL_SOCKET, syscall.SO_LINGER, &l)
73
+ runtime.KeepAlive(fd)
74
+ return wrapSyscallError("setsockopt", err)
75
+ }
go/src/net/sockopt_solaris.go ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2011 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package net
6
+
7
+ import (
8
+ "os"
9
+ "syscall"
10
+ )
11
+
12
+ func setDefaultSockopts(s, family, sotype int, ipv6only bool) error {
13
+ if family == syscall.AF_INET6 && sotype != syscall.SOCK_RAW {
14
+ // Allow both IP versions even if the OS default
15
+ // is otherwise. Note that some operating systems
16
+ // never admit this option.
17
+ syscall.SetsockoptInt(s, syscall.IPPROTO_IPV6, syscall.IPV6_V6ONLY, boolint(ipv6only))
18
+ }
19
+ if (sotype == syscall.SOCK_DGRAM || sotype == syscall.SOCK_RAW) && family != syscall.AF_UNIX {
20
+ // Allow broadcast.
21
+ return os.NewSyscallError("setsockopt", syscall.SetsockoptInt(s, syscall.SOL_SOCKET, syscall.SO_BROADCAST, 1))
22
+ }
23
+ return nil
24
+ }
25
+
26
+ func setDefaultListenerSockopts(s int) error {
27
+ // Allow reuse of recently-used addresses.
28
+ return os.NewSyscallError("setsockopt", syscall.SetsockoptInt(s, syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1))
29
+ }
30
+
31
+ func setDefaultMulticastSockopts(s int) error {
32
+ // Allow multicast UDP and raw IP datagram sockets to listen
33
+ // concurrently across multiple listeners.
34
+ return os.NewSyscallError("setsockopt", syscall.SetsockoptInt(s, syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1))
35
+ }
go/src/net/sockopt_windows.go ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2011 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package net
6
+
7
+ import (
8
+ "os"
9
+ "syscall"
10
+ )
11
+
12
+ func setDefaultSockopts(s syscall.Handle, family, sotype int, ipv6only bool) error {
13
+ if family == syscall.AF_INET6 && sotype != syscall.SOCK_RAW {
14
+ // Allow both IP versions even if the OS default
15
+ // is otherwise. Note that some operating systems
16
+ // never admit this option.
17
+ syscall.SetsockoptInt(s, syscall.IPPROTO_IPV6, syscall.IPV6_V6ONLY, boolint(ipv6only))
18
+ }
19
+ if (sotype == syscall.SOCK_DGRAM || sotype == syscall.SOCK_RAW) && family != syscall.AF_UNIX && family != syscall.AF_INET6 {
20
+ // Allow broadcast.
21
+ return os.NewSyscallError("setsockopt", syscall.SetsockoptInt(s, syscall.SOL_SOCKET, syscall.SO_BROADCAST, 1))
22
+ }
23
+ return nil
24
+ }
25
+
26
+ func setDefaultListenerSockopts(s syscall.Handle) error {
27
+ // Windows will reuse recently-used addresses by default.
28
+ // SO_REUSEADDR should not be used here, as it allows
29
+ // a socket to forcibly bind to a port in use by another socket.
30
+ // This could lead to a non-deterministic behavior, where
31
+ // connection requests over the port cannot be guaranteed
32
+ // to be handled by the correct socket.
33
+ return nil
34
+ }
35
+
36
+ func setDefaultMulticastSockopts(s syscall.Handle) error {
37
+ // Allow multicast UDP and raw IP datagram sockets to listen
38
+ // concurrently across multiple listeners.
39
+ return os.NewSyscallError("setsockopt", syscall.SetsockoptInt(s, syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1))
40
+ }
go/src/net/sockoptip4_bsdvar.go ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2011 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build aix || darwin || dragonfly || freebsd || netbsd || openbsd || solaris
6
+
7
+ package net
8
+
9
+ import (
10
+ "runtime"
11
+ "syscall"
12
+ )
13
+
14
+ func setIPv4MulticastInterface(fd *netFD, ifi *Interface) error {
15
+ ip, err := interfaceToIPv4Addr(ifi)
16
+ if err != nil {
17
+ return wrapSyscallError("setsockopt", err)
18
+ }
19
+ var a [4]byte
20
+ copy(a[:], ip.To4())
21
+ err = fd.pfd.SetsockoptInet4Addr(syscall.IPPROTO_IP, syscall.IP_MULTICAST_IF, a)
22
+ runtime.KeepAlive(fd)
23
+ return wrapSyscallError("setsockopt", err)
24
+ }
25
+
26
+ func setIPv4MulticastLoopback(fd *netFD, v bool) error {
27
+ err := fd.pfd.SetsockoptByte(syscall.IPPROTO_IP, syscall.IP_MULTICAST_LOOP, byte(boolint(v)))
28
+ runtime.KeepAlive(fd)
29
+ return wrapSyscallError("setsockopt", err)
30
+ }
go/src/net/sockoptip4_linux.go ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2011 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package net
6
+
7
+ import (
8
+ "runtime"
9
+ "syscall"
10
+ )
11
+
12
+ func joinIPv4Group(fd *netFD, ifi *Interface, ip IP) error {
13
+ mreq := &syscall.IPMreqn{Multiaddr: [4]byte{ip[0], ip[1], ip[2], ip[3]}}
14
+ if ifi != nil {
15
+ mreq.Ifindex = int32(ifi.Index)
16
+ }
17
+ err := fd.pfd.SetsockoptIPMreqn(syscall.IPPROTO_IP, syscall.IP_ADD_MEMBERSHIP, mreq)
18
+ runtime.KeepAlive(fd)
19
+ return wrapSyscallError("setsockopt", err)
20
+ }
21
+
22
+ func setIPv4MulticastInterface(fd *netFD, ifi *Interface) error {
23
+ var v int32
24
+ if ifi != nil {
25
+ v = int32(ifi.Index)
26
+ }
27
+ mreq := &syscall.IPMreqn{Ifindex: v}
28
+ err := fd.pfd.SetsockoptIPMreqn(syscall.IPPROTO_IP, syscall.IP_MULTICAST_IF, mreq)
29
+ runtime.KeepAlive(fd)
30
+ return wrapSyscallError("setsockopt", err)
31
+ }
32
+
33
+ func setIPv4MulticastLoopback(fd *netFD, v bool) error {
34
+ err := fd.pfd.SetsockoptInt(syscall.IPPROTO_IP, syscall.IP_MULTICAST_LOOP, boolint(v))
35
+ runtime.KeepAlive(fd)
36
+ return wrapSyscallError("setsockopt", err)
37
+ }
go/src/net/sockoptip4_posix_nonlinux.go ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2011 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build (unix && !linux) || windows
6
+
7
+ package net
8
+
9
+ import (
10
+ "internal/bytealg"
11
+ "runtime"
12
+ "syscall"
13
+ )
14
+
15
+ func joinIPv4Group(fd *netFD, ifi *Interface, ip IP) error {
16
+ mreq := &syscall.IPMreq{Multiaddr: [4]byte{ip[0], ip[1], ip[2], ip[3]}}
17
+ if err := setIPv4MreqToInterface(mreq, ifi); err != nil {
18
+ return err
19
+ }
20
+ err := fd.pfd.SetsockoptIPMreq(syscall.IPPROTO_IP, syscall.IP_ADD_MEMBERSHIP, mreq)
21
+ runtime.KeepAlive(fd)
22
+ return wrapSyscallError("setsockopt", err)
23
+ }
24
+
25
+ func setIPv4MreqToInterface(mreq *syscall.IPMreq, ifi *Interface) error {
26
+ if ifi == nil {
27
+ return nil
28
+ }
29
+ ifat, err := ifi.Addrs()
30
+ if err != nil {
31
+ return err
32
+ }
33
+ for _, ifa := range ifat {
34
+ switch v := ifa.(type) {
35
+ case *IPAddr:
36
+ if a := v.IP.To4(); a != nil {
37
+ copy(mreq.Interface[:], a)
38
+ goto done
39
+ }
40
+ case *IPNet:
41
+ if a := v.IP.To4(); a != nil {
42
+ copy(mreq.Interface[:], a)
43
+ goto done
44
+ }
45
+ }
46
+ }
47
+ done:
48
+ if bytealg.Equal(mreq.Interface[:], IPv4zero.To4()) {
49
+ return errNoSuchMulticastInterface
50
+ }
51
+ return nil
52
+ }
go/src/net/sockoptip4_windows.go ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2011 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package net
6
+
7
+ import (
8
+ "os"
9
+ "runtime"
10
+ "syscall"
11
+ )
12
+
13
+ func setIPv4MulticastInterface(fd *netFD, ifi *Interface) error {
14
+ ip, err := interfaceToIPv4Addr(ifi)
15
+ if err != nil {
16
+ return os.NewSyscallError("setsockopt", err)
17
+ }
18
+ var a [4]byte
19
+ copy(a[:], ip.To4())
20
+ err = fd.pfd.SetsockoptInet4Addr(syscall.IPPROTO_IP, syscall.IP_MULTICAST_IF, a)
21
+ runtime.KeepAlive(fd)
22
+ return wrapSyscallError("setsockopt", err)
23
+ }
24
+
25
+ func setIPv4MulticastLoopback(fd *netFD, v bool) error {
26
+ err := fd.pfd.SetsockoptInt(syscall.IPPROTO_IP, syscall.IP_MULTICAST_LOOP, boolint(v))
27
+ runtime.KeepAlive(fd)
28
+ return wrapSyscallError("setsockopt", err)
29
+ }
go/src/net/sockoptip6_posix.go ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2011 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build unix || windows
6
+
7
+ package net
8
+
9
+ import (
10
+ "runtime"
11
+ "syscall"
12
+ )
13
+
14
+ func setIPv6MulticastInterface(fd *netFD, ifi *Interface) error {
15
+ var v int
16
+ if ifi != nil {
17
+ v = ifi.Index
18
+ }
19
+ err := fd.pfd.SetsockoptInt(syscall.IPPROTO_IPV6, syscall.IPV6_MULTICAST_IF, v)
20
+ runtime.KeepAlive(fd)
21
+ return wrapSyscallError("setsockopt", err)
22
+ }
23
+
24
+ func setIPv6MulticastLoopback(fd *netFD, v bool) error {
25
+ err := fd.pfd.SetsockoptInt(syscall.IPPROTO_IPV6, syscall.IPV6_MULTICAST_LOOP, boolint(v))
26
+ runtime.KeepAlive(fd)
27
+ return wrapSyscallError("setsockopt", err)
28
+ }
29
+
30
+ func joinIPv6Group(fd *netFD, ifi *Interface, ip IP) error {
31
+ mreq := &syscall.IPv6Mreq{}
32
+ copy(mreq.Multiaddr[:], ip)
33
+ if ifi != nil {
34
+ mreq.Interface = uint32(ifi.Index)
35
+ }
36
+ err := fd.pfd.SetsockoptIPv6Mreq(syscall.IPPROTO_IPV6, syscall.IPV6_JOIN_GROUP, mreq)
37
+ runtime.KeepAlive(fd)
38
+ return wrapSyscallError("setsockopt", err)
39
+ }
go/src/net/sockoptip_stub.go ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2011 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build js || wasip1
6
+
7
+ package net
8
+
9
+ import "syscall"
10
+
11
+ func setIPv4MulticastInterface(fd *netFD, ifi *Interface) error {
12
+ return syscall.ENOPROTOOPT
13
+ }
14
+
15
+ func setIPv4MulticastLoopback(fd *netFD, v bool) error {
16
+ return syscall.ENOPROTOOPT
17
+ }
18
+
19
+ func joinIPv4Group(fd *netFD, ifi *Interface, ip IP) error {
20
+ return syscall.ENOPROTOOPT
21
+ }
22
+
23
+ func setIPv6MulticastInterface(fd *netFD, ifi *Interface) error {
24
+ return syscall.ENOPROTOOPT
25
+ }
26
+
27
+ func setIPv6MulticastLoopback(fd *netFD, v bool) error {
28
+ return syscall.ENOPROTOOPT
29
+ }
30
+
31
+ func joinIPv6Group(fd *netFD, ifi *Interface, ip IP) error {
32
+ return syscall.ENOPROTOOPT
33
+ }
go/src/net/splice_linux.go ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package net
6
+
7
+ import (
8
+ "internal/poll"
9
+ "io"
10
+ )
11
+
12
+ var pollSplice = poll.Splice
13
+
14
+ // spliceFrom transfers data from r to c using the splice system call to minimize
15
+ // copies from and to userspace. c must be a TCP connection.
16
+ // Currently, spliceFrom is only enabled if r is a TCP or a stream-oriented Unix connection.
17
+ //
18
+ // If spliceFrom returns handled == false, it has performed no work.
19
+ func spliceFrom(c *netFD, r io.Reader) (written int64, err error, handled bool) {
20
+ var remain int64 = 1<<63 - 1 // by default, copy until EOF
21
+ lr, ok := r.(*io.LimitedReader)
22
+ if ok {
23
+ remain, r = lr.N, lr.R
24
+ if remain <= 0 {
25
+ return 0, nil, true
26
+ }
27
+ }
28
+
29
+ var s *netFD
30
+ switch v := r.(type) {
31
+ case *TCPConn:
32
+ s = v.fd
33
+ case tcpConnWithoutWriteTo:
34
+ s = v.fd
35
+ case *UnixConn:
36
+ if v.fd.net != "unix" {
37
+ return 0, nil, false
38
+ }
39
+ s = v.fd
40
+ default:
41
+ return 0, nil, false
42
+ }
43
+
44
+ written, handled, err = pollSplice(&c.pfd, &s.pfd, remain)
45
+ if lr != nil {
46
+ lr.N -= written
47
+ }
48
+ return written, wrapSyscallError("splice", err), handled
49
+ }
50
+
51
+ // spliceTo transfers data from c to w using the splice system call to minimize
52
+ // copies from and to userspace. c must be a TCP connection.
53
+ // Currently, spliceTo is only enabled if w is a stream-oriented Unix connection.
54
+ //
55
+ // If spliceTo returns handled == false, it has performed no work.
56
+ func spliceTo(w io.Writer, c *netFD) (written int64, err error, handled bool) {
57
+ uc, ok := w.(*UnixConn)
58
+ if !ok || uc.fd.net != "unix" {
59
+ return
60
+ }
61
+
62
+ written, handled, err = pollSplice(&uc.fd.pfd, &c.pfd, 1<<63-1)
63
+ return written, wrapSyscallError("splice", err), handled
64
+ }
go/src/net/splice_linux_test.go ADDED
@@ -0,0 +1,541 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build linux
6
+
7
+ package net
8
+
9
+ import (
10
+ "internal/poll"
11
+ "io"
12
+ "os"
13
+ "strconv"
14
+ "sync"
15
+ "syscall"
16
+ "testing"
17
+ )
18
+
19
+ func TestSplice(t *testing.T) {
20
+ t.Run("tcp-to-tcp", func(t *testing.T) { testSplice(t, "tcp", "tcp") })
21
+ if !testableNetwork("unixgram") {
22
+ t.Skip("skipping unix-to-tcp tests")
23
+ }
24
+ t.Run("unix-to-tcp", func(t *testing.T) { testSplice(t, "unix", "tcp") })
25
+ t.Run("tcp-to-unix", func(t *testing.T) { testSplice(t, "tcp", "unix") })
26
+ t.Run("tcp-to-file", func(t *testing.T) { testSpliceToFile(t, "tcp", "file") })
27
+ t.Run("unix-to-file", func(t *testing.T) { testSpliceToFile(t, "unix", "file") })
28
+ t.Run("no-unixpacket", testSpliceNoUnixpacket)
29
+ t.Run("no-unixgram", testSpliceNoUnixgram)
30
+ }
31
+
32
+ func testSpliceToFile(t *testing.T, upNet, downNet string) {
33
+ t.Run("simple", spliceTestCase{upNet, downNet, 128, 128, 0}.testFile)
34
+ t.Run("multipleWrite", spliceTestCase{upNet, downNet, 4096, 1 << 20, 0}.testFile)
35
+ t.Run("big", spliceTestCase{upNet, downNet, 5 << 20, 1 << 30, 0}.testFile)
36
+ t.Run("honorsLimitedReader", spliceTestCase{upNet, downNet, 4096, 1 << 20, 1 << 10}.testFile)
37
+ t.Run("updatesLimitedReaderN", spliceTestCase{upNet, downNet, 1024, 4096, 4096 + 100}.testFile)
38
+ t.Run("limitedReaderAtLimit", spliceTestCase{upNet, downNet, 32, 128, 128}.testFile)
39
+ }
40
+
41
+ func testSplice(t *testing.T, upNet, downNet string) {
42
+ t.Run("simple", spliceTestCase{upNet, downNet, 128, 128, 0}.test)
43
+ t.Run("multipleWrite", spliceTestCase{upNet, downNet, 4096, 1 << 20, 0}.test)
44
+ t.Run("big", spliceTestCase{upNet, downNet, 5 << 20, 1 << 30, 0}.test)
45
+ t.Run("honorsLimitedReader", spliceTestCase{upNet, downNet, 4096, 1 << 20, 1 << 10}.test)
46
+ t.Run("updatesLimitedReaderN", spliceTestCase{upNet, downNet, 1024, 4096, 4096 + 100}.test)
47
+ t.Run("limitedReaderAtLimit", spliceTestCase{upNet, downNet, 32, 128, 128}.test)
48
+ t.Run("readerAtEOF", func(t *testing.T) { testSpliceReaderAtEOF(t, upNet, downNet) })
49
+ t.Run("issue25985", func(t *testing.T) { testSpliceIssue25985(t, upNet, downNet) })
50
+ }
51
+
52
+ type spliceTestCase struct {
53
+ upNet, downNet string
54
+
55
+ chunkSize, totalSize int
56
+ limitReadSize int
57
+ }
58
+
59
+ func (tc spliceTestCase) test(t *testing.T) {
60
+ hook := hookSplice(t)
61
+
62
+ // We need to use the actual size for startTestSocketPeer when testing with LimitedReader,
63
+ // otherwise the child process created in startTestSocketPeer will hang infinitely because of
64
+ // the mismatch of data size to transfer.
65
+ size := tc.totalSize
66
+ if tc.limitReadSize > 0 {
67
+ if tc.limitReadSize < size {
68
+ size = tc.limitReadSize
69
+ }
70
+ }
71
+
72
+ clientUp, serverUp := spawnTestSocketPair(t, tc.upNet)
73
+ defer serverUp.Close()
74
+ cleanup, err := startTestSocketPeer(t, clientUp, "w", tc.chunkSize, size)
75
+ if err != nil {
76
+ t.Fatal(err)
77
+ }
78
+ defer cleanup(t)
79
+ clientDown, serverDown := spawnTestSocketPair(t, tc.downNet)
80
+ defer serverDown.Close()
81
+ cleanup, err = startTestSocketPeer(t, clientDown, "r", tc.chunkSize, size)
82
+ if err != nil {
83
+ t.Fatal(err)
84
+ }
85
+ defer cleanup(t)
86
+
87
+ var r io.Reader = serverUp
88
+ if tc.limitReadSize > 0 {
89
+ r = &io.LimitedReader{
90
+ N: int64(tc.limitReadSize),
91
+ R: serverUp,
92
+ }
93
+ defer serverUp.Close()
94
+ }
95
+ n, err := io.Copy(serverDown, r)
96
+ if err != nil {
97
+ t.Fatal(err)
98
+ }
99
+
100
+ if want := int64(size); want != n {
101
+ t.Errorf("want %d bytes spliced, got %d", want, n)
102
+ }
103
+
104
+ if tc.limitReadSize > 0 {
105
+ wantN := 0
106
+ if tc.limitReadSize > size {
107
+ wantN = tc.limitReadSize - size
108
+ }
109
+
110
+ if n := r.(*io.LimitedReader).N; n != int64(wantN) {
111
+ t.Errorf("r.N = %d, want %d", n, wantN)
112
+ }
113
+ }
114
+
115
+ // poll.Splice is expected to be called when the source is not
116
+ // a wrapper or the destination is TCPConn.
117
+ if tc.limitReadSize == 0 || tc.downNet == "tcp" {
118
+ // We should have called poll.Splice with the right file descriptor arguments.
119
+ if n > 0 && !hook.called {
120
+ t.Fatal("expected poll.Splice to be called")
121
+ }
122
+
123
+ verifySpliceFds(t, serverDown, hook, "dst")
124
+ verifySpliceFds(t, serverUp, hook, "src")
125
+
126
+ // poll.Splice is expected to handle the data transmission successfully.
127
+ if !hook.handled || hook.written != int64(size) || hook.err != nil {
128
+ t.Errorf("expected handled = true, written = %d, err = nil, but got handled = %t, written = %d, err = %v",
129
+ size, hook.handled, hook.written, hook.err)
130
+ }
131
+ } else if hook.called {
132
+ // poll.Splice will certainly not be called when the source
133
+ // is a wrapper and the destination is not TCPConn.
134
+ t.Errorf("expected poll.Splice not be called")
135
+ }
136
+ }
137
+
138
+ func verifySpliceFds(t *testing.T, c Conn, hook *spliceHook, fdType string) {
139
+ t.Helper()
140
+
141
+ sc, ok := c.(syscall.Conn)
142
+ if !ok {
143
+ t.Fatalf("expected syscall.Conn")
144
+ }
145
+ rc, err := sc.SyscallConn()
146
+ if err != nil {
147
+ t.Fatalf("syscall.Conn.SyscallConn error: %v", err)
148
+ }
149
+ var hookFd int
150
+ switch fdType {
151
+ case "src":
152
+ hookFd = hook.srcfd
153
+ case "dst":
154
+ hookFd = hook.dstfd
155
+ default:
156
+ t.Fatalf("unknown fdType %q", fdType)
157
+ }
158
+ if err := rc.Control(func(fd uintptr) {
159
+ if hook.called && hookFd != int(fd) {
160
+ t.Fatalf("wrong %s file descriptor: got %d, want %d", fdType, hook.dstfd, int(fd))
161
+ }
162
+ }); err != nil {
163
+ t.Fatalf("syscall.RawConn.Control error: %v", err)
164
+ }
165
+ }
166
+
167
+ func (tc spliceTestCase) testFile(t *testing.T) {
168
+ hook := hookSplice(t)
169
+
170
+ // We need to use the actual size for startTestSocketPeer when testing with LimitedReader,
171
+ // otherwise the child process created in startTestSocketPeer will hang infinitely because of
172
+ // the mismatch of data size to transfer.
173
+ actualSize := tc.totalSize
174
+ if tc.limitReadSize > 0 {
175
+ if tc.limitReadSize < actualSize {
176
+ actualSize = tc.limitReadSize
177
+ }
178
+ }
179
+
180
+ f, err := os.OpenFile(os.DevNull, os.O_WRONLY, 0)
181
+ if err != nil {
182
+ t.Fatal(err)
183
+ }
184
+ defer f.Close()
185
+
186
+ client, server := spawnTestSocketPair(t, tc.upNet)
187
+ defer server.Close()
188
+
189
+ cleanup, err := startTestSocketPeer(t, client, "w", tc.chunkSize, actualSize)
190
+ if err != nil {
191
+ client.Close()
192
+ t.Fatal("failed to start splice client:", err)
193
+ }
194
+ defer cleanup(t)
195
+
196
+ var r io.Reader = server
197
+ if tc.limitReadSize > 0 {
198
+ r = &io.LimitedReader{
199
+ N: int64(tc.limitReadSize),
200
+ R: r,
201
+ }
202
+ }
203
+
204
+ got, err := io.Copy(f, r)
205
+ if err != nil {
206
+ t.Fatalf("failed to ReadFrom with error: %v", err)
207
+ }
208
+
209
+ // We shouldn't have called poll.Splice in TCPConn.WriteTo,
210
+ // it's supposed to be called from File.ReadFrom.
211
+ if got > 0 && hook.called {
212
+ t.Error("expected not poll.Splice to be called")
213
+ }
214
+
215
+ if want := int64(actualSize); got != want {
216
+ t.Errorf("got %d bytes, want %d", got, want)
217
+ }
218
+ if tc.limitReadSize > 0 {
219
+ wantN := 0
220
+ if tc.limitReadSize > actualSize {
221
+ wantN = tc.limitReadSize - actualSize
222
+ }
223
+
224
+ if gotN := r.(*io.LimitedReader).N; gotN != int64(wantN) {
225
+ t.Errorf("r.N = %d, want %d", gotN, wantN)
226
+ }
227
+ }
228
+ }
229
+
230
+ func testSpliceReaderAtEOF(t *testing.T, upNet, downNet string) {
231
+ // UnixConn doesn't implement io.ReaderFrom, which will fail
232
+ // the following test in asserting a UnixConn to be an io.ReaderFrom,
233
+ // so skip this test.
234
+ if downNet == "unix" {
235
+ t.Skip("skipping test on unix socket")
236
+ }
237
+
238
+ hook := hookSplice(t)
239
+
240
+ clientUp, serverUp := spawnTestSocketPair(t, upNet)
241
+ defer clientUp.Close()
242
+ clientDown, serverDown := spawnTestSocketPair(t, downNet)
243
+ defer clientDown.Close()
244
+ defer serverDown.Close()
245
+
246
+ serverUp.Close()
247
+
248
+ // We'd like to call net.spliceFrom here and check the handled return
249
+ // value, but we disable splice on old Linux kernels.
250
+ //
251
+ // In that case, poll.Splice and net.spliceFrom return a non-nil error
252
+ // and handled == false. We'd ideally like to see handled == true
253
+ // because the source reader is at EOF, but if we're running on an old
254
+ // kernel, and splice is disabled, we won't see EOF from net.spliceFrom,
255
+ // because we won't touch the reader at all.
256
+ //
257
+ // Trying to untangle the errors from net.spliceFrom and match them
258
+ // against the errors created by the poll package would be brittle,
259
+ // so this is a higher level test.
260
+ //
261
+ // The following ReadFrom should return immediately, regardless of
262
+ // whether splice is disabled or not. The other side should then
263
+ // get a goodbye signal. Test for the goodbye signal.
264
+ msg := "bye"
265
+ go func() {
266
+ serverDown.(io.ReaderFrom).ReadFrom(serverUp)
267
+ io.WriteString(serverDown, msg)
268
+ }()
269
+
270
+ buf := make([]byte, 3)
271
+ n, err := io.ReadFull(clientDown, buf)
272
+ if err != nil {
273
+ t.Errorf("clientDown: %v", err)
274
+ }
275
+ if string(buf) != msg {
276
+ t.Errorf("clientDown got %q, want %q", buf, msg)
277
+ }
278
+
279
+ // We should have called poll.Splice with the right file descriptor arguments.
280
+ if n > 0 && !hook.called {
281
+ t.Fatal("expected poll.Splice to be called")
282
+ }
283
+
284
+ verifySpliceFds(t, serverDown, hook, "dst")
285
+
286
+ // poll.Splice is expected to handle the data transmission but fail
287
+ // when working with a closed endpoint, return an error.
288
+ if !hook.handled || hook.written > 0 || hook.err == nil {
289
+ t.Errorf("expected handled = true, written = 0, err != nil, but got handled = %t, written = %d, err = %v",
290
+ hook.handled, hook.written, hook.err)
291
+ }
292
+ }
293
+
294
+ func testSpliceIssue25985(t *testing.T, upNet, downNet string) {
295
+ front := newLocalListener(t, upNet)
296
+ defer front.Close()
297
+ back := newLocalListener(t, downNet)
298
+ defer back.Close()
299
+
300
+ var wg sync.WaitGroup
301
+ wg.Add(2)
302
+
303
+ proxy := func() {
304
+ src, err := front.Accept()
305
+ if err != nil {
306
+ return
307
+ }
308
+ dst, err := Dial(downNet, back.Addr().String())
309
+ if err != nil {
310
+ return
311
+ }
312
+ defer dst.Close()
313
+ defer src.Close()
314
+ go func() {
315
+ io.Copy(src, dst)
316
+ wg.Done()
317
+ }()
318
+ go func() {
319
+ io.Copy(dst, src)
320
+ wg.Done()
321
+ }()
322
+ }
323
+
324
+ go proxy()
325
+
326
+ toFront, err := Dial(upNet, front.Addr().String())
327
+ if err != nil {
328
+ t.Fatal(err)
329
+ }
330
+
331
+ io.WriteString(toFront, "foo")
332
+ toFront.Close()
333
+
334
+ fromProxy, err := back.Accept()
335
+ if err != nil {
336
+ t.Fatal(err)
337
+ }
338
+ defer fromProxy.Close()
339
+
340
+ _, err = io.ReadAll(fromProxy)
341
+ if err != nil {
342
+ t.Fatal(err)
343
+ }
344
+
345
+ wg.Wait()
346
+ }
347
+
348
+ func testSpliceNoUnixpacket(t *testing.T) {
349
+ clientUp, serverUp := spawnTestSocketPair(t, "unixpacket")
350
+ defer clientUp.Close()
351
+ defer serverUp.Close()
352
+ clientDown, serverDown := spawnTestSocketPair(t, "tcp")
353
+ defer clientDown.Close()
354
+ defer serverDown.Close()
355
+ // If splice called poll.Splice here, we'd get err == syscall.EINVAL
356
+ // and handled == false. If poll.Splice gets an EINVAL on the first
357
+ // try, it assumes the kernel it's running on doesn't support splice
358
+ // for unix sockets and returns handled == false. This works for our
359
+ // purposes by somewhat of an accident, but is not entirely correct.
360
+ //
361
+ // What we want is err == nil and handled == false, i.e. we never
362
+ // called poll.Splice, because we know the unix socket's network.
363
+ _, err, handled := spliceFrom(serverDown.(*TCPConn).fd, serverUp)
364
+ if err != nil || handled != false {
365
+ t.Fatalf("got err = %v, handled = %t, want nil error, handled == false", err, handled)
366
+ }
367
+ }
368
+
369
+ func testSpliceNoUnixgram(t *testing.T) {
370
+ addr, err := ResolveUnixAddr("unixgram", testUnixAddr(t))
371
+ if err != nil {
372
+ t.Fatal(err)
373
+ }
374
+ defer os.Remove(addr.Name)
375
+ up, err := ListenUnixgram("unixgram", addr)
376
+ if err != nil {
377
+ t.Fatal(err)
378
+ }
379
+ defer up.Close()
380
+ clientDown, serverDown := spawnTestSocketPair(t, "tcp")
381
+ defer clientDown.Close()
382
+ defer serverDown.Close()
383
+ // Analogous to testSpliceNoUnixpacket.
384
+ _, err, handled := spliceFrom(serverDown.(*TCPConn).fd, up)
385
+ if err != nil || handled != false {
386
+ t.Fatalf("got err = %v, handled = %t, want nil error, handled == false", err, handled)
387
+ }
388
+ }
389
+
390
+ func BenchmarkSplice(b *testing.B) {
391
+ testHookUninstaller.Do(uninstallTestHooks)
392
+
393
+ b.Run("tcp-to-tcp", func(b *testing.B) { benchSplice(b, "tcp", "tcp") })
394
+ b.Run("unix-to-tcp", func(b *testing.B) { benchSplice(b, "unix", "tcp") })
395
+ b.Run("tcp-to-unix", func(b *testing.B) { benchSplice(b, "tcp", "unix") })
396
+ }
397
+
398
+ func benchSplice(b *testing.B, upNet, downNet string) {
399
+ for i := 0; i <= 10; i++ {
400
+ chunkSize := 1 << uint(i+10)
401
+ tc := spliceTestCase{
402
+ upNet: upNet,
403
+ downNet: downNet,
404
+ chunkSize: chunkSize,
405
+ }
406
+
407
+ b.Run(strconv.Itoa(chunkSize), tc.bench)
408
+ }
409
+ }
410
+
411
+ func (tc spliceTestCase) bench(b *testing.B) {
412
+ // To benchmark the genericReadFrom code path, set this to false.
413
+ useSplice := true
414
+
415
+ clientUp, serverUp := spawnTestSocketPair(b, tc.upNet)
416
+ defer serverUp.Close()
417
+
418
+ cleanup, err := startTestSocketPeer(b, clientUp, "w", tc.chunkSize, tc.chunkSize*b.N)
419
+ if err != nil {
420
+ b.Fatal(err)
421
+ }
422
+ defer cleanup(b)
423
+
424
+ clientDown, serverDown := spawnTestSocketPair(b, tc.downNet)
425
+ defer serverDown.Close()
426
+
427
+ cleanup, err = startTestSocketPeer(b, clientDown, "r", tc.chunkSize, tc.chunkSize*b.N)
428
+ if err != nil {
429
+ b.Fatal(err)
430
+ }
431
+ defer cleanup(b)
432
+
433
+ b.SetBytes(int64(tc.chunkSize))
434
+ b.ResetTimer()
435
+
436
+ if useSplice {
437
+ _, err := io.Copy(serverDown, serverUp)
438
+ if err != nil {
439
+ b.Fatal(err)
440
+ }
441
+ } else {
442
+ type onlyReader struct {
443
+ io.Reader
444
+ }
445
+ _, err := io.Copy(serverDown, onlyReader{serverUp})
446
+ if err != nil {
447
+ b.Fatal(err)
448
+ }
449
+ }
450
+ }
451
+
452
+ func BenchmarkSpliceFile(b *testing.B) {
453
+ b.Run("tcp-to-file", func(b *testing.B) { benchmarkSpliceFile(b, "tcp") })
454
+ b.Run("unix-to-file", func(b *testing.B) { benchmarkSpliceFile(b, "unix") })
455
+ }
456
+
457
+ func benchmarkSpliceFile(b *testing.B, proto string) {
458
+ for i := 0; i <= 10; i++ {
459
+ size := 1 << (i + 10)
460
+ bench := spliceFileBench{
461
+ proto: proto,
462
+ chunkSize: size,
463
+ }
464
+ b.Run(strconv.Itoa(size), bench.benchSpliceFile)
465
+ }
466
+ }
467
+
468
+ type spliceFileBench struct {
469
+ proto string
470
+ chunkSize int
471
+ }
472
+
473
+ func (bench spliceFileBench) benchSpliceFile(b *testing.B) {
474
+ f, err := os.OpenFile(os.DevNull, os.O_WRONLY, 0)
475
+ if err != nil {
476
+ b.Fatal(err)
477
+ }
478
+ defer f.Close()
479
+
480
+ totalSize := b.N * bench.chunkSize
481
+
482
+ client, server := spawnTestSocketPair(b, bench.proto)
483
+ defer server.Close()
484
+
485
+ cleanup, err := startTestSocketPeer(b, client, "w", bench.chunkSize, totalSize)
486
+ if err != nil {
487
+ client.Close()
488
+ b.Fatalf("failed to start splice client: %v", err)
489
+ }
490
+ defer cleanup(b)
491
+
492
+ b.ReportAllocs()
493
+ b.SetBytes(int64(bench.chunkSize))
494
+ b.ResetTimer()
495
+
496
+ got, err := io.Copy(f, server)
497
+ if err != nil {
498
+ b.Fatalf("failed to ReadFrom with error: %v", err)
499
+ }
500
+ if want := int64(totalSize); got != want {
501
+ b.Errorf("bytes sent mismatch, got: %d, want: %d", got, want)
502
+ }
503
+ }
504
+
505
+ func hookSplice(t *testing.T) *spliceHook {
506
+ t.Helper()
507
+
508
+ h := new(spliceHook)
509
+ h.install()
510
+ t.Cleanup(h.uninstall)
511
+ return h
512
+ }
513
+
514
+ type spliceHook struct {
515
+ called bool
516
+ dstfd int
517
+ srcfd int
518
+ remain int64
519
+
520
+ written int64
521
+ handled bool
522
+ err error
523
+
524
+ original func(dst, src *poll.FD, remain int64) (int64, bool, error)
525
+ }
526
+
527
+ func (h *spliceHook) install() {
528
+ h.original = pollSplice
529
+ pollSplice = func(dst, src *poll.FD, remain int64) (int64, bool, error) {
530
+ h.called = true
531
+ h.dstfd = dst.Sysfd
532
+ h.srcfd = src.Sysfd
533
+ h.remain = remain
534
+ h.written, h.handled, h.err = h.original(dst, src, remain)
535
+ return h.written, h.handled, h.err
536
+ }
537
+ }
538
+
539
+ func (h *spliceHook) uninstall() {
540
+ pollSplice = h.original
541
+ }
go/src/net/splice_stub.go ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build !linux
6
+
7
+ package net
8
+
9
+ import "io"
10
+
11
+ func spliceFrom(_ *netFD, _ io.Reader) (int64, error, bool) {
12
+ return 0, nil, false
13
+ }
14
+
15
+ func spliceTo(_ io.Writer, _ *netFD) (int64, error, bool) {
16
+ return 0, nil, false
17
+ }
go/src/net/sys_cloexec.go ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2013 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ // This file implements sysSocket for platforms that do not provide a fast path
6
+ // for setting SetNonblock and CloseOnExec.
7
+
8
+ //go:build aix || darwin
9
+
10
+ package net
11
+
12
+ import (
13
+ "internal/poll"
14
+ "os"
15
+ "syscall"
16
+ )
17
+
18
+ // Wrapper around the socket system call that marks the returned file
19
+ // descriptor as nonblocking and close-on-exec.
20
+ func sysSocket(family, sotype, proto int) (int, error) {
21
+ // See ../syscall/exec_unix.go for description of ForkLock.
22
+ syscall.ForkLock.RLock()
23
+ s, err := socketFunc(family, sotype, proto)
24
+ if err == nil {
25
+ syscall.CloseOnExec(s)
26
+ }
27
+ syscall.ForkLock.RUnlock()
28
+ if err != nil {
29
+ return -1, os.NewSyscallError("socket", err)
30
+ }
31
+ if err = syscall.SetNonblock(s, true); err != nil {
32
+ poll.CloseFunc(s)
33
+ return -1, os.NewSyscallError("setnonblock", err)
34
+ }
35
+ return s, nil
36
+ }
go/src/net/tcpconn_keepalive_conf_darwin_test.go ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2024 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build darwin
6
+
7
+ package net
8
+
9
+ import (
10
+ "syscall"
11
+ "testing"
12
+ )
13
+
14
+ const (
15
+ syscall_TCP_KEEPIDLE = syscall.TCP_KEEPALIVE
16
+ syscall_TCP_KEEPCNT = sysTCP_KEEPCNT
17
+ syscall_TCP_KEEPINTVL = sysTCP_KEEPINTVL
18
+ )
19
+
20
+ type fdType = int
21
+
22
+ func maybeSkipKeepAliveTest(_ *testing.T) {}
go/src/net/tcpconn_keepalive_conf_posix_test.go ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2024 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build aix || darwin || dragonfly || freebsd || illumos || linux || netbsd || windows
6
+
7
+ package net
8
+
9
+ import "time"
10
+
11
+ var testConfigs = []KeepAliveConfig{
12
+ {
13
+ Enable: true,
14
+ Idle: 5 * time.Second,
15
+ Interval: 3 * time.Second,
16
+ Count: 10,
17
+ },
18
+ {
19
+ Enable: true,
20
+ Idle: 0,
21
+ Interval: 0,
22
+ Count: 0,
23
+ },
24
+ {
25
+ Enable: true,
26
+ Idle: -1,
27
+ Interval: -1,
28
+ Count: -1,
29
+ },
30
+ {
31
+ Enable: true,
32
+ Idle: -1,
33
+ Interval: 3 * time.Second,
34
+ Count: 10,
35
+ },
36
+ {
37
+ Enable: true,
38
+ Idle: 5 * time.Second,
39
+ Interval: -1,
40
+ Count: 10,
41
+ },
42
+ {
43
+ Enable: true,
44
+ Idle: 5 * time.Second,
45
+ Interval: 3 * time.Second,
46
+ Count: -1,
47
+ },
48
+ {
49
+ Enable: true,
50
+ Idle: -1,
51
+ Interval: -1,
52
+ Count: 10,
53
+ },
54
+ {
55
+ Enable: true,
56
+ Idle: -1,
57
+ Interval: 3 * time.Second,
58
+ Count: -1,
59
+ },
60
+ {
61
+ Enable: true,
62
+ Idle: 5 * time.Second,
63
+ Interval: -1,
64
+ Count: -1,
65
+ },
66
+ {
67
+ Enable: true,
68
+ Idle: 0,
69
+ Interval: 3 * time.Second,
70
+ Count: 10,
71
+ },
72
+ {
73
+ Enable: true,
74
+ Idle: 5 * time.Second,
75
+ Interval: 0,
76
+ Count: 10,
77
+ },
78
+ {
79
+ Enable: true,
80
+ Idle: 5 * time.Second,
81
+ Interval: 3 * time.Second,
82
+ Count: 0,
83
+ },
84
+ {
85
+ Enable: true,
86
+ Idle: 0,
87
+ Interval: 0,
88
+ Count: 10,
89
+ },
90
+ {
91
+ Enable: true,
92
+ Idle: 0,
93
+ Interval: 3 * time.Second,
94
+ Count: 0,
95
+ },
96
+ {
97
+ Enable: true,
98
+ Idle: 5 * time.Second,
99
+ Interval: 0,
100
+ Count: 0,
101
+ },
102
+ }
go/src/net/tcpconn_keepalive_conf_solaris_test.go ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2024 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build solaris && !illumos
6
+
7
+ package net
8
+
9
+ import (
10
+ "testing"
11
+ "time"
12
+ )
13
+
14
+ const (
15
+ syscall_TCP_KEEPIDLE = sysTCP_KEEPIDLE
16
+ syscall_TCP_KEEPCNT = sysTCP_KEEPCNT
17
+ syscall_TCP_KEEPINTVL = sysTCP_KEEPINTVL
18
+ )
19
+
20
+ type fdType = int
21
+
22
+ func maybeSkipKeepAliveTest(_ *testing.T) {}
23
+
24
+ var testConfigs = []KeepAliveConfig{
25
+ {
26
+ Enable: true,
27
+ Idle: 20 * time.Second, // the minimum value is ten seconds on Solaris
28
+ Interval: 10 * time.Second, // ditto
29
+ Count: 10,
30
+ },
31
+ {
32
+ Enable: true,
33
+ Idle: 0,
34
+ Interval: 0,
35
+ Count: 0,
36
+ },
37
+ {
38
+ Enable: true,
39
+ Idle: -1,
40
+ Interval: -1,
41
+ Count: -1,
42
+ },
43
+ {
44
+ Enable: true,
45
+ Idle: -1,
46
+ Interval: 10 * time.Second,
47
+ Count: 10,
48
+ },
49
+ {
50
+ Enable: true,
51
+ Idle: 20 * time.Second,
52
+ Interval: -1,
53
+ Count: 10,
54
+ },
55
+ {
56
+ Enable: true,
57
+ Idle: 20 * time.Second,
58
+ Interval: 10 * time.Second,
59
+ Count: -1,
60
+ },
61
+ {
62
+ Enable: true,
63
+ Idle: -1,
64
+ Interval: -1,
65
+ Count: 10,
66
+ },
67
+ {
68
+ Enable: true,
69
+ Idle: -1,
70
+ Interval: 10 * time.Second,
71
+ Count: -1,
72
+ },
73
+ {
74
+ Enable: true,
75
+ Idle: 20 * time.Second,
76
+ Interval: -1,
77
+ Count: -1,
78
+ },
79
+ {
80
+ Enable: true,
81
+ Idle: 0,
82
+ Interval: 10 * time.Second,
83
+ Count: 10,
84
+ },
85
+ {
86
+ Enable: true,
87
+ Idle: 20 * time.Second,
88
+ Interval: 0,
89
+ Count: 10,
90
+ },
91
+ {
92
+ Enable: true,
93
+ Idle: 20 * time.Second,
94
+ Interval: 10 * time.Second,
95
+ Count: 0,
96
+ },
97
+ {
98
+ Enable: true,
99
+ Idle: 0,
100
+ Interval: 0,
101
+ Count: 10,
102
+ },
103
+ {
104
+ Enable: true,
105
+ Idle: 0,
106
+ Interval: 10 * time.Second,
107
+ Count: 0,
108
+ },
109
+ {
110
+ Enable: true,
111
+ Idle: 20 * time.Second,
112
+ Interval: 0,
113
+ Count: 0,
114
+ },
115
+ }
go/src/net/tcpconn_keepalive_conf_unix_test.go ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2023 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build aix || dragonfly || freebsd || illumos || linux || netbsd
6
+
7
+ package net
8
+
9
+ import (
10
+ "syscall"
11
+ "testing"
12
+ )
13
+
14
+ const (
15
+ syscall_TCP_KEEPIDLE = syscall.TCP_KEEPIDLE
16
+ syscall_TCP_KEEPCNT = syscall.TCP_KEEPCNT
17
+ syscall_TCP_KEEPINTVL = syscall.TCP_KEEPINTVL
18
+ )
19
+
20
+ type fdType = int
21
+
22
+ func maybeSkipKeepAliveTest(_ *testing.T) {}
go/src/net/tcpconn_keepalive_conf_windows_test.go ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2024 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build windows
6
+
7
+ package net
8
+
9
+ import (
10
+ "internal/syscall/windows"
11
+ "syscall"
12
+ "testing"
13
+ )
14
+
15
+ const (
16
+ syscall_TCP_KEEPIDLE = windows.TCP_KEEPIDLE
17
+ syscall_TCP_KEEPCNT = windows.TCP_KEEPCNT
18
+ syscall_TCP_KEEPINTVL = windows.TCP_KEEPINTVL
19
+ )
20
+
21
+ type fdType = syscall.Handle
22
+
23
+ func maybeSkipKeepAliveTest(t *testing.T) {
24
+ // TODO(panjf2000): Unlike Unix-like OS's, old Windows (prior to Windows 10, version 1709)
25
+ // doesn't provide any ways to retrieve the current TCP keep-alive settings, therefore
26
+ // we're not able to run the test suite similar to Unix-like OS's on Windows.
27
+ // Try to find another proper approach to test the keep-alive settings on old Windows.
28
+ if !windows.SupportTCPKeepAliveIdle() || !windows.SupportTCPKeepAliveInterval() || !windows.SupportTCPKeepAliveCount() {
29
+ t.Skip("skipping on windows")
30
+ }
31
+ }
go/src/net/tcpconn_keepalive_illumos_test.go ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2024 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build illumos
6
+
7
+ package net
8
+
9
+ import (
10
+ "syscall"
11
+ "testing"
12
+ "time"
13
+ )
14
+
15
+ func getCurrentKeepAliveSettings(fd fdType) (cfg KeepAliveConfig, err error) {
16
+ tcpKeepAlive, err := syscall.GetsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_KEEPALIVE)
17
+ if err != nil {
18
+ return
19
+ }
20
+ tcpKeepAliveIdle, err := syscall.GetsockoptInt(fd, syscall.IPPROTO_TCP, syscall_TCP_KEEPIDLE)
21
+ if err != nil {
22
+ return
23
+ }
24
+ tcpKeepAliveInterval, err := syscall.GetsockoptInt(fd, syscall.IPPROTO_TCP, syscall_TCP_KEEPINTVL)
25
+ if err != nil {
26
+ return
27
+ }
28
+ tcpKeepAliveCount, err := syscall.GetsockoptInt(fd, syscall.IPPROTO_TCP, syscall_TCP_KEEPCNT)
29
+ if err != nil {
30
+ return
31
+ }
32
+ cfg = KeepAliveConfig{
33
+ Enable: tcpKeepAlive != 0,
34
+ Idle: time.Duration(tcpKeepAliveIdle) * time.Second,
35
+ Interval: time.Duration(tcpKeepAliveInterval) * time.Second,
36
+ Count: tcpKeepAliveCount,
37
+ }
38
+ return
39
+ }
40
+
41
+ func verifyKeepAliveSettings(t *testing.T, fd fdType, oldCfg, cfg KeepAliveConfig) {
42
+ const defaultTcpKeepAliveAbortThreshold = 8 * time.Minute // default value on illumos
43
+
44
+ if cfg.Idle == 0 {
45
+ cfg.Idle = defaultTCPKeepAliveIdle
46
+ }
47
+ if cfg.Interval == 0 {
48
+ cfg.Interval = defaultTCPKeepAliveInterval
49
+ }
50
+ if cfg.Count == 0 {
51
+ cfg.Count = defaultTCPKeepAliveCount
52
+ }
53
+
54
+ if cfg.Idle == -1 {
55
+ cfg.Idle = oldCfg.Idle
56
+ }
57
+ // Check out the comment on KeepAliveConfig and the illumos code:
58
+ // https://github.com/illumos/illumos-gate/blob/0886dcadf4b2cd677c3b944167f0d16ccb243616/usr/src/uts/common/inet/tcp/tcp_opt_data.c#L786-L861
59
+ tcpKeepAliveAbortThreshold := defaultTcpKeepAliveAbortThreshold
60
+ switch {
61
+ case cfg.Interval == -1 && cfg.Count == -1:
62
+ cfg.Interval = oldCfg.Interval
63
+ cfg.Count = oldCfg.Count
64
+ case cfg.Interval == -1 && cfg.Count > 0:
65
+ cfg.Interval = defaultTcpKeepAliveAbortThreshold / time.Duration(cfg.Count)
66
+ case cfg.Count == -1 && cfg.Interval > 0:
67
+ cfg.Count = int(defaultTcpKeepAliveAbortThreshold / cfg.Interval)
68
+ case cfg.Interval > 0 && cfg.Count > 0:
69
+ // TCP_KEEPALIVE_ABORT_THRESHOLD will be recalculated only when both TCP_KEEPINTVL
70
+ // and TCP_KEEPCNT are set, otherwise it will remain the default value.
71
+ tcpKeepAliveAbortThreshold = cfg.Interval * time.Duration(cfg.Count)
72
+ }
73
+
74
+ tcpKeepAlive, err := syscall.GetsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_KEEPALIVE)
75
+ if err != nil {
76
+ t.Fatal(err)
77
+ }
78
+ if (tcpKeepAlive != 0) != cfg.Enable {
79
+ t.Fatalf("SO_KEEPALIVE: got %t; want %t", tcpKeepAlive != 0, cfg.Enable)
80
+ }
81
+
82
+ tcpKeepAliveIdle, err := syscall.GetsockoptInt(fd, syscall.IPPROTO_TCP, syscall_TCP_KEEPIDLE)
83
+ if err != nil {
84
+ t.Fatal(err)
85
+ }
86
+ if time.Duration(tcpKeepAliveIdle)*time.Second != cfg.Idle {
87
+ t.Fatalf("TCP_KEEPIDLE: got %ds; want %v", tcpKeepAliveIdle, cfg.Idle)
88
+ }
89
+ tcpKeepAliveThreshold, err := syscall.GetsockoptInt(fd, syscall.IPPROTO_TCP, syscall.TCP_KEEPALIVE_THRESHOLD)
90
+ if err != nil {
91
+ t.Fatal(err)
92
+ }
93
+ if time.Duration(tcpKeepAliveThreshold)*time.Millisecond != cfg.Idle {
94
+ t.Fatalf("TCP_KEEPALIVE_THRESHOLD: got %dms; want %v", tcpKeepAliveThreshold, cfg.Idle)
95
+ }
96
+
97
+ tcpKeepAliveInterval, err := syscall.GetsockoptInt(fd, syscall.IPPROTO_TCP, syscall_TCP_KEEPINTVL)
98
+ if err != nil {
99
+ t.Fatal(err)
100
+ }
101
+ if time.Duration(tcpKeepAliveInterval)*time.Second != cfg.Interval {
102
+ t.Fatalf("TCP_KEEPINTVL: got %ds; want %v", tcpKeepAliveInterval, cfg.Interval)
103
+ }
104
+
105
+ tcpKeepAliveCount, err := syscall.GetsockoptInt(fd, syscall.IPPROTO_TCP, syscall_TCP_KEEPCNT)
106
+ if err != nil {
107
+ t.Fatal(err)
108
+ }
109
+ if tcpKeepAliveCount != cfg.Count {
110
+ t.Fatalf("TCP_KEEPCNT: got %d; want %d", tcpKeepAliveCount, cfg.Count)
111
+ }
112
+
113
+ tcpKeepAliveAbortInterval, err := syscall.GetsockoptInt(fd, syscall.IPPROTO_TCP, syscall.TCP_KEEPALIVE_ABORT_THRESHOLD)
114
+ if err != nil {
115
+ t.Fatal(err)
116
+ }
117
+ if time.Duration(tcpKeepAliveAbortInterval)*time.Millisecond != tcpKeepAliveAbortThreshold {
118
+ t.Fatalf("TCP_KEEPALIVE_ABORT_THRESHOLD: got %dms; want %v", tcpKeepAliveAbortInterval, tcpKeepAliveAbortThreshold)
119
+ }
120
+ }
go/src/net/tcpconn_keepalive_posix_test.go ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2023 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build aix || darwin || dragonfly || freebsd || linux || netbsd || windows
6
+
7
+ package net
8
+
9
+ import (
10
+ "syscall"
11
+ "testing"
12
+ "time"
13
+ )
14
+
15
+ func getCurrentKeepAliveSettings(fd fdType) (cfg KeepAliveConfig, err error) {
16
+ tcpKeepAlive, err := syscall.GetsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_KEEPALIVE)
17
+ if err != nil {
18
+ return
19
+ }
20
+ tcpKeepAliveIdle, err := syscall.GetsockoptInt(fd, syscall.IPPROTO_TCP, syscall_TCP_KEEPIDLE)
21
+ if err != nil {
22
+ return
23
+ }
24
+ tcpKeepAliveInterval, err := syscall.GetsockoptInt(fd, syscall.IPPROTO_TCP, syscall_TCP_KEEPINTVL)
25
+ if err != nil {
26
+ return
27
+ }
28
+ tcpKeepAliveCount, err := syscall.GetsockoptInt(fd, syscall.IPPROTO_TCP, syscall_TCP_KEEPCNT)
29
+ if err != nil {
30
+ return
31
+ }
32
+ cfg = KeepAliveConfig{
33
+ Enable: tcpKeepAlive != 0,
34
+ Idle: time.Duration(tcpKeepAliveIdle) * time.Second,
35
+ Interval: time.Duration(tcpKeepAliveInterval) * time.Second,
36
+ Count: tcpKeepAliveCount,
37
+ }
38
+ return
39
+ }
40
+
41
+ func verifyKeepAliveSettings(t *testing.T, fd fdType, oldCfg, cfg KeepAliveConfig) {
42
+ if cfg.Idle == 0 {
43
+ cfg.Idle = defaultTCPKeepAliveIdle
44
+ }
45
+ if cfg.Interval == 0 {
46
+ cfg.Interval = defaultTCPKeepAliveInterval
47
+ }
48
+ if cfg.Count == 0 {
49
+ cfg.Count = defaultTCPKeepAliveCount
50
+ }
51
+ if cfg.Idle == -1 {
52
+ cfg.Idle = oldCfg.Idle
53
+ }
54
+ if cfg.Interval == -1 {
55
+ cfg.Interval = oldCfg.Interval
56
+ }
57
+ if cfg.Count == -1 {
58
+ cfg.Count = oldCfg.Count
59
+ }
60
+
61
+ tcpKeepAlive, err := syscall.GetsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_KEEPALIVE)
62
+ if err != nil {
63
+ t.Fatal(err)
64
+ }
65
+ if (tcpKeepAlive != 0) != cfg.Enable {
66
+ t.Fatalf("SO_KEEPALIVE: got %t; want %t", tcpKeepAlive != 0, cfg.Enable)
67
+ }
68
+
69
+ tcpKeepAliveIdle, err := syscall.GetsockoptInt(fd, syscall.IPPROTO_TCP, syscall_TCP_KEEPIDLE)
70
+ if err != nil {
71
+ t.Fatal(err)
72
+ }
73
+ if time.Duration(tcpKeepAliveIdle)*time.Second != cfg.Idle {
74
+ t.Fatalf("TCP_KEEPIDLE: got %ds; want %v", tcpKeepAliveIdle, cfg.Idle)
75
+ }
76
+
77
+ tcpKeepAliveInterval, err := syscall.GetsockoptInt(fd, syscall.IPPROTO_TCP, syscall_TCP_KEEPINTVL)
78
+ if err != nil {
79
+ t.Fatal(err)
80
+ }
81
+ if time.Duration(tcpKeepAliveInterval)*time.Second != cfg.Interval {
82
+ t.Fatalf("TCP_KEEPINTVL: got %ds; want %v", tcpKeepAliveInterval, cfg.Interval)
83
+ }
84
+
85
+ tcpKeepAliveCount, err := syscall.GetsockoptInt(fd, syscall.IPPROTO_TCP, syscall_TCP_KEEPCNT)
86
+ if err != nil {
87
+ t.Fatal(err)
88
+ }
89
+ if tcpKeepAliveCount != cfg.Count {
90
+ t.Fatalf("TCP_KEEPCNT: got %d; want %d", tcpKeepAliveCount, cfg.Count)
91
+ }
92
+ }
go/src/net/tcpconn_keepalive_solaris_test.go ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2023 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build solaris && !illumos
6
+
7
+ package net
8
+
9
+ import (
10
+ "internal/syscall/unix"
11
+ "syscall"
12
+ "testing"
13
+ "time"
14
+ )
15
+
16
+ func getCurrentKeepAliveSettings(fd fdType) (cfg KeepAliveConfig, err error) {
17
+ tcpKeepAlive, err := syscall.GetsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_KEEPALIVE)
18
+ if err != nil {
19
+ return
20
+ }
21
+
22
+ var (
23
+ tcpKeepAliveIdle int
24
+ tcpKeepAliveInterval int
25
+ tcpKeepAliveIdleTime time.Duration
26
+ tcpKeepAliveIntervalTime time.Duration
27
+ tcpKeepAliveCount int
28
+ )
29
+ if unix.SupportTCPKeepAliveIdleIntvlCNT() {
30
+ tcpKeepAliveIdle, err = syscall.GetsockoptInt(fd, syscall.IPPROTO_TCP, syscall_TCP_KEEPIDLE)
31
+ if err != nil {
32
+ return
33
+ }
34
+ tcpKeepAliveIdleTime = time.Duration(tcpKeepAliveIdle) * time.Second
35
+
36
+ tcpKeepAliveInterval, err = syscall.GetsockoptInt(fd, syscall.IPPROTO_TCP, syscall_TCP_KEEPINTVL)
37
+ if err != nil {
38
+ return
39
+ }
40
+ tcpKeepAliveIntervalTime = time.Duration(tcpKeepAliveInterval) * time.Second
41
+
42
+ tcpKeepAliveCount, err = syscall.GetsockoptInt(fd, syscall.IPPROTO_TCP, syscall_TCP_KEEPCNT)
43
+ if err != nil {
44
+ return
45
+ }
46
+ } else {
47
+ tcpKeepAliveIdle, err = syscall.GetsockoptInt(fd, syscall.IPPROTO_TCP, syscall.TCP_KEEPALIVE_THRESHOLD)
48
+ if err != nil {
49
+ return
50
+ }
51
+ tcpKeepAliveIdleTime = time.Duration(tcpKeepAliveIdle) * time.Millisecond
52
+
53
+ // TCP_KEEPINTVL and TCP_KEEPCNT are not available on Solaris prior to 11.4,
54
+ // so we have to use the value of TCP_KEEPALIVE_ABORT_THRESHOLD for Interval
55
+ // and 1 for Count to keep this test going.
56
+ tcpKeepAliveInterval, err = syscall.GetsockoptInt(fd, syscall.IPPROTO_TCP, syscall.TCP_KEEPALIVE_ABORT_THRESHOLD)
57
+ if err != nil {
58
+ return
59
+ }
60
+ tcpKeepAliveIntervalTime = time.Duration(tcpKeepAliveInterval) * time.Millisecond
61
+ tcpKeepAliveCount = 1
62
+ }
63
+ cfg = KeepAliveConfig{
64
+ Enable: tcpKeepAlive != 0,
65
+ Idle: tcpKeepAliveIdleTime,
66
+ Interval: tcpKeepAliveIntervalTime,
67
+ Count: tcpKeepAliveCount,
68
+ }
69
+ return
70
+ }
71
+
72
+ func verifyKeepAliveSettings(t *testing.T, fd fdType, oldCfg, cfg KeepAliveConfig) {
73
+ const defaultTcpKeepAliveAbortThreshold = 8 * time.Minute // default value on Solaris
74
+
75
+ if cfg.Idle == 0 {
76
+ cfg.Idle = defaultTCPKeepAliveIdle
77
+ }
78
+ if cfg.Interval == 0 {
79
+ cfg.Interval = defaultTCPKeepAliveInterval
80
+ }
81
+ if cfg.Count == 0 {
82
+ cfg.Count = defaultTCPKeepAliveCount
83
+ }
84
+ if cfg.Idle == -1 {
85
+ cfg.Idle = oldCfg.Idle
86
+ }
87
+
88
+ tcpKeepAliveAbortThreshold := defaultTcpKeepAliveAbortThreshold
89
+ if unix.SupportTCPKeepAliveIdleIntvlCNT() {
90
+ // Check out the comment on KeepAliveConfig to understand the following logic.
91
+ switch {
92
+ case cfg.Interval == -1 && cfg.Count == -1:
93
+ cfg.Interval = oldCfg.Interval
94
+ cfg.Count = oldCfg.Count
95
+ case cfg.Interval == -1 && cfg.Count > 0:
96
+ cfg.Interval = defaultTcpKeepAliveAbortThreshold / time.Duration(cfg.Count)
97
+ case cfg.Count == -1 && cfg.Interval > 0:
98
+ cfg.Count = int(defaultTcpKeepAliveAbortThreshold / cfg.Interval)
99
+ case cfg.Interval > 0 && cfg.Count > 0:
100
+ // TCP_KEEPALIVE_ABORT_THRESHOLD will be recalculated only when both TCP_KEEPINTVL
101
+ // and TCP_KEEPCNT are set, otherwise it will remain the default value.
102
+ tcpKeepAliveAbortThreshold = cfg.Interval * time.Duration(cfg.Count)
103
+ }
104
+ } else {
105
+ cfg.Interval = cfg.Interval * time.Duration(cfg.Count)
106
+ // Either Interval or Count is set to a negative value, TCP_KEEPALIVE_ABORT_THRESHOLD
107
+ // will remain the default value, so use the old Interval for the subsequent test.
108
+ if cfg.Interval == -1 || cfg.Count == -1 {
109
+ cfg.Interval = oldCfg.Interval
110
+ }
111
+ cfg.Count = 1
112
+ tcpKeepAliveAbortThreshold = cfg.Interval
113
+ }
114
+
115
+ tcpKeepAlive, err := syscall.GetsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_KEEPALIVE)
116
+ if err != nil {
117
+ t.Fatal(err)
118
+ }
119
+ if (tcpKeepAlive != 0) != cfg.Enable {
120
+ t.Fatalf("SO_KEEPALIVE: got %t; want %t", tcpKeepAlive != 0, cfg.Enable)
121
+ }
122
+
123
+ // TCP_KEEPALIVE_THRESHOLD and TCP_KEEPALIVE_ABORT_THRESHOLD are both available on Solaris 11.4
124
+ // and previous versions, so we can verify these two options regardless of the kernel version.
125
+ tcpKeepAliveThreshold, err := syscall.GetsockoptInt(fd, syscall.IPPROTO_TCP, syscall.TCP_KEEPALIVE_THRESHOLD)
126
+ if err != nil {
127
+ t.Fatal(err)
128
+ }
129
+ if time.Duration(tcpKeepAliveThreshold)*time.Millisecond != cfg.Idle {
130
+ t.Fatalf("TCP_KEEPIDLE: got %dms; want %v", tcpKeepAliveThreshold, cfg.Idle)
131
+ }
132
+
133
+ tcpKeepAliveAbortInterval, err := syscall.GetsockoptInt(fd, syscall.IPPROTO_TCP, syscall.TCP_KEEPALIVE_ABORT_THRESHOLD)
134
+ if err != nil {
135
+ t.Fatal(err)
136
+ }
137
+ if time.Duration(tcpKeepAliveAbortInterval)*time.Millisecond != tcpKeepAliveAbortThreshold {
138
+ t.Fatalf("TCP_KEEPALIVE_ABORT_THRESHOLD: got %dms; want %v", tcpKeepAliveAbortInterval, tcpKeepAliveAbortThreshold)
139
+ }
140
+
141
+ if unix.SupportTCPKeepAliveIdleIntvlCNT() {
142
+ tcpKeepAliveIdle, err := syscall.GetsockoptInt(fd, syscall.IPPROTO_TCP, syscall_TCP_KEEPIDLE)
143
+ if err != nil {
144
+ t.Fatal(err)
145
+ }
146
+ if time.Duration(tcpKeepAliveIdle)*time.Second != cfg.Idle {
147
+ t.Fatalf("TCP_KEEPIDLE: got %ds; want %v", tcpKeepAliveIdle, cfg.Idle)
148
+ }
149
+
150
+ tcpKeepAliveInterval, err := syscall.GetsockoptInt(fd, syscall.IPPROTO_TCP, syscall_TCP_KEEPINTVL)
151
+ if err != nil {
152
+ t.Fatal(err)
153
+ }
154
+ if time.Duration(tcpKeepAliveInterval)*time.Second != cfg.Interval {
155
+ t.Fatalf("TCP_KEEPINTVL: got %ds; want %v", tcpKeepAliveInterval, cfg.Interval)
156
+ }
157
+
158
+ tcpKeepAliveCount, err := syscall.GetsockoptInt(fd, syscall.IPPROTO_TCP, syscall_TCP_KEEPCNT)
159
+ if err != nil {
160
+ t.Fatal(err)
161
+ }
162
+ if tcpKeepAliveCount != cfg.Count {
163
+ t.Fatalf("TCP_KEEPCNT: got %d; want %d", tcpKeepAliveCount, cfg.Count)
164
+ }
165
+ } else {
166
+ if cfg.Count != 1 {
167
+ t.Fatalf("TCP_KEEPCNT: got %d; want 1", cfg.Count)
168
+ }
169
+ }
170
+ }
go/src/net/tcpconn_keepalive_test.go ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2023 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build aix || darwin || dragonfly || freebsd || linux || netbsd || solaris || windows
6
+
7
+ package net
8
+
9
+ import (
10
+ "runtime"
11
+ "testing"
12
+ )
13
+
14
+ func TestTCPConnKeepAliveConfigDialer(t *testing.T) {
15
+ maybeSkipKeepAliveTest(t)
16
+
17
+ t.Cleanup(func() {
18
+ testPreHookSetKeepAlive = func(*netFD) {}
19
+ })
20
+ var (
21
+ errHook error
22
+ oldCfg KeepAliveConfig
23
+ )
24
+ testPreHookSetKeepAlive = func(nfd *netFD) {
25
+ oldCfg, errHook = getCurrentKeepAliveSettings(nfd.pfd.Sysfd)
26
+ }
27
+
28
+ handler := func(ls *localServer, ln Listener) {
29
+ for {
30
+ c, err := ln.Accept()
31
+ if err != nil {
32
+ return
33
+ }
34
+ c.Close()
35
+ }
36
+ }
37
+ ln := newLocalListener(t, "tcp", &ListenConfig{
38
+ KeepAlive: -1, // prevent calling hook from accepting
39
+ })
40
+ ls := (&streamListener{Listener: ln}).newLocalServer()
41
+ defer ls.teardown()
42
+ if err := ls.buildup(handler); err != nil {
43
+ t.Fatal(err)
44
+ }
45
+
46
+ for _, cfg := range testConfigs {
47
+ d := Dialer{
48
+ KeepAlive: defaultTCPKeepAliveIdle, // should be ignored
49
+ KeepAliveConfig: cfg}
50
+ c, err := d.Dial("tcp", ls.Listener.Addr().String())
51
+ if err != nil {
52
+ t.Fatal(err)
53
+ }
54
+ defer c.Close()
55
+
56
+ if errHook != nil {
57
+ t.Fatal(errHook)
58
+ }
59
+
60
+ sc, err := c.(*TCPConn).SyscallConn()
61
+ if err != nil {
62
+ t.Fatal(err)
63
+ }
64
+ if err := sc.Control(func(fd uintptr) {
65
+ verifyKeepAliveSettings(t, fdType(fd), oldCfg, cfg)
66
+ }); err != nil {
67
+ t.Fatal(err)
68
+ }
69
+ }
70
+ }
71
+
72
+ func TestTCPConnKeepAliveConfigListener(t *testing.T) {
73
+ maybeSkipKeepAliveTest(t)
74
+
75
+ t.Cleanup(func() {
76
+ testPreHookSetKeepAlive = func(*netFD) {}
77
+ })
78
+ var (
79
+ errHook error
80
+ oldCfg KeepAliveConfig
81
+ )
82
+ testPreHookSetKeepAlive = func(nfd *netFD) {
83
+ oldCfg, errHook = getCurrentKeepAliveSettings(nfd.pfd.Sysfd)
84
+ }
85
+
86
+ ch := make(chan Conn, 1)
87
+ handler := func(ls *localServer, ln Listener) {
88
+ c, err := ln.Accept()
89
+ if err != nil {
90
+ return
91
+ }
92
+ ch <- c
93
+ }
94
+ for _, cfg := range testConfigs {
95
+ ln := newLocalListener(t, "tcp", &ListenConfig{
96
+ KeepAlive: defaultTCPKeepAliveIdle, // should be ignored
97
+ KeepAliveConfig: cfg})
98
+ ls := (&streamListener{Listener: ln}).newLocalServer()
99
+ defer ls.teardown()
100
+ if err := ls.buildup(handler); err != nil {
101
+ t.Fatal(err)
102
+ }
103
+ d := Dialer{KeepAlive: -1} // prevent calling hook from dialing
104
+ c, err := d.Dial("tcp", ls.Listener.Addr().String())
105
+ if err != nil {
106
+ t.Fatal(err)
107
+ }
108
+ defer c.Close()
109
+
110
+ cc := <-ch
111
+ defer cc.Close()
112
+ if errHook != nil {
113
+ t.Fatal(errHook)
114
+ }
115
+ sc, err := cc.(*TCPConn).SyscallConn()
116
+ if err != nil {
117
+ t.Fatal(err)
118
+ }
119
+ if err := sc.Control(func(fd uintptr) {
120
+ verifyKeepAliveSettings(t, fdType(fd), oldCfg, cfg)
121
+ }); err != nil {
122
+ t.Fatal(err)
123
+ }
124
+ }
125
+ }
126
+
127
+ func TestTCPConnKeepAliveConfig(t *testing.T) {
128
+ maybeSkipKeepAliveTest(t)
129
+
130
+ handler := func(ls *localServer, ln Listener) {
131
+ for {
132
+ c, err := ln.Accept()
133
+ if err != nil {
134
+ return
135
+ }
136
+ c.Close()
137
+ }
138
+ }
139
+ ls := newLocalServer(t, "tcp")
140
+ defer ls.teardown()
141
+ if err := ls.buildup(handler); err != nil {
142
+ t.Fatal(err)
143
+ }
144
+ for _, cfg := range testConfigs {
145
+ d := Dialer{KeepAlive: -1} // avoid setting default values before the test
146
+ c, err := d.Dial("tcp", ls.Listener.Addr().String())
147
+ if err != nil {
148
+ t.Fatal(err)
149
+ }
150
+ defer c.Close()
151
+
152
+ sc, err := c.(*TCPConn).SyscallConn()
153
+ if err != nil {
154
+ t.Fatal(err)
155
+ }
156
+
157
+ var (
158
+ errHook error
159
+ oldCfg KeepAliveConfig
160
+ )
161
+ if err := sc.Control(func(fd uintptr) {
162
+ oldCfg, errHook = getCurrentKeepAliveSettings(fdType(fd))
163
+ }); err != nil {
164
+ t.Fatal(err)
165
+ }
166
+ if errHook != nil {
167
+ t.Fatal(errHook)
168
+ }
169
+
170
+ err = c.(*TCPConn).SetKeepAliveConfig(cfg)
171
+ if err != nil {
172
+ if runtime.GOOS == "solaris" {
173
+ // Solaris prior to 11.4 does not support TCP_KEEPINTVL and TCP_KEEPCNT,
174
+ // so it will return syscall.ENOPROTOOPT when only one of Interval and Count
175
+ // is negative. This is expected, so skip the error check in this case.
176
+ if cfg.Interval >= 0 && cfg.Count >= 0 {
177
+ t.Fatal(err)
178
+ }
179
+ } else {
180
+ t.Fatal(err)
181
+ }
182
+ }
183
+
184
+ if err := sc.Control(func(fd uintptr) {
185
+ verifyKeepAliveSettings(t, fdType(fd), oldCfg, cfg)
186
+ }); err != nil {
187
+ t.Fatal(err)
188
+ }
189
+ }
190
+ }
go/src/net/tcpsock.go ADDED
@@ -0,0 +1,478 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2009 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package net
6
+
7
+ import (
8
+ "context"
9
+ "internal/strconv"
10
+ "io"
11
+ "net/netip"
12
+ "os"
13
+ "syscall"
14
+ "time"
15
+ )
16
+
17
+ // BUG(mikio): On JS, the File method of TCPConn and
18
+ // TCPListener is not implemented.
19
+
20
+ // TCPAddr represents the address of a TCP end point.
21
+ type TCPAddr struct {
22
+ IP IP
23
+ Port int
24
+ Zone string // IPv6 scoped addressing zone
25
+ }
26
+
27
+ // AddrPort returns the [TCPAddr] a as a [netip.AddrPort].
28
+ //
29
+ // If a.Port does not fit in a uint16, it's silently truncated.
30
+ //
31
+ // If a is nil, a zero value is returned.
32
+ func (a *TCPAddr) AddrPort() netip.AddrPort {
33
+ if a == nil {
34
+ return netip.AddrPort{}
35
+ }
36
+ na, _ := netip.AddrFromSlice(a.IP)
37
+ na = na.WithZone(a.Zone)
38
+ return netip.AddrPortFrom(na, uint16(a.Port))
39
+ }
40
+
41
+ // Network returns the address's network name, "tcp".
42
+ func (a *TCPAddr) Network() string { return "tcp" }
43
+
44
+ func (a *TCPAddr) String() string {
45
+ if a == nil {
46
+ return "<nil>"
47
+ }
48
+ ip := ipEmptyString(a.IP)
49
+ if a.Zone != "" {
50
+ return JoinHostPort(ip+"%"+a.Zone, strconv.Itoa(a.Port))
51
+ }
52
+ return JoinHostPort(ip, strconv.Itoa(a.Port))
53
+ }
54
+
55
+ func (a *TCPAddr) isWildcard() bool {
56
+ if a == nil || a.IP == nil {
57
+ return true
58
+ }
59
+ return a.IP.IsUnspecified()
60
+ }
61
+
62
+ func (a *TCPAddr) opAddr() Addr {
63
+ if a == nil {
64
+ return nil
65
+ }
66
+ return a
67
+ }
68
+
69
+ // ResolveTCPAddr returns an address of TCP end point.
70
+ //
71
+ // The network must be a TCP network name.
72
+ //
73
+ // If the host in the address parameter is not a literal IP address or
74
+ // the port is not a literal port number, ResolveTCPAddr resolves the
75
+ // address to an address of TCP end point.
76
+ // Otherwise, it parses the address as a pair of literal IP address
77
+ // and port number.
78
+ // The address parameter can use a host name, but this is not
79
+ // recommended, because it will return at most one of the host name's
80
+ // IP addresses.
81
+ //
82
+ // See func [Dial] for a description of the network and address
83
+ // parameters.
84
+ func ResolveTCPAddr(network, address string) (*TCPAddr, error) {
85
+ switch network {
86
+ case "tcp", "tcp4", "tcp6":
87
+ case "": // a hint wildcard for Go 1.0 undocumented behavior
88
+ network = "tcp"
89
+ default:
90
+ return nil, UnknownNetworkError(network)
91
+ }
92
+ addrs, err := DefaultResolver.internetAddrList(context.Background(), network, address)
93
+ if err != nil {
94
+ return nil, err
95
+ }
96
+ return addrs.forResolve(network, address).(*TCPAddr), nil
97
+ }
98
+
99
+ // TCPAddrFromAddrPort returns addr as a [TCPAddr]. If addr.IsValid() is false,
100
+ // then the returned TCPAddr will contain a nil IP field, indicating an
101
+ // address family-agnostic unspecified address.
102
+ func TCPAddrFromAddrPort(addr netip.AddrPort) *TCPAddr {
103
+ return &TCPAddr{
104
+ IP: addr.Addr().AsSlice(),
105
+ Zone: addr.Addr().Zone(),
106
+ Port: int(addr.Port()),
107
+ }
108
+ }
109
+
110
+ // TCPConn is an implementation of the [Conn] interface for TCP network
111
+ // connections.
112
+ type TCPConn struct {
113
+ conn
114
+ }
115
+
116
+ // KeepAliveConfig contains TCP keep-alive options.
117
+ //
118
+ // If the Idle, Interval, or Count fields are zero, a default value is chosen.
119
+ // If a field is negative, the corresponding socket-level option will be left unchanged.
120
+ //
121
+ // Note that prior to Windows 10 version 1709, neither setting Idle and Interval
122
+ // separately nor changing Count (which is usually 10) is supported.
123
+ // Therefore, it's recommended to set both Idle and Interval to non-negative values
124
+ // in conjunction with a -1 for Count on those old Windows if you intend to customize
125
+ // the TCP keep-alive settings.
126
+ // By contrast, if only one of Idle and Interval is set to a non-negative value,
127
+ // the other will be set to the system default value, and ultimately,
128
+ // set both Idle and Interval to negative values if you want to leave them unchanged.
129
+ //
130
+ // Note that Solaris and its derivatives do not support setting Interval to a non-negative value
131
+ // and Count to a negative value, or vice-versa.
132
+ type KeepAliveConfig struct {
133
+ // If Enable is true, keep-alive probes are enabled.
134
+ Enable bool
135
+
136
+ // Idle is the time that the connection must be idle before
137
+ // the first keep-alive probe is sent.
138
+ // If zero, a default value of 15 seconds is used.
139
+ Idle time.Duration
140
+
141
+ // Interval is the time between keep-alive probes.
142
+ // If zero, a default value of 15 seconds is used.
143
+ Interval time.Duration
144
+
145
+ // Count is the maximum number of keep-alive probes that
146
+ // can go unanswered before dropping a connection.
147
+ // If zero, a default value of 9 is used.
148
+ Count int
149
+ }
150
+
151
+ // SyscallConn returns a raw network connection.
152
+ // This implements the [syscall.Conn] interface.
153
+ func (c *TCPConn) SyscallConn() (syscall.RawConn, error) {
154
+ if !c.ok() {
155
+ return nil, syscall.EINVAL
156
+ }
157
+ return newRawConn(c.fd), nil
158
+ }
159
+
160
+ // ReadFrom implements the [io.ReaderFrom] ReadFrom method.
161
+ func (c *TCPConn) ReadFrom(r io.Reader) (int64, error) {
162
+ if !c.ok() {
163
+ return 0, syscall.EINVAL
164
+ }
165
+ n, err := c.readFrom(r)
166
+ if err != nil && err != io.EOF {
167
+ err = &OpError{Op: "readfrom", Net: c.fd.net, Source: c.fd.laddr, Addr: c.fd.raddr, Err: err}
168
+ }
169
+ return n, err
170
+ }
171
+
172
+ // WriteTo implements the io.WriterTo WriteTo method.
173
+ func (c *TCPConn) WriteTo(w io.Writer) (int64, error) {
174
+ if !c.ok() {
175
+ return 0, syscall.EINVAL
176
+ }
177
+ n, err := c.writeTo(w)
178
+ if err != nil && err != io.EOF {
179
+ err = &OpError{Op: "writeto", Net: c.fd.net, Source: c.fd.laddr, Addr: c.fd.raddr, Err: err}
180
+ }
181
+ return n, err
182
+ }
183
+
184
+ // CloseRead shuts down the reading side of the TCP connection.
185
+ // Most callers should just use Close.
186
+ func (c *TCPConn) CloseRead() error {
187
+ if !c.ok() {
188
+ return syscall.EINVAL
189
+ }
190
+ if err := c.fd.closeRead(); err != nil {
191
+ return &OpError{Op: "close", Net: c.fd.net, Source: c.fd.laddr, Addr: c.fd.raddr, Err: err}
192
+ }
193
+ return nil
194
+ }
195
+
196
+ // CloseWrite shuts down the writing side of the TCP connection.
197
+ // Most callers should just use Close.
198
+ func (c *TCPConn) CloseWrite() error {
199
+ if !c.ok() {
200
+ return syscall.EINVAL
201
+ }
202
+ if err := c.fd.closeWrite(); err != nil {
203
+ return &OpError{Op: "close", Net: c.fd.net, Source: c.fd.laddr, Addr: c.fd.raddr, Err: err}
204
+ }
205
+ return nil
206
+ }
207
+
208
+ // SetLinger sets the behavior of Close on a connection which still
209
+ // has data waiting to be sent or to be acknowledged.
210
+ //
211
+ // If sec < 0 (the default), the operating system finishes sending the
212
+ // data in the background.
213
+ //
214
+ // If sec == 0, the operating system discards any unsent or
215
+ // unacknowledged data.
216
+ //
217
+ // If sec > 0, the data is sent in the background as with sec < 0.
218
+ // On some operating systems including Linux, this may cause Close to block
219
+ // until all data has been sent or discarded.
220
+ // On some operating systems after sec seconds have elapsed any remaining
221
+ // unsent data may be discarded.
222
+ func (c *TCPConn) SetLinger(sec int) error {
223
+ if !c.ok() {
224
+ return syscall.EINVAL
225
+ }
226
+ if err := setLinger(c.fd, sec); err != nil {
227
+ return &OpError{Op: "set", Net: c.fd.net, Source: c.fd.laddr, Addr: c.fd.raddr, Err: err}
228
+ }
229
+ return nil
230
+ }
231
+
232
+ // SetKeepAlive sets whether the operating system should send
233
+ // keep-alive messages on the connection.
234
+ func (c *TCPConn) SetKeepAlive(keepalive bool) error {
235
+ if !c.ok() {
236
+ return syscall.EINVAL
237
+ }
238
+ if err := setKeepAlive(c.fd, keepalive); err != nil {
239
+ return &OpError{Op: "set", Net: c.fd.net, Source: c.fd.laddr, Addr: c.fd.raddr, Err: err}
240
+ }
241
+ return nil
242
+ }
243
+
244
+ // SetKeepAlivePeriod sets the duration the connection needs to
245
+ // remain idle before TCP starts sending keepalive probes.
246
+ //
247
+ // Note that calling this method on Windows prior to Windows 10 version 1709
248
+ // will reset the KeepAliveInterval to the default system value, which is normally 1 second.
249
+ func (c *TCPConn) SetKeepAlivePeriod(d time.Duration) error {
250
+ if !c.ok() {
251
+ return syscall.EINVAL
252
+ }
253
+ if err := setKeepAliveIdle(c.fd, d); err != nil {
254
+ return &OpError{Op: "set", Net: c.fd.net, Source: c.fd.laddr, Addr: c.fd.raddr, Err: err}
255
+ }
256
+ return nil
257
+ }
258
+
259
+ // SetNoDelay controls whether the operating system should delay
260
+ // packet transmission in hopes of sending fewer packets (Nagle's
261
+ // algorithm). The default is true (no delay), meaning that data is
262
+ // sent as soon as possible after a Write.
263
+ func (c *TCPConn) SetNoDelay(noDelay bool) error {
264
+ if !c.ok() {
265
+ return syscall.EINVAL
266
+ }
267
+ if err := setNoDelay(c.fd, noDelay); err != nil {
268
+ return &OpError{Op: "set", Net: c.fd.net, Source: c.fd.laddr, Addr: c.fd.raddr, Err: err}
269
+ }
270
+ return nil
271
+ }
272
+
273
+ // MultipathTCP reports whether the ongoing connection is using MPTCP.
274
+ //
275
+ // If Multipath TCP is not supported by the host, by the other peer or
276
+ // intentionally / accidentally filtered out by a device in between, a
277
+ // fallback to TCP will be done. This method does its best to check if
278
+ // MPTCP is still being used or not.
279
+ //
280
+ // On Linux, more conditions are verified on kernels >= v5.16, improving
281
+ // the results.
282
+ func (c *TCPConn) MultipathTCP() (bool, error) {
283
+ if !c.ok() {
284
+ return false, syscall.EINVAL
285
+ }
286
+ return isUsingMultipathTCP(c.fd), nil
287
+ }
288
+
289
+ func newTCPConn(fd *netFD, keepAliveIdle time.Duration, keepAliveCfg KeepAliveConfig, preKeepAliveHook func(*netFD), keepAliveHook func(KeepAliveConfig)) *TCPConn {
290
+ setNoDelay(fd, true)
291
+ if !keepAliveCfg.Enable && keepAliveIdle >= 0 {
292
+ keepAliveCfg = KeepAliveConfig{
293
+ Enable: true,
294
+ Idle: keepAliveIdle,
295
+ }
296
+ }
297
+ c := &TCPConn{conn{fd}}
298
+ if keepAliveCfg.Enable {
299
+ if preKeepAliveHook != nil {
300
+ preKeepAliveHook(fd)
301
+ }
302
+ c.SetKeepAliveConfig(keepAliveCfg)
303
+ if keepAliveHook != nil {
304
+ keepAliveHook(keepAliveCfg)
305
+ }
306
+ }
307
+ return c
308
+ }
309
+
310
+ // DialTCP acts like [Dial] for TCP networks.
311
+ //
312
+ // The network must be a TCP network name; see func Dial for details.
313
+ //
314
+ // If laddr is nil, a local address is automatically chosen.
315
+ // If the IP field of raddr is nil or an unspecified IP address, the
316
+ // local system is assumed.
317
+ func DialTCP(network string, laddr, raddr *TCPAddr) (*TCPConn, error) {
318
+ return dialTCP(context.Background(), nil, network, laddr, raddr)
319
+ }
320
+
321
+ func dialTCP(ctx context.Context, dialer *Dialer, network string, laddr, raddr *TCPAddr) (*TCPConn, error) {
322
+ switch network {
323
+ case "tcp", "tcp4", "tcp6":
324
+ default:
325
+ return nil, &OpError{Op: "dial", Net: network, Source: laddr.opAddr(), Addr: raddr.opAddr(), Err: UnknownNetworkError(network)}
326
+ }
327
+ if raddr == nil {
328
+ return nil, &OpError{Op: "dial", Net: network, Source: laddr.opAddr(), Addr: nil, Err: errMissingAddress}
329
+ }
330
+ sd := &sysDialer{network: network, address: raddr.String()}
331
+ var (
332
+ c *TCPConn
333
+ err error
334
+ )
335
+ if dialer != nil {
336
+ sd.Dialer = *dialer
337
+ }
338
+ if sd.MultipathTCP() {
339
+ c, err = sd.dialMPTCP(ctx, laddr, raddr)
340
+ } else {
341
+ c, err = sd.dialTCP(ctx, laddr, raddr)
342
+ }
343
+ if err != nil {
344
+ return nil, &OpError{Op: "dial", Net: network, Source: laddr.opAddr(), Addr: raddr.opAddr(), Err: err}
345
+ }
346
+ return c, nil
347
+ }
348
+
349
+ // TCPListener is a TCP network listener. Clients should typically
350
+ // use variables of type [Listener] instead of assuming TCP.
351
+ type TCPListener struct {
352
+ fd *netFD
353
+ lc ListenConfig
354
+ }
355
+
356
+ // SyscallConn returns a raw network connection.
357
+ // This implements the [syscall.Conn] interface.
358
+ //
359
+ // The returned RawConn only supports calling Control. Read and
360
+ // Write return an error.
361
+ func (l *TCPListener) SyscallConn() (syscall.RawConn, error) {
362
+ if !l.ok() {
363
+ return nil, syscall.EINVAL
364
+ }
365
+ return newRawListener(l.fd), nil
366
+ }
367
+
368
+ // AcceptTCP accepts the next incoming call and returns the new
369
+ // connection.
370
+ func (l *TCPListener) AcceptTCP() (*TCPConn, error) {
371
+ if !l.ok() {
372
+ return nil, syscall.EINVAL
373
+ }
374
+ c, err := l.accept()
375
+ if err != nil {
376
+ return nil, &OpError{Op: "accept", Net: l.fd.net, Source: nil, Addr: l.fd.laddr, Err: err}
377
+ }
378
+ return c, nil
379
+ }
380
+
381
+ // Accept implements the Accept method in the [Listener] interface; it
382
+ // waits for the next call and returns a generic [Conn].
383
+ func (l *TCPListener) Accept() (Conn, error) {
384
+ if !l.ok() {
385
+ return nil, syscall.EINVAL
386
+ }
387
+ c, err := l.accept()
388
+ if err != nil {
389
+ return nil, &OpError{Op: "accept", Net: l.fd.net, Source: nil, Addr: l.fd.laddr, Err: err}
390
+ }
391
+ return c, nil
392
+ }
393
+
394
+ // Close stops listening on the TCP address.
395
+ // Already Accepted connections are not closed.
396
+ func (l *TCPListener) Close() error {
397
+ if !l.ok() {
398
+ return syscall.EINVAL
399
+ }
400
+ if err := l.close(); err != nil {
401
+ return &OpError{Op: "close", Net: l.fd.net, Source: nil, Addr: l.fd.laddr, Err: err}
402
+ }
403
+ return nil
404
+ }
405
+
406
+ // Addr returns the listener's network address, a [*TCPAddr].
407
+ // The Addr returned is shared by all invocations of Addr, so
408
+ // do not modify it.
409
+ func (l *TCPListener) Addr() Addr { return l.fd.laddr }
410
+
411
+ // SetDeadline sets the deadline associated with the listener.
412
+ // A zero time value disables the deadline.
413
+ func (l *TCPListener) SetDeadline(t time.Time) error {
414
+ if !l.ok() {
415
+ return syscall.EINVAL
416
+ }
417
+ return l.fd.SetDeadline(t)
418
+ }
419
+
420
+ // File returns a copy of the underlying [os.File].
421
+ // It is the caller's responsibility to close f when finished.
422
+ // Closing l does not affect f, and closing f does not affect l.
423
+ //
424
+ // The returned os.File's file descriptor is different from the
425
+ // connection's. Attempting to change properties of the original
426
+ // using this duplicate may or may not have the desired effect.
427
+ //
428
+ // On Windows, the returned os.File's file descriptor is not
429
+ // usable on other processes.
430
+ func (l *TCPListener) File() (f *os.File, err error) {
431
+ if !l.ok() {
432
+ return nil, syscall.EINVAL
433
+ }
434
+ f, err = l.file()
435
+ if err != nil {
436
+ return nil, &OpError{Op: "file", Net: l.fd.net, Source: nil, Addr: l.fd.laddr, Err: err}
437
+ }
438
+ return
439
+ }
440
+
441
+ // ListenTCP acts like [Listen] for TCP networks.
442
+ //
443
+ // The network must be a TCP network name; see func Dial for details.
444
+ //
445
+ // If the IP field of laddr is nil or an unspecified IP address,
446
+ // ListenTCP listens on all available unicast and anycast IP addresses
447
+ // of the local system.
448
+ // If the Port field of laddr is 0, a port number is automatically
449
+ // chosen.
450
+ func ListenTCP(network string, laddr *TCPAddr) (*TCPListener, error) {
451
+ switch network {
452
+ case "tcp", "tcp4", "tcp6":
453
+ default:
454
+ return nil, &OpError{Op: "listen", Net: network, Source: nil, Addr: laddr.opAddr(), Err: UnknownNetworkError(network)}
455
+ }
456
+ if laddr == nil {
457
+ laddr = &TCPAddr{}
458
+ }
459
+ sl := &sysListener{network: network, address: laddr.String()}
460
+ var (
461
+ ln *TCPListener
462
+ err error
463
+ )
464
+ if sl.MultipathTCP() {
465
+ ln, err = sl.listenMPTCP(context.Background(), laddr)
466
+ } else {
467
+ ln, err = sl.listenTCP(context.Background(), laddr)
468
+ }
469
+ if err != nil {
470
+ return nil, &OpError{Op: "listen", Net: network, Source: nil, Addr: laddr.opAddr(), Err: err}
471
+ }
472
+ return ln, nil
473
+ }
474
+
475
+ // roundDurationUp rounds d to the next multiple of to.
476
+ func roundDurationUp(d time.Duration, to time.Duration) time.Duration {
477
+ return (d + to - 1) / to
478
+ }
go/src/net/tcpsock_plan9.go ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2009 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package net
6
+
7
+ import (
8
+ "context"
9
+ "io"
10
+ "os"
11
+ )
12
+
13
+ func (c *TCPConn) readFrom(r io.Reader) (int64, error) {
14
+ return genericReadFrom(c, r)
15
+ }
16
+
17
+ func (c *TCPConn) writeTo(w io.Writer) (int64, error) {
18
+ return genericWriteTo(c, w)
19
+ }
20
+
21
+ func (sd *sysDialer) dialTCP(ctx context.Context, laddr, raddr *TCPAddr) (*TCPConn, error) {
22
+ if h := sd.testHookDialTCP; h != nil {
23
+ return h(ctx, sd.network, laddr, raddr)
24
+ }
25
+ if h := testHookDialTCP; h != nil {
26
+ return h(ctx, sd.network, laddr, raddr)
27
+ }
28
+ return sd.doDialTCP(ctx, laddr, raddr)
29
+ }
30
+
31
+ func (sd *sysDialer) doDialTCP(ctx context.Context, laddr, raddr *TCPAddr) (*TCPConn, error) {
32
+ switch sd.network {
33
+ case "tcp4":
34
+ // Plan 9 doesn't complain about [::]:0->127.0.0.1, so it's up to us.
35
+ if laddr != nil && len(laddr.IP) != 0 && laddr.IP.To4() == nil {
36
+ return nil, &AddrError{Err: "non-IPv4 local address", Addr: laddr.String()}
37
+ }
38
+ case "tcp", "tcp6":
39
+ default:
40
+ return nil, UnknownNetworkError(sd.network)
41
+ }
42
+ if raddr == nil {
43
+ return nil, errMissingAddress
44
+ }
45
+ fd, err := dialPlan9(ctx, sd.network, laddr, raddr)
46
+ if err != nil {
47
+ return nil, err
48
+ }
49
+ return newTCPConn(fd, sd.Dialer.KeepAlive, sd.Dialer.KeepAliveConfig, testPreHookSetKeepAlive, testHookSetKeepAlive), nil
50
+ }
51
+
52
+ func (ln *TCPListener) ok() bool { return ln != nil && ln.fd != nil && ln.fd.ctl != nil }
53
+
54
+ func (ln *TCPListener) accept() (*TCPConn, error) {
55
+ fd, err := ln.fd.acceptPlan9()
56
+ if err != nil {
57
+ return nil, err
58
+ }
59
+ return newTCPConn(fd, ln.lc.KeepAlive, ln.lc.KeepAliveConfig, testPreHookSetKeepAlive, testHookSetKeepAlive), nil
60
+ }
61
+
62
+ func (ln *TCPListener) close() error {
63
+ if err := ln.fd.pfd.Close(); err != nil {
64
+ return err
65
+ }
66
+ if _, err := ln.fd.ctl.WriteString("hangup"); err != nil {
67
+ ln.fd.ctl.Close()
68
+ return err
69
+ }
70
+ if err := ln.fd.ctl.Close(); err != nil {
71
+ return err
72
+ }
73
+ return nil
74
+ }
75
+
76
+ func (ln *TCPListener) file() (*os.File, error) {
77
+ f, err := ln.dup()
78
+ if err != nil {
79
+ return nil, err
80
+ }
81
+ return f, nil
82
+ }
83
+
84
+ func (sl *sysListener) listenTCP(ctx context.Context, laddr *TCPAddr) (*TCPListener, error) {
85
+ fd, err := listenPlan9(ctx, sl.network, laddr)
86
+ if err != nil {
87
+ return nil, err
88
+ }
89
+ return &TCPListener{fd: fd, lc: sl.ListenConfig}, nil
90
+ }
go/src/net/tcpsock_posix.go ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2009 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build unix || js || wasip1 || windows
6
+
7
+ package net
8
+
9
+ import (
10
+ "context"
11
+ "io"
12
+ "os"
13
+ "syscall"
14
+ )
15
+
16
+ func sockaddrToTCP(sa syscall.Sockaddr) Addr {
17
+ switch sa := sa.(type) {
18
+ case *syscall.SockaddrInet4:
19
+ return &TCPAddr{IP: sa.Addr[0:], Port: sa.Port}
20
+ case *syscall.SockaddrInet6:
21
+ return &TCPAddr{IP: sa.Addr[0:], Port: sa.Port, Zone: zoneCache.name(int(sa.ZoneId))}
22
+ }
23
+ return nil
24
+ }
25
+
26
+ func (a *TCPAddr) family() int {
27
+ if a == nil || len(a.IP) <= IPv4len {
28
+ return syscall.AF_INET
29
+ }
30
+ if a.IP.To4() != nil {
31
+ return syscall.AF_INET
32
+ }
33
+ return syscall.AF_INET6
34
+ }
35
+
36
+ func (a *TCPAddr) sockaddr(family int) (syscall.Sockaddr, error) {
37
+ if a == nil {
38
+ return nil, nil
39
+ }
40
+ return ipToSockaddr(family, a.IP, a.Port, a.Zone)
41
+ }
42
+
43
+ func (a *TCPAddr) toLocal(net string) sockaddr {
44
+ return &TCPAddr{loopbackIP(net), a.Port, a.Zone}
45
+ }
46
+
47
+ func (c *TCPConn) readFrom(r io.Reader) (int64, error) {
48
+ if n, err, handled := spliceFrom(c.fd, r); handled {
49
+ return n, err
50
+ }
51
+ if n, err, handled := sendFile(c.fd, r); handled {
52
+ return n, err
53
+ }
54
+ return genericReadFrom(c, r)
55
+ }
56
+
57
+ func (c *TCPConn) writeTo(w io.Writer) (int64, error) {
58
+ if n, err, handled := spliceTo(w, c.fd); handled {
59
+ return n, err
60
+ }
61
+ return genericWriteTo(c, w)
62
+ }
63
+
64
+ func (sd *sysDialer) dialTCP(ctx context.Context, laddr, raddr *TCPAddr) (*TCPConn, error) {
65
+ if h := sd.testHookDialTCP; h != nil {
66
+ return h(ctx, sd.network, laddr, raddr)
67
+ }
68
+ if h := testHookDialTCP; h != nil {
69
+ return h(ctx, sd.network, laddr, raddr)
70
+ }
71
+ return sd.doDialTCP(ctx, laddr, raddr)
72
+ }
73
+
74
+ func (sd *sysDialer) doDialTCP(ctx context.Context, laddr, raddr *TCPAddr) (*TCPConn, error) {
75
+ return sd.doDialTCPProto(ctx, laddr, raddr, 0)
76
+ }
77
+
78
+ func (sd *sysDialer) doDialTCPProto(ctx context.Context, laddr, raddr *TCPAddr, proto int) (*TCPConn, error) {
79
+ ctrlCtxFn := sd.Dialer.ControlContext
80
+ if ctrlCtxFn == nil && sd.Dialer.Control != nil {
81
+ ctrlCtxFn = func(ctx context.Context, network, address string, c syscall.RawConn) error {
82
+ return sd.Dialer.Control(network, address, c)
83
+ }
84
+ }
85
+ fd, err := internetSocket(ctx, sd.network, laddr, raddr, syscall.SOCK_STREAM, proto, "dial", ctrlCtxFn)
86
+
87
+ // TCP has a rarely used mechanism called a 'simultaneous connection' in
88
+ // which Dial("tcp", addr1, addr2) run on the machine at addr1 can
89
+ // connect to a simultaneous Dial("tcp", addr2, addr1) run on the machine
90
+ // at addr2, without either machine executing Listen. If laddr == nil,
91
+ // it means we want the kernel to pick an appropriate originating local
92
+ // address. Some Linux kernels cycle blindly through a fixed range of
93
+ // local ports, regardless of destination port. If a kernel happens to
94
+ // pick local port 50001 as the source for a Dial("tcp", "", "localhost:50001"),
95
+ // then the Dial will succeed, having simultaneously connected to itself.
96
+ // This can only happen when we are letting the kernel pick a port (laddr == nil)
97
+ // and when there is no listener for the destination address.
98
+ // It's hard to argue this is anything other than a kernel bug. If we
99
+ // see this happen, rather than expose the buggy effect to users, we
100
+ // close the fd and try again. If it happens twice more, we relent and
101
+ // use the result. See also:
102
+ // https://golang.org/issue/2690
103
+ // https://stackoverflow.com/questions/4949858/
104
+ //
105
+ // The opposite can also happen: if we ask the kernel to pick an appropriate
106
+ // originating local address, sometimes it picks one that is already in use.
107
+ // So if the error is EADDRNOTAVAIL, we have to try again too, just for
108
+ // a different reason.
109
+ //
110
+ // The kernel socket code is no doubt enjoying watching us squirm.
111
+ for i := 0; i < 2 && (laddr == nil || laddr.Port == 0) && (selfConnect(fd, err) || spuriousENOTAVAIL(err)); i++ {
112
+ if err == nil {
113
+ fd.Close()
114
+ }
115
+ fd, err = internetSocket(ctx, sd.network, laddr, raddr, syscall.SOCK_STREAM, proto, "dial", ctrlCtxFn)
116
+ }
117
+
118
+ if err != nil {
119
+ return nil, err
120
+ }
121
+ return newTCPConn(fd, sd.Dialer.KeepAlive, sd.Dialer.KeepAliveConfig, testPreHookSetKeepAlive, testHookSetKeepAlive), nil
122
+ }
123
+
124
+ func selfConnect(fd *netFD, err error) bool {
125
+ // If the connect failed, we clearly didn't connect to ourselves.
126
+ if err != nil {
127
+ return false
128
+ }
129
+
130
+ // The socket constructor can return an fd with raddr nil under certain
131
+ // unknown conditions. The errors in the calls there to Getpeername
132
+ // are discarded, but we can't catch the problem there because those
133
+ // calls are sometimes legally erroneous with a "socket not connected".
134
+ // Since this code (selfConnect) is already trying to work around
135
+ // a problem, we make sure if this happens we recognize trouble and
136
+ // ask the DialTCP routine to try again.
137
+ // TODO: try to understand what's really going on.
138
+ if fd.laddr == nil || fd.raddr == nil {
139
+ return true
140
+ }
141
+ l := fd.laddr.(*TCPAddr)
142
+ r := fd.raddr.(*TCPAddr)
143
+ return l.Port == r.Port && l.IP.Equal(r.IP)
144
+ }
145
+
146
+ func spuriousENOTAVAIL(err error) bool {
147
+ if op, ok := err.(*OpError); ok {
148
+ err = op.Err
149
+ }
150
+ if sys, ok := err.(*os.SyscallError); ok {
151
+ err = sys.Err
152
+ }
153
+ return err == syscall.EADDRNOTAVAIL
154
+ }
155
+
156
+ func (ln *TCPListener) ok() bool { return ln != nil && ln.fd != nil }
157
+
158
+ func (ln *TCPListener) accept() (*TCPConn, error) {
159
+ fd, err := ln.fd.accept()
160
+ if err != nil {
161
+ return nil, err
162
+ }
163
+ return newTCPConn(fd, ln.lc.KeepAlive, ln.lc.KeepAliveConfig, testPreHookSetKeepAlive, testHookSetKeepAlive), nil
164
+ }
165
+
166
+ func (ln *TCPListener) close() error {
167
+ return ln.fd.Close()
168
+ }
169
+
170
+ func (ln *TCPListener) file() (*os.File, error) {
171
+ f, err := ln.fd.dup()
172
+ if err != nil {
173
+ return nil, err
174
+ }
175
+ return f, nil
176
+ }
177
+
178
+ func (sl *sysListener) listenTCP(ctx context.Context, laddr *TCPAddr) (*TCPListener, error) {
179
+ return sl.listenTCPProto(ctx, laddr, 0)
180
+ }
181
+
182
+ func (sl *sysListener) listenTCPProto(ctx context.Context, laddr *TCPAddr, proto int) (*TCPListener, error) {
183
+ var ctrlCtxFn func(ctx context.Context, network, address string, c syscall.RawConn) error
184
+ if sl.ListenConfig.Control != nil {
185
+ ctrlCtxFn = func(ctx context.Context, network, address string, c syscall.RawConn) error {
186
+ return sl.ListenConfig.Control(network, address, c)
187
+ }
188
+ }
189
+ fd, err := internetSocket(ctx, sl.network, laddr, nil, syscall.SOCK_STREAM, proto, "listen", ctrlCtxFn)
190
+ if err != nil {
191
+ return nil, err
192
+ }
193
+ return &TCPListener{fd: fd, lc: sl.ListenConfig}, nil
194
+ }