ADAPT-Chase commited on
Commit
0e0d680
·
verified ·
1 Parent(s): 1e92419

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. platform/dbops/binaries/go/go/src/net/ip_test.go +782 -0
  2. platform/dbops/binaries/go/go/src/net/iprawsock.go +240 -0
  3. platform/dbops/binaries/go/go/src/net/iprawsock_plan9.go +34 -0
  4. platform/dbops/binaries/go/go/src/net/iprawsock_posix.go +159 -0
  5. platform/dbops/binaries/go/go/src/net/iprawsock_test.go +200 -0
  6. platform/dbops/binaries/go/go/src/net/ipsock.go +315 -0
  7. platform/dbops/binaries/go/go/src/net/ipsock_plan9.go +366 -0
  8. platform/dbops/binaries/go/go/src/net/ipsock_plan9_test.go +29 -0
  9. platform/dbops/binaries/go/go/src/net/ipsock_posix.go +244 -0
  10. platform/dbops/binaries/go/go/src/net/ipsock_test.go +282 -0
  11. platform/dbops/binaries/go/go/src/net/listen_test.go +750 -0
  12. platform/dbops/binaries/go/go/src/net/lookup.go +920 -0
  13. platform/dbops/binaries/go/go/src/net/lookup_plan9.go +394 -0
  14. platform/dbops/binaries/go/go/src/net/lookup_test.go +1648 -0
  15. platform/dbops/binaries/go/go/src/net/lookup_unix.go +121 -0
  16. platform/dbops/binaries/go/go/src/net/lookup_windows.go +471 -0
  17. platform/dbops/binaries/go/go/src/net/lookup_windows_test.go +340 -0
  18. platform/dbops/binaries/go/go/src/net/mac.go +86 -0
  19. platform/dbops/binaries/go/go/src/net/mac_test.go +109 -0
  20. platform/dbops/binaries/go/go/src/net/main_cloexec_test.go +27 -0
  21. platform/dbops/binaries/go/go/src/net/main_conf_test.go +59 -0
  22. platform/dbops/binaries/go/go/src/net/main_noconf_test.go +22 -0
  23. platform/dbops/binaries/go/go/src/net/main_plan9_test.go +16 -0
  24. platform/dbops/binaries/go/go/src/net/main_posix_test.go +50 -0
  25. platform/dbops/binaries/go/go/src/net/main_test.go +222 -0
  26. platform/dbops/binaries/go/go/src/net/main_unix_test.go +55 -0
  27. platform/dbops/binaries/go/go/src/net/main_wasm_test.go +13 -0
  28. platform/dbops/binaries/go/go/src/net/main_windows_test.go +42 -0
  29. platform/dbops/binaries/go/go/src/net/mockserver_test.go +508 -0
  30. platform/dbops/binaries/go/go/src/net/mptcpsock_linux.go +127 -0
  31. platform/dbops/binaries/go/go/src/net/mptcpsock_linux_test.go +192 -0
  32. platform/dbops/binaries/go/go/src/net/mptcpsock_stub.go +23 -0
  33. platform/dbops/binaries/go/go/src/net/net.go +815 -0
  34. platform/dbops/binaries/go/go/src/net/net_fake.go +1170 -0
  35. platform/dbops/binaries/go/go/src/net/net_fake_test.go +107 -0
  36. platform/dbops/binaries/go/go/src/net/net_test.go +601 -0
  37. platform/dbops/binaries/go/go/src/net/net_windows_test.go +631 -0
  38. platform/dbops/binaries/go/go/src/net/netcgo_off.go +9 -0
  39. platform/dbops/binaries/go/go/src/net/netcgo_on.go +9 -0
  40. platform/dbops/binaries/go/go/src/net/netgo_netcgo.go +14 -0
  41. platform/dbops/binaries/go/go/src/net/netgo_off.go +9 -0
  42. platform/dbops/binaries/go/go/src/net/netgo_on.go +9 -0
  43. platform/dbops/binaries/go/go/src/net/nss.go +249 -0
  44. platform/dbops/binaries/go/go/src/net/nss_test.go +172 -0
  45. platform/dbops/binaries/go/go/src/net/packetconn_test.go +149 -0
  46. platform/dbops/binaries/go/go/src/net/parse.go +283 -0
  47. platform/dbops/binaries/go/go/src/net/parse_test.go +74 -0
  48. platform/dbops/binaries/go/go/src/net/pipe.go +238 -0
  49. platform/dbops/binaries/go/go/src/net/pipe_test.go +49 -0
  50. platform/dbops/binaries/go/go/src/net/platform_test.go +178 -0
platform/dbops/binaries/go/go/src/net/ip_test.go ADDED
@@ -0,0 +1,782 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "bytes"
9
+ "math/rand"
10
+ "reflect"
11
+ "runtime"
12
+ "testing"
13
+ )
14
+
15
+ var parseIPTests = []struct {
16
+ in string
17
+ out IP
18
+ }{
19
+ {"127.0.1.2", IPv4(127, 0, 1, 2)},
20
+ {"127.0.0.1", IPv4(127, 0, 0, 1)},
21
+ {"::ffff:127.1.2.3", IPv4(127, 1, 2, 3)},
22
+ {"::ffff:7f01:0203", IPv4(127, 1, 2, 3)},
23
+ {"0:0:0:0:0000:ffff:127.1.2.3", IPv4(127, 1, 2, 3)},
24
+ {"0:0:0:0:000000:ffff:127.1.2.3", IPv4(127, 1, 2, 3)},
25
+ {"0:0:0:0::ffff:127.1.2.3", IPv4(127, 1, 2, 3)},
26
+
27
+ {"2001:4860:0:2001::68", IP{0x20, 0x01, 0x48, 0x60, 0, 0, 0x20, 0x01, 0, 0, 0, 0, 0, 0, 0x00, 0x68}},
28
+ {"2001:4860:0000:2001:0000:0000:0000:0068", IP{0x20, 0x01, 0x48, 0x60, 0, 0, 0x20, 0x01, 0, 0, 0, 0, 0, 0, 0x00, 0x68}},
29
+
30
+ {"-0.0.0.0", nil},
31
+ {"0.-1.0.0", nil},
32
+ {"0.0.-2.0", nil},
33
+ {"0.0.0.-3", nil},
34
+ {"127.0.0.256", nil},
35
+ {"abc", nil},
36
+ {"123:", nil},
37
+ {"fe80::1%lo0", nil},
38
+ {"fe80::1%911", nil},
39
+ {"", nil},
40
+ {"a1:a2:a3:a4::b1:b2:b3:b4", nil}, // Issue 6628
41
+ {"127.001.002.003", nil},
42
+ {"::ffff:127.001.002.003", nil},
43
+ {"123.000.000.000", nil},
44
+ {"1.2..4", nil},
45
+ {"0123.0.0.1", nil},
46
+ }
47
+
48
+ func TestParseIP(t *testing.T) {
49
+ for _, tt := range parseIPTests {
50
+ if out := ParseIP(tt.in); !reflect.DeepEqual(out, tt.out) {
51
+ t.Errorf("ParseIP(%q) = %v, want %v", tt.in, out, tt.out)
52
+ }
53
+ if tt.in == "" {
54
+ // Tested in TestMarshalEmptyIP below.
55
+ continue
56
+ }
57
+ var out IP
58
+ if err := out.UnmarshalText([]byte(tt.in)); !reflect.DeepEqual(out, tt.out) || (tt.out == nil) != (err != nil) {
59
+ t.Errorf("IP.UnmarshalText(%q) = %v, %v, want %v", tt.in, out, err, tt.out)
60
+ }
61
+ }
62
+ }
63
+
64
+ func TestLookupWithIP(t *testing.T) {
65
+ _, err := LookupIP("")
66
+ if err == nil {
67
+ t.Errorf(`LookupIP("") succeeded, should fail`)
68
+ }
69
+ _, err = LookupHost("")
70
+ if err == nil {
71
+ t.Errorf(`LookupIP("") succeeded, should fail`)
72
+ }
73
+
74
+ // Test that LookupHost and LookupIP, which normally
75
+ // expect host names, work with IP addresses.
76
+ for _, tt := range parseIPTests {
77
+ if tt.out != nil {
78
+ addrs, err := LookupHost(tt.in)
79
+ if len(addrs) != 1 || addrs[0] != tt.in || err != nil {
80
+ t.Errorf("LookupHost(%q) = %v, %v, want %v, nil", tt.in, addrs, err, []string{tt.in})
81
+ }
82
+ } else if !testing.Short() {
83
+ // We can't control what the host resolver does; if it can resolve, say,
84
+ // 127.0.0.256 or fe80::1%911 or a host named 'abc', who are we to judge?
85
+ // Warn about these discrepancies but don't fail the test.
86
+ addrs, err := LookupHost(tt.in)
87
+ if err == nil {
88
+ t.Logf("warning: LookupHost(%q) = %v, want error", tt.in, addrs)
89
+ }
90
+ }
91
+
92
+ if tt.out != nil {
93
+ ips, err := LookupIP(tt.in)
94
+ if len(ips) != 1 || !reflect.DeepEqual(ips[0], tt.out) || err != nil {
95
+ t.Errorf("LookupIP(%q) = %v, %v, want %v, nil", tt.in, ips, err, []IP{tt.out})
96
+ }
97
+ } else if !testing.Short() {
98
+ ips, err := LookupIP(tt.in)
99
+ // We can't control what the host resolver does. See above.
100
+ if err == nil {
101
+ t.Logf("warning: LookupIP(%q) = %v, want error", tt.in, ips)
102
+ }
103
+ }
104
+ }
105
+ }
106
+
107
+ func BenchmarkParseIP(b *testing.B) {
108
+ testHookUninstaller.Do(uninstallTestHooks)
109
+
110
+ for i := 0; i < b.N; i++ {
111
+ for _, tt := range parseIPTests {
112
+ ParseIP(tt.in)
113
+ }
114
+ }
115
+ }
116
+
117
+ func BenchmarkParseIPValidIPv4(b *testing.B) {
118
+ testHookUninstaller.Do(uninstallTestHooks)
119
+
120
+ for i := 0; i < b.N; i++ {
121
+ ParseIP("192.0.2.1")
122
+ }
123
+ }
124
+
125
+ func BenchmarkParseIPValidIPv6(b *testing.B) {
126
+ testHookUninstaller.Do(uninstallTestHooks)
127
+
128
+ for i := 0; i < b.N; i++ {
129
+ ParseIP("2001:DB8::1")
130
+ }
131
+ }
132
+
133
+ // Issue 6339
134
+ func TestMarshalEmptyIP(t *testing.T) {
135
+ for _, in := range [][]byte{nil, []byte("")} {
136
+ var out = IP{1, 2, 3, 4}
137
+ if err := out.UnmarshalText(in); err != nil || out != nil {
138
+ t.Errorf("UnmarshalText(%v) = %v, %v; want nil, nil", in, out, err)
139
+ }
140
+ }
141
+ var ip IP
142
+ got, err := ip.MarshalText()
143
+ if err != nil {
144
+ t.Fatal(err)
145
+ }
146
+ if !reflect.DeepEqual(got, []byte("")) {
147
+ t.Errorf(`got %#v, want []byte("")`, got)
148
+ }
149
+ }
150
+
151
+ var ipStringTests = []*struct {
152
+ in IP // see RFC 791 and RFC 4291
153
+ str string // see RFC 791, RFC 4291 and RFC 5952
154
+ byt []byte
155
+ error
156
+ }{
157
+ // IPv4 address
158
+ {
159
+ IP{192, 0, 2, 1},
160
+ "192.0.2.1",
161
+ []byte("192.0.2.1"),
162
+ nil,
163
+ },
164
+ {
165
+ IP{0, 0, 0, 0},
166
+ "0.0.0.0",
167
+ []byte("0.0.0.0"),
168
+ nil,
169
+ },
170
+
171
+ // IPv4-mapped IPv6 address
172
+ {
173
+ IP{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 192, 0, 2, 1},
174
+ "192.0.2.1",
175
+ []byte("192.0.2.1"),
176
+ nil,
177
+ },
178
+ {
179
+ IP{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 0, 0, 0, 0},
180
+ "0.0.0.0",
181
+ []byte("0.0.0.0"),
182
+ nil,
183
+ },
184
+
185
+ // IPv6 address
186
+ {
187
+ IP{0x20, 0x1, 0xd, 0xb8, 0, 0, 0, 0, 0, 0, 0x1, 0x23, 0, 0x12, 0, 0x1},
188
+ "2001:db8::123:12:1",
189
+ []byte("2001:db8::123:12:1"),
190
+ nil,
191
+ },
192
+ {
193
+ IP{0x20, 0x1, 0xd, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x1},
194
+ "2001:db8::1",
195
+ []byte("2001:db8::1"),
196
+ nil,
197
+ },
198
+ {
199
+ IP{0x20, 0x1, 0xd, 0xb8, 0, 0, 0, 0x1, 0, 0, 0, 0x1, 0, 0, 0, 0x1},
200
+ "2001:db8:0:1:0:1:0:1",
201
+ []byte("2001:db8:0:1:0:1:0:1"),
202
+ nil,
203
+ },
204
+ {
205
+ IP{0x20, 0x1, 0xd, 0xb8, 0, 0x1, 0, 0, 0, 0x1, 0, 0, 0, 0x1, 0, 0},
206
+ "2001:db8:1:0:1:0:1:0",
207
+ []byte("2001:db8:1:0:1:0:1:0"),
208
+ nil,
209
+ },
210
+ {
211
+ IP{0x20, 0x1, 0, 0, 0, 0, 0, 0, 0, 0x1, 0, 0, 0, 0, 0, 0x1},
212
+ "2001::1:0:0:1",
213
+ []byte("2001::1:0:0:1"),
214
+ nil,
215
+ },
216
+ {
217
+ IP{0x20, 0x1, 0xd, 0xb8, 0, 0, 0, 0, 0, 0x1, 0, 0, 0, 0, 0, 0},
218
+ "2001:db8:0:0:1::",
219
+ []byte("2001:db8:0:0:1::"),
220
+ nil,
221
+ },
222
+ {
223
+ IP{0x20, 0x1, 0xd, 0xb8, 0, 0, 0, 0, 0, 0x1, 0, 0, 0, 0, 0, 0x1},
224
+ "2001:db8::1:0:0:1",
225
+ []byte("2001:db8::1:0:0:1"),
226
+ nil,
227
+ },
228
+ {
229
+ IP{0x20, 0x1, 0xd, 0xb8, 0, 0, 0, 0, 0, 0xa, 0, 0xb, 0, 0xc, 0, 0xd},
230
+ "2001:db8::a:b:c:d",
231
+ []byte("2001:db8::a:b:c:d"),
232
+ nil,
233
+ },
234
+ {
235
+ IPv6unspecified,
236
+ "::",
237
+ []byte("::"),
238
+ nil,
239
+ },
240
+
241
+ // IP wildcard equivalent address in Dial/Listen API
242
+ {
243
+ nil,
244
+ "<nil>",
245
+ nil,
246
+ nil,
247
+ },
248
+
249
+ // Opaque byte sequence
250
+ {
251
+ IP{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef},
252
+ "?0123456789abcdef",
253
+ nil,
254
+ &AddrError{Err: "invalid IP address", Addr: "0123456789abcdef"},
255
+ },
256
+ }
257
+
258
+ func TestIPString(t *testing.T) {
259
+ for _, tt := range ipStringTests {
260
+ if out := tt.in.String(); out != tt.str {
261
+ t.Errorf("IP.String(%v) = %q, want %q", tt.in, out, tt.str)
262
+ }
263
+ if out, err := tt.in.MarshalText(); !bytes.Equal(out, tt.byt) || !reflect.DeepEqual(err, tt.error) {
264
+ t.Errorf("IP.MarshalText(%v) = %v, %v, want %v, %v", tt.in, out, err, tt.byt, tt.error)
265
+ }
266
+ }
267
+ }
268
+
269
+ var sink string
270
+
271
+ func BenchmarkIPString(b *testing.B) {
272
+ testHookUninstaller.Do(uninstallTestHooks)
273
+
274
+ b.Run("IPv4", func(b *testing.B) {
275
+ benchmarkIPString(b, IPv4len)
276
+ })
277
+
278
+ b.Run("IPv6", func(b *testing.B) {
279
+ benchmarkIPString(b, IPv6len)
280
+ })
281
+ }
282
+
283
+ func benchmarkIPString(b *testing.B, size int) {
284
+ b.ReportAllocs()
285
+ b.ResetTimer()
286
+ for i := 0; i < b.N; i++ {
287
+ for _, tt := range ipStringTests {
288
+ if tt.in != nil && len(tt.in) == size {
289
+ sink = tt.in.String()
290
+ }
291
+ }
292
+ }
293
+ }
294
+
295
+ var ipMaskTests = []struct {
296
+ in IP
297
+ mask IPMask
298
+ out IP
299
+ }{
300
+ {IPv4(192, 168, 1, 127), IPv4Mask(255, 255, 255, 128), IPv4(192, 168, 1, 0)},
301
+ {IPv4(192, 168, 1, 127), IPMask(ParseIP("255.255.255.192")), IPv4(192, 168, 1, 64)},
302
+ {IPv4(192, 168, 1, 127), IPMask(ParseIP("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffe0")), IPv4(192, 168, 1, 96)},
303
+ {IPv4(192, 168, 1, 127), IPv4Mask(255, 0, 255, 0), IPv4(192, 0, 1, 0)},
304
+ {ParseIP("2001:db8::1"), IPMask(ParseIP("ffff:ff80::")), ParseIP("2001:d80::")},
305
+ {ParseIP("2001:db8::1"), IPMask(ParseIP("f0f0:0f0f::")), ParseIP("2000:d08::")},
306
+ }
307
+
308
+ func TestIPMask(t *testing.T) {
309
+ for _, tt := range ipMaskTests {
310
+ if out := tt.in.Mask(tt.mask); out == nil || !tt.out.Equal(out) {
311
+ t.Errorf("IP(%v).Mask(%v) = %v, want %v", tt.in, tt.mask, out, tt.out)
312
+ }
313
+ }
314
+ }
315
+
316
+ var ipMaskStringTests = []struct {
317
+ in IPMask
318
+ out string
319
+ }{
320
+ {IPv4Mask(255, 255, 255, 240), "fffffff0"},
321
+ {IPv4Mask(255, 0, 128, 0), "ff008000"},
322
+ {IPMask(ParseIP("ffff:ff80::")), "ffffff80000000000000000000000000"},
323
+ {IPMask(ParseIP("ef00:ff80::cafe:0")), "ef00ff800000000000000000cafe0000"},
324
+ {nil, "<nil>"},
325
+ }
326
+
327
+ func TestIPMaskString(t *testing.T) {
328
+ for _, tt := range ipMaskStringTests {
329
+ if out := tt.in.String(); out != tt.out {
330
+ t.Errorf("IPMask.String(%v) = %q, want %q", tt.in, out, tt.out)
331
+ }
332
+ }
333
+ }
334
+
335
+ func BenchmarkIPMaskString(b *testing.B) {
336
+ testHookUninstaller.Do(uninstallTestHooks)
337
+
338
+ for i := 0; i < b.N; i++ {
339
+ for _, tt := range ipMaskStringTests {
340
+ sink = tt.in.String()
341
+ }
342
+ }
343
+ }
344
+
345
+ var parseCIDRTests = []struct {
346
+ in string
347
+ ip IP
348
+ net *IPNet
349
+ err error
350
+ }{
351
+ {"135.104.0.0/32", IPv4(135, 104, 0, 0), &IPNet{IP: IPv4(135, 104, 0, 0), Mask: IPv4Mask(255, 255, 255, 255)}, nil},
352
+ {"0.0.0.0/24", IPv4(0, 0, 0, 0), &IPNet{IP: IPv4(0, 0, 0, 0), Mask: IPv4Mask(255, 255, 255, 0)}, nil},
353
+ {"135.104.0.0/24", IPv4(135, 104, 0, 0), &IPNet{IP: IPv4(135, 104, 0, 0), Mask: IPv4Mask(255, 255, 255, 0)}, nil},
354
+ {"135.104.0.1/32", IPv4(135, 104, 0, 1), &IPNet{IP: IPv4(135, 104, 0, 1), Mask: IPv4Mask(255, 255, 255, 255)}, nil},
355
+ {"135.104.0.1/24", IPv4(135, 104, 0, 1), &IPNet{IP: IPv4(135, 104, 0, 0), Mask: IPv4Mask(255, 255, 255, 0)}, nil},
356
+ {"::1/128", ParseIP("::1"), &IPNet{IP: ParseIP("::1"), Mask: IPMask(ParseIP("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"))}, nil},
357
+ {"abcd:2345::/127", ParseIP("abcd:2345::"), &IPNet{IP: ParseIP("abcd:2345::"), Mask: IPMask(ParseIP("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffe"))}, nil},
358
+ {"abcd:2345::/65", ParseIP("abcd:2345::"), &IPNet{IP: ParseIP("abcd:2345::"), Mask: IPMask(ParseIP("ffff:ffff:ffff:ffff:8000::"))}, nil},
359
+ {"abcd:2345::/64", ParseIP("abcd:2345::"), &IPNet{IP: ParseIP("abcd:2345::"), Mask: IPMask(ParseIP("ffff:ffff:ffff:ffff::"))}, nil},
360
+ {"abcd:2345::/63", ParseIP("abcd:2345::"), &IPNet{IP: ParseIP("abcd:2345::"), Mask: IPMask(ParseIP("ffff:ffff:ffff:fffe::"))}, nil},
361
+ {"abcd:2345::/33", ParseIP("abcd:2345::"), &IPNet{IP: ParseIP("abcd:2345::"), Mask: IPMask(ParseIP("ffff:ffff:8000::"))}, nil},
362
+ {"abcd:2345::/32", ParseIP("abcd:2345::"), &IPNet{IP: ParseIP("abcd:2345::"), Mask: IPMask(ParseIP("ffff:ffff::"))}, nil},
363
+ {"abcd:2344::/31", ParseIP("abcd:2344::"), &IPNet{IP: ParseIP("abcd:2344::"), Mask: IPMask(ParseIP("ffff:fffe::"))}, nil},
364
+ {"abcd:2300::/24", ParseIP("abcd:2300::"), &IPNet{IP: ParseIP("abcd:2300::"), Mask: IPMask(ParseIP("ffff:ff00::"))}, nil},
365
+ {"abcd:2345::/24", ParseIP("abcd:2345::"), &IPNet{IP: ParseIP("abcd:2300::"), Mask: IPMask(ParseIP("ffff:ff00::"))}, nil},
366
+ {"2001:DB8::/48", ParseIP("2001:DB8::"), &IPNet{IP: ParseIP("2001:DB8::"), Mask: IPMask(ParseIP("ffff:ffff:ffff::"))}, nil},
367
+ {"2001:DB8::1/48", ParseIP("2001:DB8::1"), &IPNet{IP: ParseIP("2001:DB8::"), Mask: IPMask(ParseIP("ffff:ffff:ffff::"))}, nil},
368
+ {"192.168.1.1/255.255.255.0", nil, nil, &ParseError{Type: "CIDR address", Text: "192.168.1.1/255.255.255.0"}},
369
+ {"192.168.1.1/35", nil, nil, &ParseError{Type: "CIDR address", Text: "192.168.1.1/35"}},
370
+ {"2001:db8::1/-1", nil, nil, &ParseError{Type: "CIDR address", Text: "2001:db8::1/-1"}},
371
+ {"2001:db8::1/-0", nil, nil, &ParseError{Type: "CIDR address", Text: "2001:db8::1/-0"}},
372
+ {"-0.0.0.0/32", nil, nil, &ParseError{Type: "CIDR address", Text: "-0.0.0.0/32"}},
373
+ {"0.-1.0.0/32", nil, nil, &ParseError{Type: "CIDR address", Text: "0.-1.0.0/32"}},
374
+ {"0.0.-2.0/32", nil, nil, &ParseError{Type: "CIDR address", Text: "0.0.-2.0/32"}},
375
+ {"0.0.0.-3/32", nil, nil, &ParseError{Type: "CIDR address", Text: "0.0.0.-3/32"}},
376
+ {"0.0.0.0/-0", nil, nil, &ParseError{Type: "CIDR address", Text: "0.0.0.0/-0"}},
377
+ {"127.000.000.001/32", nil, nil, &ParseError{Type: "CIDR address", Text: "127.000.000.001/32"}},
378
+ {"", nil, nil, &ParseError{Type: "CIDR address", Text: ""}},
379
+ }
380
+
381
+ func TestParseCIDR(t *testing.T) {
382
+ for _, tt := range parseCIDRTests {
383
+ ip, net, err := ParseCIDR(tt.in)
384
+ if !reflect.DeepEqual(err, tt.err) {
385
+ t.Errorf("ParseCIDR(%q) = %v, %v; want %v, %v", tt.in, ip, net, tt.ip, tt.net)
386
+ }
387
+ if err == nil && (!tt.ip.Equal(ip) || !tt.net.IP.Equal(net.IP) || !reflect.DeepEqual(net.Mask, tt.net.Mask)) {
388
+ t.Errorf("ParseCIDR(%q) = %v, {%v, %v}; want %v, {%v, %v}", tt.in, ip, net.IP, net.Mask, tt.ip, tt.net.IP, tt.net.Mask)
389
+ }
390
+ }
391
+ }
392
+
393
+ var ipNetContainsTests = []struct {
394
+ ip IP
395
+ net *IPNet
396
+ ok bool
397
+ }{
398
+ {IPv4(172, 16, 1, 1), &IPNet{IP: IPv4(172, 16, 0, 0), Mask: CIDRMask(12, 32)}, true},
399
+ {IPv4(172, 24, 0, 1), &IPNet{IP: IPv4(172, 16, 0, 0), Mask: CIDRMask(13, 32)}, false},
400
+ {IPv4(192, 168, 0, 3), &IPNet{IP: IPv4(192, 168, 0, 0), Mask: IPv4Mask(0, 0, 255, 252)}, true},
401
+ {IPv4(192, 168, 0, 4), &IPNet{IP: IPv4(192, 168, 0, 0), Mask: IPv4Mask(0, 255, 0, 252)}, false},
402
+ {ParseIP("2001:db8:1:2::1"), &IPNet{IP: ParseIP("2001:db8:1::"), Mask: CIDRMask(47, 128)}, true},
403
+ {ParseIP("2001:db8:1:2::1"), &IPNet{IP: ParseIP("2001:db8:2::"), Mask: CIDRMask(47, 128)}, false},
404
+ {ParseIP("2001:db8:1:2::1"), &IPNet{IP: ParseIP("2001:db8:1::"), Mask: IPMask(ParseIP("ffff:0:ffff::"))}, true},
405
+ {ParseIP("2001:db8:1:2::1"), &IPNet{IP: ParseIP("2001:db8:1::"), Mask: IPMask(ParseIP("0:0:0:ffff::"))}, false},
406
+ }
407
+
408
+ func TestIPNetContains(t *testing.T) {
409
+ for _, tt := range ipNetContainsTests {
410
+ if ok := tt.net.Contains(tt.ip); ok != tt.ok {
411
+ t.Errorf("IPNet(%v).Contains(%v) = %v, want %v", tt.net, tt.ip, ok, tt.ok)
412
+ }
413
+ }
414
+ }
415
+
416
+ var ipNetStringTests = []struct {
417
+ in *IPNet
418
+ out string
419
+ }{
420
+ {&IPNet{IP: IPv4(192, 168, 1, 0), Mask: CIDRMask(26, 32)}, "192.168.1.0/26"},
421
+ {&IPNet{IP: IPv4(192, 168, 1, 0), Mask: IPv4Mask(255, 0, 255, 0)}, "192.168.1.0/ff00ff00"},
422
+ {&IPNet{IP: ParseIP("2001:db8::"), Mask: CIDRMask(55, 128)}, "2001:db8::/55"},
423
+ {&IPNet{IP: ParseIP("2001:db8::"), Mask: IPMask(ParseIP("8000:f123:0:cafe::"))}, "2001:db8::/8000f1230000cafe0000000000000000"},
424
+ {nil, "<nil>"},
425
+ }
426
+
427
+ func TestIPNetString(t *testing.T) {
428
+ for _, tt := range ipNetStringTests {
429
+ if out := tt.in.String(); out != tt.out {
430
+ t.Errorf("IPNet.String(%v) = %q, want %q", tt.in, out, tt.out)
431
+ }
432
+ }
433
+ }
434
+
435
+ var cidrMaskTests = []struct {
436
+ ones int
437
+ bits int
438
+ out IPMask
439
+ }{
440
+ {0, 32, IPv4Mask(0, 0, 0, 0)},
441
+ {12, 32, IPv4Mask(255, 240, 0, 0)},
442
+ {24, 32, IPv4Mask(255, 255, 255, 0)},
443
+ {32, 32, IPv4Mask(255, 255, 255, 255)},
444
+ {0, 128, IPMask{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}},
445
+ {4, 128, IPMask{0xf0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}},
446
+ {48, 128, IPMask{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}},
447
+ {128, 128, IPMask{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}},
448
+ {33, 32, nil},
449
+ {32, 33, nil},
450
+ {-1, 128, nil},
451
+ {128, -1, nil},
452
+ }
453
+
454
+ func TestCIDRMask(t *testing.T) {
455
+ for _, tt := range cidrMaskTests {
456
+ if out := CIDRMask(tt.ones, tt.bits); !reflect.DeepEqual(out, tt.out) {
457
+ t.Errorf("CIDRMask(%v, %v) = %v, want %v", tt.ones, tt.bits, out, tt.out)
458
+ }
459
+ }
460
+ }
461
+
462
+ var (
463
+ v4addr = IP{192, 168, 0, 1}
464
+ v4mappedv6addr = IP{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 192, 168, 0, 1}
465
+ v6addr = IP{0x20, 0x1, 0xd, 0xb8, 0, 0, 0, 0, 0, 0, 0x1, 0x23, 0, 0x12, 0, 0x1}
466
+ v4mask = IPMask{255, 255, 255, 0}
467
+ v4mappedv6mask = IPMask{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 255, 255, 255, 0}
468
+ v6mask = IPMask{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0, 0, 0, 0, 0, 0, 0, 0}
469
+ badaddr = IP{192, 168, 0}
470
+ badmask = IPMask{255, 255, 0}
471
+ v4maskzero = IPMask{0, 0, 0, 0}
472
+ )
473
+
474
+ var networkNumberAndMaskTests = []struct {
475
+ in IPNet
476
+ out IPNet
477
+ }{
478
+ {IPNet{IP: v4addr, Mask: v4mask}, IPNet{IP: v4addr, Mask: v4mask}},
479
+ {IPNet{IP: v4addr, Mask: v4mappedv6mask}, IPNet{IP: v4addr, Mask: v4mask}},
480
+ {IPNet{IP: v4mappedv6addr, Mask: v4mappedv6mask}, IPNet{IP: v4addr, Mask: v4mask}},
481
+ {IPNet{IP: v4mappedv6addr, Mask: v6mask}, IPNet{IP: v4addr, Mask: v4maskzero}},
482
+ {IPNet{IP: v4addr, Mask: v6mask}, IPNet{IP: v4addr, Mask: v4maskzero}},
483
+ {IPNet{IP: v6addr, Mask: v6mask}, IPNet{IP: v6addr, Mask: v6mask}},
484
+ {IPNet{IP: v6addr, Mask: v4mappedv6mask}, IPNet{IP: v6addr, Mask: v4mappedv6mask}},
485
+ {in: IPNet{IP: v6addr, Mask: v4mask}},
486
+ {in: IPNet{IP: v4addr, Mask: badmask}},
487
+ {in: IPNet{IP: v4mappedv6addr, Mask: badmask}},
488
+ {in: IPNet{IP: v6addr, Mask: badmask}},
489
+ {in: IPNet{IP: badaddr, Mask: v4mask}},
490
+ {in: IPNet{IP: badaddr, Mask: v4mappedv6mask}},
491
+ {in: IPNet{IP: badaddr, Mask: v6mask}},
492
+ {in: IPNet{IP: badaddr, Mask: badmask}},
493
+ }
494
+
495
+ func TestNetworkNumberAndMask(t *testing.T) {
496
+ for _, tt := range networkNumberAndMaskTests {
497
+ ip, m := networkNumberAndMask(&tt.in)
498
+ out := &IPNet{IP: ip, Mask: m}
499
+ if !reflect.DeepEqual(&tt.out, out) {
500
+ t.Errorf("networkNumberAndMask(%v) = %v, want %v", tt.in, out, &tt.out)
501
+ }
502
+ }
503
+ }
504
+
505
+ func TestSplitHostPort(t *testing.T) {
506
+ for _, tt := range []struct {
507
+ hostPort string
508
+ host string
509
+ port string
510
+ }{
511
+ // Host name
512
+ {"localhost:http", "localhost", "http"},
513
+ {"localhost:80", "localhost", "80"},
514
+
515
+ // Go-specific host name with zone identifier
516
+ {"localhost%lo0:http", "localhost%lo0", "http"},
517
+ {"localhost%lo0:80", "localhost%lo0", "80"},
518
+ {"[localhost%lo0]:http", "localhost%lo0", "http"}, // Go 1 behavior
519
+ {"[localhost%lo0]:80", "localhost%lo0", "80"}, // Go 1 behavior
520
+
521
+ // IP literal
522
+ {"127.0.0.1:http", "127.0.0.1", "http"},
523
+ {"127.0.0.1:80", "127.0.0.1", "80"},
524
+ {"[::1]:http", "::1", "http"},
525
+ {"[::1]:80", "::1", "80"},
526
+
527
+ // IP literal with zone identifier
528
+ {"[::1%lo0]:http", "::1%lo0", "http"},
529
+ {"[::1%lo0]:80", "::1%lo0", "80"},
530
+
531
+ // Go-specific wildcard for host name
532
+ {":http", "", "http"}, // Go 1 behavior
533
+ {":80", "", "80"}, // Go 1 behavior
534
+
535
+ // Go-specific wildcard for service name or transport port number
536
+ {"golang.org:", "golang.org", ""}, // Go 1 behavior
537
+ {"127.0.0.1:", "127.0.0.1", ""}, // Go 1 behavior
538
+ {"[::1]:", "::1", ""}, // Go 1 behavior
539
+
540
+ // Opaque service name
541
+ {"golang.org:https%foo", "golang.org", "https%foo"}, // Go 1 behavior
542
+ } {
543
+ if host, port, err := SplitHostPort(tt.hostPort); host != tt.host || port != tt.port || err != nil {
544
+ t.Errorf("SplitHostPort(%q) = %q, %q, %v; want %q, %q, nil", tt.hostPort, host, port, err, tt.host, tt.port)
545
+ }
546
+ }
547
+
548
+ for _, tt := range []struct {
549
+ hostPort string
550
+ err string
551
+ }{
552
+ {"golang.org", "missing port in address"},
553
+ {"127.0.0.1", "missing port in address"},
554
+ {"[::1]", "missing port in address"},
555
+ {"[fe80::1%lo0]", "missing port in address"},
556
+ {"[localhost%lo0]", "missing port in address"},
557
+ {"localhost%lo0", "missing port in address"},
558
+
559
+ {"::1", "too many colons in address"},
560
+ {"fe80::1%lo0", "too many colons in address"},
561
+ {"fe80::1%lo0:80", "too many colons in address"},
562
+
563
+ // Test cases that didn't fail in Go 1
564
+
565
+ {"[foo:bar]", "missing port in address"},
566
+ {"[foo:bar]baz", "missing port in address"},
567
+ {"[foo]bar:baz", "missing port in address"},
568
+
569
+ {"[foo]:[bar]:baz", "too many colons in address"},
570
+
571
+ {"[foo]:[bar]baz", "unexpected '[' in address"},
572
+ {"foo[bar]:baz", "unexpected '[' in address"},
573
+
574
+ {"foo]bar:baz", "unexpected ']' in address"},
575
+ } {
576
+ if host, port, err := SplitHostPort(tt.hostPort); err == nil {
577
+ t.Errorf("SplitHostPort(%q) should have failed", tt.hostPort)
578
+ } else {
579
+ e := err.(*AddrError)
580
+ if e.Err != tt.err {
581
+ t.Errorf("SplitHostPort(%q) = _, _, %q; want %q", tt.hostPort, e.Err, tt.err)
582
+ }
583
+ if host != "" || port != "" {
584
+ t.Errorf("SplitHostPort(%q) = %q, %q, err; want %q, %q, err on failure", tt.hostPort, host, port, "", "")
585
+ }
586
+ }
587
+ }
588
+ }
589
+
590
+ func TestJoinHostPort(t *testing.T) {
591
+ for _, tt := range []struct {
592
+ host string
593
+ port string
594
+ hostPort string
595
+ }{
596
+ // Host name
597
+ {"localhost", "http", "localhost:http"},
598
+ {"localhost", "80", "localhost:80"},
599
+
600
+ // Go-specific host name with zone identifier
601
+ {"localhost%lo0", "http", "localhost%lo0:http"},
602
+ {"localhost%lo0", "80", "localhost%lo0:80"},
603
+
604
+ // IP literal
605
+ {"127.0.0.1", "http", "127.0.0.1:http"},
606
+ {"127.0.0.1", "80", "127.0.0.1:80"},
607
+ {"::1", "http", "[::1]:http"},
608
+ {"::1", "80", "[::1]:80"},
609
+
610
+ // IP literal with zone identifier
611
+ {"::1%lo0", "http", "[::1%lo0]:http"},
612
+ {"::1%lo0", "80", "[::1%lo0]:80"},
613
+
614
+ // Go-specific wildcard for host name
615
+ {"", "http", ":http"}, // Go 1 behavior
616
+ {"", "80", ":80"}, // Go 1 behavior
617
+
618
+ // Go-specific wildcard for service name or transport port number
619
+ {"golang.org", "", "golang.org:"}, // Go 1 behavior
620
+ {"127.0.0.1", "", "127.0.0.1:"}, // Go 1 behavior
621
+ {"::1", "", "[::1]:"}, // Go 1 behavior
622
+
623
+ // Opaque service name
624
+ {"golang.org", "https%foo", "golang.org:https%foo"}, // Go 1 behavior
625
+ } {
626
+ if hostPort := JoinHostPort(tt.host, tt.port); hostPort != tt.hostPort {
627
+ t.Errorf("JoinHostPort(%q, %q) = %q; want %q", tt.host, tt.port, hostPort, tt.hostPort)
628
+ }
629
+ }
630
+ }
631
+
632
+ var ipAddrFamilyTests = []struct {
633
+ in IP
634
+ af4 bool
635
+ af6 bool
636
+ }{
637
+ {IPv4bcast, true, false},
638
+ {IPv4allsys, true, false},
639
+ {IPv4allrouter, true, false},
640
+ {IPv4zero, true, false},
641
+ {IPv4(224, 0, 0, 1), true, false},
642
+ {IPv4(127, 0, 0, 1), true, false},
643
+ {IPv4(240, 0, 0, 1), true, false},
644
+ {IPv6unspecified, false, true},
645
+ {IPv6loopback, false, true},
646
+ {IPv6interfacelocalallnodes, false, true},
647
+ {IPv6linklocalallnodes, false, true},
648
+ {IPv6linklocalallrouters, false, true},
649
+ {ParseIP("ff05::a:b:c:d"), false, true},
650
+ {ParseIP("fe80::1:2:3:4"), false, true},
651
+ {ParseIP("2001:db8::123:12:1"), false, true},
652
+ }
653
+
654
+ func TestIPAddrFamily(t *testing.T) {
655
+ for _, tt := range ipAddrFamilyTests {
656
+ if af := tt.in.To4() != nil; af != tt.af4 {
657
+ t.Errorf("verifying IPv4 address family for %q = %v, want %v", tt.in, af, tt.af4)
658
+ }
659
+ if af := len(tt.in) == IPv6len && tt.in.To4() == nil; af != tt.af6 {
660
+ t.Errorf("verifying IPv6 address family for %q = %v, want %v", tt.in, af, tt.af6)
661
+ }
662
+ }
663
+ }
664
+
665
+ var ipAddrScopeTests = []struct {
666
+ scope func(IP) bool
667
+ in IP
668
+ ok bool
669
+ }{
670
+ {IP.IsUnspecified, IPv4zero, true},
671
+ {IP.IsUnspecified, IPv4(127, 0, 0, 1), false},
672
+ {IP.IsUnspecified, IPv6unspecified, true},
673
+ {IP.IsUnspecified, IPv6interfacelocalallnodes, false},
674
+ {IP.IsUnspecified, nil, false},
675
+ {IP.IsLoopback, IPv4(127, 0, 0, 1), true},
676
+ {IP.IsLoopback, IPv4(127, 255, 255, 254), true},
677
+ {IP.IsLoopback, IPv4(128, 1, 2, 3), false},
678
+ {IP.IsLoopback, IPv6loopback, true},
679
+ {IP.IsLoopback, IPv6linklocalallrouters, false},
680
+ {IP.IsLoopback, nil, false},
681
+ {IP.IsMulticast, IPv4(224, 0, 0, 0), true},
682
+ {IP.IsMulticast, IPv4(239, 0, 0, 0), true},
683
+ {IP.IsMulticast, IPv4(240, 0, 0, 0), false},
684
+ {IP.IsMulticast, IPv6linklocalallnodes, true},
685
+ {IP.IsMulticast, IP{0xff, 0x05, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, true},
686
+ {IP.IsMulticast, IP{0xfe, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, false},
687
+ {IP.IsMulticast, nil, false},
688
+ {IP.IsInterfaceLocalMulticast, IPv4(224, 0, 0, 0), false},
689
+ {IP.IsInterfaceLocalMulticast, IPv4(0xff, 0x01, 0, 0), false},
690
+ {IP.IsInterfaceLocalMulticast, IPv6interfacelocalallnodes, true},
691
+ {IP.IsInterfaceLocalMulticast, nil, false},
692
+ {IP.IsLinkLocalMulticast, IPv4(224, 0, 0, 0), true},
693
+ {IP.IsLinkLocalMulticast, IPv4(239, 0, 0, 0), false},
694
+ {IP.IsLinkLocalMulticast, IPv4(0xff, 0x02, 0, 0), false},
695
+ {IP.IsLinkLocalMulticast, IPv6linklocalallrouters, true},
696
+ {IP.IsLinkLocalMulticast, IP{0xff, 0x05, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, false},
697
+ {IP.IsLinkLocalMulticast, nil, false},
698
+ {IP.IsLinkLocalUnicast, IPv4(169, 254, 0, 0), true},
699
+ {IP.IsLinkLocalUnicast, IPv4(169, 255, 0, 0), false},
700
+ {IP.IsLinkLocalUnicast, IPv4(0xfe, 0x80, 0, 0), false},
701
+ {IP.IsLinkLocalUnicast, IP{0xfe, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, true},
702
+ {IP.IsLinkLocalUnicast, IP{0xfe, 0xc0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, false},
703
+ {IP.IsLinkLocalUnicast, nil, false},
704
+ {IP.IsGlobalUnicast, IPv4(240, 0, 0, 0), true},
705
+ {IP.IsGlobalUnicast, IPv4(232, 0, 0, 0), false},
706
+ {IP.IsGlobalUnicast, IPv4(169, 254, 0, 0), false},
707
+ {IP.IsGlobalUnicast, IPv4bcast, false},
708
+ {IP.IsGlobalUnicast, IP{0x20, 0x1, 0xd, 0xb8, 0, 0, 0, 0, 0, 0, 0x1, 0x23, 0, 0x12, 0, 0x1}, true},
709
+ {IP.IsGlobalUnicast, IP{0xfe, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, false},
710
+ {IP.IsGlobalUnicast, IP{0xff, 0x05, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, false},
711
+ {IP.IsGlobalUnicast, nil, false},
712
+ {IP.IsPrivate, nil, false},
713
+ {IP.IsPrivate, IPv4(1, 1, 1, 1), false},
714
+ {IP.IsPrivate, IPv4(9, 255, 255, 255), false},
715
+ {IP.IsPrivate, IPv4(10, 0, 0, 0), true},
716
+ {IP.IsPrivate, IPv4(10, 255, 255, 255), true},
717
+ {IP.IsPrivate, IPv4(11, 0, 0, 0), false},
718
+ {IP.IsPrivate, IPv4(172, 15, 255, 255), false},
719
+ {IP.IsPrivate, IPv4(172, 16, 0, 0), true},
720
+ {IP.IsPrivate, IPv4(172, 16, 255, 255), true},
721
+ {IP.IsPrivate, IPv4(172, 23, 18, 255), true},
722
+ {IP.IsPrivate, IPv4(172, 31, 255, 255), true},
723
+ {IP.IsPrivate, IPv4(172, 31, 0, 0), true},
724
+ {IP.IsPrivate, IPv4(172, 32, 0, 0), false},
725
+ {IP.IsPrivate, IPv4(192, 167, 255, 255), false},
726
+ {IP.IsPrivate, IPv4(192, 168, 0, 0), true},
727
+ {IP.IsPrivate, IPv4(192, 168, 255, 255), true},
728
+ {IP.IsPrivate, IPv4(192, 169, 0, 0), false},
729
+ {IP.IsPrivate, IP{0xfb, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, false},
730
+ {IP.IsPrivate, IP{0xfc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, true},
731
+ {IP.IsPrivate, IP{0xfc, 0xff, 0x12, 0, 0, 0, 0, 0x44, 0, 0, 0, 0, 0, 0, 0, 0}, true},
732
+ {IP.IsPrivate, IP{0xfd, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, true},
733
+ {IP.IsPrivate, IP{0xfe, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, false},
734
+ }
735
+
736
+ func name(f any) string {
737
+ return runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name()
738
+ }
739
+
740
+ func TestIPAddrScope(t *testing.T) {
741
+ for _, tt := range ipAddrScopeTests {
742
+ if ok := tt.scope(tt.in); ok != tt.ok {
743
+ t.Errorf("%s(%q) = %v, want %v", name(tt.scope), tt.in, ok, tt.ok)
744
+ }
745
+ ip := tt.in.To4()
746
+ if ip == nil {
747
+ continue
748
+ }
749
+ if ok := tt.scope(ip); ok != tt.ok {
750
+ t.Errorf("%s(%q) = %v, want %v", name(tt.scope), ip, ok, tt.ok)
751
+ }
752
+ }
753
+ }
754
+
755
+ func BenchmarkIPEqual(b *testing.B) {
756
+ b.Run("IPv4", func(b *testing.B) {
757
+ benchmarkIPEqual(b, IPv4len)
758
+ })
759
+ b.Run("IPv6", func(b *testing.B) {
760
+ benchmarkIPEqual(b, IPv6len)
761
+ })
762
+ }
763
+
764
+ func benchmarkIPEqual(b *testing.B, size int) {
765
+ ips := make([]IP, 1000)
766
+ for i := range ips {
767
+ ips[i] = make(IP, size)
768
+ rand.Read(ips[i])
769
+ }
770
+ // Half of the N are equal.
771
+ for i := 0; i < b.N/2; i++ {
772
+ x := ips[i%len(ips)]
773
+ y := ips[i%len(ips)]
774
+ x.Equal(y)
775
+ }
776
+ // The other half are not equal.
777
+ for i := 0; i < b.N/2; i++ {
778
+ x := ips[i%len(ips)]
779
+ y := ips[(i+1)%len(ips)]
780
+ x.Equal(y)
781
+ }
782
+ }
platform/dbops/binaries/go/go/src/net/iprawsock.go ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2010 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
+ "syscall"
10
+ )
11
+
12
+ // BUG(mikio): On every POSIX platform, reads from the "ip4" network
13
+ // using the ReadFrom or ReadFromIP method might not return a complete
14
+ // IPv4 packet, including its header, even if there is space
15
+ // available. This can occur even in cases where Read or ReadMsgIP
16
+ // could return a complete packet. For this reason, it is recommended
17
+ // that you do not use these methods if it is important to receive a
18
+ // full packet.
19
+ //
20
+ // The Go 1 compatibility guidelines make it impossible for us to
21
+ // change the behavior of these methods; use Read or ReadMsgIP
22
+ // instead.
23
+
24
+ // BUG(mikio): On JS and Plan 9, methods and functions related
25
+ // to IPConn are not implemented.
26
+
27
+ // BUG(mikio): On Windows, the File method of IPConn is not
28
+ // implemented.
29
+
30
+ // IPAddr represents the address of an IP end point.
31
+ type IPAddr struct {
32
+ IP IP
33
+ Zone string // IPv6 scoped addressing zone
34
+ }
35
+
36
+ // Network returns the address's network name, "ip".
37
+ func (a *IPAddr) Network() string { return "ip" }
38
+
39
+ func (a *IPAddr) String() string {
40
+ if a == nil {
41
+ return "<nil>"
42
+ }
43
+ ip := ipEmptyString(a.IP)
44
+ if a.Zone != "" {
45
+ return ip + "%" + a.Zone
46
+ }
47
+ return ip
48
+ }
49
+
50
+ func (a *IPAddr) isWildcard() bool {
51
+ if a == nil || a.IP == nil {
52
+ return true
53
+ }
54
+ return a.IP.IsUnspecified()
55
+ }
56
+
57
+ func (a *IPAddr) opAddr() Addr {
58
+ if a == nil {
59
+ return nil
60
+ }
61
+ return a
62
+ }
63
+
64
+ // ResolveIPAddr returns an address of IP end point.
65
+ //
66
+ // The network must be an IP network name.
67
+ //
68
+ // If the host in the address parameter is not a literal IP address,
69
+ // ResolveIPAddr resolves the address to an address of IP end point.
70
+ // Otherwise, it parses the address as a literal IP address.
71
+ // The address parameter can use a host name, but this is not
72
+ // recommended, because it will return at most one of the host name's
73
+ // IP addresses.
74
+ //
75
+ // See func [Dial] for a description of the network and address
76
+ // parameters.
77
+ func ResolveIPAddr(network, address string) (*IPAddr, error) {
78
+ if network == "" { // a hint wildcard for Go 1.0 undocumented behavior
79
+ network = "ip"
80
+ }
81
+ afnet, _, err := parseNetwork(context.Background(), network, false)
82
+ if err != nil {
83
+ return nil, err
84
+ }
85
+ switch afnet {
86
+ case "ip", "ip4", "ip6":
87
+ default:
88
+ return nil, UnknownNetworkError(network)
89
+ }
90
+ addrs, err := DefaultResolver.internetAddrList(context.Background(), afnet, address)
91
+ if err != nil {
92
+ return nil, err
93
+ }
94
+ return addrs.forResolve(network, address).(*IPAddr), nil
95
+ }
96
+
97
+ // IPConn is the implementation of the [Conn] and [PacketConn] interfaces
98
+ // for IP network connections.
99
+ type IPConn struct {
100
+ conn
101
+ }
102
+
103
+ // SyscallConn returns a raw network connection.
104
+ // This implements the [syscall.Conn] interface.
105
+ func (c *IPConn) SyscallConn() (syscall.RawConn, error) {
106
+ if !c.ok() {
107
+ return nil, syscall.EINVAL
108
+ }
109
+ return newRawConn(c.fd), nil
110
+ }
111
+
112
+ // ReadFromIP acts like ReadFrom but returns an IPAddr.
113
+ func (c *IPConn) ReadFromIP(b []byte) (int, *IPAddr, error) {
114
+ if !c.ok() {
115
+ return 0, nil, syscall.EINVAL
116
+ }
117
+ n, addr, err := c.readFrom(b)
118
+ if err != nil {
119
+ err = &OpError{Op: "read", Net: c.fd.net, Source: c.fd.laddr, Addr: c.fd.raddr, Err: err}
120
+ }
121
+ return n, addr, err
122
+ }
123
+
124
+ // ReadFrom implements the [PacketConn] ReadFrom method.
125
+ func (c *IPConn) ReadFrom(b []byte) (int, Addr, error) {
126
+ if !c.ok() {
127
+ return 0, nil, syscall.EINVAL
128
+ }
129
+ n, addr, err := c.readFrom(b)
130
+ if err != nil {
131
+ err = &OpError{Op: "read", Net: c.fd.net, Source: c.fd.laddr, Addr: c.fd.raddr, Err: err}
132
+ }
133
+ if addr == nil {
134
+ return n, nil, err
135
+ }
136
+ return n, addr, err
137
+ }
138
+
139
+ // ReadMsgIP reads a message from c, copying the payload into b and
140
+ // the associated out-of-band data into oob. It returns the number of
141
+ // bytes copied into b, the number of bytes copied into oob, the flags
142
+ // that were set on the message and the source address of the message.
143
+ //
144
+ // The packages golang.org/x/net/ipv4 and golang.org/x/net/ipv6 can be
145
+ // used to manipulate IP-level socket options in oob.
146
+ func (c *IPConn) ReadMsgIP(b, oob []byte) (n, oobn, flags int, addr *IPAddr, err error) {
147
+ if !c.ok() {
148
+ return 0, 0, 0, nil, syscall.EINVAL
149
+ }
150
+ n, oobn, flags, addr, err = c.readMsg(b, oob)
151
+ if err != nil {
152
+ err = &OpError{Op: "read", Net: c.fd.net, Source: c.fd.laddr, Addr: c.fd.raddr, Err: err}
153
+ }
154
+ return
155
+ }
156
+
157
+ // WriteToIP acts like [IPConn.WriteTo] but takes an [IPAddr].
158
+ func (c *IPConn) WriteToIP(b []byte, addr *IPAddr) (int, error) {
159
+ if !c.ok() {
160
+ return 0, syscall.EINVAL
161
+ }
162
+ n, err := c.writeTo(b, addr)
163
+ if err != nil {
164
+ err = &OpError{Op: "write", Net: c.fd.net, Source: c.fd.laddr, Addr: addr.opAddr(), Err: err}
165
+ }
166
+ return n, err
167
+ }
168
+
169
+ // WriteTo implements the [PacketConn] WriteTo method.
170
+ func (c *IPConn) WriteTo(b []byte, addr Addr) (int, error) {
171
+ if !c.ok() {
172
+ return 0, syscall.EINVAL
173
+ }
174
+ a, ok := addr.(*IPAddr)
175
+ if !ok {
176
+ return 0, &OpError{Op: "write", Net: c.fd.net, Source: c.fd.laddr, Addr: addr, Err: syscall.EINVAL}
177
+ }
178
+ n, err := c.writeTo(b, a)
179
+ if err != nil {
180
+ err = &OpError{Op: "write", Net: c.fd.net, Source: c.fd.laddr, Addr: a.opAddr(), Err: err}
181
+ }
182
+ return n, err
183
+ }
184
+
185
+ // WriteMsgIP writes a message to addr via c, copying the payload from
186
+ // b and the associated out-of-band data from oob. It returns the
187
+ // number of payload and out-of-band bytes written.
188
+ //
189
+ // The packages golang.org/x/net/ipv4 and golang.org/x/net/ipv6 can be
190
+ // used to manipulate IP-level socket options in oob.
191
+ func (c *IPConn) WriteMsgIP(b, oob []byte, addr *IPAddr) (n, oobn int, err error) {
192
+ if !c.ok() {
193
+ return 0, 0, syscall.EINVAL
194
+ }
195
+ n, oobn, err = c.writeMsg(b, oob, addr)
196
+ if err != nil {
197
+ err = &OpError{Op: "write", Net: c.fd.net, Source: c.fd.laddr, Addr: addr.opAddr(), Err: err}
198
+ }
199
+ return
200
+ }
201
+
202
+ func newIPConn(fd *netFD) *IPConn { return &IPConn{conn{fd}} }
203
+
204
+ // DialIP acts like [Dial] for IP networks.
205
+ //
206
+ // The network must be an IP network name; see func Dial for details.
207
+ //
208
+ // If laddr is nil, a local address is automatically chosen.
209
+ // If the IP field of raddr is nil or an unspecified IP address, the
210
+ // local system is assumed.
211
+ func DialIP(network string, laddr, raddr *IPAddr) (*IPConn, error) {
212
+ if raddr == nil {
213
+ return nil, &OpError{Op: "dial", Net: network, Source: laddr.opAddr(), Addr: nil, Err: errMissingAddress}
214
+ }
215
+ sd := &sysDialer{network: network, address: raddr.String()}
216
+ c, err := sd.dialIP(context.Background(), laddr, raddr)
217
+ if err != nil {
218
+ return nil, &OpError{Op: "dial", Net: network, Source: laddr.opAddr(), Addr: raddr.opAddr(), Err: err}
219
+ }
220
+ return c, nil
221
+ }
222
+
223
+ // ListenIP acts like [ListenPacket] for IP networks.
224
+ //
225
+ // The network must be an IP network name; see func Dial for details.
226
+ //
227
+ // If the IP field of laddr is nil or an unspecified IP address,
228
+ // ListenIP listens on all available IP addresses of the local system
229
+ // except multicast IP addresses.
230
+ func ListenIP(network string, laddr *IPAddr) (*IPConn, error) {
231
+ if laddr == nil {
232
+ laddr = &IPAddr{}
233
+ }
234
+ sl := &sysListener{network: network, address: laddr.String()}
235
+ c, err := sl.listenIP(context.Background(), laddr)
236
+ if err != nil {
237
+ return nil, &OpError{Op: "listen", Net: network, Source: nil, Addr: laddr.opAddr(), Err: err}
238
+ }
239
+ return c, nil
240
+ }
platform/dbops/binaries/go/go/src/net/iprawsock_plan9.go ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2010 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
+ "syscall"
10
+ )
11
+
12
+ func (c *IPConn) readFrom(b []byte) (int, *IPAddr, error) {
13
+ return 0, nil, syscall.EPLAN9
14
+ }
15
+
16
+ func (c *IPConn) readMsg(b, oob []byte) (n, oobn, flags int, addr *IPAddr, err error) {
17
+ return 0, 0, 0, nil, syscall.EPLAN9
18
+ }
19
+
20
+ func (c *IPConn) writeTo(b []byte, addr *IPAddr) (int, error) {
21
+ return 0, syscall.EPLAN9
22
+ }
23
+
24
+ func (c *IPConn) writeMsg(b, oob []byte, addr *IPAddr) (n, oobn int, err error) {
25
+ return 0, 0, syscall.EPLAN9
26
+ }
27
+
28
+ func (sd *sysDialer) dialIP(ctx context.Context, laddr, raddr *IPAddr) (*IPConn, error) {
29
+ return nil, syscall.EPLAN9
30
+ }
31
+
32
+ func (sl *sysListener) listenIP(ctx context.Context, laddr *IPAddr) (*IPConn, error) {
33
+ return nil, syscall.EPLAN9
34
+ }
platform/dbops/binaries/go/go/src/net/iprawsock_posix.go ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2010 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
+ "syscall"
12
+ )
13
+
14
+ func sockaddrToIP(sa syscall.Sockaddr) Addr {
15
+ switch sa := sa.(type) {
16
+ case *syscall.SockaddrInet4:
17
+ return &IPAddr{IP: sa.Addr[0:]}
18
+ case *syscall.SockaddrInet6:
19
+ return &IPAddr{IP: sa.Addr[0:], Zone: zoneCache.name(int(sa.ZoneId))}
20
+ }
21
+ return nil
22
+ }
23
+
24
+ func (a *IPAddr) family() int {
25
+ if a == nil || len(a.IP) <= IPv4len {
26
+ return syscall.AF_INET
27
+ }
28
+ if a.IP.To4() != nil {
29
+ return syscall.AF_INET
30
+ }
31
+ return syscall.AF_INET6
32
+ }
33
+
34
+ func (a *IPAddr) sockaddr(family int) (syscall.Sockaddr, error) {
35
+ if a == nil {
36
+ return nil, nil
37
+ }
38
+ return ipToSockaddr(family, a.IP, 0, a.Zone)
39
+ }
40
+
41
+ func (a *IPAddr) toLocal(net string) sockaddr {
42
+ return &IPAddr{loopbackIP(net), a.Zone}
43
+ }
44
+
45
+ func (c *IPConn) readFrom(b []byte) (int, *IPAddr, error) {
46
+ // TODO(cw,rsc): consider using readv if we know the family
47
+ // type to avoid the header trim/copy
48
+ var addr *IPAddr
49
+ n, sa, err := c.fd.readFrom(b)
50
+ switch sa := sa.(type) {
51
+ case *syscall.SockaddrInet4:
52
+ addr = &IPAddr{IP: sa.Addr[0:]}
53
+ n = stripIPv4Header(n, b)
54
+ case *syscall.SockaddrInet6:
55
+ addr = &IPAddr{IP: sa.Addr[0:], Zone: zoneCache.name(int(sa.ZoneId))}
56
+ }
57
+ return n, addr, err
58
+ }
59
+
60
+ func stripIPv4Header(n int, b []byte) int {
61
+ if len(b) < 20 {
62
+ return n
63
+ }
64
+ l := int(b[0]&0x0f) << 2
65
+ if 20 > l || l > len(b) {
66
+ return n
67
+ }
68
+ if b[0]>>4 != 4 {
69
+ return n
70
+ }
71
+ copy(b, b[l:])
72
+ return n - l
73
+ }
74
+
75
+ func (c *IPConn) readMsg(b, oob []byte) (n, oobn, flags int, addr *IPAddr, err error) {
76
+ var sa syscall.Sockaddr
77
+ n, oobn, flags, sa, err = c.fd.readMsg(b, oob, 0)
78
+ switch sa := sa.(type) {
79
+ case *syscall.SockaddrInet4:
80
+ addr = &IPAddr{IP: sa.Addr[0:]}
81
+ case *syscall.SockaddrInet6:
82
+ addr = &IPAddr{IP: sa.Addr[0:], Zone: zoneCache.name(int(sa.ZoneId))}
83
+ }
84
+ return
85
+ }
86
+
87
+ func (c *IPConn) writeTo(b []byte, addr *IPAddr) (int, error) {
88
+ if c.fd.isConnected {
89
+ return 0, ErrWriteToConnected
90
+ }
91
+ if addr == nil {
92
+ return 0, errMissingAddress
93
+ }
94
+ sa, err := addr.sockaddr(c.fd.family)
95
+ if err != nil {
96
+ return 0, err
97
+ }
98
+ return c.fd.writeTo(b, sa)
99
+ }
100
+
101
+ func (c *IPConn) writeMsg(b, oob []byte, addr *IPAddr) (n, oobn int, err error) {
102
+ if c.fd.isConnected {
103
+ return 0, 0, ErrWriteToConnected
104
+ }
105
+ if addr == nil {
106
+ return 0, 0, errMissingAddress
107
+ }
108
+ sa, err := addr.sockaddr(c.fd.family)
109
+ if err != nil {
110
+ return 0, 0, err
111
+ }
112
+ return c.fd.writeMsg(b, oob, sa)
113
+ }
114
+
115
+ func (sd *sysDialer) dialIP(ctx context.Context, laddr, raddr *IPAddr) (*IPConn, error) {
116
+ network, proto, err := parseNetwork(ctx, sd.network, true)
117
+ if err != nil {
118
+ return nil, err
119
+ }
120
+ switch network {
121
+ case "ip", "ip4", "ip6":
122
+ default:
123
+ return nil, UnknownNetworkError(sd.network)
124
+ }
125
+ ctrlCtxFn := sd.Dialer.ControlContext
126
+ if ctrlCtxFn == nil && sd.Dialer.Control != nil {
127
+ ctrlCtxFn = func(cxt context.Context, network, address string, c syscall.RawConn) error {
128
+ return sd.Dialer.Control(network, address, c)
129
+ }
130
+ }
131
+ fd, err := internetSocket(ctx, network, laddr, raddr, syscall.SOCK_RAW, proto, "dial", ctrlCtxFn)
132
+ if err != nil {
133
+ return nil, err
134
+ }
135
+ return newIPConn(fd), nil
136
+ }
137
+
138
+ func (sl *sysListener) listenIP(ctx context.Context, laddr *IPAddr) (*IPConn, error) {
139
+ network, proto, err := parseNetwork(ctx, sl.network, true)
140
+ if err != nil {
141
+ return nil, err
142
+ }
143
+ switch network {
144
+ case "ip", "ip4", "ip6":
145
+ default:
146
+ return nil, UnknownNetworkError(sl.network)
147
+ }
148
+ var ctrlCtxFn func(cxt context.Context, network, address string, c syscall.RawConn) error
149
+ if sl.ListenConfig.Control != nil {
150
+ ctrlCtxFn = func(cxt context.Context, network, address string, c syscall.RawConn) error {
151
+ return sl.ListenConfig.Control(network, address, c)
152
+ }
153
+ }
154
+ fd, err := internetSocket(ctx, network, laddr, nil, syscall.SOCK_RAW, proto, "listen", ctrlCtxFn)
155
+ if err != nil {
156
+ return nil, err
157
+ }
158
+ return newIPConn(fd), nil
159
+ }
platform/dbops/binaries/go/go/src/net/iprawsock_test.go ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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/testenv"
9
+ "reflect"
10
+ "testing"
11
+ )
12
+
13
+ // The full stack test cases for IPConn have been moved to the
14
+ // following:
15
+ // golang.org/x/net/ipv4
16
+ // golang.org/x/net/ipv6
17
+ // golang.org/x/net/icmp
18
+
19
+ type resolveIPAddrTest struct {
20
+ network string
21
+ litAddrOrName string
22
+ addr *IPAddr
23
+ err error
24
+ }
25
+
26
+ var resolveIPAddrTests = []resolveIPAddrTest{
27
+ {"ip", "127.0.0.1", &IPAddr{IP: IPv4(127, 0, 0, 1)}, nil},
28
+ {"ip4", "127.0.0.1", &IPAddr{IP: IPv4(127, 0, 0, 1)}, nil},
29
+ {"ip4:icmp", "127.0.0.1", &IPAddr{IP: IPv4(127, 0, 0, 1)}, nil},
30
+
31
+ {"ip", "::1", &IPAddr{IP: ParseIP("::1")}, nil},
32
+ {"ip6", "::1", &IPAddr{IP: ParseIP("::1")}, nil},
33
+ {"ip6:ipv6-icmp", "::1", &IPAddr{IP: ParseIP("::1")}, nil},
34
+ {"ip6:IPv6-ICMP", "::1", &IPAddr{IP: ParseIP("::1")}, nil},
35
+
36
+ {"ip", "::1%en0", &IPAddr{IP: ParseIP("::1"), Zone: "en0"}, nil},
37
+ {"ip6", "::1%911", &IPAddr{IP: ParseIP("::1"), Zone: "911"}, nil},
38
+
39
+ {"", "127.0.0.1", &IPAddr{IP: IPv4(127, 0, 0, 1)}, nil}, // Go 1.0 behavior
40
+ {"", "::1", &IPAddr{IP: ParseIP("::1")}, nil}, // Go 1.0 behavior
41
+
42
+ {"ip4:icmp", "", &IPAddr{}, nil},
43
+
44
+ {"l2tp", "127.0.0.1", nil, UnknownNetworkError("l2tp")},
45
+ {"l2tp:gre", "127.0.0.1", nil, UnknownNetworkError("l2tp:gre")},
46
+ {"tcp", "1.2.3.4:123", nil, UnknownNetworkError("tcp")},
47
+
48
+ {"ip4", "2001:db8::1", nil, &AddrError{Err: errNoSuitableAddress.Error(), Addr: "2001:db8::1"}},
49
+ {"ip4:icmp", "2001:db8::1", nil, &AddrError{Err: errNoSuitableAddress.Error(), Addr: "2001:db8::1"}},
50
+ {"ip6", "127.0.0.1", nil, &AddrError{Err: errNoSuitableAddress.Error(), Addr: "127.0.0.1"}},
51
+ {"ip6", "::ffff:127.0.0.1", nil, &AddrError{Err: errNoSuitableAddress.Error(), Addr: "::ffff:127.0.0.1"}},
52
+ {"ip6:ipv6-icmp", "127.0.0.1", nil, &AddrError{Err: errNoSuitableAddress.Error(), Addr: "127.0.0.1"}},
53
+ {"ip6:ipv6-icmp", "::ffff:127.0.0.1", nil, &AddrError{Err: errNoSuitableAddress.Error(), Addr: "::ffff:127.0.0.1"}},
54
+ }
55
+
56
+ func TestResolveIPAddr(t *testing.T) {
57
+ if !testableNetwork("ip+nopriv") {
58
+ t.Skip("ip+nopriv test")
59
+ }
60
+
61
+ origTestHookLookupIP := testHookLookupIP
62
+ defer func() { testHookLookupIP = origTestHookLookupIP }()
63
+ testHookLookupIP = lookupLocalhost
64
+
65
+ for _, tt := range resolveIPAddrTests {
66
+ addr, err := ResolveIPAddr(tt.network, tt.litAddrOrName)
67
+ if !reflect.DeepEqual(addr, tt.addr) || !reflect.DeepEqual(err, tt.err) {
68
+ t.Errorf("ResolveIPAddr(%q, %q) = %#v, %v, want %#v, %v", tt.network, tt.litAddrOrName, addr, err, tt.addr, tt.err)
69
+ continue
70
+ }
71
+ if err == nil {
72
+ addr2, err := ResolveIPAddr(addr.Network(), addr.String())
73
+ if !reflect.DeepEqual(addr2, tt.addr) || err != tt.err {
74
+ t.Errorf("(%q, %q): ResolveIPAddr(%q, %q) = %#v, %v, want %#v, %v", tt.network, tt.litAddrOrName, addr.Network(), addr.String(), addr2, err, tt.addr, tt.err)
75
+ }
76
+ }
77
+ }
78
+ }
79
+
80
+ var ipConnLocalNameTests = []struct {
81
+ net string
82
+ laddr *IPAddr
83
+ }{
84
+ {"ip4:icmp", &IPAddr{IP: IPv4(127, 0, 0, 1)}},
85
+ {"ip4:icmp", &IPAddr{}},
86
+ {"ip4:icmp", nil},
87
+ }
88
+
89
+ func TestIPConnLocalName(t *testing.T) {
90
+ for _, tt := range ipConnLocalNameTests {
91
+ if !testableNetwork(tt.net) {
92
+ t.Logf("skipping %s test", tt.net)
93
+ continue
94
+ }
95
+ c, err := ListenIP(tt.net, tt.laddr)
96
+ if testenv.SyscallIsNotSupported(err) {
97
+ // May be inside a container that disallows creating a socket.
98
+ t.Logf("skipping %s test: %v", tt.net, err)
99
+ continue
100
+ } else if err != nil {
101
+ t.Fatal(err)
102
+ }
103
+ defer c.Close()
104
+ if la := c.LocalAddr(); la == nil {
105
+ t.Fatal("should not fail")
106
+ }
107
+ }
108
+ }
109
+
110
+ func TestIPConnRemoteName(t *testing.T) {
111
+ network := "ip:tcp"
112
+ if !testableNetwork(network) {
113
+ t.Skipf("skipping %s test", network)
114
+ }
115
+
116
+ raddr := &IPAddr{IP: IPv4(127, 0, 0, 1).To4()}
117
+ c, err := DialIP(network, &IPAddr{IP: IPv4(127, 0, 0, 1)}, raddr)
118
+ if testenv.SyscallIsNotSupported(err) {
119
+ // May be inside a container that disallows creating a socket.
120
+ t.Skipf("skipping %s test: %v", network, err)
121
+ } else if err != nil {
122
+ t.Fatal(err)
123
+ }
124
+ defer c.Close()
125
+ if !reflect.DeepEqual(raddr, c.RemoteAddr()) {
126
+ t.Fatalf("got %#v; want %#v", c.RemoteAddr(), raddr)
127
+ }
128
+ }
129
+
130
+ func TestDialListenIPArgs(t *testing.T) {
131
+ type test struct {
132
+ argLists [][2]string
133
+ shouldFail bool
134
+ }
135
+ tests := []test{
136
+ {
137
+ argLists: [][2]string{
138
+ {"ip", "127.0.0.1"},
139
+ {"ip:", "127.0.0.1"},
140
+ {"ip::", "127.0.0.1"},
141
+ {"ip", "::1"},
142
+ {"ip:", "::1"},
143
+ {"ip::", "::1"},
144
+ {"ip4", "127.0.0.1"},
145
+ {"ip4:", "127.0.0.1"},
146
+ {"ip4::", "127.0.0.1"},
147
+ {"ip6", "::1"},
148
+ {"ip6:", "::1"},
149
+ {"ip6::", "::1"},
150
+ },
151
+ shouldFail: true,
152
+ },
153
+ }
154
+ if testableNetwork("ip") {
155
+ priv := test{shouldFail: false}
156
+ for _, tt := range []struct {
157
+ network, address string
158
+ args [2]string
159
+ }{
160
+ {"ip4:47", "127.0.0.1", [2]string{"ip4:47", "127.0.0.1"}},
161
+ {"ip6:47", "::1", [2]string{"ip6:47", "::1"}},
162
+ } {
163
+ c, err := ListenPacket(tt.network, tt.address)
164
+ if err != nil {
165
+ continue
166
+ }
167
+ c.Close()
168
+ priv.argLists = append(priv.argLists, tt.args)
169
+ }
170
+ if len(priv.argLists) > 0 {
171
+ tests = append(tests, priv)
172
+ }
173
+ }
174
+
175
+ for _, tt := range tests {
176
+ for _, args := range tt.argLists {
177
+ _, err := Dial(args[0], args[1])
178
+ if tt.shouldFail != (err != nil) {
179
+ t.Errorf("Dial(%q, %q) = %v; want (err != nil) is %t", args[0], args[1], err, tt.shouldFail)
180
+ }
181
+ _, err = ListenPacket(args[0], args[1])
182
+ if tt.shouldFail != (err != nil) {
183
+ t.Errorf("ListenPacket(%q, %q) = %v; want (err != nil) is %t", args[0], args[1], err, tt.shouldFail)
184
+ }
185
+ a, err := ResolveIPAddr("ip", args[1])
186
+ if err != nil {
187
+ t.Errorf("ResolveIPAddr(\"ip\", %q) = %v", args[1], err)
188
+ continue
189
+ }
190
+ _, err = DialIP(args[0], nil, a)
191
+ if tt.shouldFail != (err != nil) {
192
+ t.Errorf("DialIP(%q, %v) = %v; want (err != nil) is %t", args[0], a, err, tt.shouldFail)
193
+ }
194
+ _, err = ListenIP(args[0], a)
195
+ if tt.shouldFail != (err != nil) {
196
+ t.Errorf("ListenIP(%q, %v) = %v; want (err != nil) is %t", args[0], a, err, tt.shouldFail)
197
+ }
198
+ }
199
+ }
200
+ }
platform/dbops/binaries/go/go/src/net/ipsock.go ADDED
@@ -0,0 +1,315 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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/bytealg"
10
+ "runtime"
11
+ "sync"
12
+ )
13
+
14
+ // BUG(rsc,mikio): On DragonFly BSD and OpenBSD, listening on the
15
+ // "tcp" and "udp" networks does not listen for both IPv4 and IPv6
16
+ // connections. This is due to the fact that IPv4 traffic will not be
17
+ // routed to an IPv6 socket - two separate sockets are required if
18
+ // both address families are to be supported.
19
+ // See inet6(4) for details.
20
+
21
+ type ipStackCapabilities struct {
22
+ sync.Once // guards following
23
+ ipv4Enabled bool
24
+ ipv6Enabled bool
25
+ ipv4MappedIPv6Enabled bool
26
+ }
27
+
28
+ var ipStackCaps ipStackCapabilities
29
+
30
+ // supportsIPv4 reports whether the platform supports IPv4 networking
31
+ // functionality.
32
+ func supportsIPv4() bool {
33
+ ipStackCaps.Once.Do(ipStackCaps.probe)
34
+ return ipStackCaps.ipv4Enabled
35
+ }
36
+
37
+ // supportsIPv6 reports whether the platform supports IPv6 networking
38
+ // functionality.
39
+ func supportsIPv6() bool {
40
+ ipStackCaps.Once.Do(ipStackCaps.probe)
41
+ return ipStackCaps.ipv6Enabled
42
+ }
43
+
44
+ // supportsIPv4map reports whether the platform supports mapping an
45
+ // IPv4 address inside an IPv6 address at transport layer
46
+ // protocols. See RFC 4291, RFC 4038 and RFC 3493.
47
+ func supportsIPv4map() bool {
48
+ // Some operating systems provide no support for mapping IPv4
49
+ // addresses to IPv6, and a runtime check is unnecessary.
50
+ switch runtime.GOOS {
51
+ case "dragonfly", "openbsd":
52
+ return false
53
+ }
54
+
55
+ ipStackCaps.Once.Do(ipStackCaps.probe)
56
+ return ipStackCaps.ipv4MappedIPv6Enabled
57
+ }
58
+
59
+ // An addrList represents a list of network endpoint addresses.
60
+ type addrList []Addr
61
+
62
+ // isIPv4 reports whether addr contains an IPv4 address.
63
+ func isIPv4(addr Addr) bool {
64
+ switch addr := addr.(type) {
65
+ case *TCPAddr:
66
+ return addr.IP.To4() != nil
67
+ case *UDPAddr:
68
+ return addr.IP.To4() != nil
69
+ case *IPAddr:
70
+ return addr.IP.To4() != nil
71
+ }
72
+ return false
73
+ }
74
+
75
+ // isNotIPv4 reports whether addr does not contain an IPv4 address.
76
+ func isNotIPv4(addr Addr) bool { return !isIPv4(addr) }
77
+
78
+ // forResolve returns the most appropriate address in address for
79
+ // a call to ResolveTCPAddr, ResolveUDPAddr, or ResolveIPAddr.
80
+ // IPv4 is preferred, unless addr contains an IPv6 literal.
81
+ func (addrs addrList) forResolve(network, addr string) Addr {
82
+ var want6 bool
83
+ switch network {
84
+ case "ip":
85
+ // IPv6 literal (addr does NOT contain a port)
86
+ want6 = bytealg.CountString(addr, ':') > 0
87
+ case "tcp", "udp":
88
+ // IPv6 literal. (addr contains a port, so look for '[')
89
+ want6 = bytealg.CountString(addr, '[') > 0
90
+ }
91
+ if want6 {
92
+ return addrs.first(isNotIPv4)
93
+ }
94
+ return addrs.first(isIPv4)
95
+ }
96
+
97
+ // first returns the first address which satisfies strategy, or if
98
+ // none do, then the first address of any kind.
99
+ func (addrs addrList) first(strategy func(Addr) bool) Addr {
100
+ for _, addr := range addrs {
101
+ if strategy(addr) {
102
+ return addr
103
+ }
104
+ }
105
+ return addrs[0]
106
+ }
107
+
108
+ // partition divides an address list into two categories, using a
109
+ // strategy function to assign a boolean label to each address.
110
+ // The first address, and any with a matching label, are returned as
111
+ // primaries, while addresses with the opposite label are returned
112
+ // as fallbacks. For non-empty inputs, primaries is guaranteed to be
113
+ // non-empty.
114
+ func (addrs addrList) partition(strategy func(Addr) bool) (primaries, fallbacks addrList) {
115
+ var primaryLabel bool
116
+ for i, addr := range addrs {
117
+ label := strategy(addr)
118
+ if i == 0 || label == primaryLabel {
119
+ primaryLabel = label
120
+ primaries = append(primaries, addr)
121
+ } else {
122
+ fallbacks = append(fallbacks, addr)
123
+ }
124
+ }
125
+ return
126
+ }
127
+
128
+ // filterAddrList applies a filter to a list of IP addresses,
129
+ // yielding a list of Addr objects. Known filters are nil, ipv4only,
130
+ // and ipv6only. It returns every address when the filter is nil.
131
+ // The result contains at least one address when error is nil.
132
+ func filterAddrList(filter func(IPAddr) bool, ips []IPAddr, inetaddr func(IPAddr) Addr, originalAddr string) (addrList, error) {
133
+ var addrs addrList
134
+ for _, ip := range ips {
135
+ if filter == nil || filter(ip) {
136
+ addrs = append(addrs, inetaddr(ip))
137
+ }
138
+ }
139
+ if len(addrs) == 0 {
140
+ return nil, &AddrError{Err: errNoSuitableAddress.Error(), Addr: originalAddr}
141
+ }
142
+ return addrs, nil
143
+ }
144
+
145
+ // ipv4only reports whether addr is an IPv4 address.
146
+ func ipv4only(addr IPAddr) bool {
147
+ return addr.IP.To4() != nil
148
+ }
149
+
150
+ // ipv6only reports whether addr is an IPv6 address except IPv4-mapped IPv6 address.
151
+ func ipv6only(addr IPAddr) bool {
152
+ return len(addr.IP) == IPv6len && addr.IP.To4() == nil
153
+ }
154
+
155
+ // SplitHostPort splits a network address of the form "host:port",
156
+ // "host%zone:port", "[host]:port" or "[host%zone]:port" into host or
157
+ // host%zone and port.
158
+ //
159
+ // A literal IPv6 address in hostport must be enclosed in square
160
+ // brackets, as in "[::1]:80", "[::1%lo0]:80".
161
+ //
162
+ // See func Dial for a description of the hostport parameter, and host
163
+ // and port results.
164
+ func SplitHostPort(hostport string) (host, port string, err error) {
165
+ const (
166
+ missingPort = "missing port in address"
167
+ tooManyColons = "too many colons in address"
168
+ )
169
+ addrErr := func(addr, why string) (host, port string, err error) {
170
+ return "", "", &AddrError{Err: why, Addr: addr}
171
+ }
172
+ j, k := 0, 0
173
+
174
+ // The port starts after the last colon.
175
+ i := bytealg.LastIndexByteString(hostport, ':')
176
+ if i < 0 {
177
+ return addrErr(hostport, missingPort)
178
+ }
179
+
180
+ if hostport[0] == '[' {
181
+ // Expect the first ']' just before the last ':'.
182
+ end := bytealg.IndexByteString(hostport, ']')
183
+ if end < 0 {
184
+ return addrErr(hostport, "missing ']' in address")
185
+ }
186
+ switch end + 1 {
187
+ case len(hostport):
188
+ // There can't be a ':' behind the ']' now.
189
+ return addrErr(hostport, missingPort)
190
+ case i:
191
+ // The expected result.
192
+ default:
193
+ // Either ']' isn't followed by a colon, or it is
194
+ // followed by a colon that is not the last one.
195
+ if hostport[end+1] == ':' {
196
+ return addrErr(hostport, tooManyColons)
197
+ }
198
+ return addrErr(hostport, missingPort)
199
+ }
200
+ host = hostport[1:end]
201
+ j, k = 1, end+1 // there can't be a '[' resp. ']' before these positions
202
+ } else {
203
+ host = hostport[:i]
204
+ if bytealg.IndexByteString(host, ':') >= 0 {
205
+ return addrErr(hostport, tooManyColons)
206
+ }
207
+ }
208
+ if bytealg.IndexByteString(hostport[j:], '[') >= 0 {
209
+ return addrErr(hostport, "unexpected '[' in address")
210
+ }
211
+ if bytealg.IndexByteString(hostport[k:], ']') >= 0 {
212
+ return addrErr(hostport, "unexpected ']' in address")
213
+ }
214
+
215
+ port = hostport[i+1:]
216
+ return host, port, nil
217
+ }
218
+
219
+ func splitHostZone(s string) (host, zone string) {
220
+ // The IPv6 scoped addressing zone identifier starts after the
221
+ // last percent sign.
222
+ if i := bytealg.LastIndexByteString(s, '%'); i > 0 {
223
+ host, zone = s[:i], s[i+1:]
224
+ } else {
225
+ host = s
226
+ }
227
+ return
228
+ }
229
+
230
+ // JoinHostPort combines host and port into a network address of the
231
+ // form "host:port". If host contains a colon, as found in literal
232
+ // IPv6 addresses, then JoinHostPort returns "[host]:port".
233
+ //
234
+ // See func Dial for a description of the host and port parameters.
235
+ func JoinHostPort(host, port string) string {
236
+ // We assume that host is a literal IPv6 address if host has
237
+ // colons.
238
+ if bytealg.IndexByteString(host, ':') >= 0 {
239
+ return "[" + host + "]:" + port
240
+ }
241
+ return host + ":" + port
242
+ }
243
+
244
+ // internetAddrList resolves addr, which may be a literal IP
245
+ // address or a DNS name, and returns a list of internet protocol
246
+ // family addresses. The result contains at least one address when
247
+ // error is nil.
248
+ func (r *Resolver) internetAddrList(ctx context.Context, net, addr string) (addrList, error) {
249
+ var (
250
+ err error
251
+ host, port string
252
+ portnum int
253
+ )
254
+ switch net {
255
+ case "tcp", "tcp4", "tcp6", "udp", "udp4", "udp6":
256
+ if addr != "" {
257
+ if host, port, err = SplitHostPort(addr); err != nil {
258
+ return nil, err
259
+ }
260
+ if portnum, err = r.LookupPort(ctx, net, port); err != nil {
261
+ return nil, err
262
+ }
263
+ }
264
+ case "ip", "ip4", "ip6":
265
+ if addr != "" {
266
+ host = addr
267
+ }
268
+ default:
269
+ return nil, UnknownNetworkError(net)
270
+ }
271
+ inetaddr := func(ip IPAddr) Addr {
272
+ switch net {
273
+ case "tcp", "tcp4", "tcp6":
274
+ return &TCPAddr{IP: ip.IP, Port: portnum, Zone: ip.Zone}
275
+ case "udp", "udp4", "udp6":
276
+ return &UDPAddr{IP: ip.IP, Port: portnum, Zone: ip.Zone}
277
+ case "ip", "ip4", "ip6":
278
+ return &IPAddr{IP: ip.IP, Zone: ip.Zone}
279
+ default:
280
+ panic("unexpected network: " + net)
281
+ }
282
+ }
283
+ if host == "" {
284
+ return addrList{inetaddr(IPAddr{})}, nil
285
+ }
286
+
287
+ // Try as a literal IP address, then as a DNS name.
288
+ ips, err := r.lookupIPAddr(ctx, net, host)
289
+ if err != nil {
290
+ return nil, err
291
+ }
292
+ // Issue 18806: if the machine has halfway configured
293
+ // IPv6 such that it can bind on "::" (IPv6unspecified)
294
+ // but not connect back to that same address, fall
295
+ // back to dialing 0.0.0.0.
296
+ if len(ips) == 1 && ips[0].IP.Equal(IPv6unspecified) {
297
+ ips = append(ips, IPAddr{IP: IPv4zero})
298
+ }
299
+
300
+ var filter func(IPAddr) bool
301
+ if net != "" && net[len(net)-1] == '4' {
302
+ filter = ipv4only
303
+ }
304
+ if net != "" && net[len(net)-1] == '6' {
305
+ filter = ipv6only
306
+ }
307
+ return filterAddrList(filter, ips, inetaddr, host)
308
+ }
309
+
310
+ func loopbackIP(net string) IP {
311
+ if net != "" && net[len(net)-1] == '6' {
312
+ return IPv6loopback
313
+ }
314
+ return IP{127, 0, 0, 1}
315
+ }
platform/dbops/binaries/go/go/src/net/ipsock_plan9.go ADDED
@@ -0,0 +1,366 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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/bytealg"
10
+ "internal/itoa"
11
+ "io/fs"
12
+ "os"
13
+ "syscall"
14
+ )
15
+
16
+ // probe probes IPv4, IPv6 and IPv4-mapped IPv6 communication
17
+ // capabilities.
18
+ //
19
+ // Plan 9 uses IPv6 natively, see ip(3).
20
+ func (p *ipStackCapabilities) probe() {
21
+ p.ipv4Enabled = probe(netdir+"/iproute", "4i")
22
+ p.ipv6Enabled = probe(netdir+"/iproute", "6i")
23
+ if p.ipv4Enabled && p.ipv6Enabled {
24
+ p.ipv4MappedIPv6Enabled = true
25
+ }
26
+ }
27
+
28
+ func probe(filename, query string) bool {
29
+ var file *file
30
+ var err error
31
+ if file, err = open(filename); err != nil {
32
+ return false
33
+ }
34
+ defer file.close()
35
+
36
+ r := false
37
+ for line, ok := file.readLine(); ok && !r; line, ok = file.readLine() {
38
+ f := getFields(line)
39
+ if len(f) < 3 {
40
+ continue
41
+ }
42
+ for i := 0; i < len(f); i++ {
43
+ if query == f[i] {
44
+ r = true
45
+ break
46
+ }
47
+ }
48
+ }
49
+ return r
50
+ }
51
+
52
+ // parsePlan9Addr parses address of the form [ip!]port (e.g. 127.0.0.1!80).
53
+ func parsePlan9Addr(s string) (ip IP, iport int, err error) {
54
+ addr := IPv4zero // address contains port only
55
+ i := bytealg.IndexByteString(s, '!')
56
+ if i >= 0 {
57
+ addr = ParseIP(s[:i])
58
+ if addr == nil {
59
+ return nil, 0, &ParseError{Type: "IP address", Text: s}
60
+ }
61
+ }
62
+ p, plen, ok := dtoi(s[i+1:])
63
+ if !ok {
64
+ return nil, 0, &ParseError{Type: "port", Text: s}
65
+ }
66
+ if p < 0 || p > 0xFFFF {
67
+ return nil, 0, &AddrError{Err: "invalid port", Addr: s[i+1 : i+1+plen]}
68
+ }
69
+ return addr, p, nil
70
+ }
71
+
72
+ func readPlan9Addr(net, filename string) (addr Addr, err error) {
73
+ var buf [128]byte
74
+
75
+ f, err := os.Open(filename)
76
+ if err != nil {
77
+ return
78
+ }
79
+ defer f.Close()
80
+ n, err := f.Read(buf[:])
81
+ if err != nil {
82
+ return
83
+ }
84
+ ip, port, err := parsePlan9Addr(string(buf[:n]))
85
+ if err != nil {
86
+ return
87
+ }
88
+ switch net {
89
+ case "tcp4", "udp4":
90
+ if ip.Equal(IPv6zero) {
91
+ ip = ip[:IPv4len]
92
+ }
93
+ }
94
+ switch net {
95
+ case "tcp", "tcp4", "tcp6":
96
+ addr = &TCPAddr{IP: ip, Port: port}
97
+ case "udp", "udp4", "udp6":
98
+ addr = &UDPAddr{IP: ip, Port: port}
99
+ default:
100
+ return nil, UnknownNetworkError(net)
101
+ }
102
+ return addr, nil
103
+ }
104
+
105
+ func startPlan9(ctx context.Context, net string, addr Addr) (ctl *os.File, dest, proto, name string, err error) {
106
+ var (
107
+ ip IP
108
+ port int
109
+ )
110
+ switch a := addr.(type) {
111
+ case *TCPAddr:
112
+ proto = "tcp"
113
+ ip = a.IP
114
+ port = a.Port
115
+ case *UDPAddr:
116
+ proto = "udp"
117
+ ip = a.IP
118
+ port = a.Port
119
+ default:
120
+ err = UnknownNetworkError(net)
121
+ return
122
+ }
123
+
124
+ if port > 65535 {
125
+ err = InvalidAddrError("port should be < 65536")
126
+ return
127
+ }
128
+
129
+ clone, dest, err := queryCS1(ctx, proto, ip, port)
130
+ if err != nil {
131
+ return
132
+ }
133
+ f, err := os.OpenFile(clone, os.O_RDWR, 0)
134
+ if err != nil {
135
+ return
136
+ }
137
+ var buf [16]byte
138
+ n, err := f.Read(buf[:])
139
+ if err != nil {
140
+ f.Close()
141
+ return
142
+ }
143
+ return f, dest, proto, string(buf[:n]), nil
144
+ }
145
+
146
+ func fixErr(err error) {
147
+ oe, ok := err.(*OpError)
148
+ if !ok {
149
+ return
150
+ }
151
+ nonNilInterface := func(a Addr) bool {
152
+ switch a := a.(type) {
153
+ case *TCPAddr:
154
+ return a == nil
155
+ case *UDPAddr:
156
+ return a == nil
157
+ case *IPAddr:
158
+ return a == nil
159
+ default:
160
+ return false
161
+ }
162
+ }
163
+ if nonNilInterface(oe.Source) {
164
+ oe.Source = nil
165
+ }
166
+ if nonNilInterface(oe.Addr) {
167
+ oe.Addr = nil
168
+ }
169
+ if pe, ok := oe.Err.(*fs.PathError); ok {
170
+ if _, ok = pe.Err.(syscall.ErrorString); ok {
171
+ oe.Err = pe.Err
172
+ }
173
+ }
174
+ }
175
+
176
+ func dialPlan9(ctx context.Context, net string, laddr, raddr Addr) (fd *netFD, err error) {
177
+ defer func() { fixErr(err) }()
178
+ type res struct {
179
+ fd *netFD
180
+ err error
181
+ }
182
+ resc := make(chan res)
183
+ go func() {
184
+ fd, err := dialPlan9Blocking(ctx, net, laddr, raddr)
185
+ select {
186
+ case resc <- res{fd, err}:
187
+ case <-ctx.Done():
188
+ if fd != nil {
189
+ fd.Close()
190
+ }
191
+ }
192
+ }()
193
+ select {
194
+ case res := <-resc:
195
+ return res.fd, res.err
196
+ case <-ctx.Done():
197
+ return nil, mapErr(ctx.Err())
198
+ }
199
+ }
200
+
201
+ func dialPlan9Blocking(ctx context.Context, net string, laddr, raddr Addr) (fd *netFD, err error) {
202
+ if isWildcard(raddr) {
203
+ raddr = toLocal(raddr, net)
204
+ }
205
+ f, dest, proto, name, err := startPlan9(ctx, net, raddr)
206
+ if err != nil {
207
+ return nil, err
208
+ }
209
+ if la := plan9LocalAddr(laddr); la == "" {
210
+ err = hangupCtlWrite(ctx, proto, f, "connect "+dest)
211
+ } else {
212
+ err = hangupCtlWrite(ctx, proto, f, "connect "+dest+" "+la)
213
+ }
214
+ if err != nil {
215
+ f.Close()
216
+ return nil, err
217
+ }
218
+ data, err := os.OpenFile(netdir+"/"+proto+"/"+name+"/data", os.O_RDWR, 0)
219
+ if err != nil {
220
+ f.Close()
221
+ return nil, err
222
+ }
223
+ laddr, err = readPlan9Addr(net, netdir+"/"+proto+"/"+name+"/local")
224
+ if err != nil {
225
+ data.Close()
226
+ f.Close()
227
+ return nil, err
228
+ }
229
+ return newFD(proto, name, nil, f, data, laddr, raddr)
230
+ }
231
+
232
+ func listenPlan9(ctx context.Context, net string, laddr Addr) (fd *netFD, err error) {
233
+ defer func() { fixErr(err) }()
234
+ f, dest, proto, name, err := startPlan9(ctx, net, laddr)
235
+ if err != nil {
236
+ return nil, err
237
+ }
238
+ _, err = f.WriteString("announce " + dest)
239
+ if err != nil {
240
+ f.Close()
241
+ return nil, &OpError{Op: "announce", Net: net, Source: laddr, Addr: nil, Err: err}
242
+ }
243
+ laddr, err = readPlan9Addr(net, netdir+"/"+proto+"/"+name+"/local")
244
+ if err != nil {
245
+ f.Close()
246
+ return nil, err
247
+ }
248
+ return newFD(proto, name, nil, f, nil, laddr, nil)
249
+ }
250
+
251
+ func (fd *netFD) netFD() (*netFD, error) {
252
+ return newFD(fd.net, fd.n, fd.listen, fd.ctl, fd.data, fd.laddr, fd.raddr)
253
+ }
254
+
255
+ func (fd *netFD) acceptPlan9() (nfd *netFD, err error) {
256
+ defer func() { fixErr(err) }()
257
+ if err := fd.pfd.ReadLock(); err != nil {
258
+ return nil, err
259
+ }
260
+ defer fd.pfd.ReadUnlock()
261
+ listen, err := os.Open(fd.dir + "/listen")
262
+ if err != nil {
263
+ return nil, err
264
+ }
265
+ var buf [16]byte
266
+ n, err := listen.Read(buf[:])
267
+ if err != nil {
268
+ listen.Close()
269
+ return nil, err
270
+ }
271
+ name := string(buf[:n])
272
+ ctl, err := os.OpenFile(netdir+"/"+fd.net+"/"+name+"/ctl", os.O_RDWR, 0)
273
+ if err != nil {
274
+ listen.Close()
275
+ return nil, err
276
+ }
277
+ data, err := os.OpenFile(netdir+"/"+fd.net+"/"+name+"/data", os.O_RDWR, 0)
278
+ if err != nil {
279
+ listen.Close()
280
+ ctl.Close()
281
+ return nil, err
282
+ }
283
+ raddr, err := readPlan9Addr(fd.net, netdir+"/"+fd.net+"/"+name+"/remote")
284
+ if err != nil {
285
+ listen.Close()
286
+ ctl.Close()
287
+ data.Close()
288
+ return nil, err
289
+ }
290
+ return newFD(fd.net, name, listen, ctl, data, fd.laddr, raddr)
291
+ }
292
+
293
+ func isWildcard(a Addr) bool {
294
+ var wildcard bool
295
+ switch a := a.(type) {
296
+ case *TCPAddr:
297
+ wildcard = a.isWildcard()
298
+ case *UDPAddr:
299
+ wildcard = a.isWildcard()
300
+ case *IPAddr:
301
+ wildcard = a.isWildcard()
302
+ }
303
+ return wildcard
304
+ }
305
+
306
+ func toLocal(a Addr, net string) Addr {
307
+ switch a := a.(type) {
308
+ case *TCPAddr:
309
+ a.IP = loopbackIP(net)
310
+ case *UDPAddr:
311
+ a.IP = loopbackIP(net)
312
+ case *IPAddr:
313
+ a.IP = loopbackIP(net)
314
+ }
315
+ return a
316
+ }
317
+
318
+ // plan9LocalAddr returns a Plan 9 local address string.
319
+ // See setladdrport at https://9p.io/sources/plan9/sys/src/9/ip/devip.c.
320
+ func plan9LocalAddr(addr Addr) string {
321
+ var ip IP
322
+ port := 0
323
+ switch a := addr.(type) {
324
+ case *TCPAddr:
325
+ if a != nil {
326
+ ip = a.IP
327
+ port = a.Port
328
+ }
329
+ case *UDPAddr:
330
+ if a != nil {
331
+ ip = a.IP
332
+ port = a.Port
333
+ }
334
+ }
335
+ if len(ip) == 0 || ip.IsUnspecified() {
336
+ if port == 0 {
337
+ return ""
338
+ }
339
+ return itoa.Itoa(port)
340
+ }
341
+ return ip.String() + "!" + itoa.Itoa(port)
342
+ }
343
+
344
+ func hangupCtlWrite(ctx context.Context, proto string, ctl *os.File, msg string) error {
345
+ if proto != "tcp" {
346
+ _, err := ctl.WriteString(msg)
347
+ return err
348
+ }
349
+ written := make(chan struct{})
350
+ errc := make(chan error)
351
+ go func() {
352
+ select {
353
+ case <-ctx.Done():
354
+ ctl.WriteString("hangup")
355
+ errc <- mapErr(ctx.Err())
356
+ case <-written:
357
+ errc <- nil
358
+ }
359
+ }()
360
+ _, err := ctl.WriteString(msg)
361
+ close(written)
362
+ if e := <-errc; err == nil && e != nil { // we hung up
363
+ return e
364
+ }
365
+ return err
366
+ }
platform/dbops/binaries/go/go/src/net/ipsock_plan9_test.go ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 "testing"
8
+
9
+ func TestTCP4ListenZero(t *testing.T) {
10
+ l, err := Listen("tcp4", "0.0.0.0:0")
11
+ if err != nil {
12
+ t.Fatal(err)
13
+ }
14
+ defer l.Close()
15
+ if a := l.Addr(); isNotIPv4(a) {
16
+ t.Errorf("address does not contain IPv4: %v", a)
17
+ }
18
+ }
19
+
20
+ func TestUDP4ListenZero(t *testing.T) {
21
+ c, err := ListenPacket("udp4", "0.0.0.0:0")
22
+ if err != nil {
23
+ t.Fatal(err)
24
+ }
25
+ defer c.Close()
26
+ if a := c.LocalAddr(); isNotIPv4(a) {
27
+ t.Errorf("address does not contain IPv4: %v", a)
28
+ }
29
+ }
platform/dbops/binaries/go/go/src/net/ipsock_posix.go ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "internal/poll"
12
+ "net/netip"
13
+ "runtime"
14
+ "syscall"
15
+ )
16
+
17
+ // probe probes IPv4, IPv6 and IPv4-mapped IPv6 communication
18
+ // capabilities which are controlled by the IPV6_V6ONLY socket option
19
+ // and kernel configuration.
20
+ //
21
+ // Should we try to use the IPv4 socket interface if we're only
22
+ // dealing with IPv4 sockets? As long as the host system understands
23
+ // IPv4-mapped IPv6, it's okay to pass IPv4-mapped IPv6 addresses to
24
+ // the IPv6 interface. That simplifies our code and is most
25
+ // general. Unfortunately, we need to run on kernels built without
26
+ // IPv6 support too. So probe the kernel to figure it out.
27
+ func (p *ipStackCapabilities) probe() {
28
+ switch runtime.GOOS {
29
+ case "js", "wasip1":
30
+ // Both ipv4 and ipv6 are faked; see net_fake.go.
31
+ p.ipv4Enabled = true
32
+ p.ipv6Enabled = true
33
+ p.ipv4MappedIPv6Enabled = true
34
+ return
35
+ }
36
+
37
+ s, err := sysSocket(syscall.AF_INET, syscall.SOCK_STREAM, syscall.IPPROTO_TCP)
38
+ switch err {
39
+ case syscall.EAFNOSUPPORT, syscall.EPROTONOSUPPORT:
40
+ case nil:
41
+ poll.CloseFunc(s)
42
+ p.ipv4Enabled = true
43
+ }
44
+ var probes = []struct {
45
+ laddr TCPAddr
46
+ value int
47
+ }{
48
+ // IPv6 communication capability
49
+ {laddr: TCPAddr{IP: ParseIP("::1")}, value: 1},
50
+ // IPv4-mapped IPv6 address communication capability
51
+ {laddr: TCPAddr{IP: IPv4(127, 0, 0, 1)}, value: 0},
52
+ }
53
+ switch runtime.GOOS {
54
+ case "dragonfly", "openbsd":
55
+ // The latest DragonFly BSD and OpenBSD kernels don't
56
+ // support IPV6_V6ONLY=0. They always return an error
57
+ // and we don't need to probe the capability.
58
+ probes = probes[:1]
59
+ }
60
+ for i := range probes {
61
+ s, err := sysSocket(syscall.AF_INET6, syscall.SOCK_STREAM, syscall.IPPROTO_TCP)
62
+ if err != nil {
63
+ continue
64
+ }
65
+ defer poll.CloseFunc(s)
66
+ syscall.SetsockoptInt(s, syscall.IPPROTO_IPV6, syscall.IPV6_V6ONLY, probes[i].value)
67
+ sa, err := probes[i].laddr.sockaddr(syscall.AF_INET6)
68
+ if err != nil {
69
+ continue
70
+ }
71
+ if err := syscall.Bind(s, sa); err != nil {
72
+ continue
73
+ }
74
+ if i == 0 {
75
+ p.ipv6Enabled = true
76
+ } else {
77
+ p.ipv4MappedIPv6Enabled = true
78
+ }
79
+ }
80
+ }
81
+
82
+ // favoriteAddrFamily returns the appropriate address family for the
83
+ // given network, laddr, raddr and mode.
84
+ //
85
+ // If mode indicates "listen" and laddr is a wildcard, we assume that
86
+ // the user wants to make a passive-open connection with a wildcard
87
+ // address family, both AF_INET and AF_INET6, and a wildcard address
88
+ // like the following:
89
+ //
90
+ // - A listen for a wildcard communication domain, "tcp" or
91
+ // "udp", with a wildcard address: If the platform supports
92
+ // both IPv6 and IPv4-mapped IPv6 communication capabilities,
93
+ // or does not support IPv4, we use a dual stack, AF_INET6 and
94
+ // IPV6_V6ONLY=0, wildcard address listen. The dual stack
95
+ // wildcard address listen may fall back to an IPv6-only,
96
+ // AF_INET6 and IPV6_V6ONLY=1, wildcard address listen.
97
+ // Otherwise we prefer an IPv4-only, AF_INET, wildcard address
98
+ // listen.
99
+ //
100
+ // - A listen for a wildcard communication domain, "tcp" or
101
+ // "udp", with an IPv4 wildcard address: same as above.
102
+ //
103
+ // - A listen for a wildcard communication domain, "tcp" or
104
+ // "udp", with an IPv6 wildcard address: same as above.
105
+ //
106
+ // - A listen for an IPv4 communication domain, "tcp4" or "udp4",
107
+ // with an IPv4 wildcard address: We use an IPv4-only, AF_INET,
108
+ // wildcard address listen.
109
+ //
110
+ // - A listen for an IPv6 communication domain, "tcp6" or "udp6",
111
+ // with an IPv6 wildcard address: We use an IPv6-only, AF_INET6
112
+ // and IPV6_V6ONLY=1, wildcard address listen.
113
+ //
114
+ // Otherwise guess: If the addresses are IPv4 then returns AF_INET,
115
+ // or else returns AF_INET6. It also returns a boolean value what
116
+ // designates IPV6_V6ONLY option.
117
+ //
118
+ // Note that the latest DragonFly BSD and OpenBSD kernels allow
119
+ // neither "net.inet6.ip6.v6only=1" change nor IPPROTO_IPV6 level
120
+ // IPV6_V6ONLY socket option setting.
121
+ func favoriteAddrFamily(network string, laddr, raddr sockaddr, mode string) (family int, ipv6only bool) {
122
+ switch network[len(network)-1] {
123
+ case '4':
124
+ return syscall.AF_INET, false
125
+ case '6':
126
+ return syscall.AF_INET6, true
127
+ }
128
+
129
+ if mode == "listen" && (laddr == nil || laddr.isWildcard()) {
130
+ if supportsIPv4map() || !supportsIPv4() {
131
+ return syscall.AF_INET6, false
132
+ }
133
+ if laddr == nil {
134
+ return syscall.AF_INET, false
135
+ }
136
+ return laddr.family(), false
137
+ }
138
+
139
+ if (laddr == nil || laddr.family() == syscall.AF_INET) &&
140
+ (raddr == nil || raddr.family() == syscall.AF_INET) {
141
+ return syscall.AF_INET, false
142
+ }
143
+ return syscall.AF_INET6, false
144
+ }
145
+
146
+ func internetSocket(ctx context.Context, net string, laddr, raddr sockaddr, sotype, proto int, mode string, ctrlCtxFn func(context.Context, string, string, syscall.RawConn) error) (fd *netFD, err error) {
147
+ switch runtime.GOOS {
148
+ case "aix", "windows", "openbsd", "js", "wasip1":
149
+ if mode == "dial" && raddr.isWildcard() {
150
+ raddr = raddr.toLocal(net)
151
+ }
152
+ }
153
+ family, ipv6only := favoriteAddrFamily(net, laddr, raddr, mode)
154
+ return socket(ctx, net, family, sotype, proto, ipv6only, laddr, raddr, ctrlCtxFn)
155
+ }
156
+
157
+ func ipToSockaddrInet4(ip IP, port int) (syscall.SockaddrInet4, error) {
158
+ if len(ip) == 0 {
159
+ ip = IPv4zero
160
+ }
161
+ ip4 := ip.To4()
162
+ if ip4 == nil {
163
+ return syscall.SockaddrInet4{}, &AddrError{Err: "non-IPv4 address", Addr: ip.String()}
164
+ }
165
+ sa := syscall.SockaddrInet4{Port: port}
166
+ copy(sa.Addr[:], ip4)
167
+ return sa, nil
168
+ }
169
+
170
+ func ipToSockaddrInet6(ip IP, port int, zone string) (syscall.SockaddrInet6, error) {
171
+ // In general, an IP wildcard address, which is either
172
+ // "0.0.0.0" or "::", means the entire IP addressing
173
+ // space. For some historical reason, it is used to
174
+ // specify "any available address" on some operations
175
+ // of IP node.
176
+ //
177
+ // When the IP node supports IPv4-mapped IPv6 address,
178
+ // we allow a listener to listen to the wildcard
179
+ // address of both IP addressing spaces by specifying
180
+ // IPv6 wildcard address.
181
+ if len(ip) == 0 || ip.Equal(IPv4zero) {
182
+ ip = IPv6zero
183
+ }
184
+ // We accept any IPv6 address including IPv4-mapped
185
+ // IPv6 address.
186
+ ip6 := ip.To16()
187
+ if ip6 == nil {
188
+ return syscall.SockaddrInet6{}, &AddrError{Err: "non-IPv6 address", Addr: ip.String()}
189
+ }
190
+ sa := syscall.SockaddrInet6{Port: port, ZoneId: uint32(zoneCache.index(zone))}
191
+ copy(sa.Addr[:], ip6)
192
+ return sa, nil
193
+ }
194
+
195
+ func ipToSockaddr(family int, ip IP, port int, zone string) (syscall.Sockaddr, error) {
196
+ switch family {
197
+ case syscall.AF_INET:
198
+ sa, err := ipToSockaddrInet4(ip, port)
199
+ if err != nil {
200
+ return nil, err
201
+ }
202
+ return &sa, nil
203
+ case syscall.AF_INET6:
204
+ sa, err := ipToSockaddrInet6(ip, port, zone)
205
+ if err != nil {
206
+ return nil, err
207
+ }
208
+ return &sa, nil
209
+ }
210
+ return nil, &AddrError{Err: "invalid address family", Addr: ip.String()}
211
+ }
212
+
213
+ func addrPortToSockaddrInet4(ap netip.AddrPort) (syscall.SockaddrInet4, error) {
214
+ // ipToSockaddrInet4 has special handling here for zero length slices.
215
+ // We do not, because netip has no concept of a generic zero IP address.
216
+ addr := ap.Addr()
217
+ if !addr.Is4() {
218
+ return syscall.SockaddrInet4{}, &AddrError{Err: "non-IPv4 address", Addr: addr.String()}
219
+ }
220
+ sa := syscall.SockaddrInet4{
221
+ Addr: addr.As4(),
222
+ Port: int(ap.Port()),
223
+ }
224
+ return sa, nil
225
+ }
226
+
227
+ func addrPortToSockaddrInet6(ap netip.AddrPort) (syscall.SockaddrInet6, error) {
228
+ // ipToSockaddrInet6 has special handling here for zero length slices.
229
+ // We do not, because netip has no concept of a generic zero IP address.
230
+ //
231
+ // addr is allowed to be an IPv4 address, because As16 will convert it
232
+ // to an IPv4-mapped IPv6 address.
233
+ // The error message is kept consistent with ipToSockaddrInet6.
234
+ addr := ap.Addr()
235
+ if !addr.IsValid() {
236
+ return syscall.SockaddrInet6{}, &AddrError{Err: "non-IPv6 address", Addr: addr.String()}
237
+ }
238
+ sa := syscall.SockaddrInet6{
239
+ Addr: addr.As16(),
240
+ Port: int(ap.Port()),
241
+ ZoneId: uint32(zoneCache.index(addr.Zone())),
242
+ }
243
+ return sa, nil
244
+ }
platform/dbops/binaries/go/go/src/net/ipsock_test.go ADDED
@@ -0,0 +1,282 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import (
8
+ "reflect"
9
+ "testing"
10
+ )
11
+
12
+ var testInetaddr = func(ip IPAddr) Addr { return &TCPAddr{IP: ip.IP, Port: 5682, Zone: ip.Zone} }
13
+
14
+ var addrListTests = []struct {
15
+ filter func(IPAddr) bool
16
+ ips []IPAddr
17
+ inetaddr func(IPAddr) Addr
18
+ first Addr
19
+ primaries addrList
20
+ fallbacks addrList
21
+ err error
22
+ }{
23
+ {
24
+ nil,
25
+ []IPAddr{
26
+ {IP: IPv4(127, 0, 0, 1)},
27
+ {IP: IPv6loopback},
28
+ },
29
+ testInetaddr,
30
+ &TCPAddr{IP: IPv4(127, 0, 0, 1), Port: 5682},
31
+ addrList{&TCPAddr{IP: IPv4(127, 0, 0, 1), Port: 5682}},
32
+ addrList{&TCPAddr{IP: IPv6loopback, Port: 5682}},
33
+ nil,
34
+ },
35
+ {
36
+ nil,
37
+ []IPAddr{
38
+ {IP: IPv6loopback},
39
+ {IP: IPv4(127, 0, 0, 1)},
40
+ },
41
+ testInetaddr,
42
+ &TCPAddr{IP: IPv4(127, 0, 0, 1), Port: 5682},
43
+ addrList{&TCPAddr{IP: IPv6loopback, Port: 5682}},
44
+ addrList{&TCPAddr{IP: IPv4(127, 0, 0, 1), Port: 5682}},
45
+ nil,
46
+ },
47
+ {
48
+ nil,
49
+ []IPAddr{
50
+ {IP: IPv4(127, 0, 0, 1)},
51
+ {IP: IPv4(192, 168, 0, 1)},
52
+ },
53
+ testInetaddr,
54
+ &TCPAddr{IP: IPv4(127, 0, 0, 1), Port: 5682},
55
+ addrList{
56
+ &TCPAddr{IP: IPv4(127, 0, 0, 1), Port: 5682},
57
+ &TCPAddr{IP: IPv4(192, 168, 0, 1), Port: 5682},
58
+ },
59
+ nil,
60
+ nil,
61
+ },
62
+ {
63
+ nil,
64
+ []IPAddr{
65
+ {IP: IPv6loopback},
66
+ {IP: ParseIP("fe80::1"), Zone: "eth0"},
67
+ },
68
+ testInetaddr,
69
+ &TCPAddr{IP: IPv6loopback, Port: 5682},
70
+ addrList{
71
+ &TCPAddr{IP: IPv6loopback, Port: 5682},
72
+ &TCPAddr{IP: ParseIP("fe80::1"), Port: 5682, Zone: "eth0"},
73
+ },
74
+ nil,
75
+ nil,
76
+ },
77
+ {
78
+ nil,
79
+ []IPAddr{
80
+ {IP: IPv4(127, 0, 0, 1)},
81
+ {IP: IPv4(192, 168, 0, 1)},
82
+ {IP: IPv6loopback},
83
+ {IP: ParseIP("fe80::1"), Zone: "eth0"},
84
+ },
85
+ testInetaddr,
86
+ &TCPAddr{IP: IPv4(127, 0, 0, 1), Port: 5682},
87
+ addrList{
88
+ &TCPAddr{IP: IPv4(127, 0, 0, 1), Port: 5682},
89
+ &TCPAddr{IP: IPv4(192, 168, 0, 1), Port: 5682},
90
+ },
91
+ addrList{
92
+ &TCPAddr{IP: IPv6loopback, Port: 5682},
93
+ &TCPAddr{IP: ParseIP("fe80::1"), Port: 5682, Zone: "eth0"},
94
+ },
95
+ nil,
96
+ },
97
+ {
98
+ nil,
99
+ []IPAddr{
100
+ {IP: IPv6loopback},
101
+ {IP: ParseIP("fe80::1"), Zone: "eth0"},
102
+ {IP: IPv4(127, 0, 0, 1)},
103
+ {IP: IPv4(192, 168, 0, 1)},
104
+ },
105
+ testInetaddr,
106
+ &TCPAddr{IP: IPv4(127, 0, 0, 1), Port: 5682},
107
+ addrList{
108
+ &TCPAddr{IP: IPv6loopback, Port: 5682},
109
+ &TCPAddr{IP: ParseIP("fe80::1"), Port: 5682, Zone: "eth0"},
110
+ },
111
+ addrList{
112
+ &TCPAddr{IP: IPv4(127, 0, 0, 1), Port: 5682},
113
+ &TCPAddr{IP: IPv4(192, 168, 0, 1), Port: 5682},
114
+ },
115
+ nil,
116
+ },
117
+ {
118
+ nil,
119
+ []IPAddr{
120
+ {IP: IPv4(127, 0, 0, 1)},
121
+ {IP: IPv6loopback},
122
+ {IP: IPv4(192, 168, 0, 1)},
123
+ {IP: ParseIP("fe80::1"), Zone: "eth0"},
124
+ },
125
+ testInetaddr,
126
+ &TCPAddr{IP: IPv4(127, 0, 0, 1), Port: 5682},
127
+ addrList{
128
+ &TCPAddr{IP: IPv4(127, 0, 0, 1), Port: 5682},
129
+ &TCPAddr{IP: IPv4(192, 168, 0, 1), Port: 5682},
130
+ },
131
+ addrList{
132
+ &TCPAddr{IP: IPv6loopback, Port: 5682},
133
+ &TCPAddr{IP: ParseIP("fe80::1"), Port: 5682, Zone: "eth0"},
134
+ },
135
+ nil,
136
+ },
137
+ {
138
+ nil,
139
+ []IPAddr{
140
+ {IP: IPv6loopback},
141
+ {IP: IPv4(127, 0, 0, 1)},
142
+ {IP: ParseIP("fe80::1"), Zone: "eth0"},
143
+ {IP: IPv4(192, 168, 0, 1)},
144
+ },
145
+ testInetaddr,
146
+ &TCPAddr{IP: IPv4(127, 0, 0, 1), Port: 5682},
147
+ addrList{
148
+ &TCPAddr{IP: IPv6loopback, Port: 5682},
149
+ &TCPAddr{IP: ParseIP("fe80::1"), Port: 5682, Zone: "eth0"},
150
+ },
151
+ addrList{
152
+ &TCPAddr{IP: IPv4(127, 0, 0, 1), Port: 5682},
153
+ &TCPAddr{IP: IPv4(192, 168, 0, 1), Port: 5682},
154
+ },
155
+ nil,
156
+ },
157
+
158
+ {
159
+ ipv4only,
160
+ []IPAddr{
161
+ {IP: IPv4(127, 0, 0, 1)},
162
+ {IP: IPv6loopback},
163
+ },
164
+ testInetaddr,
165
+ &TCPAddr{IP: IPv4(127, 0, 0, 1), Port: 5682},
166
+ addrList{&TCPAddr{IP: IPv4(127, 0, 0, 1), Port: 5682}},
167
+ nil,
168
+ nil,
169
+ },
170
+ {
171
+ ipv4only,
172
+ []IPAddr{
173
+ {IP: IPv6loopback},
174
+ {IP: IPv4(127, 0, 0, 1)},
175
+ },
176
+ testInetaddr,
177
+ &TCPAddr{IP: IPv4(127, 0, 0, 1), Port: 5682},
178
+ addrList{&TCPAddr{IP: IPv4(127, 0, 0, 1), Port: 5682}},
179
+ nil,
180
+ nil,
181
+ },
182
+
183
+ {
184
+ ipv6only,
185
+ []IPAddr{
186
+ {IP: IPv4(127, 0, 0, 1)},
187
+ {IP: IPv6loopback},
188
+ },
189
+ testInetaddr,
190
+ &TCPAddr{IP: IPv6loopback, Port: 5682},
191
+ addrList{&TCPAddr{IP: IPv6loopback, Port: 5682}},
192
+ nil,
193
+ nil,
194
+ },
195
+ {
196
+ ipv6only,
197
+ []IPAddr{
198
+ {IP: IPv6loopback},
199
+ {IP: IPv4(127, 0, 0, 1)},
200
+ },
201
+ testInetaddr,
202
+ &TCPAddr{IP: IPv6loopback, Port: 5682},
203
+ addrList{&TCPAddr{IP: IPv6loopback, Port: 5682}},
204
+ nil,
205
+ nil,
206
+ },
207
+
208
+ {nil, nil, testInetaddr, nil, nil, nil, &AddrError{errNoSuitableAddress.Error(), "ADDR"}},
209
+
210
+ {ipv4only, nil, testInetaddr, nil, nil, nil, &AddrError{errNoSuitableAddress.Error(), "ADDR"}},
211
+ {ipv4only, []IPAddr{{IP: IPv6loopback}}, testInetaddr, nil, nil, nil, &AddrError{errNoSuitableAddress.Error(), "ADDR"}},
212
+
213
+ {ipv6only, nil, testInetaddr, nil, nil, nil, &AddrError{errNoSuitableAddress.Error(), "ADDR"}},
214
+ {ipv6only, []IPAddr{{IP: IPv4(127, 0, 0, 1)}}, testInetaddr, nil, nil, nil, &AddrError{errNoSuitableAddress.Error(), "ADDR"}},
215
+ }
216
+
217
+ func TestAddrList(t *testing.T) {
218
+ if !supportsIPv4() || !supportsIPv6() {
219
+ t.Skip("both IPv4 and IPv6 are required")
220
+ }
221
+
222
+ for i, tt := range addrListTests {
223
+ addrs, err := filterAddrList(tt.filter, tt.ips, tt.inetaddr, "ADDR")
224
+ if !reflect.DeepEqual(err, tt.err) {
225
+ t.Errorf("#%v: got %v; want %v", i, err, tt.err)
226
+ }
227
+ if tt.err != nil {
228
+ if len(addrs) != 0 {
229
+ t.Errorf("#%v: got %v; want 0", i, len(addrs))
230
+ }
231
+ continue
232
+ }
233
+ first := addrs.first(isIPv4)
234
+ if !reflect.DeepEqual(first, tt.first) {
235
+ t.Errorf("#%v: got %v; want %v", i, first, tt.first)
236
+ }
237
+ primaries, fallbacks := addrs.partition(isIPv4)
238
+ if !reflect.DeepEqual(primaries, tt.primaries) {
239
+ t.Errorf("#%v: got %v; want %v", i, primaries, tt.primaries)
240
+ }
241
+ if !reflect.DeepEqual(fallbacks, tt.fallbacks) {
242
+ t.Errorf("#%v: got %v; want %v", i, fallbacks, tt.fallbacks)
243
+ }
244
+ expectedLen := len(primaries) + len(fallbacks)
245
+ if len(addrs) != expectedLen {
246
+ t.Errorf("#%v: got %v; want %v", i, len(addrs), expectedLen)
247
+ }
248
+ }
249
+ }
250
+
251
+ func TestAddrListPartition(t *testing.T) {
252
+ addrs := addrList{
253
+ &IPAddr{IP: ParseIP("fe80::"), Zone: "eth0"},
254
+ &IPAddr{IP: ParseIP("fe80::1"), Zone: "eth0"},
255
+ &IPAddr{IP: ParseIP("fe80::2"), Zone: "eth0"},
256
+ }
257
+ cases := []struct {
258
+ lastByte byte
259
+ primaries addrList
260
+ fallbacks addrList
261
+ }{
262
+ {0, addrList{addrs[0]}, addrList{addrs[1], addrs[2]}},
263
+ {1, addrList{addrs[0], addrs[2]}, addrList{addrs[1]}},
264
+ {2, addrList{addrs[0], addrs[1]}, addrList{addrs[2]}},
265
+ {3, addrList{addrs[0], addrs[1], addrs[2]}, nil},
266
+ }
267
+ for i, tt := range cases {
268
+ // Inverting the function's output should not affect the outcome.
269
+ for _, invert := range []bool{false, true} {
270
+ primaries, fallbacks := addrs.partition(func(a Addr) bool {
271
+ ip := a.(*IPAddr).IP
272
+ return (ip[len(ip)-1] == tt.lastByte) != invert
273
+ })
274
+ if !reflect.DeepEqual(primaries, tt.primaries) {
275
+ t.Errorf("#%v: got %v; want %v", i, primaries, tt.primaries)
276
+ }
277
+ if !reflect.DeepEqual(fallbacks, tt.fallbacks) {
278
+ t.Errorf("#%v: got %v; want %v", i, fallbacks, tt.fallbacks)
279
+ }
280
+ }
281
+ }
282
+ }
platform/dbops/binaries/go/go/src/net/listen_test.go ADDED
@@ -0,0 +1,750 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 !plan9
6
+
7
+ package net
8
+
9
+ import (
10
+ "fmt"
11
+ "internal/testenv"
12
+ "os"
13
+ "runtime"
14
+ "syscall"
15
+ "testing"
16
+ "time"
17
+ )
18
+
19
+ func (ln *TCPListener) port() string {
20
+ _, port, err := SplitHostPort(ln.Addr().String())
21
+ if err != nil {
22
+ return ""
23
+ }
24
+ return port
25
+ }
26
+
27
+ func (c *UDPConn) port() string {
28
+ _, port, err := SplitHostPort(c.LocalAddr().String())
29
+ if err != nil {
30
+ return ""
31
+ }
32
+ return port
33
+ }
34
+
35
+ var tcpListenerTests = []struct {
36
+ network string
37
+ address string
38
+ }{
39
+ {"tcp", ""},
40
+ {"tcp", "0.0.0.0"},
41
+ {"tcp", "::ffff:0.0.0.0"},
42
+ {"tcp", "::"},
43
+
44
+ {"tcp", "127.0.0.1"},
45
+ {"tcp", "::ffff:127.0.0.1"},
46
+ {"tcp", "::1"},
47
+
48
+ {"tcp4", ""},
49
+ {"tcp4", "0.0.0.0"},
50
+ {"tcp4", "::ffff:0.0.0.0"},
51
+
52
+ {"tcp4", "127.0.0.1"},
53
+ {"tcp4", "::ffff:127.0.0.1"},
54
+
55
+ {"tcp6", ""},
56
+ {"tcp6", "::"},
57
+
58
+ {"tcp6", "::1"},
59
+ }
60
+
61
+ // TestTCPListener tests both single and double listen to a test
62
+ // listener with same address family, same listening address and
63
+ // same port.
64
+ func TestTCPListener(t *testing.T) {
65
+ switch runtime.GOOS {
66
+ case "plan9":
67
+ t.Skipf("not supported on %s", runtime.GOOS)
68
+ }
69
+
70
+ for _, tt := range tcpListenerTests {
71
+ if !testableListenArgs(tt.network, JoinHostPort(tt.address, "0"), "") {
72
+ t.Logf("skipping %s test", tt.network+" "+tt.address)
73
+ continue
74
+ }
75
+
76
+ ln1, err := Listen(tt.network, JoinHostPort(tt.address, "0"))
77
+ if err != nil {
78
+ t.Fatal(err)
79
+ }
80
+ if err := checkFirstListener(tt.network, ln1); err != nil {
81
+ ln1.Close()
82
+ t.Fatal(err)
83
+ }
84
+ ln2, err := Listen(tt.network, JoinHostPort(tt.address, ln1.(*TCPListener).port()))
85
+ if err == nil {
86
+ ln2.Close()
87
+ }
88
+ if err := checkSecondListener(tt.network, tt.address, err); err != nil {
89
+ ln1.Close()
90
+ t.Fatal(err)
91
+ }
92
+ ln1.Close()
93
+ }
94
+ }
95
+
96
+ var udpListenerTests = []struct {
97
+ network string
98
+ address string
99
+ }{
100
+ {"udp", ""},
101
+ {"udp", "0.0.0.0"},
102
+ {"udp", "::ffff:0.0.0.0"},
103
+ {"udp", "::"},
104
+
105
+ {"udp", "127.0.0.1"},
106
+ {"udp", "::ffff:127.0.0.1"},
107
+ {"udp", "::1"},
108
+
109
+ {"udp4", ""},
110
+ {"udp4", "0.0.0.0"},
111
+ {"udp4", "::ffff:0.0.0.0"},
112
+
113
+ {"udp4", "127.0.0.1"},
114
+ {"udp4", "::ffff:127.0.0.1"},
115
+
116
+ {"udp6", ""},
117
+ {"udp6", "::"},
118
+
119
+ {"udp6", "::1"},
120
+ }
121
+
122
+ // TestUDPListener tests both single and double listen to a test
123
+ // listener with same address family, same listening address and
124
+ // same port.
125
+ func TestUDPListener(t *testing.T) {
126
+ switch runtime.GOOS {
127
+ case "plan9":
128
+ t.Skipf("not supported on %s", runtime.GOOS)
129
+ }
130
+
131
+ for _, tt := range udpListenerTests {
132
+ if !testableListenArgs(tt.network, JoinHostPort(tt.address, "0"), "") {
133
+ t.Logf("skipping %s test", tt.network+" "+tt.address)
134
+ continue
135
+ }
136
+
137
+ c1, err := ListenPacket(tt.network, JoinHostPort(tt.address, "0"))
138
+ if err != nil {
139
+ t.Fatal(err)
140
+ }
141
+ if err := checkFirstListener(tt.network, c1); err != nil {
142
+ c1.Close()
143
+ t.Fatal(err)
144
+ }
145
+ c2, err := ListenPacket(tt.network, JoinHostPort(tt.address, c1.(*UDPConn).port()))
146
+ if err == nil {
147
+ c2.Close()
148
+ }
149
+ if err := checkSecondListener(tt.network, tt.address, err); err != nil {
150
+ c1.Close()
151
+ t.Fatal(err)
152
+ }
153
+ c1.Close()
154
+ }
155
+ }
156
+
157
+ var dualStackTCPListenerTests = []struct {
158
+ network1, address1 string // first listener
159
+ network2, address2 string // second listener
160
+ xerr error // expected error value, nil or other
161
+ }{
162
+ // Test cases and expected results for the attempting 2nd listen on the same port
163
+ // 1st listen 2nd listen darwin freebsd linux openbsd
164
+ // ------------------------------------------------------------------------------------
165
+ // "tcp" "" "tcp" "" - - - -
166
+ // "tcp" "" "tcp" "0.0.0.0" - - - -
167
+ // "tcp" "0.0.0.0" "tcp" "" - - - -
168
+ // ------------------------------------------------------------------------------------
169
+ // "tcp" "" "tcp" "[::]" - - - ok
170
+ // "tcp" "[::]" "tcp" "" - - - ok
171
+ // "tcp" "0.0.0.0" "tcp" "[::]" - - - ok
172
+ // "tcp" "[::]" "tcp" "0.0.0.0" - - - ok
173
+ // "tcp" "[::ffff:0.0.0.0]" "tcp" "[::]" - - - ok
174
+ // "tcp" "[::]" "tcp" "[::ffff:0.0.0.0]" - - - ok
175
+ // ------------------------------------------------------------------------------------
176
+ // "tcp4" "" "tcp6" "" ok ok ok ok
177
+ // "tcp6" "" "tcp4" "" ok ok ok ok
178
+ // "tcp4" "0.0.0.0" "tcp6" "[::]" ok ok ok ok
179
+ // "tcp6" "[::]" "tcp4" "0.0.0.0" ok ok ok ok
180
+ // ------------------------------------------------------------------------------------
181
+ // "tcp" "127.0.0.1" "tcp" "[::1]" ok ok ok ok
182
+ // "tcp" "[::1]" "tcp" "127.0.0.1" ok ok ok ok
183
+ // "tcp4" "127.0.0.1" "tcp6" "[::1]" ok ok ok ok
184
+ // "tcp6" "[::1]" "tcp4" "127.0.0.1" ok ok ok ok
185
+ //
186
+ // Platform default configurations:
187
+ // darwin, kernel version 11.3.0
188
+ // net.inet6.ip6.v6only=0 (overridable by sysctl or IPV6_V6ONLY option)
189
+ // freebsd, kernel version 8.2
190
+ // net.inet6.ip6.v6only=1 (overridable by sysctl or IPV6_V6ONLY option)
191
+ // linux, kernel version 3.0.0
192
+ // net.ipv6.bindv6only=0 (overridable by sysctl or IPV6_V6ONLY option)
193
+ // openbsd, kernel version 5.0
194
+ // net.inet6.ip6.v6only=1 (overriding is prohibited)
195
+
196
+ {"tcp", "", "tcp", "", syscall.EADDRINUSE},
197
+ {"tcp", "", "tcp", "0.0.0.0", syscall.EADDRINUSE},
198
+ {"tcp", "0.0.0.0", "tcp", "", syscall.EADDRINUSE},
199
+
200
+ {"tcp", "", "tcp", "::", syscall.EADDRINUSE},
201
+ {"tcp", "::", "tcp", "", syscall.EADDRINUSE},
202
+ {"tcp", "0.0.0.0", "tcp", "::", syscall.EADDRINUSE},
203
+ {"tcp", "::", "tcp", "0.0.0.0", syscall.EADDRINUSE},
204
+ {"tcp", "::ffff:0.0.0.0", "tcp", "::", syscall.EADDRINUSE},
205
+ {"tcp", "::", "tcp", "::ffff:0.0.0.0", syscall.EADDRINUSE},
206
+
207
+ {"tcp4", "", "tcp6", "", nil},
208
+ {"tcp6", "", "tcp4", "", nil},
209
+ {"tcp4", "0.0.0.0", "tcp6", "::", nil},
210
+ {"tcp6", "::", "tcp4", "0.0.0.0", nil},
211
+
212
+ {"tcp", "127.0.0.1", "tcp", "::1", nil},
213
+ {"tcp", "::1", "tcp", "127.0.0.1", nil},
214
+ {"tcp4", "127.0.0.1", "tcp6", "::1", nil},
215
+ {"tcp6", "::1", "tcp4", "127.0.0.1", nil},
216
+ }
217
+
218
+ // TestDualStackTCPListener tests both single and double listen
219
+ // to a test listener with various address families, different
220
+ // listening address and same port.
221
+ //
222
+ // On DragonFly BSD, we expect the kernel version of node under test
223
+ // to be greater than or equal to 4.4.
224
+ func TestDualStackTCPListener(t *testing.T) {
225
+ switch runtime.GOOS {
226
+ case "plan9":
227
+ t.Skipf("not supported on %s", runtime.GOOS)
228
+ }
229
+ if !supportsIPv4() || !supportsIPv6() {
230
+ t.Skip("both IPv4 and IPv6 are required")
231
+ }
232
+
233
+ for _, tt := range dualStackTCPListenerTests {
234
+ if !testableListenArgs(tt.network1, JoinHostPort(tt.address1, "0"), "") {
235
+ t.Logf("skipping %s test", tt.network1+" "+tt.address1)
236
+ continue
237
+ }
238
+
239
+ if !supportsIPv4map() && differentWildcardAddr(tt.address1, tt.address2) {
240
+ tt.xerr = nil
241
+ }
242
+ var firstErr, secondErr error
243
+ for i := 0; i < 5; i++ {
244
+ lns, err := newDualStackListener()
245
+ if err != nil {
246
+ t.Fatal(err)
247
+ }
248
+ port := lns[0].port()
249
+ for _, ln := range lns {
250
+ ln.Close()
251
+ }
252
+ var ln1 Listener
253
+ ln1, firstErr = Listen(tt.network1, JoinHostPort(tt.address1, port))
254
+ if firstErr != nil {
255
+ continue
256
+ }
257
+ if err := checkFirstListener(tt.network1, ln1); err != nil {
258
+ ln1.Close()
259
+ t.Fatal(err)
260
+ }
261
+ ln2, err := Listen(tt.network2, JoinHostPort(tt.address2, ln1.(*TCPListener).port()))
262
+ if err == nil {
263
+ ln2.Close()
264
+ }
265
+ if secondErr = checkDualStackSecondListener(tt.network2, tt.address2, err, tt.xerr); secondErr != nil {
266
+ ln1.Close()
267
+ continue
268
+ }
269
+ ln1.Close()
270
+ break
271
+ }
272
+ if firstErr != nil {
273
+ t.Error(firstErr)
274
+ }
275
+ if secondErr != nil {
276
+ t.Error(secondErr)
277
+ }
278
+ }
279
+ }
280
+
281
+ var dualStackUDPListenerTests = []struct {
282
+ network1, address1 string // first listener
283
+ network2, address2 string // second listener
284
+ xerr error // expected error value, nil or other
285
+ }{
286
+ {"udp", "", "udp", "", syscall.EADDRINUSE},
287
+ {"udp", "", "udp", "0.0.0.0", syscall.EADDRINUSE},
288
+ {"udp", "0.0.0.0", "udp", "", syscall.EADDRINUSE},
289
+
290
+ {"udp", "", "udp", "::", syscall.EADDRINUSE},
291
+ {"udp", "::", "udp", "", syscall.EADDRINUSE},
292
+ {"udp", "0.0.0.0", "udp", "::", syscall.EADDRINUSE},
293
+ {"udp", "::", "udp", "0.0.0.0", syscall.EADDRINUSE},
294
+ {"udp", "::ffff:0.0.0.0", "udp", "::", syscall.EADDRINUSE},
295
+ {"udp", "::", "udp", "::ffff:0.0.0.0", syscall.EADDRINUSE},
296
+
297
+ {"udp4", "", "udp6", "", nil},
298
+ {"udp6", "", "udp4", "", nil},
299
+ {"udp4", "0.0.0.0", "udp6", "::", nil},
300
+ {"udp6", "::", "udp4", "0.0.0.0", nil},
301
+
302
+ {"udp", "127.0.0.1", "udp", "::1", nil},
303
+ {"udp", "::1", "udp", "127.0.0.1", nil},
304
+ {"udp4", "127.0.0.1", "udp6", "::1", nil},
305
+ {"udp6", "::1", "udp4", "127.0.0.1", nil},
306
+ }
307
+
308
+ // TestDualStackUDPListener tests both single and double listen
309
+ // to a test listener with various address families, different
310
+ // listening address and same port.
311
+ //
312
+ // On DragonFly BSD, we expect the kernel version of node under test
313
+ // to be greater than or equal to 4.4.
314
+ func TestDualStackUDPListener(t *testing.T) {
315
+ switch runtime.GOOS {
316
+ case "plan9":
317
+ t.Skipf("not supported on %s", runtime.GOOS)
318
+ }
319
+ if !supportsIPv4() || !supportsIPv6() {
320
+ t.Skip("both IPv4 and IPv6 are required")
321
+ }
322
+
323
+ for _, tt := range dualStackUDPListenerTests {
324
+ if !testableListenArgs(tt.network1, JoinHostPort(tt.address1, "0"), "") {
325
+ t.Logf("skipping %s test", tt.network1+" "+tt.address1)
326
+ continue
327
+ }
328
+
329
+ if !supportsIPv4map() && differentWildcardAddr(tt.address1, tt.address2) {
330
+ tt.xerr = nil
331
+ }
332
+ var firstErr, secondErr error
333
+ for i := 0; i < 5; i++ {
334
+ cs, err := newDualStackPacketListener()
335
+ if err != nil {
336
+ t.Fatal(err)
337
+ }
338
+ port := cs[0].port()
339
+ for _, c := range cs {
340
+ c.Close()
341
+ }
342
+ var c1 PacketConn
343
+ c1, firstErr = ListenPacket(tt.network1, JoinHostPort(tt.address1, port))
344
+ if firstErr != nil {
345
+ continue
346
+ }
347
+ if err := checkFirstListener(tt.network1, c1); err != nil {
348
+ c1.Close()
349
+ t.Fatal(err)
350
+ }
351
+ c2, err := ListenPacket(tt.network2, JoinHostPort(tt.address2, c1.(*UDPConn).port()))
352
+ if err == nil {
353
+ c2.Close()
354
+ }
355
+ if secondErr = checkDualStackSecondListener(tt.network2, tt.address2, err, tt.xerr); secondErr != nil {
356
+ c1.Close()
357
+ continue
358
+ }
359
+ c1.Close()
360
+ break
361
+ }
362
+ if firstErr != nil {
363
+ t.Error(firstErr)
364
+ }
365
+ if secondErr != nil {
366
+ t.Error(secondErr)
367
+ }
368
+ }
369
+ }
370
+
371
+ func differentWildcardAddr(i, j string) bool {
372
+ if (i == "" || i == "0.0.0.0" || i == "::ffff:0.0.0.0") && (j == "" || j == "0.0.0.0" || j == "::ffff:0.0.0.0") {
373
+ return false
374
+ }
375
+ if i == "[::]" && j == "[::]" {
376
+ return false
377
+ }
378
+ return true
379
+ }
380
+
381
+ func checkFirstListener(network string, ln any) error {
382
+ switch network {
383
+ case "tcp":
384
+ fd := ln.(*TCPListener).fd
385
+ if err := checkDualStackAddrFamily(fd); err != nil {
386
+ return err
387
+ }
388
+ case "tcp4":
389
+ fd := ln.(*TCPListener).fd
390
+ if fd.family != syscall.AF_INET {
391
+ return fmt.Errorf("%v got %v; want %v", fd.laddr, fd.family, syscall.AF_INET)
392
+ }
393
+ case "tcp6":
394
+ fd := ln.(*TCPListener).fd
395
+ if fd.family != syscall.AF_INET6 {
396
+ return fmt.Errorf("%v got %v; want %v", fd.laddr, fd.family, syscall.AF_INET6)
397
+ }
398
+ case "udp":
399
+ fd := ln.(*UDPConn).fd
400
+ if err := checkDualStackAddrFamily(fd); err != nil {
401
+ return err
402
+ }
403
+ case "udp4":
404
+ fd := ln.(*UDPConn).fd
405
+ if fd.family != syscall.AF_INET {
406
+ return fmt.Errorf("%v got %v; want %v", fd.laddr, fd.family, syscall.AF_INET)
407
+ }
408
+ case "udp6":
409
+ fd := ln.(*UDPConn).fd
410
+ if fd.family != syscall.AF_INET6 {
411
+ return fmt.Errorf("%v got %v; want %v", fd.laddr, fd.family, syscall.AF_INET6)
412
+ }
413
+ default:
414
+ return UnknownNetworkError(network)
415
+ }
416
+ return nil
417
+ }
418
+
419
+ func checkSecondListener(network, address string, err error) error {
420
+ switch network {
421
+ case "tcp", "tcp4", "tcp6":
422
+ if err == nil {
423
+ return fmt.Errorf("%s should fail", network+" "+address)
424
+ }
425
+ case "udp", "udp4", "udp6":
426
+ if err == nil {
427
+ return fmt.Errorf("%s should fail", network+" "+address)
428
+ }
429
+ default:
430
+ return UnknownNetworkError(network)
431
+ }
432
+ return nil
433
+ }
434
+
435
+ func checkDualStackSecondListener(network, address string, err, xerr error) error {
436
+ switch network {
437
+ case "tcp", "tcp4", "tcp6":
438
+ if xerr == nil && err != nil || xerr != nil && err == nil {
439
+ return fmt.Errorf("%s got %v; want %v", network+" "+address, err, xerr)
440
+ }
441
+ case "udp", "udp4", "udp6":
442
+ if xerr == nil && err != nil || xerr != nil && err == nil {
443
+ return fmt.Errorf("%s got %v; want %v", network+" "+address, err, xerr)
444
+ }
445
+ default:
446
+ return UnknownNetworkError(network)
447
+ }
448
+ return nil
449
+ }
450
+
451
+ func checkDualStackAddrFamily(fd *netFD) error {
452
+ switch a := fd.laddr.(type) {
453
+ case *TCPAddr:
454
+ // If a node under test supports both IPv6 capability
455
+ // and IPv6 IPv4-mapping capability, we can assume
456
+ // that the node listens on a wildcard address with an
457
+ // AF_INET6 socket.
458
+ if supportsIPv4map() && fd.laddr.(*TCPAddr).isWildcard() {
459
+ if fd.family != syscall.AF_INET6 {
460
+ return fmt.Errorf("Listen(%s, %v) returns %v; want %v", fd.net, fd.laddr, fd.family, syscall.AF_INET6)
461
+ }
462
+ } else {
463
+ if fd.family != a.family() {
464
+ return fmt.Errorf("Listen(%s, %v) returns %v; want %v", fd.net, fd.laddr, fd.family, a.family())
465
+ }
466
+ }
467
+ case *UDPAddr:
468
+ // If a node under test supports both IPv6 capability
469
+ // and IPv6 IPv4-mapping capability, we can assume
470
+ // that the node listens on a wildcard address with an
471
+ // AF_INET6 socket.
472
+ if supportsIPv4map() && fd.laddr.(*UDPAddr).isWildcard() {
473
+ if fd.family != syscall.AF_INET6 {
474
+ return fmt.Errorf("ListenPacket(%s, %v) returns %v; want %v", fd.net, fd.laddr, fd.family, syscall.AF_INET6)
475
+ }
476
+ } else {
477
+ if fd.family != a.family() {
478
+ return fmt.Errorf("ListenPacket(%s, %v) returns %v; want %v", fd.net, fd.laddr, fd.family, a.family())
479
+ }
480
+ }
481
+ default:
482
+ return fmt.Errorf("unexpected protocol address type: %T", a)
483
+ }
484
+ return nil
485
+ }
486
+
487
+ func TestWildWildcardListener(t *testing.T) {
488
+ testenv.MustHaveExternalNetwork(t)
489
+
490
+ switch runtime.GOOS {
491
+ case "plan9":
492
+ t.Skipf("not supported on %s", runtime.GOOS)
493
+ }
494
+
495
+ defer func() {
496
+ if p := recover(); p != nil {
497
+ t.Fatalf("panicked: %v", p)
498
+ }
499
+ }()
500
+
501
+ if ln, err := Listen("tcp", ""); err == nil {
502
+ ln.Close()
503
+ }
504
+ if ln, err := ListenPacket("udp", ""); err == nil {
505
+ ln.Close()
506
+ }
507
+ if ln, err := ListenTCP("tcp", nil); err == nil {
508
+ ln.Close()
509
+ }
510
+ if ln, err := ListenUDP("udp", nil); err == nil {
511
+ ln.Close()
512
+ }
513
+ if ln, err := ListenIP("ip:icmp", nil); err == nil {
514
+ ln.Close()
515
+ }
516
+ }
517
+
518
+ var ipv4MulticastListenerTests = []struct {
519
+ net string
520
+ gaddr *UDPAddr // see RFC 4727
521
+ }{
522
+ {"udp", &UDPAddr{IP: IPv4(224, 0, 0, 254), Port: 12345}},
523
+
524
+ {"udp4", &UDPAddr{IP: IPv4(224, 0, 0, 254), Port: 12345}},
525
+ }
526
+
527
+ // TestIPv4MulticastListener tests both single and double listen to a
528
+ // test listener with same address family, same group address and same
529
+ // port.
530
+ func TestIPv4MulticastListener(t *testing.T) {
531
+ testenv.MustHaveExternalNetwork(t)
532
+
533
+ switch runtime.GOOS {
534
+ case "android", "plan9":
535
+ t.Skipf("not supported on %s", runtime.GOOS)
536
+ }
537
+ if !supportsIPv4() {
538
+ t.Skip("IPv4 is not supported")
539
+ }
540
+
541
+ closer := func(cs []*UDPConn) {
542
+ for _, c := range cs {
543
+ if c != nil {
544
+ c.Close()
545
+ }
546
+ }
547
+ }
548
+
549
+ for _, ifi := range []*Interface{loopbackInterface(), nil} {
550
+ // Note that multicast interface assignment by system
551
+ // is not recommended because it usually relies on
552
+ // routing stuff for finding out an appropriate
553
+ // nexthop containing both network and link layer
554
+ // adjacencies.
555
+ if ifi == nil || !*testIPv4 {
556
+ continue
557
+ }
558
+ for _, tt := range ipv4MulticastListenerTests {
559
+ var err error
560
+ cs := make([]*UDPConn, 2)
561
+ if cs[0], err = ListenMulticastUDP(tt.net, ifi, tt.gaddr); err != nil {
562
+ t.Fatal(err)
563
+ }
564
+ if err := checkMulticastListener(cs[0], tt.gaddr.IP); err != nil {
565
+ closer(cs)
566
+ t.Fatal(err)
567
+ }
568
+ if cs[1], err = ListenMulticastUDP(tt.net, ifi, tt.gaddr); err != nil {
569
+ closer(cs)
570
+ t.Fatal(err)
571
+ }
572
+ if err := checkMulticastListener(cs[1], tt.gaddr.IP); err != nil {
573
+ closer(cs)
574
+ t.Fatal(err)
575
+ }
576
+ closer(cs)
577
+ }
578
+ }
579
+ }
580
+
581
+ var ipv6MulticastListenerTests = []struct {
582
+ net string
583
+ gaddr *UDPAddr // see RFC 4727
584
+ }{
585
+ {"udp", &UDPAddr{IP: ParseIP("ff01::114"), Port: 12345}},
586
+ {"udp", &UDPAddr{IP: ParseIP("ff02::114"), Port: 12345}},
587
+ {"udp", &UDPAddr{IP: ParseIP("ff04::114"), Port: 12345}},
588
+ {"udp", &UDPAddr{IP: ParseIP("ff05::114"), Port: 12345}},
589
+ {"udp", &UDPAddr{IP: ParseIP("ff08::114"), Port: 12345}},
590
+ {"udp", &UDPAddr{IP: ParseIP("ff0e::114"), Port: 12345}},
591
+
592
+ {"udp6", &UDPAddr{IP: ParseIP("ff01::114"), Port: 12345}},
593
+ {"udp6", &UDPAddr{IP: ParseIP("ff02::114"), Port: 12345}},
594
+ {"udp6", &UDPAddr{IP: ParseIP("ff04::114"), Port: 12345}},
595
+ {"udp6", &UDPAddr{IP: ParseIP("ff05::114"), Port: 12345}},
596
+ {"udp6", &UDPAddr{IP: ParseIP("ff08::114"), Port: 12345}},
597
+ {"udp6", &UDPAddr{IP: ParseIP("ff0e::114"), Port: 12345}},
598
+ }
599
+
600
+ // TestIPv6MulticastListener tests both single and double listen to a
601
+ // test listener with same address family, same group address and same
602
+ // port.
603
+ func TestIPv6MulticastListener(t *testing.T) {
604
+ testenv.MustHaveExternalNetwork(t)
605
+
606
+ switch runtime.GOOS {
607
+ case "plan9":
608
+ t.Skipf("not supported on %s", runtime.GOOS)
609
+ }
610
+ if !supportsIPv6() {
611
+ t.Skip("IPv6 is not supported")
612
+ }
613
+ if os.Getuid() != 0 {
614
+ t.Skip("must be root")
615
+ }
616
+
617
+ closer := func(cs []*UDPConn) {
618
+ for _, c := range cs {
619
+ if c != nil {
620
+ c.Close()
621
+ }
622
+ }
623
+ }
624
+
625
+ for _, ifi := range []*Interface{loopbackInterface(), nil} {
626
+ // Note that multicast interface assignment by system
627
+ // is not recommended because it usually relies on
628
+ // routing stuff for finding out an appropriate
629
+ // nexthop containing both network and link layer
630
+ // adjacencies.
631
+ if ifi == nil && !*testIPv6 {
632
+ continue
633
+ }
634
+ for _, tt := range ipv6MulticastListenerTests {
635
+ var err error
636
+ cs := make([]*UDPConn, 2)
637
+ if cs[0], err = ListenMulticastUDP(tt.net, ifi, tt.gaddr); err != nil {
638
+ t.Fatal(err)
639
+ }
640
+ if err := checkMulticastListener(cs[0], tt.gaddr.IP); err != nil {
641
+ closer(cs)
642
+ t.Fatal(err)
643
+ }
644
+ if cs[1], err = ListenMulticastUDP(tt.net, ifi, tt.gaddr); err != nil {
645
+ closer(cs)
646
+ t.Fatal(err)
647
+ }
648
+ if err := checkMulticastListener(cs[1], tt.gaddr.IP); err != nil {
649
+ closer(cs)
650
+ t.Fatal(err)
651
+ }
652
+ closer(cs)
653
+ }
654
+ }
655
+ }
656
+
657
+ func checkMulticastListener(c *UDPConn, ip IP) error {
658
+ if ok, err := multicastRIBContains(ip); err != nil {
659
+ return err
660
+ } else if !ok {
661
+ return fmt.Errorf("%s not found in multicast rib", ip.String())
662
+ }
663
+ la := c.LocalAddr()
664
+ if la, ok := la.(*UDPAddr); !ok || la.Port == 0 {
665
+ return fmt.Errorf("got %v; want a proper address with non-zero port number", la)
666
+ }
667
+ return nil
668
+ }
669
+
670
+ func multicastRIBContains(ip IP) (bool, error) {
671
+ switch runtime.GOOS {
672
+ case "aix", "dragonfly", "netbsd", "openbsd", "plan9", "solaris", "illumos", "windows":
673
+ return true, nil // not implemented yet
674
+ case "linux":
675
+ if runtime.GOARCH == "arm" || runtime.GOARCH == "alpha" {
676
+ return true, nil // not implemented yet
677
+ }
678
+ }
679
+ ift, err := Interfaces()
680
+ if err != nil {
681
+ return false, err
682
+ }
683
+ for _, ifi := range ift {
684
+ ifmat, err := ifi.MulticastAddrs()
685
+ if err != nil {
686
+ return false, err
687
+ }
688
+ for _, ifma := range ifmat {
689
+ if ifma.(*IPAddr).IP.Equal(ip) {
690
+ return true, nil
691
+ }
692
+ }
693
+ }
694
+ return false, nil
695
+ }
696
+
697
+ // Issue 21856.
698
+ func TestClosingListener(t *testing.T) {
699
+ ln := newLocalListener(t, "tcp")
700
+ addr := ln.Addr()
701
+
702
+ go func() {
703
+ for {
704
+ c, err := ln.Accept()
705
+ if err != nil {
706
+ return
707
+ }
708
+ c.Close()
709
+ }
710
+ }()
711
+
712
+ // Let the goroutine start. We don't sleep long: if the
713
+ // goroutine doesn't start, the test will pass without really
714
+ // testing anything, which is OK.
715
+ time.Sleep(time.Millisecond)
716
+
717
+ ln.Close()
718
+
719
+ ln2, err := Listen("tcp", addr.String())
720
+ if err != nil {
721
+ t.Fatal(err)
722
+ }
723
+ ln2.Close()
724
+ }
725
+
726
+ func TestListenConfigControl(t *testing.T) {
727
+ switch runtime.GOOS {
728
+ case "plan9":
729
+ t.Skipf("not supported on %s", runtime.GOOS)
730
+ }
731
+
732
+ t.Run("StreamListen", func(t *testing.T) {
733
+ for _, network := range []string{"tcp", "tcp4", "tcp6", "unix", "unixpacket"} {
734
+ if !testableNetwork(network) {
735
+ continue
736
+ }
737
+ ln := newLocalListener(t, network, &ListenConfig{Control: controlOnConnSetup})
738
+ ln.Close()
739
+ }
740
+ })
741
+ t.Run("PacketListen", func(t *testing.T) {
742
+ for _, network := range []string{"udp", "udp4", "udp6", "unixgram"} {
743
+ if !testableNetwork(network) {
744
+ continue
745
+ }
746
+ c := newLocalPacketListener(t, network, &ListenConfig{Control: controlOnConnSetup})
747
+ c.Close()
748
+ }
749
+ })
750
+ }
platform/dbops/binaries/go/go/src/net/lookup.go ADDED
@@ -0,0 +1,920 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2012 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
+ "errors"
10
+ "internal/nettrace"
11
+ "internal/singleflight"
12
+ "net/netip"
13
+ "sync"
14
+
15
+ "golang.org/x/net/dns/dnsmessage"
16
+ )
17
+
18
+ // protocols contains minimal mappings between internet protocol
19
+ // names and numbers for platforms that don't have a complete list of
20
+ // protocol numbers.
21
+ //
22
+ // See https://www.iana.org/assignments/protocol-numbers
23
+ //
24
+ // On Unix, this map is augmented by readProtocols via lookupProtocol.
25
+ var protocols = map[string]int{
26
+ "icmp": 1,
27
+ "igmp": 2,
28
+ "tcp": 6,
29
+ "udp": 17,
30
+ "ipv6-icmp": 58,
31
+ }
32
+
33
+ // services contains minimal mappings between services names and port
34
+ // numbers for platforms that don't have a complete list of port numbers.
35
+ //
36
+ // See https://www.iana.org/assignments/service-names-port-numbers
37
+ //
38
+ // On Unix, this map is augmented by readServices via goLookupPort.
39
+ var services = map[string]map[string]int{
40
+ "udp": {
41
+ "domain": 53,
42
+ },
43
+ "tcp": {
44
+ "ftp": 21,
45
+ "ftps": 990,
46
+ "gopher": 70, // ʕ◔ϖ◔ʔ
47
+ "http": 80,
48
+ "https": 443,
49
+ "imap2": 143,
50
+ "imap3": 220,
51
+ "imaps": 993,
52
+ "pop3": 110,
53
+ "pop3s": 995,
54
+ "smtp": 25,
55
+ "submissions": 465,
56
+ "ssh": 22,
57
+ "telnet": 23,
58
+ },
59
+ }
60
+
61
+ // dnsWaitGroup can be used by tests to wait for all DNS goroutines to
62
+ // complete. This avoids races on the test hooks.
63
+ var dnsWaitGroup sync.WaitGroup
64
+
65
+ const maxProtoLength = len("RSVP-E2E-IGNORE") + 10 // with room to grow
66
+
67
+ func lookupProtocolMap(name string) (int, error) {
68
+ var lowerProtocol [maxProtoLength]byte
69
+ n := copy(lowerProtocol[:], name)
70
+ lowerASCIIBytes(lowerProtocol[:n])
71
+ proto, found := protocols[string(lowerProtocol[:n])]
72
+ if !found || n != len(name) {
73
+ return 0, &AddrError{Err: "unknown IP protocol specified", Addr: name}
74
+ }
75
+ return proto, nil
76
+ }
77
+
78
+ // maxPortBufSize is the longest reasonable name of a service
79
+ // (non-numeric port).
80
+ // Currently the longest known IANA-unregistered name is
81
+ // "mobility-header", so we use that length, plus some slop in case
82
+ // something longer is added in the future.
83
+ const maxPortBufSize = len("mobility-header") + 10
84
+
85
+ func lookupPortMap(network, service string) (port int, error error) {
86
+ switch network {
87
+ case "ip": // no hints
88
+ if p, err := lookupPortMapWithNetwork("tcp", "ip", service); err == nil {
89
+ return p, nil
90
+ }
91
+ return lookupPortMapWithNetwork("udp", "ip", service)
92
+ case "tcp", "tcp4", "tcp6":
93
+ return lookupPortMapWithNetwork("tcp", "tcp", service)
94
+ case "udp", "udp4", "udp6":
95
+ return lookupPortMapWithNetwork("udp", "udp", service)
96
+ }
97
+ return 0, &DNSError{Err: "unknown network", Name: network + "/" + service}
98
+ }
99
+
100
+ func lookupPortMapWithNetwork(network, errNetwork, service string) (port int, error error) {
101
+ if m, ok := services[network]; ok {
102
+ var lowerService [maxPortBufSize]byte
103
+ n := copy(lowerService[:], service)
104
+ lowerASCIIBytes(lowerService[:n])
105
+ if port, ok := m[string(lowerService[:n])]; ok && n == len(service) {
106
+ return port, nil
107
+ }
108
+ return 0, &DNSError{Err: "unknown port", Name: errNetwork + "/" + service, IsNotFound: true}
109
+ }
110
+ return 0, &DNSError{Err: "unknown network", Name: errNetwork + "/" + service}
111
+ }
112
+
113
+ // ipVersion returns the provided network's IP version: '4', '6' or 0
114
+ // if network does not end in a '4' or '6' byte.
115
+ func ipVersion(network string) byte {
116
+ if network == "" {
117
+ return 0
118
+ }
119
+ n := network[len(network)-1]
120
+ if n != '4' && n != '6' {
121
+ n = 0
122
+ }
123
+ return n
124
+ }
125
+
126
+ // DefaultResolver is the resolver used by the package-level Lookup
127
+ // functions and by Dialers without a specified Resolver.
128
+ var DefaultResolver = &Resolver{}
129
+
130
+ // A Resolver looks up names and numbers.
131
+ //
132
+ // A nil *Resolver is equivalent to a zero Resolver.
133
+ type Resolver struct {
134
+ // PreferGo controls whether Go's built-in DNS resolver is preferred
135
+ // on platforms where it's available. It is equivalent to setting
136
+ // GODEBUG=netdns=go, but scoped to just this resolver.
137
+ PreferGo bool
138
+
139
+ // StrictErrors controls the behavior of temporary errors
140
+ // (including timeout, socket errors, and SERVFAIL) when using
141
+ // Go's built-in resolver. For a query composed of multiple
142
+ // sub-queries (such as an A+AAAA address lookup, or walking the
143
+ // DNS search list), this option causes such errors to abort the
144
+ // whole query instead of returning a partial result. This is
145
+ // not enabled by default because it may affect compatibility
146
+ // with resolvers that process AAAA queries incorrectly.
147
+ StrictErrors bool
148
+
149
+ // Dial optionally specifies an alternate dialer for use by
150
+ // Go's built-in DNS resolver to make TCP and UDP connections
151
+ // to DNS services. The host in the address parameter will
152
+ // always be a literal IP address and not a host name, and the
153
+ // port in the address parameter will be a literal port number
154
+ // and not a service name.
155
+ // If the Conn returned is also a PacketConn, sent and received DNS
156
+ // messages must adhere to RFC 1035 section 4.2.1, "UDP usage".
157
+ // Otherwise, DNS messages transmitted over Conn must adhere
158
+ // to RFC 7766 section 5, "Transport Protocol Selection".
159
+ // If nil, the default dialer is used.
160
+ Dial func(ctx context.Context, network, address string) (Conn, error)
161
+
162
+ // lookupGroup merges LookupIPAddr calls together for lookups for the same
163
+ // host. The lookupGroup key is the LookupIPAddr.host argument.
164
+ // The return values are ([]IPAddr, error).
165
+ lookupGroup singleflight.Group
166
+
167
+ // TODO(bradfitz): optional interface impl override hook
168
+ // TODO(bradfitz): Timeout time.Duration?
169
+ }
170
+
171
+ func (r *Resolver) preferGo() bool { return r != nil && r.PreferGo }
172
+ func (r *Resolver) strictErrors() bool { return r != nil && r.StrictErrors }
173
+
174
+ func (r *Resolver) getLookupGroup() *singleflight.Group {
175
+ if r == nil {
176
+ return &DefaultResolver.lookupGroup
177
+ }
178
+ return &r.lookupGroup
179
+ }
180
+
181
+ // LookupHost looks up the given host using the local resolver.
182
+ // It returns a slice of that host's addresses.
183
+ //
184
+ // LookupHost uses [context.Background] internally; to specify the context, use
185
+ // [Resolver.LookupHost].
186
+ func LookupHost(host string) (addrs []string, err error) {
187
+ return DefaultResolver.LookupHost(context.Background(), host)
188
+ }
189
+
190
+ // LookupHost looks up the given host using the local resolver.
191
+ // It returns a slice of that host's addresses.
192
+ func (r *Resolver) LookupHost(ctx context.Context, host string) (addrs []string, err error) {
193
+ // Make sure that no matter what we do later, host=="" is rejected.
194
+ if host == "" {
195
+ return nil, &DNSError{Err: errNoSuchHost.Error(), Name: host, IsNotFound: true}
196
+ }
197
+ if _, err := netip.ParseAddr(host); err == nil {
198
+ return []string{host}, nil
199
+ }
200
+ return r.lookupHost(ctx, host)
201
+ }
202
+
203
+ // LookupIP looks up host using the local resolver.
204
+ // It returns a slice of that host's IPv4 and IPv6 addresses.
205
+ func LookupIP(host string) ([]IP, error) {
206
+ addrs, err := DefaultResolver.LookupIPAddr(context.Background(), host)
207
+ if err != nil {
208
+ return nil, err
209
+ }
210
+ ips := make([]IP, len(addrs))
211
+ for i, ia := range addrs {
212
+ ips[i] = ia.IP
213
+ }
214
+ return ips, nil
215
+ }
216
+
217
+ // LookupIPAddr looks up host using the local resolver.
218
+ // It returns a slice of that host's IPv4 and IPv6 addresses.
219
+ func (r *Resolver) LookupIPAddr(ctx context.Context, host string) ([]IPAddr, error) {
220
+ return r.lookupIPAddr(ctx, "ip", host)
221
+ }
222
+
223
+ // LookupIP looks up host for the given network using the local resolver.
224
+ // It returns a slice of that host's IP addresses of the type specified by
225
+ // network.
226
+ // network must be one of "ip", "ip4" or "ip6".
227
+ func (r *Resolver) LookupIP(ctx context.Context, network, host string) ([]IP, error) {
228
+ afnet, _, err := parseNetwork(ctx, network, false)
229
+ if err != nil {
230
+ return nil, err
231
+ }
232
+ switch afnet {
233
+ case "ip", "ip4", "ip6":
234
+ default:
235
+ return nil, UnknownNetworkError(network)
236
+ }
237
+
238
+ if host == "" {
239
+ return nil, &DNSError{Err: errNoSuchHost.Error(), Name: host, IsNotFound: true}
240
+ }
241
+ addrs, err := r.internetAddrList(ctx, afnet, host)
242
+ if err != nil {
243
+ return nil, err
244
+ }
245
+
246
+ ips := make([]IP, 0, len(addrs))
247
+ for _, addr := range addrs {
248
+ ips = append(ips, addr.(*IPAddr).IP)
249
+ }
250
+ return ips, nil
251
+ }
252
+
253
+ // LookupNetIP looks up host using the local resolver.
254
+ // It returns a slice of that host's IP addresses of the type specified by
255
+ // network.
256
+ // The network must be one of "ip", "ip4" or "ip6".
257
+ func (r *Resolver) LookupNetIP(ctx context.Context, network, host string) ([]netip.Addr, error) {
258
+ // TODO(bradfitz): make this efficient, making the internal net package
259
+ // type throughout be netip.Addr and only converting to the net.IP slice
260
+ // version at the edge. But for now (2021-10-20), this is a wrapper around
261
+ // the old way.
262
+ ips, err := r.LookupIP(ctx, network, host)
263
+ if err != nil {
264
+ return nil, err
265
+ }
266
+ ret := make([]netip.Addr, 0, len(ips))
267
+ for _, ip := range ips {
268
+ if a, ok := netip.AddrFromSlice(ip); ok {
269
+ ret = append(ret, a)
270
+ }
271
+ }
272
+ return ret, nil
273
+ }
274
+
275
+ // onlyValuesCtx is a context that uses an underlying context
276
+ // for value lookup if the underlying context hasn't yet expired.
277
+ type onlyValuesCtx struct {
278
+ context.Context
279
+ lookupValues context.Context
280
+ }
281
+
282
+ var _ context.Context = (*onlyValuesCtx)(nil)
283
+
284
+ // Value performs a lookup if the original context hasn't expired.
285
+ func (ovc *onlyValuesCtx) Value(key any) any {
286
+ select {
287
+ case <-ovc.lookupValues.Done():
288
+ return nil
289
+ default:
290
+ return ovc.lookupValues.Value(key)
291
+ }
292
+ }
293
+
294
+ // withUnexpiredValuesPreserved returns a context.Context that only uses lookupCtx
295
+ // for its values, otherwise it is never canceled and has no deadline.
296
+ // If the lookup context expires, any looked up values will return nil.
297
+ // See Issue 28600.
298
+ func withUnexpiredValuesPreserved(lookupCtx context.Context) context.Context {
299
+ return &onlyValuesCtx{Context: context.Background(), lookupValues: lookupCtx}
300
+ }
301
+
302
+ // lookupIPAddr looks up host using the local resolver and particular network.
303
+ // It returns a slice of that host's IPv4 and IPv6 addresses.
304
+ func (r *Resolver) lookupIPAddr(ctx context.Context, network, host string) ([]IPAddr, error) {
305
+ // Make sure that no matter what we do later, host=="" is rejected.
306
+ if host == "" {
307
+ return nil, &DNSError{Err: errNoSuchHost.Error(), Name: host, IsNotFound: true}
308
+ }
309
+ if ip, err := netip.ParseAddr(host); err == nil {
310
+ return []IPAddr{{IP: IP(ip.AsSlice()).To16(), Zone: ip.Zone()}}, nil
311
+ }
312
+ trace, _ := ctx.Value(nettrace.TraceKey{}).(*nettrace.Trace)
313
+ if trace != nil && trace.DNSStart != nil {
314
+ trace.DNSStart(host)
315
+ }
316
+ // The underlying resolver func is lookupIP by default but it
317
+ // can be overridden by tests. This is needed by net/http, so it
318
+ // uses a context key instead of unexported variables.
319
+ resolverFunc := r.lookupIP
320
+ if alt, _ := ctx.Value(nettrace.LookupIPAltResolverKey{}).(func(context.Context, string, string) ([]IPAddr, error)); alt != nil {
321
+ resolverFunc = alt
322
+ }
323
+
324
+ // We don't want a cancellation of ctx to affect the
325
+ // lookupGroup operation. Otherwise if our context gets
326
+ // canceled it might cause an error to be returned to a lookup
327
+ // using a completely different context. However we need to preserve
328
+ // only the values in context. See Issue 28600.
329
+ lookupGroupCtx, lookupGroupCancel := context.WithCancel(withUnexpiredValuesPreserved(ctx))
330
+
331
+ lookupKey := network + "\000" + host
332
+ dnsWaitGroup.Add(1)
333
+ ch := r.getLookupGroup().DoChan(lookupKey, func() (any, error) {
334
+ return testHookLookupIP(lookupGroupCtx, resolverFunc, network, host)
335
+ })
336
+
337
+ dnsWaitGroupDone := func(ch <-chan singleflight.Result, cancelFn context.CancelFunc) {
338
+ <-ch
339
+ dnsWaitGroup.Done()
340
+ cancelFn()
341
+ }
342
+ select {
343
+ case <-ctx.Done():
344
+ // Our context was canceled. If we are the only
345
+ // goroutine looking up this key, then drop the key
346
+ // from the lookupGroup and cancel the lookup.
347
+ // If there are other goroutines looking up this key,
348
+ // let the lookup continue uncanceled, and let later
349
+ // lookups with the same key share the result.
350
+ // See issues 8602, 20703, 22724.
351
+ if r.getLookupGroup().ForgetUnshared(lookupKey) {
352
+ lookupGroupCancel()
353
+ go dnsWaitGroupDone(ch, func() {})
354
+ } else {
355
+ go dnsWaitGroupDone(ch, lookupGroupCancel)
356
+ }
357
+ ctxErr := ctx.Err()
358
+ err := &DNSError{
359
+ Err: mapErr(ctxErr).Error(),
360
+ Name: host,
361
+ IsTimeout: ctxErr == context.DeadlineExceeded,
362
+ }
363
+ if trace != nil && trace.DNSDone != nil {
364
+ trace.DNSDone(nil, false, err)
365
+ }
366
+ return nil, err
367
+ case r := <-ch:
368
+ dnsWaitGroup.Done()
369
+ lookupGroupCancel()
370
+ err := r.Err
371
+ if err != nil {
372
+ if _, ok := err.(*DNSError); !ok {
373
+ isTimeout := false
374
+ if err == context.DeadlineExceeded {
375
+ isTimeout = true
376
+ } else if terr, ok := err.(timeout); ok {
377
+ isTimeout = terr.Timeout()
378
+ }
379
+ err = &DNSError{
380
+ Err: err.Error(),
381
+ Name: host,
382
+ IsTimeout: isTimeout,
383
+ }
384
+ }
385
+ }
386
+ if trace != nil && trace.DNSDone != nil {
387
+ addrs, _ := r.Val.([]IPAddr)
388
+ trace.DNSDone(ipAddrsEface(addrs), r.Shared, err)
389
+ }
390
+ return lookupIPReturn(r.Val, err, r.Shared)
391
+ }
392
+ }
393
+
394
+ // lookupIPReturn turns the return values from singleflight.Do into
395
+ // the return values from LookupIP.
396
+ func lookupIPReturn(addrsi any, err error, shared bool) ([]IPAddr, error) {
397
+ if err != nil {
398
+ return nil, err
399
+ }
400
+ addrs := addrsi.([]IPAddr)
401
+ if shared {
402
+ clone := make([]IPAddr, len(addrs))
403
+ copy(clone, addrs)
404
+ addrs = clone
405
+ }
406
+ return addrs, nil
407
+ }
408
+
409
+ // ipAddrsEface returns an empty interface slice of addrs.
410
+ func ipAddrsEface(addrs []IPAddr) []any {
411
+ s := make([]any, len(addrs))
412
+ for i, v := range addrs {
413
+ s[i] = v
414
+ }
415
+ return s
416
+ }
417
+
418
+ // LookupPort looks up the port for the given network and service.
419
+ //
420
+ // LookupPort uses [context.Background] internally; to specify the context, use
421
+ // [Resolver.LookupPort].
422
+ func LookupPort(network, service string) (port int, err error) {
423
+ return DefaultResolver.LookupPort(context.Background(), network, service)
424
+ }
425
+
426
+ // LookupPort looks up the port for the given network and service.
427
+ //
428
+ // The network must be one of "tcp", "tcp4", "tcp6", "udp", "udp4", "udp6" or "ip".
429
+ func (r *Resolver) LookupPort(ctx context.Context, network, service string) (port int, err error) {
430
+ port, needsLookup := parsePort(service)
431
+ if needsLookup {
432
+ switch network {
433
+ case "tcp", "tcp4", "tcp6", "udp", "udp4", "udp6", "ip":
434
+ case "": // a hint wildcard for Go 1.0 undocumented behavior
435
+ network = "ip"
436
+ default:
437
+ return 0, &AddrError{Err: "unknown network", Addr: network}
438
+ }
439
+ port, err = r.lookupPort(ctx, network, service)
440
+ if err != nil {
441
+ return 0, err
442
+ }
443
+ }
444
+ if 0 > port || port > 65535 {
445
+ return 0, &AddrError{Err: "invalid port", Addr: service}
446
+ }
447
+ return port, nil
448
+ }
449
+
450
+ // LookupCNAME returns the canonical name for the given host.
451
+ // Callers that do not care about the canonical name can call
452
+ // [LookupHost] or [LookupIP] directly; both take care of resolving
453
+ // the canonical name as part of the lookup.
454
+ //
455
+ // A canonical name is the final name after following zero
456
+ // or more CNAME records.
457
+ // LookupCNAME does not return an error if host does not
458
+ // contain DNS "CNAME" records, as long as host resolves to
459
+ // address records.
460
+ //
461
+ // The returned canonical name is validated to be a properly
462
+ // formatted presentation-format domain name.
463
+ //
464
+ // LookupCNAME uses [context.Background] internally; to specify the context, use
465
+ // [Resolver.LookupCNAME].
466
+ func LookupCNAME(host string) (cname string, err error) {
467
+ return DefaultResolver.LookupCNAME(context.Background(), host)
468
+ }
469
+
470
+ // LookupCNAME returns the canonical name for the given host.
471
+ // Callers that do not care about the canonical name can call
472
+ // [LookupHost] or [LookupIP] directly; both take care of resolving
473
+ // the canonical name as part of the lookup.
474
+ //
475
+ // A canonical name is the final name after following zero
476
+ // or more CNAME records.
477
+ // LookupCNAME does not return an error if host does not
478
+ // contain DNS "CNAME" records, as long as host resolves to
479
+ // address records.
480
+ //
481
+ // The returned canonical name is validated to be a properly
482
+ // formatted presentation-format domain name.
483
+ func (r *Resolver) LookupCNAME(ctx context.Context, host string) (string, error) {
484
+ cname, err := r.lookupCNAME(ctx, host)
485
+ if err != nil {
486
+ return "", err
487
+ }
488
+ if !isDomainName(cname) {
489
+ return "", &DNSError{Err: errMalformedDNSRecordsDetail, Name: host}
490
+ }
491
+ return cname, nil
492
+ }
493
+
494
+ // LookupSRV tries to resolve an [SRV] query of the given service,
495
+ // protocol, and domain name. The proto is "tcp" or "udp".
496
+ // The returned records are sorted by priority and randomized
497
+ // by weight within a priority.
498
+ //
499
+ // LookupSRV constructs the DNS name to look up following RFC 2782.
500
+ // That is, it looks up _service._proto.name. To accommodate services
501
+ // publishing SRV records under non-standard names, if both service
502
+ // and proto are empty strings, LookupSRV looks up name directly.
503
+ //
504
+ // The returned service names are validated to be properly
505
+ // formatted presentation-format domain names. If the response contains
506
+ // invalid names, those records are filtered out and an error
507
+ // will be returned alongside the remaining results, if any.
508
+ func LookupSRV(service, proto, name string) (cname string, addrs []*SRV, err error) {
509
+ return DefaultResolver.LookupSRV(context.Background(), service, proto, name)
510
+ }
511
+
512
+ // LookupSRV tries to resolve an [SRV] query of the given service,
513
+ // protocol, and domain name. The proto is "tcp" or "udp".
514
+ // The returned records are sorted by priority and randomized
515
+ // by weight within a priority.
516
+ //
517
+ // LookupSRV constructs the DNS name to look up following RFC 2782.
518
+ // That is, it looks up _service._proto.name. To accommodate services
519
+ // publishing SRV records under non-standard names, if both service
520
+ // and proto are empty strings, LookupSRV looks up name directly.
521
+ //
522
+ // The returned service names are validated to be properly
523
+ // formatted presentation-format domain names. If the response contains
524
+ // invalid names, those records are filtered out and an error
525
+ // will be returned alongside the remaining results, if any.
526
+ func (r *Resolver) LookupSRV(ctx context.Context, service, proto, name string) (string, []*SRV, error) {
527
+ cname, addrs, err := r.lookupSRV(ctx, service, proto, name)
528
+ if err != nil {
529
+ return "", nil, err
530
+ }
531
+ if cname != "" && !isDomainName(cname) {
532
+ return "", nil, &DNSError{Err: "SRV header name is invalid", Name: name}
533
+ }
534
+ filteredAddrs := make([]*SRV, 0, len(addrs))
535
+ for _, addr := range addrs {
536
+ if addr == nil {
537
+ continue
538
+ }
539
+ if !isDomainName(addr.Target) {
540
+ continue
541
+ }
542
+ filteredAddrs = append(filteredAddrs, addr)
543
+ }
544
+ if len(addrs) != len(filteredAddrs) {
545
+ return cname, filteredAddrs, &DNSError{Err: errMalformedDNSRecordsDetail, Name: name}
546
+ }
547
+ return cname, filteredAddrs, nil
548
+ }
549
+
550
+ // LookupMX returns the DNS MX records for the given domain name sorted by preference.
551
+ //
552
+ // The returned mail server names are validated to be properly
553
+ // formatted presentation-format domain names. If the response contains
554
+ // invalid names, those records are filtered out and an error
555
+ // will be returned alongside the remaining results, if any.
556
+ //
557
+ // LookupMX uses [context.Background] internally; to specify the context, use
558
+ // [Resolver.LookupMX].
559
+ func LookupMX(name string) ([]*MX, error) {
560
+ return DefaultResolver.LookupMX(context.Background(), name)
561
+ }
562
+
563
+ // LookupMX returns the DNS MX records for the given domain name sorted by preference.
564
+ //
565
+ // The returned mail server names are validated to be properly
566
+ // formatted presentation-format domain names. If the response contains
567
+ // invalid names, those records are filtered out and an error
568
+ // will be returned alongside the remaining results, if any.
569
+ func (r *Resolver) LookupMX(ctx context.Context, name string) ([]*MX, error) {
570
+ records, err := r.lookupMX(ctx, name)
571
+ if err != nil {
572
+ return nil, err
573
+ }
574
+ filteredMX := make([]*MX, 0, len(records))
575
+ for _, mx := range records {
576
+ if mx == nil {
577
+ continue
578
+ }
579
+ if !isDomainName(mx.Host) {
580
+ continue
581
+ }
582
+ filteredMX = append(filteredMX, mx)
583
+ }
584
+ if len(records) != len(filteredMX) {
585
+ return filteredMX, &DNSError{Err: errMalformedDNSRecordsDetail, Name: name}
586
+ }
587
+ return filteredMX, nil
588
+ }
589
+
590
+ // LookupNS returns the DNS NS records for the given domain name.
591
+ //
592
+ // The returned name server names are validated to be properly
593
+ // formatted presentation-format domain names. If the response contains
594
+ // invalid names, those records are filtered out and an error
595
+ // will be returned alongside the remaining results, if any.
596
+ //
597
+ // LookupNS uses [context.Background] internally; to specify the context, use
598
+ // [Resolver.LookupNS].
599
+ func LookupNS(name string) ([]*NS, error) {
600
+ return DefaultResolver.LookupNS(context.Background(), name)
601
+ }
602
+
603
+ // LookupNS returns the DNS NS records for the given domain name.
604
+ //
605
+ // The returned name server names are validated to be properly
606
+ // formatted presentation-format domain names. If the response contains
607
+ // invalid names, those records are filtered out and an error
608
+ // will be returned alongside the remaining results, if any.
609
+ func (r *Resolver) LookupNS(ctx context.Context, name string) ([]*NS, error) {
610
+ records, err := r.lookupNS(ctx, name)
611
+ if err != nil {
612
+ return nil, err
613
+ }
614
+ filteredNS := make([]*NS, 0, len(records))
615
+ for _, ns := range records {
616
+ if ns == nil {
617
+ continue
618
+ }
619
+ if !isDomainName(ns.Host) {
620
+ continue
621
+ }
622
+ filteredNS = append(filteredNS, ns)
623
+ }
624
+ if len(records) != len(filteredNS) {
625
+ return filteredNS, &DNSError{Err: errMalformedDNSRecordsDetail, Name: name}
626
+ }
627
+ return filteredNS, nil
628
+ }
629
+
630
+ // LookupTXT returns the DNS TXT records for the given domain name.
631
+ //
632
+ // LookupTXT uses [context.Background] internally; to specify the context, use
633
+ // [Resolver.LookupTXT].
634
+ func LookupTXT(name string) ([]string, error) {
635
+ return DefaultResolver.lookupTXT(context.Background(), name)
636
+ }
637
+
638
+ // LookupTXT returns the DNS TXT records for the given domain name.
639
+ func (r *Resolver) LookupTXT(ctx context.Context, name string) ([]string, error) {
640
+ return r.lookupTXT(ctx, name)
641
+ }
642
+
643
+ // LookupAddr performs a reverse lookup for the given address, returning a list
644
+ // of names mapping to that address.
645
+ //
646
+ // The returned names are validated to be properly formatted presentation-format
647
+ // domain names. If the response contains invalid names, those records are filtered
648
+ // out and an error will be returned alongside the remaining results, if any.
649
+ //
650
+ // When using the host C library resolver, at most one result will be
651
+ // returned. To bypass the host resolver, use a custom [Resolver].
652
+ //
653
+ // LookupAddr uses [context.Background] internally; to specify the context, use
654
+ // [Resolver.LookupAddr].
655
+ func LookupAddr(addr string) (names []string, err error) {
656
+ return DefaultResolver.LookupAddr(context.Background(), addr)
657
+ }
658
+
659
+ // LookupAddr performs a reverse lookup for the given address, returning a list
660
+ // of names mapping to that address.
661
+ //
662
+ // The returned names are validated to be properly formatted presentation-format
663
+ // domain names. If the response contains invalid names, those records are filtered
664
+ // out and an error will be returned alongside the remaining results, if any.
665
+ func (r *Resolver) LookupAddr(ctx context.Context, addr string) ([]string, error) {
666
+ names, err := r.lookupAddr(ctx, addr)
667
+ if err != nil {
668
+ return nil, err
669
+ }
670
+ filteredNames := make([]string, 0, len(names))
671
+ for _, name := range names {
672
+ if isDomainName(name) {
673
+ filteredNames = append(filteredNames, name)
674
+ }
675
+ }
676
+ if len(names) != len(filteredNames) {
677
+ return filteredNames, &DNSError{Err: errMalformedDNSRecordsDetail, Name: addr}
678
+ }
679
+ return filteredNames, nil
680
+ }
681
+
682
+ // errMalformedDNSRecordsDetail is the DNSError detail which is returned when a Resolver.Lookup...
683
+ // method receives DNS records which contain invalid DNS names. This may be returned alongside
684
+ // results which have had the malformed records filtered out.
685
+ var errMalformedDNSRecordsDetail = "DNS response contained records which contain invalid names"
686
+
687
+ // dial makes a new connection to the provided server (which must be
688
+ // an IP address) with the provided network type, using either r.Dial
689
+ // (if both r and r.Dial are non-nil) or else Dialer.DialContext.
690
+ func (r *Resolver) dial(ctx context.Context, network, server string) (Conn, error) {
691
+ // Calling Dial here is scary -- we have to be sure not to
692
+ // dial a name that will require a DNS lookup, or Dial will
693
+ // call back here to translate it. The DNS config parser has
694
+ // already checked that all the cfg.servers are IP
695
+ // addresses, which Dial will use without a DNS lookup.
696
+ var c Conn
697
+ var err error
698
+ if r != nil && r.Dial != nil {
699
+ c, err = r.Dial(ctx, network, server)
700
+ } else {
701
+ var d Dialer
702
+ c, err = d.DialContext(ctx, network, server)
703
+ }
704
+ if err != nil {
705
+ return nil, mapErr(err)
706
+ }
707
+ return c, nil
708
+ }
709
+
710
+ // goLookupSRV returns the SRV records for a target name, built either
711
+ // from its component service ("sip"), protocol ("tcp"), and name
712
+ // ("example.com."), or from name directly (if service and proto are
713
+ // both empty).
714
+ //
715
+ // In either case, the returned target name ("_sip._tcp.example.com.")
716
+ // is also returned on success.
717
+ //
718
+ // The records are sorted by weight.
719
+ func (r *Resolver) goLookupSRV(ctx context.Context, service, proto, name string) (target string, srvs []*SRV, err error) {
720
+ if service == "" && proto == "" {
721
+ target = name
722
+ } else {
723
+ target = "_" + service + "._" + proto + "." + name
724
+ }
725
+ p, server, err := r.lookup(ctx, target, dnsmessage.TypeSRV, nil)
726
+ if err != nil {
727
+ return "", nil, err
728
+ }
729
+ var cname dnsmessage.Name
730
+ for {
731
+ h, err := p.AnswerHeader()
732
+ if err == dnsmessage.ErrSectionDone {
733
+ break
734
+ }
735
+ if err != nil {
736
+ return "", nil, &DNSError{
737
+ Err: "cannot unmarshal DNS message",
738
+ Name: name,
739
+ Server: server,
740
+ }
741
+ }
742
+ if h.Type != dnsmessage.TypeSRV {
743
+ if err := p.SkipAnswer(); err != nil {
744
+ return "", nil, &DNSError{
745
+ Err: "cannot unmarshal DNS message",
746
+ Name: name,
747
+ Server: server,
748
+ }
749
+ }
750
+ continue
751
+ }
752
+ if cname.Length == 0 && h.Name.Length != 0 {
753
+ cname = h.Name
754
+ }
755
+ srv, err := p.SRVResource()
756
+ if err != nil {
757
+ return "", nil, &DNSError{
758
+ Err: "cannot unmarshal DNS message",
759
+ Name: name,
760
+ Server: server,
761
+ }
762
+ }
763
+ srvs = append(srvs, &SRV{Target: srv.Target.String(), Port: srv.Port, Priority: srv.Priority, Weight: srv.Weight})
764
+ }
765
+ byPriorityWeight(srvs).sort()
766
+ return cname.String(), srvs, nil
767
+ }
768
+
769
+ // goLookupMX returns the MX records for name.
770
+ func (r *Resolver) goLookupMX(ctx context.Context, name string) ([]*MX, error) {
771
+ p, server, err := r.lookup(ctx, name, dnsmessage.TypeMX, nil)
772
+ if err != nil {
773
+ return nil, err
774
+ }
775
+ var mxs []*MX
776
+ for {
777
+ h, err := p.AnswerHeader()
778
+ if err == dnsmessage.ErrSectionDone {
779
+ break
780
+ }
781
+ if err != nil {
782
+ return nil, &DNSError{
783
+ Err: "cannot unmarshal DNS message",
784
+ Name: name,
785
+ Server: server,
786
+ }
787
+ }
788
+ if h.Type != dnsmessage.TypeMX {
789
+ if err := p.SkipAnswer(); err != nil {
790
+ return nil, &DNSError{
791
+ Err: "cannot unmarshal DNS message",
792
+ Name: name,
793
+ Server: server,
794
+ }
795
+ }
796
+ continue
797
+ }
798
+ mx, err := p.MXResource()
799
+ if err != nil {
800
+ return nil, &DNSError{
801
+ Err: "cannot unmarshal DNS message",
802
+ Name: name,
803
+ Server: server,
804
+ }
805
+ }
806
+ mxs = append(mxs, &MX{Host: mx.MX.String(), Pref: mx.Pref})
807
+
808
+ }
809
+ byPref(mxs).sort()
810
+ return mxs, nil
811
+ }
812
+
813
+ // goLookupNS returns the NS records for name.
814
+ func (r *Resolver) goLookupNS(ctx context.Context, name string) ([]*NS, error) {
815
+ p, server, err := r.lookup(ctx, name, dnsmessage.TypeNS, nil)
816
+ if err != nil {
817
+ return nil, err
818
+ }
819
+ var nss []*NS
820
+ for {
821
+ h, err := p.AnswerHeader()
822
+ if err == dnsmessage.ErrSectionDone {
823
+ break
824
+ }
825
+ if err != nil {
826
+ return nil, &DNSError{
827
+ Err: "cannot unmarshal DNS message",
828
+ Name: name,
829
+ Server: server,
830
+ }
831
+ }
832
+ if h.Type != dnsmessage.TypeNS {
833
+ if err := p.SkipAnswer(); err != nil {
834
+ return nil, &DNSError{
835
+ Err: "cannot unmarshal DNS message",
836
+ Name: name,
837
+ Server: server,
838
+ }
839
+ }
840
+ continue
841
+ }
842
+ ns, err := p.NSResource()
843
+ if err != nil {
844
+ return nil, &DNSError{
845
+ Err: "cannot unmarshal DNS message",
846
+ Name: name,
847
+ Server: server,
848
+ }
849
+ }
850
+ nss = append(nss, &NS{Host: ns.NS.String()})
851
+ }
852
+ return nss, nil
853
+ }
854
+
855
+ // goLookupTXT returns the TXT records from name.
856
+ func (r *Resolver) goLookupTXT(ctx context.Context, name string) ([]string, error) {
857
+ p, server, err := r.lookup(ctx, name, dnsmessage.TypeTXT, nil)
858
+ if err != nil {
859
+ return nil, err
860
+ }
861
+ var txts []string
862
+ for {
863
+ h, err := p.AnswerHeader()
864
+ if err == dnsmessage.ErrSectionDone {
865
+ break
866
+ }
867
+ if err != nil {
868
+ return nil, &DNSError{
869
+ Err: "cannot unmarshal DNS message",
870
+ Name: name,
871
+ Server: server,
872
+ }
873
+ }
874
+ if h.Type != dnsmessage.TypeTXT {
875
+ if err := p.SkipAnswer(); err != nil {
876
+ return nil, &DNSError{
877
+ Err: "cannot unmarshal DNS message",
878
+ Name: name,
879
+ Server: server,
880
+ }
881
+ }
882
+ continue
883
+ }
884
+ txt, err := p.TXTResource()
885
+ if err != nil {
886
+ return nil, &DNSError{
887
+ Err: "cannot unmarshal DNS message",
888
+ Name: name,
889
+ Server: server,
890
+ }
891
+ }
892
+ // Multiple strings in one TXT record need to be
893
+ // concatenated without separator to be consistent
894
+ // with previous Go resolver.
895
+ n := 0
896
+ for _, s := range txt.TXT {
897
+ n += len(s)
898
+ }
899
+ txtJoin := make([]byte, 0, n)
900
+ for _, s := range txt.TXT {
901
+ txtJoin = append(txtJoin, s...)
902
+ }
903
+ if len(txts) == 0 {
904
+ txts = make([]string, 0, 1)
905
+ }
906
+ txts = append(txts, string(txtJoin))
907
+ }
908
+ return txts, nil
909
+ }
910
+
911
+ func parseCNAMEFromResources(resources []dnsmessage.Resource) (string, error) {
912
+ if len(resources) == 0 {
913
+ return "", errors.New("no CNAME record received")
914
+ }
915
+ c, ok := resources[0].Body.(*dnsmessage.CNAMEResource)
916
+ if !ok {
917
+ return "", errors.New("could not parse CNAME record")
918
+ }
919
+ return c.CNAME.String(), nil
920
+ }
platform/dbops/binaries/go/go/src/net/lookup_plan9.go ADDED
@@ -0,0 +1,394 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "context"
9
+ "errors"
10
+ "internal/bytealg"
11
+ "internal/itoa"
12
+ "io"
13
+ "os"
14
+ )
15
+
16
+ // cgoAvailable set to true to indicate that the cgo resolver
17
+ // is available on Plan 9. Note that on Plan 9 the cgo resolver
18
+ // does not actually use cgo.
19
+ const cgoAvailable = true
20
+
21
+ func query(ctx context.Context, filename, query string, bufSize int) (addrs []string, err error) {
22
+ queryAddrs := func() (addrs []string, err error) {
23
+ file, err := os.OpenFile(filename, os.O_RDWR, 0)
24
+ if err != nil {
25
+ return nil, err
26
+ }
27
+ defer file.Close()
28
+
29
+ _, err = file.Seek(0, io.SeekStart)
30
+ if err != nil {
31
+ return nil, err
32
+ }
33
+ _, err = file.WriteString(query)
34
+ if err != nil {
35
+ return nil, err
36
+ }
37
+ _, err = file.Seek(0, io.SeekStart)
38
+ if err != nil {
39
+ return nil, err
40
+ }
41
+ buf := make([]byte, bufSize)
42
+ for {
43
+ n, _ := file.Read(buf)
44
+ if n <= 0 {
45
+ break
46
+ }
47
+ addrs = append(addrs, string(buf[:n]))
48
+ }
49
+ return addrs, nil
50
+ }
51
+
52
+ type ret struct {
53
+ addrs []string
54
+ err error
55
+ }
56
+
57
+ ch := make(chan ret, 1)
58
+ go func() {
59
+ addrs, err := queryAddrs()
60
+ ch <- ret{addrs: addrs, err: err}
61
+ }()
62
+
63
+ select {
64
+ case r := <-ch:
65
+ return r.addrs, r.err
66
+ case <-ctx.Done():
67
+ return nil, &DNSError{
68
+ Name: query,
69
+ Err: ctx.Err().Error(),
70
+ IsTimeout: ctx.Err() == context.DeadlineExceeded,
71
+ }
72
+ }
73
+ }
74
+
75
+ func queryCS(ctx context.Context, net, host, service string) (res []string, err error) {
76
+ switch net {
77
+ case "tcp4", "tcp6":
78
+ net = "tcp"
79
+ case "udp4", "udp6":
80
+ net = "udp"
81
+ }
82
+ if host == "" {
83
+ host = "*"
84
+ }
85
+ return query(ctx, netdir+"/cs", net+"!"+host+"!"+service, 128)
86
+ }
87
+
88
+ func queryCS1(ctx context.Context, net string, ip IP, port int) (clone, dest string, err error) {
89
+ ips := "*"
90
+ if len(ip) != 0 && !ip.IsUnspecified() {
91
+ ips = ip.String()
92
+ }
93
+ lines, err := queryCS(ctx, net, ips, itoa.Itoa(port))
94
+ if err != nil {
95
+ return
96
+ }
97
+ f := getFields(lines[0])
98
+ if len(f) < 2 {
99
+ return "", "", errors.New("bad response from ndb/cs")
100
+ }
101
+ clone, dest = f[0], f[1]
102
+ return
103
+ }
104
+
105
+ func queryDNS(ctx context.Context, addr string, typ string) (res []string, err error) {
106
+ return query(ctx, netdir+"/dns", addr+" "+typ, 1024)
107
+ }
108
+
109
+ func handlePlan9DNSError(err error, name string) error {
110
+ if stringsHasSuffix(err.Error(), "dns: name does not exist") ||
111
+ stringsHasSuffix(err.Error(), "dns: resource does not exist; negrcode 0") ||
112
+ stringsHasSuffix(err.Error(), "dns: resource does not exist; negrcode") {
113
+ return &DNSError{
114
+ Err: errNoSuchHost.Error(),
115
+ Name: name,
116
+ IsNotFound: true,
117
+ }
118
+ }
119
+ return &DNSError{
120
+ Err: err.Error(),
121
+ Name: name,
122
+ }
123
+ }
124
+
125
+ // toLower returns a lower-case version of in. Restricting us to
126
+ // ASCII is sufficient to handle the IP protocol names and allow
127
+ // us to not depend on the strings and unicode packages.
128
+ func toLower(in string) string {
129
+ for _, c := range in {
130
+ if 'A' <= c && c <= 'Z' {
131
+ // Has upper case; need to fix.
132
+ out := []byte(in)
133
+ for i := 0; i < len(in); i++ {
134
+ c := in[i]
135
+ if 'A' <= c && c <= 'Z' {
136
+ c += 'a' - 'A'
137
+ }
138
+ out[i] = c
139
+ }
140
+ return string(out)
141
+ }
142
+ }
143
+ return in
144
+ }
145
+
146
+ // lookupProtocol looks up IP protocol name and returns
147
+ // the corresponding protocol number.
148
+ func lookupProtocol(ctx context.Context, name string) (proto int, err error) {
149
+ lines, err := query(ctx, netdir+"/cs", "!protocol="+toLower(name), 128)
150
+ if err != nil {
151
+ return 0, err
152
+ }
153
+ if len(lines) == 0 {
154
+ return 0, UnknownNetworkError(name)
155
+ }
156
+ f := getFields(lines[0])
157
+ if len(f) < 2 {
158
+ return 0, UnknownNetworkError(name)
159
+ }
160
+ s := f[1]
161
+ if n, _, ok := dtoi(s[bytealg.IndexByteString(s, '=')+1:]); ok {
162
+ return n, nil
163
+ }
164
+ return 0, UnknownNetworkError(name)
165
+ }
166
+
167
+ func (*Resolver) lookupHost(ctx context.Context, host string) (addrs []string, err error) {
168
+ // Use netdir/cs instead of netdir/dns because cs knows about
169
+ // host names in local network (e.g. from /lib/ndb/local)
170
+ lines, err := queryCS(ctx, "net", host, "1")
171
+ if err != nil {
172
+ if stringsHasSuffix(err.Error(), "dns failure") {
173
+ return nil, &DNSError{Err: errNoSuchHost.Error(), Name: host, IsNotFound: true}
174
+ }
175
+ return nil, handlePlan9DNSError(err, host)
176
+ }
177
+ loop:
178
+ for _, line := range lines {
179
+ f := getFields(line)
180
+ if len(f) < 2 {
181
+ continue
182
+ }
183
+ addr := f[1]
184
+ if i := bytealg.IndexByteString(addr, '!'); i >= 0 {
185
+ addr = addr[:i] // remove port
186
+ }
187
+ if ParseIP(addr) == nil {
188
+ continue
189
+ }
190
+ // only return unique addresses
191
+ for _, a := range addrs {
192
+ if a == addr {
193
+ continue loop
194
+ }
195
+ }
196
+ addrs = append(addrs, addr)
197
+ }
198
+ return
199
+ }
200
+
201
+ func (r *Resolver) lookupIP(ctx context.Context, network, host string) (addrs []IPAddr, err error) {
202
+ if order, conf := systemConf().hostLookupOrder(r, host); order != hostLookupCgo {
203
+ return r.goLookupIP(ctx, network, host, order, conf)
204
+ }
205
+
206
+ lits, err := r.lookupHost(ctx, host)
207
+ if err != nil {
208
+ return
209
+ }
210
+ for _, lit := range lits {
211
+ host, zone := splitHostZone(lit)
212
+ if ip := ParseIP(host); ip != nil {
213
+ addr := IPAddr{IP: ip, Zone: zone}
214
+ addrs = append(addrs, addr)
215
+ }
216
+ }
217
+ return
218
+ }
219
+
220
+ func (r *Resolver) lookupPort(ctx context.Context, network, service string) (port int, err error) {
221
+ switch network {
222
+ case "ip": // no hints
223
+ if p, err := r.lookupPortWithNetwork(ctx, "tcp", "ip", service); err == nil {
224
+ return p, nil
225
+ }
226
+ return r.lookupPortWithNetwork(ctx, "udp", "ip", service)
227
+ case "tcp", "tcp4", "tcp6":
228
+ return r.lookupPortWithNetwork(ctx, "tcp", "tcp", service)
229
+ case "udp", "udp4", "udp6":
230
+ return r.lookupPortWithNetwork(ctx, "udp", "udp", service)
231
+ default:
232
+ return 0, &DNSError{Err: "unknown network", Name: network + "/" + service}
233
+ }
234
+ }
235
+
236
+ func (*Resolver) lookupPortWithNetwork(ctx context.Context, network, errNetwork, service string) (port int, err error) {
237
+ lines, err := queryCS(ctx, network, "127.0.0.1", toLower(service))
238
+ if err != nil {
239
+ if stringsHasSuffix(err.Error(), "can't translate service") {
240
+ return 0, &DNSError{Err: "unknown port", Name: errNetwork + "/" + service, IsNotFound: true}
241
+ }
242
+ return
243
+ }
244
+ if len(lines) == 0 {
245
+ return 0, &DNSError{Err: "unknown port", Name: errNetwork + "/" + service, IsNotFound: true}
246
+ }
247
+ f := getFields(lines[0])
248
+ if len(f) < 2 {
249
+ return 0, &DNSError{Err: "unknown port", Name: errNetwork + "/" + service, IsNotFound: true}
250
+ }
251
+ s := f[1]
252
+ if i := bytealg.IndexByteString(s, '!'); i >= 0 {
253
+ s = s[i+1:] // remove address
254
+ }
255
+ if n, _, ok := dtoi(s); ok {
256
+ return n, nil
257
+ }
258
+ return 0, &DNSError{Err: "unknown port", Name: errNetwork + "/" + service, IsNotFound: true}
259
+ }
260
+
261
+ func (r *Resolver) lookupCNAME(ctx context.Context, name string) (cname string, err error) {
262
+ if order, conf := systemConf().hostLookupOrder(r, name); order != hostLookupCgo {
263
+ return r.goLookupCNAME(ctx, name, order, conf)
264
+ }
265
+
266
+ lines, err := queryDNS(ctx, name, "cname")
267
+ if err != nil {
268
+ if stringsHasSuffix(err.Error(), "dns failure") || stringsHasSuffix(err.Error(), "resource does not exist; negrcode 0") {
269
+ return absDomainName(name), nil
270
+ }
271
+ return "", handlePlan9DNSError(err, cname)
272
+ }
273
+ if len(lines) > 0 {
274
+ if f := getFields(lines[0]); len(f) >= 3 {
275
+ return f[2] + ".", nil
276
+ }
277
+ }
278
+ return "", errors.New("bad response from ndb/dns")
279
+ }
280
+
281
+ func (r *Resolver) lookupSRV(ctx context.Context, service, proto, name string) (cname string, addrs []*SRV, err error) {
282
+ if systemConf().mustUseGoResolver(r) {
283
+ return r.goLookupSRV(ctx, service, proto, name)
284
+ }
285
+ var target string
286
+ if service == "" && proto == "" {
287
+ target = name
288
+ } else {
289
+ target = "_" + service + "._" + proto + "." + name
290
+ }
291
+ lines, err := queryDNS(ctx, target, "srv")
292
+ if err != nil {
293
+ return "", nil, handlePlan9DNSError(err, name)
294
+ }
295
+ for _, line := range lines {
296
+ f := getFields(line)
297
+ if len(f) < 6 {
298
+ continue
299
+ }
300
+ port, _, portOk := dtoi(f[4])
301
+ priority, _, priorityOk := dtoi(f[3])
302
+ weight, _, weightOk := dtoi(f[2])
303
+ if !(portOk && priorityOk && weightOk) {
304
+ continue
305
+ }
306
+ addrs = append(addrs, &SRV{absDomainName(f[5]), uint16(port), uint16(priority), uint16(weight)})
307
+ cname = absDomainName(f[0])
308
+ }
309
+ byPriorityWeight(addrs).sort()
310
+ return
311
+ }
312
+
313
+ func (r *Resolver) lookupMX(ctx context.Context, name string) (mx []*MX, err error) {
314
+ if systemConf().mustUseGoResolver(r) {
315
+ return r.goLookupMX(ctx, name)
316
+ }
317
+ lines, err := queryDNS(ctx, name, "mx")
318
+ if err != nil {
319
+ return nil, handlePlan9DNSError(err, name)
320
+ }
321
+ for _, line := range lines {
322
+ f := getFields(line)
323
+ if len(f) < 4 {
324
+ continue
325
+ }
326
+ if pref, _, ok := dtoi(f[2]); ok {
327
+ mx = append(mx, &MX{absDomainName(f[3]), uint16(pref)})
328
+ }
329
+ }
330
+ byPref(mx).sort()
331
+ return
332
+ }
333
+
334
+ func (r *Resolver) lookupNS(ctx context.Context, name string) (ns []*NS, err error) {
335
+ if systemConf().mustUseGoResolver(r) {
336
+ return r.goLookupNS(ctx, name)
337
+ }
338
+ lines, err := queryDNS(ctx, name, "ns")
339
+ if err != nil {
340
+ return nil, handlePlan9DNSError(err, name)
341
+ }
342
+ for _, line := range lines {
343
+ f := getFields(line)
344
+ if len(f) < 3 {
345
+ continue
346
+ }
347
+ ns = append(ns, &NS{absDomainName(f[2])})
348
+ }
349
+ return
350
+ }
351
+
352
+ func (r *Resolver) lookupTXT(ctx context.Context, name string) (txt []string, err error) {
353
+ if systemConf().mustUseGoResolver(r) {
354
+ return r.goLookupTXT(ctx, name)
355
+ }
356
+ lines, err := queryDNS(ctx, name, "txt")
357
+ if err != nil {
358
+ return nil, handlePlan9DNSError(err, name)
359
+ }
360
+ for _, line := range lines {
361
+ if i := bytealg.IndexByteString(line, '\t'); i >= 0 {
362
+ txt = append(txt, line[i+1:])
363
+ }
364
+ }
365
+ return
366
+ }
367
+
368
+ func (r *Resolver) lookupAddr(ctx context.Context, addr string) (name []string, err error) {
369
+ if order, conf := systemConf().addrLookupOrder(r, addr); order != hostLookupCgo {
370
+ return r.goLookupPTR(ctx, addr, order, conf)
371
+ }
372
+ arpa, err := reverseaddr(addr)
373
+ if err != nil {
374
+ return
375
+ }
376
+ lines, err := queryDNS(ctx, arpa, "ptr")
377
+ if err != nil {
378
+ return nil, handlePlan9DNSError(err, addr)
379
+ }
380
+ for _, line := range lines {
381
+ f := getFields(line)
382
+ if len(f) < 3 {
383
+ continue
384
+ }
385
+ name = append(name, absDomainName(f[2]))
386
+ }
387
+ return
388
+ }
389
+
390
+ // concurrentThreadsLimit returns the number of threads we permit to
391
+ // run concurrently doing DNS lookups.
392
+ func concurrentThreadsLimit() int {
393
+ return 500
394
+ }
platform/dbops/binaries/go/go/src/net/lookup_test.go ADDED
@@ -0,0 +1,1648 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "errors"
10
+ "fmt"
11
+ "internal/testenv"
12
+ "net/netip"
13
+ "reflect"
14
+ "runtime"
15
+ "sort"
16
+ "strings"
17
+ "sync"
18
+ "sync/atomic"
19
+ "testing"
20
+ "time"
21
+ )
22
+
23
+ func hasSuffixFold(s, suffix string) bool {
24
+ return strings.HasSuffix(strings.ToLower(s), strings.ToLower(suffix))
25
+ }
26
+
27
+ func lookupLocalhost(ctx context.Context, fn func(context.Context, string, string) ([]IPAddr, error), network, host string) ([]IPAddr, error) {
28
+ switch host {
29
+ case "localhost":
30
+ return []IPAddr{
31
+ {IP: IPv4(127, 0, 0, 1)},
32
+ {IP: IPv6loopback},
33
+ }, nil
34
+ default:
35
+ return fn(ctx, network, host)
36
+ }
37
+ }
38
+
39
+ // The Lookup APIs use various sources such as local database, DNS or
40
+ // mDNS, and may use platform-dependent DNS stub resolver if possible.
41
+ // The APIs accept any of forms for a query; host name in various
42
+ // encodings, UTF-8 encoded net name, domain name, FQDN or absolute
43
+ // FQDN, but the result would be one of the forms and it depends on
44
+ // the circumstances.
45
+
46
+ var lookupGoogleSRVTests = []struct {
47
+ service, proto, name string
48
+ cname, target string
49
+ }{
50
+ {
51
+ "ldap", "tcp", "google.com",
52
+ "google.com.", "google.com.",
53
+ },
54
+ {
55
+ "ldap", "tcp", "google.com.",
56
+ "google.com.", "google.com.",
57
+ },
58
+
59
+ // non-standard back door
60
+ {
61
+ "", "", "_ldap._tcp.google.com",
62
+ "google.com.", "google.com.",
63
+ },
64
+ {
65
+ "", "", "_ldap._tcp.google.com.",
66
+ "google.com.", "google.com.",
67
+ },
68
+ }
69
+
70
+ var backoffDuration = [...]time.Duration{time.Second, 5 * time.Second, 30 * time.Second}
71
+
72
+ func TestLookupGoogleSRV(t *testing.T) {
73
+ t.Parallel()
74
+ mustHaveExternalNetwork(t)
75
+
76
+ if runtime.GOOS == "ios" {
77
+ t.Skip("no resolv.conf on iOS")
78
+ }
79
+
80
+ if !supportsIPv4() || !*testIPv4 {
81
+ t.Skip("IPv4 is required")
82
+ }
83
+
84
+ attempts := 0
85
+ for i := 0; i < len(lookupGoogleSRVTests); i++ {
86
+ tt := lookupGoogleSRVTests[i]
87
+ cname, srvs, err := LookupSRV(tt.service, tt.proto, tt.name)
88
+ if err != nil {
89
+ testenv.SkipFlakyNet(t)
90
+ if attempts < len(backoffDuration) {
91
+ dur := backoffDuration[attempts]
92
+ t.Logf("backoff %v after failure %v\n", dur, err)
93
+ time.Sleep(dur)
94
+ attempts++
95
+ i--
96
+ continue
97
+ }
98
+ t.Fatal(err)
99
+ }
100
+ if len(srvs) == 0 {
101
+ t.Error("got no record")
102
+ }
103
+ if !hasSuffixFold(cname, tt.cname) {
104
+ t.Errorf("got %s; want %s", cname, tt.cname)
105
+ }
106
+ for _, srv := range srvs {
107
+ if !hasSuffixFold(srv.Target, tt.target) {
108
+ t.Errorf("got %v; want a record containing %s", srv, tt.target)
109
+ }
110
+ }
111
+ }
112
+ }
113
+
114
+ var lookupGmailMXTests = []struct {
115
+ name, host string
116
+ }{
117
+ {"gmail.com", "google.com."},
118
+ {"gmail.com.", "google.com."},
119
+ }
120
+
121
+ func TestLookupGmailMX(t *testing.T) {
122
+ t.Parallel()
123
+ mustHaveExternalNetwork(t)
124
+
125
+ if runtime.GOOS == "ios" {
126
+ t.Skip("no resolv.conf on iOS")
127
+ }
128
+
129
+ if !supportsIPv4() || !*testIPv4 {
130
+ t.Skip("IPv4 is required")
131
+ }
132
+
133
+ attempts := 0
134
+ for i := 0; i < len(lookupGmailMXTests); i++ {
135
+ tt := lookupGmailMXTests[i]
136
+ mxs, err := LookupMX(tt.name)
137
+ if err != nil {
138
+ testenv.SkipFlakyNet(t)
139
+ if attempts < len(backoffDuration) {
140
+ dur := backoffDuration[attempts]
141
+ t.Logf("backoff %v after failure %v\n", dur, err)
142
+ time.Sleep(dur)
143
+ attempts++
144
+ i--
145
+ continue
146
+ }
147
+ t.Fatal(err)
148
+ }
149
+ if len(mxs) == 0 {
150
+ t.Error("got no record")
151
+ }
152
+ for _, mx := range mxs {
153
+ if !hasSuffixFold(mx.Host, tt.host) {
154
+ t.Errorf("got %v; want a record containing %s", mx, tt.host)
155
+ }
156
+ }
157
+ }
158
+ }
159
+
160
+ var lookupGmailNSTests = []struct {
161
+ name, host string
162
+ }{
163
+ {"gmail.com", "google.com."},
164
+ {"gmail.com.", "google.com."},
165
+ }
166
+
167
+ func TestLookupGmailNS(t *testing.T) {
168
+ t.Parallel()
169
+ mustHaveExternalNetwork(t)
170
+
171
+ if runtime.GOOS == "ios" {
172
+ t.Skip("no resolv.conf on iOS")
173
+ }
174
+
175
+ if !supportsIPv4() || !*testIPv4 {
176
+ t.Skip("IPv4 is required")
177
+ }
178
+
179
+ attempts := 0
180
+ for i := 0; i < len(lookupGmailNSTests); i++ {
181
+ tt := lookupGmailNSTests[i]
182
+ nss, err := LookupNS(tt.name)
183
+ if err != nil {
184
+ testenv.SkipFlakyNet(t)
185
+ if attempts < len(backoffDuration) {
186
+ dur := backoffDuration[attempts]
187
+ t.Logf("backoff %v after failure %v\n", dur, err)
188
+ time.Sleep(dur)
189
+ attempts++
190
+ i--
191
+ continue
192
+ }
193
+ t.Fatal(err)
194
+ }
195
+ if len(nss) == 0 {
196
+ t.Error("got no record")
197
+ }
198
+ for _, ns := range nss {
199
+ if !hasSuffixFold(ns.Host, tt.host) {
200
+ t.Errorf("got %v; want a record containing %s", ns, tt.host)
201
+ }
202
+ }
203
+ }
204
+ }
205
+
206
+ var lookupGmailTXTTests = []struct {
207
+ name, txt, host string
208
+ }{
209
+ {"gmail.com", "spf", "google.com"},
210
+ {"gmail.com.", "spf", "google.com"},
211
+ }
212
+
213
+ func TestLookupGmailTXT(t *testing.T) {
214
+ if runtime.GOOS == "plan9" {
215
+ t.Skip("skipping on plan9; see https://golang.org/issue/29722")
216
+ }
217
+ t.Parallel()
218
+ mustHaveExternalNetwork(t)
219
+
220
+ if runtime.GOOS == "ios" {
221
+ t.Skip("no resolv.conf on iOS")
222
+ }
223
+
224
+ if !supportsIPv4() || !*testIPv4 {
225
+ t.Skip("IPv4 is required")
226
+ }
227
+
228
+ attempts := 0
229
+ for i := 0; i < len(lookupGmailTXTTests); i++ {
230
+ tt := lookupGmailTXTTests[i]
231
+ txts, err := LookupTXT(tt.name)
232
+ if err != nil {
233
+ testenv.SkipFlakyNet(t)
234
+ if attempts < len(backoffDuration) {
235
+ dur := backoffDuration[attempts]
236
+ t.Logf("backoff %v after failure %v\n", dur, err)
237
+ time.Sleep(dur)
238
+ attempts++
239
+ i--
240
+ continue
241
+ }
242
+ t.Fatal(err)
243
+ }
244
+ if len(txts) == 0 {
245
+ t.Error("got no record")
246
+ }
247
+ found := false
248
+ for _, txt := range txts {
249
+ if strings.Contains(txt, tt.txt) && (strings.HasSuffix(txt, tt.host) || strings.HasSuffix(txt, tt.host+".")) {
250
+ found = true
251
+ break
252
+ }
253
+ }
254
+ if !found {
255
+ t.Errorf("got %v; want a record containing %s, %s", txts, tt.txt, tt.host)
256
+ }
257
+ }
258
+ }
259
+
260
+ var lookupGooglePublicDNSAddrTests = []string{
261
+ "8.8.8.8",
262
+ "8.8.4.4",
263
+ "2001:4860:4860::8888",
264
+ "2001:4860:4860::8844",
265
+ }
266
+
267
+ func TestLookupGooglePublicDNSAddr(t *testing.T) {
268
+ mustHaveExternalNetwork(t)
269
+
270
+ if !supportsIPv4() || !supportsIPv6() || !*testIPv4 || !*testIPv6 {
271
+ t.Skip("both IPv4 and IPv6 are required")
272
+ }
273
+
274
+ defer dnsWaitGroup.Wait()
275
+
276
+ for _, ip := range lookupGooglePublicDNSAddrTests {
277
+ names, err := LookupAddr(ip)
278
+ if err != nil {
279
+ t.Fatal(err)
280
+ }
281
+ if len(names) == 0 {
282
+ t.Error("got no record")
283
+ }
284
+ for _, name := range names {
285
+ if !hasSuffixFold(name, ".google.com.") && !hasSuffixFold(name, ".google.") {
286
+ t.Errorf("got %q; want a record ending in .google.com. or .google.", name)
287
+ }
288
+ }
289
+ }
290
+ }
291
+
292
+ func TestLookupIPv6LinkLocalAddr(t *testing.T) {
293
+ if !supportsIPv6() || !*testIPv6 {
294
+ t.Skip("IPv6 is required")
295
+ }
296
+
297
+ defer dnsWaitGroup.Wait()
298
+
299
+ addrs, err := LookupHost("localhost")
300
+ if err != nil {
301
+ t.Fatal(err)
302
+ }
303
+ found := false
304
+ for _, addr := range addrs {
305
+ if addr == "fe80::1%lo0" {
306
+ found = true
307
+ break
308
+ }
309
+ }
310
+ if !found {
311
+ t.Skipf("not supported on %s", runtime.GOOS)
312
+ }
313
+ if _, err := LookupAddr("fe80::1%lo0"); err != nil {
314
+ t.Error(err)
315
+ }
316
+ }
317
+
318
+ func TestLookupIPv6LinkLocalAddrWithZone(t *testing.T) {
319
+ if !supportsIPv6() || !*testIPv6 {
320
+ t.Skip("IPv6 is required")
321
+ }
322
+
323
+ ipaddrs, err := DefaultResolver.LookupIPAddr(context.Background(), "fe80::1%lo0")
324
+ if err != nil {
325
+ t.Error(err)
326
+ }
327
+ for _, addr := range ipaddrs {
328
+ if e, a := "lo0", addr.Zone; e != a {
329
+ t.Errorf("wrong zone: want %q, got %q", e, a)
330
+ }
331
+ }
332
+
333
+ addrs, err := DefaultResolver.LookupHost(context.Background(), "fe80::1%lo0")
334
+ if err != nil {
335
+ t.Error(err)
336
+ }
337
+ for _, addr := range addrs {
338
+ if e, a := "fe80::1%lo0", addr; e != a {
339
+ t.Errorf("wrong host: want %q got %q", e, a)
340
+ }
341
+ }
342
+ }
343
+
344
+ var lookupCNAMETests = []struct {
345
+ name, cname string
346
+ }{
347
+ {"www.iana.org", "icann.org."},
348
+ {"www.iana.org.", "icann.org."},
349
+ {"www.google.com", "google.com."},
350
+ {"google.com", "google.com."},
351
+ {"cname-to-txt.go4.org", "test-txt-record.go4.org."},
352
+ }
353
+
354
+ func TestLookupCNAME(t *testing.T) {
355
+ mustHaveExternalNetwork(t)
356
+ testenv.SkipFlakyNet(t)
357
+
358
+ if !supportsIPv4() || !*testIPv4 {
359
+ t.Skip("IPv4 is required")
360
+ }
361
+
362
+ defer dnsWaitGroup.Wait()
363
+
364
+ attempts := 0
365
+ for i := 0; i < len(lookupCNAMETests); i++ {
366
+ tt := lookupCNAMETests[i]
367
+ cname, err := LookupCNAME(tt.name)
368
+ if err != nil {
369
+ testenv.SkipFlakyNet(t)
370
+ if attempts < len(backoffDuration) {
371
+ dur := backoffDuration[attempts]
372
+ t.Logf("backoff %v after failure %v\n", dur, err)
373
+ time.Sleep(dur)
374
+ attempts++
375
+ i--
376
+ continue
377
+ }
378
+ t.Fatal(err)
379
+ }
380
+ if !hasSuffixFold(cname, tt.cname) {
381
+ t.Errorf("got %s; want a record containing %s", cname, tt.cname)
382
+ }
383
+ }
384
+ }
385
+
386
+ var lookupGoogleHostTests = []struct {
387
+ name string
388
+ }{
389
+ {"google.com"},
390
+ {"google.com."},
391
+ }
392
+
393
+ func TestLookupGoogleHost(t *testing.T) {
394
+ mustHaveExternalNetwork(t)
395
+ testenv.SkipFlakyNet(t)
396
+
397
+ if !supportsIPv4() || !*testIPv4 {
398
+ t.Skip("IPv4 is required")
399
+ }
400
+
401
+ defer dnsWaitGroup.Wait()
402
+
403
+ for _, tt := range lookupGoogleHostTests {
404
+ addrs, err := LookupHost(tt.name)
405
+ if err != nil {
406
+ t.Fatal(err)
407
+ }
408
+ if len(addrs) == 0 {
409
+ t.Error("got no record")
410
+ }
411
+ for _, addr := range addrs {
412
+ if ParseIP(addr) == nil {
413
+ t.Errorf("got %q; want a literal IP address", addr)
414
+ }
415
+ }
416
+ }
417
+ }
418
+
419
+ func TestLookupLongTXT(t *testing.T) {
420
+ testenv.SkipFlaky(t, 22857)
421
+ mustHaveExternalNetwork(t)
422
+
423
+ defer dnsWaitGroup.Wait()
424
+
425
+ txts, err := LookupTXT("golang.rsc.io")
426
+ if err != nil {
427
+ t.Fatal(err)
428
+ }
429
+ sort.Strings(txts)
430
+ want := []string{
431
+ strings.Repeat("abcdefghijklmnopqrstuvwxyABCDEFGHJIKLMNOPQRSTUVWXY", 10),
432
+ "gophers rule",
433
+ }
434
+ if !reflect.DeepEqual(txts, want) {
435
+ t.Fatalf("LookupTXT golang.rsc.io incorrect\nhave %q\nwant %q", txts, want)
436
+ }
437
+ }
438
+
439
+ var lookupGoogleIPTests = []struct {
440
+ name string
441
+ }{
442
+ {"google.com"},
443
+ {"google.com."},
444
+ }
445
+
446
+ func TestLookupGoogleIP(t *testing.T) {
447
+ mustHaveExternalNetwork(t)
448
+ testenv.SkipFlakyNet(t)
449
+
450
+ if !supportsIPv4() || !*testIPv4 {
451
+ t.Skip("IPv4 is required")
452
+ }
453
+
454
+ defer dnsWaitGroup.Wait()
455
+
456
+ for _, tt := range lookupGoogleIPTests {
457
+ ips, err := LookupIP(tt.name)
458
+ if err != nil {
459
+ t.Fatal(err)
460
+ }
461
+ if len(ips) == 0 {
462
+ t.Error("got no record")
463
+ }
464
+ for _, ip := range ips {
465
+ if ip.To4() == nil && ip.To16() == nil {
466
+ t.Errorf("got %v; want an IP address", ip)
467
+ }
468
+ }
469
+ }
470
+ }
471
+
472
+ var revAddrTests = []struct {
473
+ Addr string
474
+ Reverse string
475
+ ErrPrefix string
476
+ }{
477
+ {"1.2.3.4", "4.3.2.1.in-addr.arpa.", ""},
478
+ {"245.110.36.114", "114.36.110.245.in-addr.arpa.", ""},
479
+ {"::ffff:12.34.56.78", "78.56.34.12.in-addr.arpa.", ""},
480
+ {"::1", "1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa.", ""},
481
+ {"1::", "0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.1.0.0.0.ip6.arpa.", ""},
482
+ {"1234:567::89a:bcde", "e.d.c.b.a.9.8.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.7.6.5.0.4.3.2.1.ip6.arpa.", ""},
483
+ {"1234:567:fefe:bcbc:adad:9e4a:89a:bcde", "e.d.c.b.a.9.8.0.a.4.e.9.d.a.d.a.c.b.c.b.e.f.e.f.7.6.5.0.4.3.2.1.ip6.arpa.", ""},
484
+ {"1.2.3", "", "unrecognized address"},
485
+ {"1.2.3.4.5", "", "unrecognized address"},
486
+ {"1234:567:bcbca::89a:bcde", "", "unrecognized address"},
487
+ {"1234:567::bcbc:adad::89a:bcde", "", "unrecognized address"},
488
+ }
489
+
490
+ func TestReverseAddress(t *testing.T) {
491
+ defer dnsWaitGroup.Wait()
492
+ for i, tt := range revAddrTests {
493
+ a, err := reverseaddr(tt.Addr)
494
+ if len(tt.ErrPrefix) > 0 && err == nil {
495
+ t.Errorf("#%d: expected %q, got <nil> (error)", i, tt.ErrPrefix)
496
+ continue
497
+ }
498
+ if len(tt.ErrPrefix) == 0 && err != nil {
499
+ t.Errorf("#%d: expected <nil>, got %q (error)", i, err)
500
+ }
501
+ if err != nil && err.(*DNSError).Err != tt.ErrPrefix {
502
+ t.Errorf("#%d: expected %q, got %q (mismatched error)", i, tt.ErrPrefix, err.(*DNSError).Err)
503
+ }
504
+ if a != tt.Reverse {
505
+ t.Errorf("#%d: expected %q, got %q (reverse address)", i, tt.Reverse, a)
506
+ }
507
+ }
508
+ }
509
+
510
+ func TestDNSFlood(t *testing.T) {
511
+ if !*testDNSFlood {
512
+ t.Skip("test disabled; use -dnsflood to enable")
513
+ }
514
+
515
+ defer dnsWaitGroup.Wait()
516
+
517
+ var N = 5000
518
+ if runtime.GOOS == "darwin" || runtime.GOOS == "ios" {
519
+ // On Darwin this test consumes kernel threads much
520
+ // than other platforms for some reason.
521
+ // When we monitor the number of allocated Ms by
522
+ // observing on runtime.newm calls, we can see that it
523
+ // easily reaches the per process ceiling
524
+ // kern.num_threads when CGO_ENABLED=1 and
525
+ // GODEBUG=netdns=go.
526
+ N = 500
527
+ }
528
+
529
+ const timeout = 3 * time.Second
530
+ ctxHalfTimeout, cancel := context.WithTimeout(context.Background(), timeout/2)
531
+ defer cancel()
532
+ ctxTimeout, cancel := context.WithTimeout(context.Background(), timeout)
533
+ defer cancel()
534
+
535
+ c := make(chan error, 2*N)
536
+ for i := 0; i < N; i++ {
537
+ name := fmt.Sprintf("%d.net-test.golang.org", i)
538
+ go func() {
539
+ _, err := DefaultResolver.LookupIPAddr(ctxHalfTimeout, name)
540
+ c <- err
541
+ }()
542
+ go func() {
543
+ _, err := DefaultResolver.LookupIPAddr(ctxTimeout, name)
544
+ c <- err
545
+ }()
546
+ }
547
+ qstats := struct {
548
+ succeeded, failed int
549
+ timeout, temporary, other int
550
+ unknown int
551
+ }{}
552
+ deadline := time.After(timeout + time.Second)
553
+ for i := 0; i < 2*N; i++ {
554
+ select {
555
+ case <-deadline:
556
+ t.Fatal("deadline exceeded")
557
+ case err := <-c:
558
+ switch err := err.(type) {
559
+ case nil:
560
+ qstats.succeeded++
561
+ case Error:
562
+ qstats.failed++
563
+ if err.Timeout() {
564
+ qstats.timeout++
565
+ }
566
+ if err.Temporary() {
567
+ qstats.temporary++
568
+ }
569
+ if !err.Timeout() && !err.Temporary() {
570
+ qstats.other++
571
+ }
572
+ default:
573
+ qstats.failed++
574
+ qstats.unknown++
575
+ }
576
+ }
577
+ }
578
+
579
+ // A high volume of DNS queries for sub-domain of golang.org
580
+ // would be coordinated by authoritative or recursive server,
581
+ // or stub resolver which implements query-response rate
582
+ // limitation, so we can expect some query successes and more
583
+ // failures including timeout, temporary and other here.
584
+ // As a rule, unknown must not be shown but it might possibly
585
+ // happen due to issue 4856 for now.
586
+ t.Logf("%v succeeded, %v failed (%v timeout, %v temporary, %v other, %v unknown)", qstats.succeeded, qstats.failed, qstats.timeout, qstats.temporary, qstats.other, qstats.unknown)
587
+ }
588
+
589
+ func TestLookupDotsWithLocalSource(t *testing.T) {
590
+ if !supportsIPv4() || !*testIPv4 {
591
+ t.Skip("IPv4 is required")
592
+ }
593
+
594
+ mustHaveExternalNetwork(t)
595
+
596
+ defer dnsWaitGroup.Wait()
597
+
598
+ for i, fn := range []func() func(){forceGoDNS, forceCgoDNS} {
599
+ fixup := fn()
600
+ if fixup == nil {
601
+ continue
602
+ }
603
+ names, err := LookupAddr("127.0.0.1")
604
+ fixup()
605
+ if err != nil {
606
+ t.Logf("#%d: %v", i, err)
607
+ continue
608
+ }
609
+ mode := "netgo"
610
+ if i == 1 {
611
+ mode = "netcgo"
612
+ }
613
+ loop:
614
+ for i, name := range names {
615
+ if strings.Index(name, ".") == len(name)-1 { // "localhost" not "localhost."
616
+ for j := range names {
617
+ if j == i {
618
+ continue
619
+ }
620
+ if names[j] == name[:len(name)-1] {
621
+ // It's OK if we find the name without the dot,
622
+ // as some systems say 127.0.0.1 localhost localhost.
623
+ continue loop
624
+ }
625
+ }
626
+ t.Errorf("%s: got %s; want %s", mode, name, name[:len(name)-1])
627
+ } else if strings.Contains(name, ".") && !strings.HasSuffix(name, ".") { // "localhost.localdomain." not "localhost.localdomain"
628
+ t.Errorf("%s: got %s; want name ending with trailing dot", mode, name)
629
+ }
630
+ }
631
+ }
632
+ }
633
+
634
+ func TestLookupDotsWithRemoteSource(t *testing.T) {
635
+ if runtime.GOOS == "darwin" || runtime.GOOS == "ios" {
636
+ testenv.SkipFlaky(t, 27992)
637
+ }
638
+ mustHaveExternalNetwork(t)
639
+ testenv.SkipFlakyNet(t)
640
+
641
+ if !supportsIPv4() || !*testIPv4 {
642
+ t.Skip("IPv4 is required")
643
+ }
644
+
645
+ if runtime.GOOS == "ios" {
646
+ t.Skip("no resolv.conf on iOS")
647
+ }
648
+
649
+ defer dnsWaitGroup.Wait()
650
+
651
+ if fixup := forceGoDNS(); fixup != nil {
652
+ testDots(t, "go")
653
+ fixup()
654
+ }
655
+ if fixup := forceCgoDNS(); fixup != nil {
656
+ testDots(t, "cgo")
657
+ fixup()
658
+ }
659
+ }
660
+
661
+ func testDots(t *testing.T, mode string) {
662
+ names, err := LookupAddr("8.8.8.8") // Google dns server
663
+ if err != nil {
664
+ t.Errorf("LookupAddr(8.8.8.8): %v (mode=%v)", err, mode)
665
+ } else {
666
+ for _, name := range names {
667
+ if !hasSuffixFold(name, ".google.com.") && !hasSuffixFold(name, ".google.") {
668
+ t.Errorf("LookupAddr(8.8.8.8) = %v, want names ending in .google.com or .google with trailing dot (mode=%v)", names, mode)
669
+ break
670
+ }
671
+ }
672
+ }
673
+
674
+ cname, err := LookupCNAME("www.mit.edu")
675
+ if err != nil {
676
+ t.Errorf("LookupCNAME(www.mit.edu, mode=%v): %v", mode, err)
677
+ } else if !strings.HasSuffix(cname, ".") {
678
+ t.Errorf("LookupCNAME(www.mit.edu) = %v, want cname ending in . with trailing dot (mode=%v)", cname, mode)
679
+ }
680
+
681
+ mxs, err := LookupMX("google.com")
682
+ if err != nil {
683
+ t.Errorf("LookupMX(google.com): %v (mode=%v)", err, mode)
684
+ } else {
685
+ for _, mx := range mxs {
686
+ if !hasSuffixFold(mx.Host, ".google.com.") {
687
+ t.Errorf("LookupMX(google.com) = %v, want names ending in .google.com. with trailing dot (mode=%v)", mxString(mxs), mode)
688
+ break
689
+ }
690
+ }
691
+ }
692
+
693
+ nss, err := LookupNS("google.com")
694
+ if err != nil {
695
+ t.Errorf("LookupNS(google.com): %v (mode=%v)", err, mode)
696
+ } else {
697
+ for _, ns := range nss {
698
+ if !hasSuffixFold(ns.Host, ".google.com.") {
699
+ t.Errorf("LookupNS(google.com) = %v, want names ending in .google.com. with trailing dot (mode=%v)", nsString(nss), mode)
700
+ break
701
+ }
702
+ }
703
+ }
704
+
705
+ cname, srvs, err := LookupSRV("ldap", "tcp", "google.com")
706
+ if err != nil {
707
+ t.Errorf("LookupSRV(ldap, tcp, google.com): %v (mode=%v)", err, mode)
708
+ } else {
709
+ if !hasSuffixFold(cname, ".google.com.") {
710
+ t.Errorf("LookupSRV(ldap, tcp, google.com) returned cname=%v, want name ending in .google.com. with trailing dot (mode=%v)", cname, mode)
711
+ }
712
+ for _, srv := range srvs {
713
+ if !hasSuffixFold(srv.Target, ".google.com.") {
714
+ t.Errorf("LookupSRV(ldap, tcp, google.com) returned addrs=%v, want names ending in .google.com. with trailing dot (mode=%v)", srvString(srvs), mode)
715
+ break
716
+ }
717
+ }
718
+ }
719
+ }
720
+
721
+ func mxString(mxs []*MX) string {
722
+ var buf strings.Builder
723
+ sep := ""
724
+ fmt.Fprintf(&buf, "[")
725
+ for _, mx := range mxs {
726
+ fmt.Fprintf(&buf, "%s%s:%d", sep, mx.Host, mx.Pref)
727
+ sep = " "
728
+ }
729
+ fmt.Fprintf(&buf, "]")
730
+ return buf.String()
731
+ }
732
+
733
+ func nsString(nss []*NS) string {
734
+ var buf strings.Builder
735
+ sep := ""
736
+ fmt.Fprintf(&buf, "[")
737
+ for _, ns := range nss {
738
+ fmt.Fprintf(&buf, "%s%s", sep, ns.Host)
739
+ sep = " "
740
+ }
741
+ fmt.Fprintf(&buf, "]")
742
+ return buf.String()
743
+ }
744
+
745
+ func srvString(srvs []*SRV) string {
746
+ var buf strings.Builder
747
+ sep := ""
748
+ fmt.Fprintf(&buf, "[")
749
+ for _, srv := range srvs {
750
+ fmt.Fprintf(&buf, "%s%s:%d:%d:%d", sep, srv.Target, srv.Port, srv.Priority, srv.Weight)
751
+ sep = " "
752
+ }
753
+ fmt.Fprintf(&buf, "]")
754
+ return buf.String()
755
+ }
756
+
757
+ func TestLookupPort(t *testing.T) {
758
+ // See https://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml
759
+ //
760
+ // Please be careful about adding new test cases.
761
+ // There are platforms which have incomplete mappings for
762
+ // restricted resource access and security reasons.
763
+ type test struct {
764
+ network string
765
+ name string
766
+ port int
767
+ ok bool
768
+ }
769
+ var tests = []test{
770
+ {"tcp", "0", 0, true},
771
+ {"udp", "0", 0, true},
772
+ {"udp", "domain", 53, true},
773
+
774
+ {"--badnet--", "zzz", 0, false},
775
+ {"tcp", "--badport--", 0, false},
776
+ {"tcp", "-1", 0, false},
777
+ {"tcp", "65536", 0, false},
778
+ {"udp", "-1", 0, false},
779
+ {"udp", "65536", 0, false},
780
+ {"tcp", "123456789", 0, false},
781
+
782
+ // Issue 13610: LookupPort("tcp", "")
783
+ {"tcp", "", 0, true},
784
+ {"tcp4", "", 0, true},
785
+ {"tcp6", "", 0, true},
786
+ {"udp", "", 0, true},
787
+ {"udp4", "", 0, true},
788
+ {"udp6", "", 0, true},
789
+ }
790
+
791
+ switch runtime.GOOS {
792
+ case "android":
793
+ if netGoBuildTag {
794
+ t.Skipf("not supported on %s without cgo; see golang.org/issues/14576", runtime.GOOS)
795
+ }
796
+ default:
797
+ tests = append(tests, test{"tcp", "http", 80, true})
798
+ }
799
+
800
+ for _, tt := range tests {
801
+ port, err := LookupPort(tt.network, tt.name)
802
+ if port != tt.port || (err == nil) != tt.ok {
803
+ t.Errorf("LookupPort(%q, %q) = %d, %v; want %d, error=%t", tt.network, tt.name, port, err, tt.port, !tt.ok)
804
+ }
805
+ if err != nil {
806
+ if perr := parseLookupPortError(err); perr != nil {
807
+ t.Error(perr)
808
+ }
809
+ }
810
+ }
811
+ }
812
+
813
+ // Like TestLookupPort but with minimal tests that should always pass
814
+ // because the answers are baked-in to the net package.
815
+ func TestLookupPort_Minimal(t *testing.T) {
816
+ type test struct {
817
+ network string
818
+ name string
819
+ port int
820
+ }
821
+ var tests = []test{
822
+ {"tcp", "http", 80},
823
+ {"tcp", "HTTP", 80}, // case shouldn't matter
824
+ {"tcp", "https", 443},
825
+ {"tcp", "ssh", 22},
826
+ {"tcp", "gopher", 70},
827
+ {"tcp4", "http", 80},
828
+ {"tcp6", "http", 80},
829
+ }
830
+
831
+ for _, tt := range tests {
832
+ port, err := LookupPort(tt.network, tt.name)
833
+ if port != tt.port || err != nil {
834
+ t.Errorf("LookupPort(%q, %q) = %d, %v; want %d, error=nil", tt.network, tt.name, port, err, tt.port)
835
+ }
836
+ }
837
+ }
838
+
839
+ func TestLookupProtocol_Minimal(t *testing.T) {
840
+ type test struct {
841
+ name string
842
+ want int
843
+ }
844
+ var tests = []test{
845
+ {"tcp", 6},
846
+ {"TcP", 6}, // case shouldn't matter
847
+ {"icmp", 1},
848
+ {"igmp", 2},
849
+ {"udp", 17},
850
+ {"ipv6-icmp", 58},
851
+ }
852
+
853
+ for _, tt := range tests {
854
+ got, err := lookupProtocol(context.Background(), tt.name)
855
+ if got != tt.want || err != nil {
856
+ t.Errorf("LookupProtocol(%q) = %d, %v; want %d, error=nil", tt.name, got, err, tt.want)
857
+ }
858
+ }
859
+
860
+ }
861
+
862
+ func TestLookupNonLDH(t *testing.T) {
863
+ defer dnsWaitGroup.Wait()
864
+
865
+ if fixup := forceGoDNS(); fixup != nil {
866
+ defer fixup()
867
+ }
868
+
869
+ // "LDH" stands for letters, digits, and hyphens and is the usual
870
+ // description of standard DNS names.
871
+ // This test is checking that other kinds of names are reported
872
+ // as not found, not reported as invalid names.
873
+ addrs, err := LookupHost("!!!.###.bogus..domain.")
874
+ if err == nil {
875
+ t.Fatalf("lookup succeeded: %v", addrs)
876
+ }
877
+ if !strings.HasSuffix(err.Error(), errNoSuchHost.Error()) {
878
+ t.Fatalf("lookup error = %v, want %v", err, errNoSuchHost)
879
+ }
880
+ if !err.(*DNSError).IsNotFound {
881
+ t.Fatalf("lookup error = %v, want true", err.(*DNSError).IsNotFound)
882
+ }
883
+ }
884
+
885
+ func TestLookupContextCancel(t *testing.T) {
886
+ mustHaveExternalNetwork(t)
887
+ testenv.SkipFlakyNet(t)
888
+
889
+ origTestHookLookupIP := testHookLookupIP
890
+ defer func() {
891
+ dnsWaitGroup.Wait()
892
+ testHookLookupIP = origTestHookLookupIP
893
+ }()
894
+
895
+ lookupCtx, cancelLookup := context.WithCancel(context.Background())
896
+ unblockLookup := make(chan struct{})
897
+
898
+ // Set testHookLookupIP to start a new, concurrent call to LookupIPAddr
899
+ // and cancel the original one, then block until the canceled call has returned
900
+ // (ensuring that it has performed any synchronous cleanup).
901
+ testHookLookupIP = func(
902
+ ctx context.Context,
903
+ fn func(context.Context, string, string) ([]IPAddr, error),
904
+ network string,
905
+ host string,
906
+ ) ([]IPAddr, error) {
907
+ select {
908
+ case <-unblockLookup:
909
+ default:
910
+ // Start a concurrent LookupIPAddr for the same host while the caller is
911
+ // still blocked, and sleep a little to give it time to be deduplicated
912
+ // before we cancel (and unblock) the caller.
913
+ // (If the timing doesn't quite work out, we'll end up testing sequential
914
+ // calls instead of concurrent ones, but the test should still pass.)
915
+ t.Logf("starting concurrent LookupIPAddr")
916
+ dnsWaitGroup.Add(1)
917
+ go func() {
918
+ defer dnsWaitGroup.Done()
919
+ _, err := DefaultResolver.LookupIPAddr(context.Background(), host)
920
+ if err != nil {
921
+ t.Error(err)
922
+ }
923
+ }()
924
+ time.Sleep(1 * time.Millisecond)
925
+ }
926
+
927
+ cancelLookup()
928
+ <-unblockLookup
929
+ // If the concurrent lookup above is deduplicated to this one
930
+ // (as we expect to happen most of the time), it is important
931
+ // that the original call does not cancel the shared Context.
932
+ // (See https://go.dev/issue/22724.) Explicitly check for
933
+ // cancellation now, just in case fn itself doesn't notice it.
934
+ if err := ctx.Err(); err != nil {
935
+ t.Logf("testHookLookupIP canceled")
936
+ return nil, err
937
+ }
938
+ t.Logf("testHookLookupIP performing lookup")
939
+ return fn(ctx, network, host)
940
+ }
941
+
942
+ _, err := DefaultResolver.LookupIPAddr(lookupCtx, "google.com")
943
+ if dnsErr, ok := err.(*DNSError); !ok || dnsErr.Err != errCanceled.Error() {
944
+ t.Errorf("unexpected error from canceled, blocked LookupIPAddr: %v", err)
945
+ }
946
+ close(unblockLookup)
947
+ }
948
+
949
+ // Issue 24330: treat the nil *Resolver like a zero value. Verify nothing
950
+ // crashes if nil is used.
951
+ func TestNilResolverLookup(t *testing.T) {
952
+ mustHaveExternalNetwork(t)
953
+ var r *Resolver = nil
954
+ ctx := context.Background()
955
+
956
+ // Don't care about the results, just that nothing panics:
957
+ r.LookupAddr(ctx, "8.8.8.8")
958
+ r.LookupCNAME(ctx, "google.com")
959
+ r.LookupHost(ctx, "google.com")
960
+ r.LookupIPAddr(ctx, "google.com")
961
+ r.LookupIP(ctx, "ip", "google.com")
962
+ r.LookupMX(ctx, "gmail.com")
963
+ r.LookupNS(ctx, "google.com")
964
+ r.LookupPort(ctx, "tcp", "smtp")
965
+ r.LookupSRV(ctx, "service", "proto", "name")
966
+ r.LookupTXT(ctx, "gmail.com")
967
+ }
968
+
969
+ // TestLookupHostCancel verifies that lookup works even after many
970
+ // canceled lookups (see golang.org/issue/24178 for details).
971
+ func TestLookupHostCancel(t *testing.T) {
972
+ mustHaveExternalNetwork(t)
973
+ testenv.SkipFlakyNet(t)
974
+ t.Parallel() // Executes 600ms worth of sequential sleeps.
975
+
976
+ const (
977
+ google = "www.google.com"
978
+ invalidDomain = "invalid.invalid" // RFC 2606 reserves .invalid
979
+ n = 600 // this needs to be larger than threadLimit size
980
+ )
981
+
982
+ _, err := LookupHost(google)
983
+ if err != nil {
984
+ t.Fatal(err)
985
+ }
986
+
987
+ ctx, cancel := context.WithCancel(context.Background())
988
+ cancel()
989
+ for i := 0; i < n; i++ {
990
+ addr, err := DefaultResolver.LookupHost(ctx, invalidDomain)
991
+ if err == nil {
992
+ t.Fatalf("LookupHost(%q): returns %v, but should fail", invalidDomain, addr)
993
+ }
994
+
995
+ // Don't verify what the actual error is.
996
+ // We know that it must be non-nil because the domain is invalid,
997
+ // but we don't have any guarantee that LookupHost actually bothers
998
+ // to check for cancellation on the fast path.
999
+ // (For example, it could use a local cache to avoid blocking entirely.)
1000
+
1001
+ // The lookup may deduplicate in-flight requests, so give it time to settle
1002
+ // in between.
1003
+ time.Sleep(time.Millisecond * 1)
1004
+ }
1005
+
1006
+ _, err = LookupHost(google)
1007
+ if err != nil {
1008
+ t.Fatal(err)
1009
+ }
1010
+ }
1011
+
1012
+ type lookupCustomResolver struct {
1013
+ *Resolver
1014
+ mu sync.RWMutex
1015
+ dialed bool
1016
+ }
1017
+
1018
+ func (lcr *lookupCustomResolver) dial() func(ctx context.Context, network, address string) (Conn, error) {
1019
+ return func(ctx context.Context, network, address string) (Conn, error) {
1020
+ lcr.mu.Lock()
1021
+ lcr.dialed = true
1022
+ lcr.mu.Unlock()
1023
+ return Dial(network, address)
1024
+ }
1025
+ }
1026
+
1027
+ // TestConcurrentPreferGoResolversDial tests that multiple resolvers with the
1028
+ // PreferGo option used concurrently are all dialed properly.
1029
+ func TestConcurrentPreferGoResolversDial(t *testing.T) {
1030
+ switch runtime.GOOS {
1031
+ case "plan9":
1032
+ // TODO: plan9 implementation of the resolver uses the Dial function since
1033
+ // https://go.dev/cl/409234, this test could probably be reenabled.
1034
+ t.Skipf("skip on %v", runtime.GOOS)
1035
+ }
1036
+
1037
+ testenv.MustHaveExternalNetwork(t)
1038
+ testenv.SkipFlakyNet(t)
1039
+
1040
+ defer dnsWaitGroup.Wait()
1041
+
1042
+ resolvers := make([]*lookupCustomResolver, 2)
1043
+ for i := range resolvers {
1044
+ cs := lookupCustomResolver{Resolver: &Resolver{PreferGo: true}}
1045
+ cs.Dial = cs.dial()
1046
+ resolvers[i] = &cs
1047
+ }
1048
+
1049
+ var wg sync.WaitGroup
1050
+ wg.Add(len(resolvers))
1051
+ for i, resolver := range resolvers {
1052
+ go func(r *Resolver, index int) {
1053
+ defer wg.Done()
1054
+ _, err := r.LookupIPAddr(context.Background(), "google.com")
1055
+ if err != nil {
1056
+ t.Errorf("lookup failed for resolver %d: %q", index, err)
1057
+ }
1058
+ }(resolver.Resolver, i)
1059
+ }
1060
+ wg.Wait()
1061
+
1062
+ if t.Failed() {
1063
+ t.FailNow()
1064
+ }
1065
+
1066
+ for i, resolver := range resolvers {
1067
+ if !resolver.dialed {
1068
+ t.Errorf("custom resolver %d not dialed during lookup", i)
1069
+ }
1070
+ }
1071
+ }
1072
+
1073
+ var ipVersionTests = []struct {
1074
+ network string
1075
+ version byte
1076
+ }{
1077
+ {"tcp", 0},
1078
+ {"tcp4", '4'},
1079
+ {"tcp6", '6'},
1080
+ {"udp", 0},
1081
+ {"udp4", '4'},
1082
+ {"udp6", '6'},
1083
+ {"ip", 0},
1084
+ {"ip4", '4'},
1085
+ {"ip6", '6'},
1086
+ {"ip7", 0},
1087
+ {"", 0},
1088
+ }
1089
+
1090
+ func TestIPVersion(t *testing.T) {
1091
+ for _, tt := range ipVersionTests {
1092
+ if version := ipVersion(tt.network); version != tt.version {
1093
+ t.Errorf("Family for: %s. Expected: %s, Got: %s", tt.network,
1094
+ string(tt.version), string(version))
1095
+ }
1096
+ }
1097
+ }
1098
+
1099
+ // Issue 28600: The context that is used to lookup ips should always
1100
+ // preserve the values from the context that was passed into LookupIPAddr.
1101
+ func TestLookupIPAddrPreservesContextValues(t *testing.T) {
1102
+ origTestHookLookupIP := testHookLookupIP
1103
+ defer func() { testHookLookupIP = origTestHookLookupIP }()
1104
+
1105
+ keyValues := []struct {
1106
+ key, value any
1107
+ }{
1108
+ {"key-1", 12},
1109
+ {384, "value2"},
1110
+ {new(float64), 137},
1111
+ }
1112
+ ctx := context.Background()
1113
+ for _, kv := range keyValues {
1114
+ ctx = context.WithValue(ctx, kv.key, kv.value)
1115
+ }
1116
+
1117
+ wantIPs := []IPAddr{
1118
+ {IP: IPv4(127, 0, 0, 1)},
1119
+ {IP: IPv6loopback},
1120
+ }
1121
+
1122
+ checkCtxValues := func(ctx_ context.Context, fn func(context.Context, string, string) ([]IPAddr, error), network, host string) ([]IPAddr, error) {
1123
+ for _, kv := range keyValues {
1124
+ g, w := ctx_.Value(kv.key), kv.value
1125
+ if !reflect.DeepEqual(g, w) {
1126
+ t.Errorf("Value lookup:\n\tGot: %v\n\tWant: %v", g, w)
1127
+ }
1128
+ }
1129
+ return wantIPs, nil
1130
+ }
1131
+ testHookLookupIP = checkCtxValues
1132
+
1133
+ resolvers := []*Resolver{
1134
+ nil,
1135
+ new(Resolver),
1136
+ }
1137
+
1138
+ for i, resolver := range resolvers {
1139
+ gotIPs, err := resolver.LookupIPAddr(ctx, "golang.org")
1140
+ if err != nil {
1141
+ t.Errorf("Resolver #%d: unexpected error: %v", i, err)
1142
+ }
1143
+ if !reflect.DeepEqual(gotIPs, wantIPs) {
1144
+ t.Errorf("#%d: mismatched IPAddr results\n\tGot: %v\n\tWant: %v", i, gotIPs, wantIPs)
1145
+ }
1146
+ }
1147
+ }
1148
+
1149
+ // Issue 30521: The lookup group should call the resolver for each network.
1150
+ func TestLookupIPAddrConcurrentCallsForNetworks(t *testing.T) {
1151
+ origTestHookLookupIP := testHookLookupIP
1152
+ defer func() { testHookLookupIP = origTestHookLookupIP }()
1153
+
1154
+ queries := [][]string{
1155
+ {"udp", "golang.org"},
1156
+ {"udp4", "golang.org"},
1157
+ {"udp6", "golang.org"},
1158
+ {"udp", "golang.org"},
1159
+ {"udp", "golang.org"},
1160
+ }
1161
+ results := map[[2]string][]IPAddr{
1162
+ {"udp", "golang.org"}: {
1163
+ {IP: IPv4(127, 0, 0, 1)},
1164
+ {IP: IPv6loopback},
1165
+ },
1166
+ {"udp4", "golang.org"}: {
1167
+ {IP: IPv4(127, 0, 0, 1)},
1168
+ },
1169
+ {"udp6", "golang.org"}: {
1170
+ {IP: IPv6loopback},
1171
+ },
1172
+ }
1173
+ calls := int32(0)
1174
+ waitCh := make(chan struct{})
1175
+ testHookLookupIP = func(ctx context.Context, fn func(context.Context, string, string) ([]IPAddr, error), network, host string) ([]IPAddr, error) {
1176
+ // We'll block until this is called one time for each different
1177
+ // expected result. This will ensure that the lookup group would wait
1178
+ // for the existing call if it was to be reused.
1179
+ if atomic.AddInt32(&calls, 1) == int32(len(results)) {
1180
+ close(waitCh)
1181
+ }
1182
+ select {
1183
+ case <-waitCh:
1184
+ case <-ctx.Done():
1185
+ return nil, ctx.Err()
1186
+ }
1187
+ return results[[2]string{network, host}], nil
1188
+ }
1189
+
1190
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
1191
+ defer cancel()
1192
+ wg := sync.WaitGroup{}
1193
+ for _, q := range queries {
1194
+ network := q[0]
1195
+ host := q[1]
1196
+ wg.Add(1)
1197
+ go func() {
1198
+ defer wg.Done()
1199
+ gotIPs, err := DefaultResolver.lookupIPAddr(ctx, network, host)
1200
+ if err != nil {
1201
+ t.Errorf("lookupIPAddr(%v, %v): unexpected error: %v", network, host, err)
1202
+ }
1203
+ wantIPs := results[[2]string{network, host}]
1204
+ if !reflect.DeepEqual(gotIPs, wantIPs) {
1205
+ t.Errorf("lookupIPAddr(%v, %v): mismatched IPAddr results\n\tGot: %v\n\tWant: %v", network, host, gotIPs, wantIPs)
1206
+ }
1207
+ }()
1208
+ }
1209
+ wg.Wait()
1210
+ }
1211
+
1212
+ // Issue 53995: Resolver.LookupIP should return error for empty host name.
1213
+ func TestResolverLookupIPWithEmptyHost(t *testing.T) {
1214
+ _, err := DefaultResolver.LookupIP(context.Background(), "ip", "")
1215
+ if err == nil {
1216
+ t.Fatal("DefaultResolver.LookupIP for empty host success, want no host error")
1217
+ }
1218
+ if !strings.HasSuffix(err.Error(), errNoSuchHost.Error()) {
1219
+ t.Fatalf("lookup error = %v, want %v", err, errNoSuchHost)
1220
+ }
1221
+ }
1222
+
1223
+ func TestWithUnexpiredValuesPreserved(t *testing.T) {
1224
+ ctx, cancel := context.WithCancel(context.Background())
1225
+
1226
+ // Insert a value into it.
1227
+ key, value := "key-1", 2
1228
+ ctx = context.WithValue(ctx, key, value)
1229
+
1230
+ // Now use the "values preserving context" like
1231
+ // we would for LookupIPAddr. See Issue 28600.
1232
+ ctx = withUnexpiredValuesPreserved(ctx)
1233
+
1234
+ // Lookup before expiry.
1235
+ if g, w := ctx.Value(key), value; g != w {
1236
+ t.Errorf("Lookup before expiry: Got %v Want %v", g, w)
1237
+ }
1238
+
1239
+ // Cancel the context.
1240
+ cancel()
1241
+
1242
+ // Lookup after expiry should return nil
1243
+ if g := ctx.Value(key); g != nil {
1244
+ t.Errorf("Lookup after expiry: Got %v want nil", g)
1245
+ }
1246
+ }
1247
+
1248
+ // Issue 31597: don't panic on null byte in name
1249
+ func TestLookupNullByte(t *testing.T) {
1250
+ testenv.MustHaveExternalNetwork(t)
1251
+ testenv.SkipFlakyNet(t)
1252
+ LookupHost("foo\x00bar") // check that it doesn't panic; it used to on Windows
1253
+ }
1254
+
1255
+ func TestResolverLookupIP(t *testing.T) {
1256
+ testenv.MustHaveExternalNetwork(t)
1257
+
1258
+ v4Ok := supportsIPv4() && *testIPv4
1259
+ v6Ok := supportsIPv6() && *testIPv6
1260
+
1261
+ defer dnsWaitGroup.Wait()
1262
+
1263
+ for _, impl := range []struct {
1264
+ name string
1265
+ fn func() func()
1266
+ }{
1267
+ {"go", forceGoDNS},
1268
+ {"cgo", forceCgoDNS},
1269
+ } {
1270
+ t.Run("implementation: "+impl.name, func(t *testing.T) {
1271
+ fixup := impl.fn()
1272
+ if fixup == nil {
1273
+ t.Skip("not supported")
1274
+ }
1275
+ defer fixup()
1276
+
1277
+ for _, network := range []string{"ip", "ip4", "ip6"} {
1278
+ t.Run("network: "+network, func(t *testing.T) {
1279
+ switch {
1280
+ case network == "ip4" && !v4Ok:
1281
+ t.Skip("IPv4 is not supported")
1282
+ case network == "ip6" && !v6Ok:
1283
+ t.Skip("IPv6 is not supported")
1284
+ }
1285
+
1286
+ // google.com has both A and AAAA records.
1287
+ const host = "google.com"
1288
+ ips, err := DefaultResolver.LookupIP(context.Background(), network, host)
1289
+ if err != nil {
1290
+ testenv.SkipFlakyNet(t)
1291
+ t.Fatalf("DefaultResolver.LookupIP(%q, %q): failed with unexpected error: %v", network, host, err)
1292
+ }
1293
+
1294
+ var v4Addrs []netip.Addr
1295
+ var v6Addrs []netip.Addr
1296
+ for _, ip := range ips {
1297
+ if addr, ok := netip.AddrFromSlice(ip); ok {
1298
+ if addr.Is4() {
1299
+ v4Addrs = append(v4Addrs, addr)
1300
+ } else {
1301
+ v6Addrs = append(v6Addrs, addr)
1302
+ }
1303
+ } else {
1304
+ t.Fatalf("IP=%q is neither IPv4 nor IPv6", ip)
1305
+ }
1306
+ }
1307
+
1308
+ // Check that we got the expected addresses.
1309
+ if network == "ip4" || network == "ip" && v4Ok {
1310
+ if len(v4Addrs) == 0 {
1311
+ t.Errorf("DefaultResolver.LookupIP(%q, %q): no IPv4 addresses", network, host)
1312
+ }
1313
+ }
1314
+ if network == "ip6" || network == "ip" && v6Ok {
1315
+ if len(v6Addrs) == 0 {
1316
+ t.Errorf("DefaultResolver.LookupIP(%q, %q): no IPv6 addresses", network, host)
1317
+ }
1318
+ }
1319
+
1320
+ // Check that we didn't get any unexpected addresses.
1321
+ if network == "ip6" && len(v4Addrs) > 0 {
1322
+ t.Errorf("DefaultResolver.LookupIP(%q, %q): unexpected IPv4 addresses: %v", network, host, v4Addrs)
1323
+ }
1324
+ if network == "ip4" && len(v6Addrs) > 0 {
1325
+ t.Errorf("DefaultResolver.LookupIP(%q, %q): unexpected IPv6 or IPv4-mapped IPv6 addresses: %v", network, host, v6Addrs)
1326
+ }
1327
+ })
1328
+ }
1329
+ })
1330
+ }
1331
+ }
1332
+
1333
+ // A context timeout should still return a DNSError.
1334
+ func TestDNSTimeout(t *testing.T) {
1335
+ origTestHookLookupIP := testHookLookupIP
1336
+ defer func() { testHookLookupIP = origTestHookLookupIP }()
1337
+ defer dnsWaitGroup.Wait()
1338
+
1339
+ timeoutHookGo := make(chan bool, 1)
1340
+ timeoutHook := func(ctx context.Context, fn func(context.Context, string, string) ([]IPAddr, error), network, host string) ([]IPAddr, error) {
1341
+ <-timeoutHookGo
1342
+ return nil, context.DeadlineExceeded
1343
+ }
1344
+ testHookLookupIP = timeoutHook
1345
+
1346
+ checkErr := func(err error) {
1347
+ t.Helper()
1348
+ if err == nil {
1349
+ t.Error("expected an error")
1350
+ } else if dnserr, ok := err.(*DNSError); !ok {
1351
+ t.Errorf("got error type %T, want %T", err, (*DNSError)(nil))
1352
+ } else if !dnserr.IsTimeout {
1353
+ t.Errorf("got error %#v, want IsTimeout == true", dnserr)
1354
+ } else if isTimeout := dnserr.Timeout(); !isTimeout {
1355
+ t.Errorf("got err.Timeout() == %t, want true", isTimeout)
1356
+ }
1357
+ }
1358
+
1359
+ // Single lookup.
1360
+ timeoutHookGo <- true
1361
+ _, err := LookupIP("golang.org")
1362
+ checkErr(err)
1363
+
1364
+ // Double lookup.
1365
+ var err1, err2 error
1366
+ var wg sync.WaitGroup
1367
+ wg.Add(2)
1368
+ go func() {
1369
+ defer wg.Done()
1370
+ _, err1 = LookupIP("golang1.org")
1371
+ }()
1372
+ go func() {
1373
+ defer wg.Done()
1374
+ _, err2 = LookupIP("golang1.org")
1375
+ }()
1376
+ close(timeoutHookGo)
1377
+ wg.Wait()
1378
+ checkErr(err1)
1379
+ checkErr(err2)
1380
+
1381
+ // Double lookup with context.
1382
+ timeoutHookGo = make(chan bool)
1383
+ ctx, cancel := context.WithTimeout(context.Background(), time.Nanosecond)
1384
+ wg.Add(2)
1385
+ go func() {
1386
+ defer wg.Done()
1387
+ _, err1 = DefaultResolver.LookupIPAddr(ctx, "golang2.org")
1388
+ }()
1389
+ go func() {
1390
+ defer wg.Done()
1391
+ _, err2 = DefaultResolver.LookupIPAddr(ctx, "golang2.org")
1392
+ }()
1393
+ time.Sleep(10 * time.Nanosecond)
1394
+ close(timeoutHookGo)
1395
+ wg.Wait()
1396
+ checkErr(err1)
1397
+ checkErr(err2)
1398
+ cancel()
1399
+ }
1400
+
1401
+ func TestLookupNoData(t *testing.T) {
1402
+ if runtime.GOOS == "plan9" {
1403
+ t.Skip("not supported on plan9")
1404
+ }
1405
+
1406
+ mustHaveExternalNetwork(t)
1407
+
1408
+ testLookupNoData(t, "default resolver")
1409
+
1410
+ func() {
1411
+ defer forceGoDNS()()
1412
+ testLookupNoData(t, "forced go resolver")
1413
+ }()
1414
+
1415
+ func() {
1416
+ defer forceCgoDNS()()
1417
+ testLookupNoData(t, "forced cgo resolver")
1418
+ }()
1419
+ }
1420
+
1421
+ func testLookupNoData(t *testing.T, prefix string) {
1422
+ attempts := 0
1423
+ for {
1424
+ // Domain that doesn't have any A/AAAA RRs, but has different one (in this case a TXT),
1425
+ // so that it returns an empty response without any error codes (NXDOMAIN).
1426
+ _, err := LookupHost("golang.rsc.io.")
1427
+ if err == nil {
1428
+ t.Errorf("%v: unexpected success", prefix)
1429
+ return
1430
+ }
1431
+
1432
+ var dnsErr *DNSError
1433
+ if errors.As(err, &dnsErr) {
1434
+ succeeded := true
1435
+ if !dnsErr.IsNotFound {
1436
+ succeeded = false
1437
+ t.Logf("%v: IsNotFound is set to false", prefix)
1438
+ }
1439
+
1440
+ if dnsErr.Err != errNoSuchHost.Error() {
1441
+ succeeded = false
1442
+ t.Logf("%v: error message is not equal to: %v", prefix, errNoSuchHost.Error())
1443
+ }
1444
+
1445
+ if succeeded {
1446
+ return
1447
+ }
1448
+ }
1449
+
1450
+ testenv.SkipFlakyNet(t)
1451
+ if attempts < len(backoffDuration) {
1452
+ dur := backoffDuration[attempts]
1453
+ t.Logf("%v: backoff %v after failure %v\n", prefix, dur, err)
1454
+ time.Sleep(dur)
1455
+ attempts++
1456
+ continue
1457
+ }
1458
+
1459
+ t.Errorf("%v: unexpected error: %v", prefix, err)
1460
+ return
1461
+ }
1462
+ }
1463
+
1464
+ func TestLookupPortNotFound(t *testing.T) {
1465
+ allResolvers(t, func(t *testing.T) {
1466
+ _, err := LookupPort("udp", "_-unknown-service-")
1467
+ var dnsErr *DNSError
1468
+ if !errors.As(err, &dnsErr) || !dnsErr.IsNotFound {
1469
+ t.Fatalf("unexpected error: %v", err)
1470
+ }
1471
+ })
1472
+ }
1473
+
1474
+ // submissions service is only available through a tcp network, see:
1475
+ // https://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml?search=submissions
1476
+ var tcpOnlyService = func() string {
1477
+ // plan9 does not have submissions service defined in the service database.
1478
+ if runtime.GOOS == "plan9" {
1479
+ return "https"
1480
+ }
1481
+ return "submissions"
1482
+ }()
1483
+
1484
+ func TestLookupPortDifferentNetwork(t *testing.T) {
1485
+ allResolvers(t, func(t *testing.T) {
1486
+ _, err := LookupPort("udp", tcpOnlyService)
1487
+ var dnsErr *DNSError
1488
+ if !errors.As(err, &dnsErr) || !dnsErr.IsNotFound {
1489
+ t.Fatalf("unexpected error: %v", err)
1490
+ }
1491
+ })
1492
+ }
1493
+
1494
+ func TestLookupPortEmptyNetworkString(t *testing.T) {
1495
+ allResolvers(t, func(t *testing.T) {
1496
+ _, err := LookupPort("", tcpOnlyService)
1497
+ if err != nil {
1498
+ t.Fatalf("unexpected error: %v", err)
1499
+ }
1500
+ })
1501
+ }
1502
+
1503
+ func TestLookupPortIPNetworkString(t *testing.T) {
1504
+ allResolvers(t, func(t *testing.T) {
1505
+ _, err := LookupPort("ip", tcpOnlyService)
1506
+ if err != nil {
1507
+ t.Fatalf("unexpected error: %v", err)
1508
+ }
1509
+ })
1510
+ }
1511
+
1512
+ func allResolvers(t *testing.T, f func(t *testing.T)) {
1513
+ t.Run("default resolver", f)
1514
+ t.Run("forced go resolver", func(t *testing.T) {
1515
+ if fixup := forceGoDNS(); fixup != nil {
1516
+ defer fixup()
1517
+ f(t)
1518
+ }
1519
+ })
1520
+ t.Run("forced cgo resolver", func(t *testing.T) {
1521
+ if fixup := forceCgoDNS(); fixup != nil {
1522
+ defer fixup()
1523
+ f(t)
1524
+ }
1525
+ })
1526
+ }
1527
+
1528
+ func TestLookupNoSuchHost(t *testing.T) {
1529
+ mustHaveExternalNetwork(t)
1530
+
1531
+ const testNXDOMAIN = "invalid.invalid."
1532
+ const testNODATA = "_ldap._tcp.google.com."
1533
+
1534
+ tests := []struct {
1535
+ name string
1536
+ query func() error
1537
+ }{
1538
+ {
1539
+ name: "LookupCNAME NXDOMAIN",
1540
+ query: func() error {
1541
+ _, err := LookupCNAME(testNXDOMAIN)
1542
+ return err
1543
+ },
1544
+ },
1545
+ {
1546
+ name: "LookupHost NXDOMAIN",
1547
+ query: func() error {
1548
+ _, err := LookupHost(testNXDOMAIN)
1549
+ return err
1550
+ },
1551
+ },
1552
+ {
1553
+ name: "LookupHost NODATA",
1554
+ query: func() error {
1555
+ _, err := LookupHost(testNODATA)
1556
+ return err
1557
+ },
1558
+ },
1559
+ {
1560
+ name: "LookupMX NXDOMAIN",
1561
+ query: func() error {
1562
+ _, err := LookupMX(testNXDOMAIN)
1563
+ return err
1564
+ },
1565
+ },
1566
+ {
1567
+ name: "LookupMX NODATA",
1568
+ query: func() error {
1569
+ _, err := LookupMX(testNODATA)
1570
+ return err
1571
+ },
1572
+ },
1573
+ {
1574
+ name: "LookupNS NXDOMAIN",
1575
+ query: func() error {
1576
+ _, err := LookupNS(testNXDOMAIN)
1577
+ return err
1578
+ },
1579
+ },
1580
+ {
1581
+ name: "LookupNS NODATA",
1582
+ query: func() error {
1583
+ _, err := LookupNS(testNODATA)
1584
+ return err
1585
+ },
1586
+ },
1587
+ {
1588
+ name: "LookupSRV NXDOMAIN",
1589
+ query: func() error {
1590
+ _, _, err := LookupSRV("unknown", "tcp", testNXDOMAIN)
1591
+ return err
1592
+ },
1593
+ },
1594
+ {
1595
+ name: "LookupTXT NXDOMAIN",
1596
+ query: func() error {
1597
+ _, err := LookupTXT(testNXDOMAIN)
1598
+ return err
1599
+ },
1600
+ },
1601
+ {
1602
+ name: "LookupTXT NODATA",
1603
+ query: func() error {
1604
+ _, err := LookupTXT(testNODATA)
1605
+ return err
1606
+ },
1607
+ },
1608
+ }
1609
+
1610
+ for _, v := range tests {
1611
+ t.Run(v.name, func(t *testing.T) {
1612
+ allResolvers(t, func(t *testing.T) {
1613
+ attempts := 0
1614
+ for {
1615
+ err := v.query()
1616
+ if err == nil {
1617
+ t.Errorf("unexpected success")
1618
+ return
1619
+ }
1620
+ if dnsErr, ok := err.(*DNSError); ok {
1621
+ succeeded := true
1622
+ if !dnsErr.IsNotFound {
1623
+ succeeded = false
1624
+ t.Log("IsNotFound is set to false")
1625
+ }
1626
+ if dnsErr.Err != errNoSuchHost.Error() {
1627
+ succeeded = false
1628
+ t.Logf("error message is not equal to: %v", errNoSuchHost.Error())
1629
+ }
1630
+ if succeeded {
1631
+ return
1632
+ }
1633
+ }
1634
+ testenv.SkipFlakyNet(t)
1635
+ if attempts < len(backoffDuration) {
1636
+ dur := backoffDuration[attempts]
1637
+ t.Logf("backoff %v after failure %v\n", dur, err)
1638
+ time.Sleep(dur)
1639
+ attempts++
1640
+ continue
1641
+ }
1642
+ t.Errorf("unexpected error: %v", err)
1643
+ return
1644
+ }
1645
+ })
1646
+ })
1647
+ }
1648
+ }
platform/dbops/binaries/go/go/src/net/lookup_unix.go ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 || js || wasip1
6
+
7
+ package net
8
+
9
+ import (
10
+ "context"
11
+ "internal/bytealg"
12
+ "sync"
13
+ )
14
+
15
+ var onceReadProtocols sync.Once
16
+
17
+ // readProtocols loads contents of /etc/protocols into protocols map
18
+ // for quick access.
19
+ func readProtocols() {
20
+ file, err := open("/etc/protocols")
21
+ if err != nil {
22
+ return
23
+ }
24
+ defer file.close()
25
+
26
+ for line, ok := file.readLine(); ok; line, ok = file.readLine() {
27
+ // tcp 6 TCP # transmission control protocol
28
+ if i := bytealg.IndexByteString(line, '#'); i >= 0 {
29
+ line = line[0:i]
30
+ }
31
+ f := getFields(line)
32
+ if len(f) < 2 {
33
+ continue
34
+ }
35
+ if proto, _, ok := dtoi(f[1]); ok {
36
+ if _, ok := protocols[f[0]]; !ok {
37
+ protocols[f[0]] = proto
38
+ }
39
+ for _, alias := range f[2:] {
40
+ if _, ok := protocols[alias]; !ok {
41
+ protocols[alias] = proto
42
+ }
43
+ }
44
+ }
45
+ }
46
+ }
47
+
48
+ // lookupProtocol looks up IP protocol name in /etc/protocols and
49
+ // returns correspondent protocol number.
50
+ func lookupProtocol(_ context.Context, name string) (int, error) {
51
+ onceReadProtocols.Do(readProtocols)
52
+ return lookupProtocolMap(name)
53
+ }
54
+
55
+ func (r *Resolver) lookupHost(ctx context.Context, host string) (addrs []string, err error) {
56
+ order, conf := systemConf().hostLookupOrder(r, host)
57
+ if order == hostLookupCgo {
58
+ return cgoLookupHost(ctx, host)
59
+ }
60
+ return r.goLookupHostOrder(ctx, host, order, conf)
61
+ }
62
+
63
+ func (r *Resolver) lookupIP(ctx context.Context, network, host string) (addrs []IPAddr, err error) {
64
+ order, conf := systemConf().hostLookupOrder(r, host)
65
+ if order == hostLookupCgo {
66
+ return cgoLookupIP(ctx, network, host)
67
+ }
68
+ ips, _, err := r.goLookupIPCNAMEOrder(ctx, network, host, order, conf)
69
+ return ips, err
70
+ }
71
+
72
+ func (r *Resolver) lookupPort(ctx context.Context, network, service string) (int, error) {
73
+ // Port lookup is not a DNS operation.
74
+ // Prefer the cgo resolver if possible.
75
+ if !systemConf().mustUseGoResolver(r) {
76
+ port, err := cgoLookupPort(ctx, network, service)
77
+ if err != nil {
78
+ // Issue 18213: if cgo fails, first check to see whether we
79
+ // have the answer baked-in to the net package.
80
+ if port, err := goLookupPort(network, service); err == nil {
81
+ return port, nil
82
+ }
83
+ }
84
+ return port, err
85
+ }
86
+ return goLookupPort(network, service)
87
+ }
88
+
89
+ func (r *Resolver) lookupCNAME(ctx context.Context, name string) (string, error) {
90
+ order, conf := systemConf().hostLookupOrder(r, name)
91
+ if order == hostLookupCgo {
92
+ if cname, err, ok := cgoLookupCNAME(ctx, name); ok {
93
+ return cname, err
94
+ }
95
+ }
96
+ return r.goLookupCNAME(ctx, name, order, conf)
97
+ }
98
+
99
+ func (r *Resolver) lookupSRV(ctx context.Context, service, proto, name string) (string, []*SRV, error) {
100
+ return r.goLookupSRV(ctx, service, proto, name)
101
+ }
102
+
103
+ func (r *Resolver) lookupMX(ctx context.Context, name string) ([]*MX, error) {
104
+ return r.goLookupMX(ctx, name)
105
+ }
106
+
107
+ func (r *Resolver) lookupNS(ctx context.Context, name string) ([]*NS, error) {
108
+ return r.goLookupNS(ctx, name)
109
+ }
110
+
111
+ func (r *Resolver) lookupTXT(ctx context.Context, name string) ([]string, error) {
112
+ return r.goLookupTXT(ctx, name)
113
+ }
114
+
115
+ func (r *Resolver) lookupAddr(ctx context.Context, addr string) ([]string, error) {
116
+ order, conf := systemConf().addrLookupOrder(r, addr)
117
+ if order == hostLookupCgo {
118
+ return cgoLookupPTR(ctx, addr)
119
+ }
120
+ return r.goLookupPTR(ctx, addr, order, conf)
121
+ }
platform/dbops/binaries/go/go/src/net/lookup_windows.go ADDED
@@ -0,0 +1,471 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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/syscall/windows"
10
+ "os"
11
+ "runtime"
12
+ "syscall"
13
+ "time"
14
+ "unsafe"
15
+ )
16
+
17
+ // cgoAvailable set to true to indicate that the cgo resolver
18
+ // is available on Windows. Note that on Windows the cgo resolver
19
+ // does not actually use cgo.
20
+ const cgoAvailable = true
21
+
22
+ const (
23
+ _DNS_ERROR_RCODE_NAME_ERROR = syscall.Errno(9003)
24
+ _DNS_INFO_NO_RECORDS = syscall.Errno(9501)
25
+
26
+ _WSAHOST_NOT_FOUND = syscall.Errno(11001)
27
+ _WSATRY_AGAIN = syscall.Errno(11002)
28
+ _WSATYPE_NOT_FOUND = syscall.Errno(10109)
29
+ )
30
+
31
+ func winError(call string, err error) error {
32
+ switch err {
33
+ case _WSAHOST_NOT_FOUND, _DNS_ERROR_RCODE_NAME_ERROR, _DNS_INFO_NO_RECORDS:
34
+ return errNoSuchHost
35
+ }
36
+ return os.NewSyscallError(call, err)
37
+ }
38
+
39
+ func getprotobyname(name string) (proto int, err error) {
40
+ p, err := syscall.GetProtoByName(name)
41
+ if err != nil {
42
+ return 0, winError("getprotobyname", err)
43
+ }
44
+ return int(p.Proto), nil
45
+ }
46
+
47
+ // lookupProtocol looks up IP protocol name and returns correspondent protocol number.
48
+ func lookupProtocol(ctx context.Context, name string) (int, error) {
49
+ // GetProtoByName return value is stored in thread local storage.
50
+ // Start new os thread before the call to prevent races.
51
+ type result struct {
52
+ proto int
53
+ err error
54
+ }
55
+ ch := make(chan result) // unbuffered
56
+ go func() {
57
+ acquireThread()
58
+ defer releaseThread()
59
+ runtime.LockOSThread()
60
+ defer runtime.UnlockOSThread()
61
+ proto, err := getprotobyname(name)
62
+ select {
63
+ case ch <- result{proto: proto, err: err}:
64
+ case <-ctx.Done():
65
+ }
66
+ }()
67
+ select {
68
+ case r := <-ch:
69
+ if r.err != nil {
70
+ if proto, err := lookupProtocolMap(name); err == nil {
71
+ return proto, nil
72
+ }
73
+
74
+ dnsError := &DNSError{Err: r.err.Error(), Name: name}
75
+ if r.err == errNoSuchHost {
76
+ dnsError.IsNotFound = true
77
+ }
78
+ r.err = dnsError
79
+ }
80
+ return r.proto, r.err
81
+ case <-ctx.Done():
82
+ return 0, mapErr(ctx.Err())
83
+ }
84
+ }
85
+
86
+ func (r *Resolver) lookupHost(ctx context.Context, name string) ([]string, error) {
87
+ ips, err := r.lookupIP(ctx, "ip", name)
88
+ if err != nil {
89
+ return nil, err
90
+ }
91
+ addrs := make([]string, 0, len(ips))
92
+ for _, ip := range ips {
93
+ addrs = append(addrs, ip.String())
94
+ }
95
+ return addrs, nil
96
+ }
97
+
98
+ func (r *Resolver) lookupIP(ctx context.Context, network, name string) ([]IPAddr, error) {
99
+ if order, conf := systemConf().hostLookupOrder(r, name); order != hostLookupCgo {
100
+ return r.goLookupIP(ctx, network, name, order, conf)
101
+ }
102
+
103
+ // TODO(bradfitz,brainman): use ctx more. See TODO below.
104
+
105
+ var family int32 = syscall.AF_UNSPEC
106
+ switch ipVersion(network) {
107
+ case '4':
108
+ family = syscall.AF_INET
109
+ case '6':
110
+ family = syscall.AF_INET6
111
+ }
112
+
113
+ getaddr := func() ([]IPAddr, error) {
114
+ acquireThread()
115
+ defer releaseThread()
116
+ hints := syscall.AddrinfoW{
117
+ Family: family,
118
+ Socktype: syscall.SOCK_STREAM,
119
+ Protocol: syscall.IPPROTO_IP,
120
+ }
121
+ var result *syscall.AddrinfoW
122
+ name16p, err := syscall.UTF16PtrFromString(name)
123
+ if err != nil {
124
+ return nil, &DNSError{Name: name, Err: err.Error()}
125
+ }
126
+
127
+ dnsConf := getSystemDNSConfig()
128
+ start := time.Now()
129
+
130
+ var e error
131
+ for i := 0; i < dnsConf.attempts; i++ {
132
+ e = syscall.GetAddrInfoW(name16p, nil, &hints, &result)
133
+ if e == nil || e != _WSATRY_AGAIN || time.Since(start) > dnsConf.timeout {
134
+ break
135
+ }
136
+ }
137
+ if e != nil {
138
+ err := winError("getaddrinfow", e)
139
+ dnsError := &DNSError{Err: err.Error(), Name: name}
140
+ if err == errNoSuchHost {
141
+ dnsError.IsNotFound = true
142
+ }
143
+ return nil, dnsError
144
+ }
145
+ defer syscall.FreeAddrInfoW(result)
146
+ addrs := make([]IPAddr, 0, 5)
147
+ for ; result != nil; result = result.Next {
148
+ addr := unsafe.Pointer(result.Addr)
149
+ switch result.Family {
150
+ case syscall.AF_INET:
151
+ a := (*syscall.RawSockaddrInet4)(addr).Addr
152
+ addrs = append(addrs, IPAddr{IP: copyIP(a[:])})
153
+ case syscall.AF_INET6:
154
+ a := (*syscall.RawSockaddrInet6)(addr).Addr
155
+ zone := zoneCache.name(int((*syscall.RawSockaddrInet6)(addr).Scope_id))
156
+ addrs = append(addrs, IPAddr{IP: copyIP(a[:]), Zone: zone})
157
+ default:
158
+ return nil, &DNSError{Err: syscall.EWINDOWS.Error(), Name: name}
159
+ }
160
+ }
161
+ return addrs, nil
162
+ }
163
+
164
+ type ret struct {
165
+ addrs []IPAddr
166
+ err error
167
+ }
168
+
169
+ var ch chan ret
170
+ if ctx.Err() == nil {
171
+ ch = make(chan ret, 1)
172
+ go func() {
173
+ addr, err := getaddr()
174
+ ch <- ret{addrs: addr, err: err}
175
+ }()
176
+ }
177
+
178
+ select {
179
+ case r := <-ch:
180
+ return r.addrs, r.err
181
+ case <-ctx.Done():
182
+ // TODO(bradfitz,brainman): cancel the ongoing
183
+ // GetAddrInfoW? It would require conditionally using
184
+ // GetAddrInfoEx with lpOverlapped, which requires
185
+ // Windows 8 or newer. I guess we'll need oldLookupIP,
186
+ // newLookupIP, and newerLookUP.
187
+ //
188
+ // For now we just let it finish and write to the
189
+ // buffered channel.
190
+ return nil, &DNSError{
191
+ Name: name,
192
+ Err: ctx.Err().Error(),
193
+ IsTimeout: ctx.Err() == context.DeadlineExceeded,
194
+ }
195
+ }
196
+ }
197
+
198
+ func (r *Resolver) lookupPort(ctx context.Context, network, service string) (int, error) {
199
+ if systemConf().mustUseGoResolver(r) {
200
+ return lookupPortMap(network, service)
201
+ }
202
+
203
+ // TODO(bradfitz): finish ctx plumbing. Nothing currently depends on this.
204
+ acquireThread()
205
+ defer releaseThread()
206
+
207
+ var hints syscall.AddrinfoW
208
+
209
+ switch network {
210
+ case "ip": // no hints
211
+ case "tcp", "tcp4", "tcp6":
212
+ hints.Socktype = syscall.SOCK_STREAM
213
+ hints.Protocol = syscall.IPPROTO_TCP
214
+ case "udp", "udp4", "udp6":
215
+ hints.Socktype = syscall.SOCK_DGRAM
216
+ hints.Protocol = syscall.IPPROTO_UDP
217
+ default:
218
+ return 0, &DNSError{Err: "unknown network", Name: network + "/" + service}
219
+ }
220
+
221
+ switch ipVersion(network) {
222
+ case '4':
223
+ hints.Family = syscall.AF_INET
224
+ case '6':
225
+ hints.Family = syscall.AF_INET6
226
+ }
227
+
228
+ var result *syscall.AddrinfoW
229
+ e := syscall.GetAddrInfoW(nil, syscall.StringToUTF16Ptr(service), &hints, &result)
230
+ if e != nil {
231
+ if port, err := lookupPortMap(network, service); err == nil {
232
+ return port, nil
233
+ }
234
+
235
+ // The _WSATYPE_NOT_FOUND error is returned by GetAddrInfoW
236
+ // when the service name is unknown. We are also checking
237
+ // for _WSAHOST_NOT_FOUND here to match the cgo (unix) version
238
+ // cgo_unix.go (cgoLookupServicePort).
239
+ if e == _WSATYPE_NOT_FOUND || e == _WSAHOST_NOT_FOUND {
240
+ return 0, &DNSError{Err: "unknown port", Name: network + "/" + service, IsNotFound: true}
241
+ }
242
+ err := os.NewSyscallError("getaddrinfow", e)
243
+ return 0, &DNSError{Err: err.Error(), Name: network + "/" + service}
244
+ }
245
+ defer syscall.FreeAddrInfoW(result)
246
+ if result == nil {
247
+ return 0, &DNSError{Err: syscall.EINVAL.Error(), Name: network + "/" + service}
248
+ }
249
+ addr := unsafe.Pointer(result.Addr)
250
+ switch result.Family {
251
+ case syscall.AF_INET:
252
+ a := (*syscall.RawSockaddrInet4)(addr)
253
+ return int(syscall.Ntohs(a.Port)), nil
254
+ case syscall.AF_INET6:
255
+ a := (*syscall.RawSockaddrInet6)(addr)
256
+ return int(syscall.Ntohs(a.Port)), nil
257
+ }
258
+ return 0, &DNSError{Err: syscall.EINVAL.Error(), Name: network + "/" + service}
259
+ }
260
+
261
+ func (r *Resolver) lookupCNAME(ctx context.Context, name string) (string, error) {
262
+ if order, conf := systemConf().hostLookupOrder(r, name); order != hostLookupCgo {
263
+ return r.goLookupCNAME(ctx, name, order, conf)
264
+ }
265
+
266
+ // TODO(bradfitz): finish ctx plumbing. Nothing currently depends on this.
267
+ acquireThread()
268
+ defer releaseThread()
269
+ var rec *syscall.DNSRecord
270
+ e := syscall.DnsQuery(name, syscall.DNS_TYPE_CNAME, 0, nil, &rec, nil)
271
+ // windows returns DNS_INFO_NO_RECORDS if there are no CNAME-s
272
+ if errno, ok := e.(syscall.Errno); ok && errno == syscall.DNS_INFO_NO_RECORDS {
273
+ // if there are no aliases, the canonical name is the input name
274
+ return absDomainName(name), nil
275
+ }
276
+ if e != nil {
277
+ err := winError("dnsquery", e)
278
+ return "", &DNSError{Err: err.Error(), Name: name, IsNotFound: err == errNoSuchHost}
279
+ }
280
+ defer syscall.DnsRecordListFree(rec, 1)
281
+
282
+ resolved := resolveCNAME(syscall.StringToUTF16Ptr(name), rec)
283
+ cname := windows.UTF16PtrToString(resolved)
284
+ return absDomainName(cname), nil
285
+ }
286
+
287
+ func (r *Resolver) lookupSRV(ctx context.Context, service, proto, name string) (string, []*SRV, error) {
288
+ if systemConf().mustUseGoResolver(r) {
289
+ return r.goLookupSRV(ctx, service, proto, name)
290
+ }
291
+ // TODO(bradfitz): finish ctx plumbing. Nothing currently depends on this.
292
+ acquireThread()
293
+ defer releaseThread()
294
+ var target string
295
+ if service == "" && proto == "" {
296
+ target = name
297
+ } else {
298
+ target = "_" + service + "._" + proto + "." + name
299
+ }
300
+ var rec *syscall.DNSRecord
301
+ e := syscall.DnsQuery(target, syscall.DNS_TYPE_SRV, 0, nil, &rec, nil)
302
+ if e != nil {
303
+ err := winError("dnsquery", e)
304
+ return "", nil, &DNSError{Err: err.Error(), Name: name, IsNotFound: err == errNoSuchHost}
305
+ }
306
+ defer syscall.DnsRecordListFree(rec, 1)
307
+
308
+ srvs := make([]*SRV, 0, 10)
309
+ for _, p := range validRecs(rec, syscall.DNS_TYPE_SRV, target) {
310
+ v := (*syscall.DNSSRVData)(unsafe.Pointer(&p.Data[0]))
311
+ srvs = append(srvs, &SRV{absDomainName(syscall.UTF16ToString((*[256]uint16)(unsafe.Pointer(v.Target))[:])), v.Port, v.Priority, v.Weight})
312
+ }
313
+ byPriorityWeight(srvs).sort()
314
+ return absDomainName(target), srvs, nil
315
+ }
316
+
317
+ func (r *Resolver) lookupMX(ctx context.Context, name string) ([]*MX, error) {
318
+ if systemConf().mustUseGoResolver(r) {
319
+ return r.goLookupMX(ctx, name)
320
+ }
321
+ // TODO(bradfitz): finish ctx plumbing. Nothing currently depends on this.
322
+ acquireThread()
323
+ defer releaseThread()
324
+ var rec *syscall.DNSRecord
325
+ e := syscall.DnsQuery(name, syscall.DNS_TYPE_MX, 0, nil, &rec, nil)
326
+ if e != nil {
327
+ err := winError("dnsquery", e)
328
+ return nil, &DNSError{Err: err.Error(), Name: name, IsNotFound: err == errNoSuchHost}
329
+ }
330
+ defer syscall.DnsRecordListFree(rec, 1)
331
+
332
+ mxs := make([]*MX, 0, 10)
333
+ for _, p := range validRecs(rec, syscall.DNS_TYPE_MX, name) {
334
+ v := (*syscall.DNSMXData)(unsafe.Pointer(&p.Data[0]))
335
+ mxs = append(mxs, &MX{absDomainName(windows.UTF16PtrToString(v.NameExchange)), v.Preference})
336
+ }
337
+ byPref(mxs).sort()
338
+ return mxs, nil
339
+ }
340
+
341
+ func (r *Resolver) lookupNS(ctx context.Context, name string) ([]*NS, error) {
342
+ if systemConf().mustUseGoResolver(r) {
343
+ return r.goLookupNS(ctx, name)
344
+ }
345
+ // TODO(bradfitz): finish ctx plumbing. Nothing currently depends on this.
346
+ acquireThread()
347
+ defer releaseThread()
348
+ var rec *syscall.DNSRecord
349
+ e := syscall.DnsQuery(name, syscall.DNS_TYPE_NS, 0, nil, &rec, nil)
350
+ if e != nil {
351
+ err := winError("dnsquery", e)
352
+ return nil, &DNSError{Err: err.Error(), Name: name, IsNotFound: err == errNoSuchHost}
353
+ }
354
+ defer syscall.DnsRecordListFree(rec, 1)
355
+
356
+ nss := make([]*NS, 0, 10)
357
+ for _, p := range validRecs(rec, syscall.DNS_TYPE_NS, name) {
358
+ v := (*syscall.DNSPTRData)(unsafe.Pointer(&p.Data[0]))
359
+ nss = append(nss, &NS{absDomainName(syscall.UTF16ToString((*[256]uint16)(unsafe.Pointer(v.Host))[:]))})
360
+ }
361
+ return nss, nil
362
+ }
363
+
364
+ func (r *Resolver) lookupTXT(ctx context.Context, name string) ([]string, error) {
365
+ if systemConf().mustUseGoResolver(r) {
366
+ return r.goLookupTXT(ctx, name)
367
+ }
368
+ // TODO(bradfitz): finish ctx plumbing. Nothing currently depends on this.
369
+ acquireThread()
370
+ defer releaseThread()
371
+ var rec *syscall.DNSRecord
372
+ e := syscall.DnsQuery(name, syscall.DNS_TYPE_TEXT, 0, nil, &rec, nil)
373
+ if e != nil {
374
+ err := winError("dnsquery", e)
375
+ return nil, &DNSError{Err: err.Error(), Name: name, IsNotFound: err == errNoSuchHost}
376
+ }
377
+ defer syscall.DnsRecordListFree(rec, 1)
378
+
379
+ txts := make([]string, 0, 10)
380
+ for _, p := range validRecs(rec, syscall.DNS_TYPE_TEXT, name) {
381
+ d := (*syscall.DNSTXTData)(unsafe.Pointer(&p.Data[0]))
382
+ s := ""
383
+ for _, v := range (*[1 << 10]*uint16)(unsafe.Pointer(&(d.StringArray[0])))[:d.StringCount:d.StringCount] {
384
+ s += windows.UTF16PtrToString(v)
385
+ }
386
+ txts = append(txts, s)
387
+ }
388
+ return txts, nil
389
+ }
390
+
391
+ func (r *Resolver) lookupAddr(ctx context.Context, addr string) ([]string, error) {
392
+ if order, conf := systemConf().addrLookupOrder(r, addr); order != hostLookupCgo {
393
+ return r.goLookupPTR(ctx, addr, order, conf)
394
+ }
395
+
396
+ // TODO(bradfitz): finish ctx plumbing. Nothing currently depends on this.
397
+ acquireThread()
398
+ defer releaseThread()
399
+ arpa, err := reverseaddr(addr)
400
+ if err != nil {
401
+ return nil, err
402
+ }
403
+ var rec *syscall.DNSRecord
404
+ e := syscall.DnsQuery(arpa, syscall.DNS_TYPE_PTR, 0, nil, &rec, nil)
405
+ if e != nil {
406
+ err := winError("dnsquery", e)
407
+ return nil, &DNSError{Err: err.Error(), Name: addr, IsNotFound: err == errNoSuchHost}
408
+ }
409
+ defer syscall.DnsRecordListFree(rec, 1)
410
+
411
+ ptrs := make([]string, 0, 10)
412
+ for _, p := range validRecs(rec, syscall.DNS_TYPE_PTR, arpa) {
413
+ v := (*syscall.DNSPTRData)(unsafe.Pointer(&p.Data[0]))
414
+ ptrs = append(ptrs, absDomainName(windows.UTF16PtrToString(v.Host)))
415
+ }
416
+ return ptrs, nil
417
+ }
418
+
419
+ const dnsSectionMask = 0x0003
420
+
421
+ // returns only results applicable to name and resolves CNAME entries.
422
+ func validRecs(r *syscall.DNSRecord, dnstype uint16, name string) []*syscall.DNSRecord {
423
+ cname := syscall.StringToUTF16Ptr(name)
424
+ if dnstype != syscall.DNS_TYPE_CNAME {
425
+ cname = resolveCNAME(cname, r)
426
+ }
427
+ rec := make([]*syscall.DNSRecord, 0, 10)
428
+ for p := r; p != nil; p = p.Next {
429
+ // in case of a local machine, DNS records are returned with DNSREC_QUESTION flag instead of DNS_ANSWER
430
+ if p.Dw&dnsSectionMask != syscall.DnsSectionAnswer && p.Dw&dnsSectionMask != syscall.DnsSectionQuestion {
431
+ continue
432
+ }
433
+ if p.Type != dnstype {
434
+ continue
435
+ }
436
+ if !syscall.DnsNameCompare(cname, p.Name) {
437
+ continue
438
+ }
439
+ rec = append(rec, p)
440
+ }
441
+ return rec
442
+ }
443
+
444
+ // returns the last CNAME in chain.
445
+ func resolveCNAME(name *uint16, r *syscall.DNSRecord) *uint16 {
446
+ // limit cname resolving to 10 in case of an infinite CNAME loop
447
+ Cname:
448
+ for cnameloop := 0; cnameloop < 10; cnameloop++ {
449
+ for p := r; p != nil; p = p.Next {
450
+ if p.Dw&dnsSectionMask != syscall.DnsSectionAnswer {
451
+ continue
452
+ }
453
+ if p.Type != syscall.DNS_TYPE_CNAME {
454
+ continue
455
+ }
456
+ if !syscall.DnsNameCompare(name, p.Name) {
457
+ continue
458
+ }
459
+ name = (*syscall.DNSPTRData)(unsafe.Pointer(&r.Data[0])).Host
460
+ continue Cname
461
+ }
462
+ break
463
+ }
464
+ return name
465
+ }
466
+
467
+ // concurrentThreadsLimit returns the number of threads we permit to
468
+ // run concurrently doing DNS lookups.
469
+ func concurrentThreadsLimit() int {
470
+ return 500
471
+ }
platform/dbops/binaries/go/go/src/net/lookup_windows_test.go ADDED
@@ -0,0 +1,340 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "encoding/json"
10
+ "errors"
11
+ "fmt"
12
+ "internal/testenv"
13
+ "os/exec"
14
+ "reflect"
15
+ "regexp"
16
+ "sort"
17
+ "strings"
18
+ "syscall"
19
+ "testing"
20
+ )
21
+
22
+ var nslookupTestServers = []string{"mail.golang.com", "gmail.com"}
23
+ var lookupTestIPs = []string{"8.8.8.8", "1.1.1.1"}
24
+
25
+ func toJson(v any) string {
26
+ data, _ := json.Marshal(v)
27
+ return string(data)
28
+ }
29
+
30
+ func testLookup(t *testing.T, fn func(*testing.T, *Resolver, string)) {
31
+ for _, def := range []bool{true, false} {
32
+ def := def
33
+ for _, server := range nslookupTestServers {
34
+ server := server
35
+ var name string
36
+ if def {
37
+ name = "default/"
38
+ } else {
39
+ name = "go/"
40
+ }
41
+ t.Run(name+server, func(t *testing.T) {
42
+ t.Parallel()
43
+ r := DefaultResolver
44
+ if !def {
45
+ r = &Resolver{PreferGo: true}
46
+ }
47
+ fn(t, r, server)
48
+ })
49
+ }
50
+ }
51
+ }
52
+
53
+ func TestNSLookupMX(t *testing.T) {
54
+ testenv.MustHaveExternalNetwork(t)
55
+
56
+ testLookup(t, func(t *testing.T, r *Resolver, server string) {
57
+ mx, err := r.LookupMX(context.Background(), server)
58
+ if err != nil {
59
+ t.Fatal(err)
60
+ }
61
+ if len(mx) == 0 {
62
+ t.Fatal("no results")
63
+ }
64
+ expected, err := nslookupMX(server)
65
+ if err != nil {
66
+ t.Skipf("skipping failed nslookup %s test: %s", server, err)
67
+ }
68
+ sort.Sort(byPrefAndHost(expected))
69
+ sort.Sort(byPrefAndHost(mx))
70
+ if !reflect.DeepEqual(expected, mx) {
71
+ t.Errorf("different results %s:\texp:%v\tgot:%v", server, toJson(expected), toJson(mx))
72
+ }
73
+ })
74
+ }
75
+
76
+ func TestNSLookupCNAME(t *testing.T) {
77
+ testenv.MustHaveExternalNetwork(t)
78
+
79
+ testLookup(t, func(t *testing.T, r *Resolver, server string) {
80
+ cname, err := r.LookupCNAME(context.Background(), server)
81
+ if err != nil {
82
+ t.Fatalf("failed %s: %s", server, err)
83
+ }
84
+ if cname == "" {
85
+ t.Fatalf("no result %s", server)
86
+ }
87
+ expected, err := nslookupCNAME(server)
88
+ if err != nil {
89
+ t.Skipf("skipping failed nslookup %s test: %s", server, err)
90
+ }
91
+ if expected != cname {
92
+ t.Errorf("different results %s:\texp:%v\tgot:%v", server, expected, cname)
93
+ }
94
+ })
95
+ }
96
+
97
+ func TestNSLookupNS(t *testing.T) {
98
+ testenv.MustHaveExternalNetwork(t)
99
+
100
+ testLookup(t, func(t *testing.T, r *Resolver, server string) {
101
+ ns, err := r.LookupNS(context.Background(), server)
102
+ if err != nil {
103
+ t.Fatalf("failed %s: %s", server, err)
104
+ }
105
+ if len(ns) == 0 {
106
+ t.Fatal("no results")
107
+ }
108
+ expected, err := nslookupNS(server)
109
+ if err != nil {
110
+ t.Skipf("skipping failed nslookup %s test: %s", server, err)
111
+ }
112
+ sort.Sort(byHost(expected))
113
+ sort.Sort(byHost(ns))
114
+ if !reflect.DeepEqual(expected, ns) {
115
+ t.Errorf("different results %s:\texp:%v\tgot:%v", toJson(server), toJson(expected), ns)
116
+ }
117
+ })
118
+ }
119
+
120
+ func TestNSLookupTXT(t *testing.T) {
121
+ testenv.MustHaveExternalNetwork(t)
122
+
123
+ testLookup(t, func(t *testing.T, r *Resolver, server string) {
124
+ txt, err := r.LookupTXT(context.Background(), server)
125
+ if err != nil {
126
+ t.Fatalf("failed %s: %s", server, err)
127
+ }
128
+ if len(txt) == 0 {
129
+ t.Fatalf("no results")
130
+ }
131
+ expected, err := nslookupTXT(server)
132
+ if err != nil {
133
+ t.Skipf("skipping failed nslookup %s test: %s", server, err)
134
+ }
135
+ sort.Strings(expected)
136
+ sort.Strings(txt)
137
+ if !reflect.DeepEqual(expected, txt) {
138
+ t.Errorf("different results %s:\texp:%v\tgot:%v", server, toJson(expected), toJson(txt))
139
+ }
140
+ })
141
+ }
142
+
143
+ func TestLookupLocalPTR(t *testing.T) {
144
+ testenv.MustHaveExternalNetwork(t)
145
+
146
+ addr, err := localIP()
147
+ if err != nil {
148
+ t.Errorf("failed to get local ip: %s", err)
149
+ }
150
+ names, err := LookupAddr(addr.String())
151
+ if err != nil {
152
+ t.Errorf("failed %s: %s", addr, err)
153
+ }
154
+ if len(names) == 0 {
155
+ t.Errorf("no results")
156
+ }
157
+ expected, err := lookupPTR(addr.String())
158
+ if err != nil {
159
+ t.Skipf("skipping failed lookup %s test: %s", addr.String(), err)
160
+ }
161
+ sort.Strings(expected)
162
+ sort.Strings(names)
163
+ if !reflect.DeepEqual(expected, names) {
164
+ t.Errorf("different results %s:\texp:%v\tgot:%v", addr, toJson(expected), toJson(names))
165
+ }
166
+ }
167
+
168
+ func TestLookupPTR(t *testing.T) {
169
+ testenv.MustHaveExternalNetwork(t)
170
+
171
+ for _, addr := range lookupTestIPs {
172
+ names, err := LookupAddr(addr)
173
+ if err != nil {
174
+ // The DNSError type stores the error as a string, so it cannot wrap the
175
+ // original error code and we cannot check for it here. However, we can at
176
+ // least use its error string to identify the correct localized text for
177
+ // the error to skip.
178
+ var DNS_ERROR_RCODE_SERVER_FAILURE syscall.Errno = 9002
179
+ if strings.HasSuffix(err.Error(), DNS_ERROR_RCODE_SERVER_FAILURE.Error()) {
180
+ testenv.SkipFlaky(t, 38111)
181
+ }
182
+ t.Errorf("failed %s: %s", addr, err)
183
+ }
184
+ if len(names) == 0 {
185
+ t.Errorf("no results")
186
+ }
187
+ expected, err := lookupPTR(addr)
188
+ if err != nil {
189
+ t.Logf("skipping failed lookup %s test: %s", addr, err)
190
+ continue
191
+ }
192
+ sort.Strings(expected)
193
+ sort.Strings(names)
194
+ if !reflect.DeepEqual(expected, names) {
195
+ t.Errorf("different results %s:\texp:%v\tgot:%v", addr, toJson(expected), toJson(names))
196
+ }
197
+ }
198
+ }
199
+
200
+ type byPrefAndHost []*MX
201
+
202
+ func (s byPrefAndHost) Len() int { return len(s) }
203
+ func (s byPrefAndHost) Less(i, j int) bool {
204
+ if s[i].Pref != s[j].Pref {
205
+ return s[i].Pref < s[j].Pref
206
+ }
207
+ return s[i].Host < s[j].Host
208
+ }
209
+ func (s byPrefAndHost) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
210
+
211
+ type byHost []*NS
212
+
213
+ func (s byHost) Len() int { return len(s) }
214
+ func (s byHost) Less(i, j int) bool { return s[i].Host < s[j].Host }
215
+ func (s byHost) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
216
+
217
+ func nslookup(qtype, name string) (string, error) {
218
+ var out strings.Builder
219
+ var err strings.Builder
220
+ cmd := exec.Command("nslookup", "-querytype="+qtype, name)
221
+ cmd.Stdout = &out
222
+ cmd.Stderr = &err
223
+ if err := cmd.Run(); err != nil {
224
+ return "", err
225
+ }
226
+ r := strings.ReplaceAll(out.String(), "\r\n", "\n")
227
+ // nslookup stderr output contains also debug information such as
228
+ // "Non-authoritative answer" and it doesn't return the correct errcode
229
+ if strings.Contains(err.String(), "can't find") {
230
+ return r, errors.New(err.String())
231
+ }
232
+ return r, nil
233
+ }
234
+
235
+ func nslookupMX(name string) (mx []*MX, err error) {
236
+ var r string
237
+ if r, err = nslookup("mx", name); err != nil {
238
+ return
239
+ }
240
+ mx = make([]*MX, 0, 10)
241
+ // linux nslookup syntax
242
+ // golang.org mail exchanger = 2 alt1.aspmx.l.google.com.
243
+ rx := regexp.MustCompile(`(?m)^([a-z0-9.\-]+)\s+mail exchanger\s*=\s*([0-9]+)\s*([a-z0-9.\-]+)$`)
244
+ for _, ans := range rx.FindAllStringSubmatch(r, -1) {
245
+ pref, _, _ := dtoi(ans[2])
246
+ mx = append(mx, &MX{absDomainName(ans[3]), uint16(pref)})
247
+ }
248
+ // windows nslookup syntax
249
+ // gmail.com MX preference = 30, mail exchanger = alt3.gmail-smtp-in.l.google.com
250
+ rx = regexp.MustCompile(`(?m)^([a-z0-9.\-]+)\s+MX preference\s*=\s*([0-9]+)\s*,\s*mail exchanger\s*=\s*([a-z0-9.\-]+)$`)
251
+ for _, ans := range rx.FindAllStringSubmatch(r, -1) {
252
+ pref, _, _ := dtoi(ans[2])
253
+ mx = append(mx, &MX{absDomainName(ans[3]), uint16(pref)})
254
+ }
255
+ return
256
+ }
257
+
258
+ func nslookupNS(name string) (ns []*NS, err error) {
259
+ var r string
260
+ if r, err = nslookup("ns", name); err != nil {
261
+ return
262
+ }
263
+ ns = make([]*NS, 0, 10)
264
+ // golang.org nameserver = ns1.google.com.
265
+ rx := regexp.MustCompile(`(?m)^([a-z0-9.\-]+)\s+nameserver\s*=\s*([a-z0-9.\-]+)$`)
266
+ for _, ans := range rx.FindAllStringSubmatch(r, -1) {
267
+ ns = append(ns, &NS{absDomainName(ans[2])})
268
+ }
269
+ return
270
+ }
271
+
272
+ func nslookupCNAME(name string) (cname string, err error) {
273
+ var r string
274
+ if r, err = nslookup("cname", name); err != nil {
275
+ return
276
+ }
277
+ // mail.golang.com canonical name = golang.org.
278
+ rx := regexp.MustCompile(`(?m)^([a-z0-9.\-]+)\s+canonical name\s*=\s*([a-z0-9.\-]+)$`)
279
+ // assumes the last CNAME is the correct one
280
+ last := name
281
+ for _, ans := range rx.FindAllStringSubmatch(r, -1) {
282
+ last = ans[2]
283
+ }
284
+ return absDomainName(last), nil
285
+ }
286
+
287
+ func nslookupTXT(name string) (txt []string, err error) {
288
+ var r string
289
+ if r, err = nslookup("txt", name); err != nil {
290
+ return
291
+ }
292
+ txt = make([]string, 0, 10)
293
+ // linux
294
+ // golang.org text = "v=spf1 redirect=_spf.google.com"
295
+
296
+ // windows
297
+ // golang.org text =
298
+ //
299
+ // "v=spf1 redirect=_spf.google.com"
300
+ rx := regexp.MustCompile(`(?m)^([a-z0-9.\-]+)\s+text\s*=\s*"(.*)"$`)
301
+ for _, ans := range rx.FindAllStringSubmatch(r, -1) {
302
+ txt = append(txt, ans[2])
303
+ }
304
+ return
305
+ }
306
+
307
+ func ping(name string) (string, error) {
308
+ cmd := exec.Command("ping", "-n", "1", "-a", name)
309
+ stdoutStderr, err := cmd.CombinedOutput()
310
+ if err != nil {
311
+ return "", fmt.Errorf("%v: %v", err, string(stdoutStderr))
312
+ }
313
+ r := strings.ReplaceAll(string(stdoutStderr), "\r\n", "\n")
314
+ return r, nil
315
+ }
316
+
317
+ func lookupPTR(name string) (ptr []string, err error) {
318
+ var r string
319
+ if r, err = ping(name); err != nil {
320
+ return
321
+ }
322
+ ptr = make([]string, 0, 10)
323
+ rx := regexp.MustCompile(`(?m)^Pinging\s+([a-zA-Z0-9.\-]+)\s+\[.*$`)
324
+ for _, ans := range rx.FindAllStringSubmatch(r, -1) {
325
+ ptr = append(ptr, absDomainName(ans[1]))
326
+ }
327
+ return
328
+ }
329
+
330
+ func localIP() (ip IP, err error) {
331
+ conn, err := Dial("udp", "golang.org:80")
332
+ if err != nil {
333
+ return nil, err
334
+ }
335
+ defer conn.Close()
336
+
337
+ localAddr := conn.LocalAddr().(*UDPAddr)
338
+
339
+ return localAddr.IP, nil
340
+ }
platform/dbops/binaries/go/go/src/net/mac.go ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ const hexDigit = "0123456789abcdef"
8
+
9
+ // A HardwareAddr represents a physical hardware address.
10
+ type HardwareAddr []byte
11
+
12
+ func (a HardwareAddr) String() string {
13
+ if len(a) == 0 {
14
+ return ""
15
+ }
16
+ buf := make([]byte, 0, len(a)*3-1)
17
+ for i, b := range a {
18
+ if i > 0 {
19
+ buf = append(buf, ':')
20
+ }
21
+ buf = append(buf, hexDigit[b>>4])
22
+ buf = append(buf, hexDigit[b&0xF])
23
+ }
24
+ return string(buf)
25
+ }
26
+
27
+ // ParseMAC parses s as an IEEE 802 MAC-48, EUI-48, EUI-64, or a 20-octet
28
+ // IP over InfiniBand link-layer address using one of the following formats:
29
+ //
30
+ // 00:00:5e:00:53:01
31
+ // 02:00:5e:10:00:00:00:01
32
+ // 00:00:00:00:fe:80:00:00:00:00:00:00:02:00:5e:10:00:00:00:01
33
+ // 00-00-5e-00-53-01
34
+ // 02-00-5e-10-00-00-00-01
35
+ // 00-00-00-00-fe-80-00-00-00-00-00-00-02-00-5e-10-00-00-00-01
36
+ // 0000.5e00.5301
37
+ // 0200.5e10.0000.0001
38
+ // 0000.0000.fe80.0000.0000.0000.0200.5e10.0000.0001
39
+ func ParseMAC(s string) (hw HardwareAddr, err error) {
40
+ if len(s) < 14 {
41
+ goto error
42
+ }
43
+
44
+ if s[2] == ':' || s[2] == '-' {
45
+ if (len(s)+1)%3 != 0 {
46
+ goto error
47
+ }
48
+ n := (len(s) + 1) / 3
49
+ if n != 6 && n != 8 && n != 20 {
50
+ goto error
51
+ }
52
+ hw = make(HardwareAddr, n)
53
+ for x, i := 0, 0; i < n; i++ {
54
+ var ok bool
55
+ if hw[i], ok = xtoi2(s[x:], s[2]); !ok {
56
+ goto error
57
+ }
58
+ x += 3
59
+ }
60
+ } else if s[4] == '.' {
61
+ if (len(s)+1)%5 != 0 {
62
+ goto error
63
+ }
64
+ n := 2 * (len(s) + 1) / 5
65
+ if n != 6 && n != 8 && n != 20 {
66
+ goto error
67
+ }
68
+ hw = make(HardwareAddr, n)
69
+ for x, i := 0, 0; i < n; i += 2 {
70
+ var ok bool
71
+ if hw[i], ok = xtoi2(s[x:x+2], 0); !ok {
72
+ goto error
73
+ }
74
+ if hw[i+1], ok = xtoi2(s[x+2:], s[4]); !ok {
75
+ goto error
76
+ }
77
+ x += 5
78
+ }
79
+ } else {
80
+ goto error
81
+ }
82
+ return hw, nil
83
+
84
+ error:
85
+ return nil, &AddrError{Err: "invalid MAC address", Addr: s}
86
+ }
platform/dbops/binaries/go/go/src/net/mac_test.go ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "reflect"
9
+ "strings"
10
+ "testing"
11
+ )
12
+
13
+ var parseMACTests = []struct {
14
+ in string
15
+ out HardwareAddr
16
+ err string
17
+ }{
18
+ // See RFC 7042, Section 2.1.1.
19
+ {"00:00:5e:00:53:01", HardwareAddr{0x00, 0x00, 0x5e, 0x00, 0x53, 0x01}, ""},
20
+ {"00-00-5e-00-53-01", HardwareAddr{0x00, 0x00, 0x5e, 0x00, 0x53, 0x01}, ""},
21
+ {"0000.5e00.5301", HardwareAddr{0x00, 0x00, 0x5e, 0x00, 0x53, 0x01}, ""},
22
+
23
+ // See RFC 7042, Section 2.2.2.
24
+ {"02:00:5e:10:00:00:00:01", HardwareAddr{0x02, 0x00, 0x5e, 0x10, 0x00, 0x00, 0x00, 0x01}, ""},
25
+ {"02-00-5e-10-00-00-00-01", HardwareAddr{0x02, 0x00, 0x5e, 0x10, 0x00, 0x00, 0x00, 0x01}, ""},
26
+ {"0200.5e10.0000.0001", HardwareAddr{0x02, 0x00, 0x5e, 0x10, 0x00, 0x00, 0x00, 0x01}, ""},
27
+
28
+ // See RFC 4391, Section 9.1.1.
29
+ {
30
+ "00:00:00:00:fe:80:00:00:00:00:00:00:02:00:5e:10:00:00:00:01",
31
+ HardwareAddr{
32
+ 0x00, 0x00, 0x00, 0x00,
33
+ 0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
34
+ 0x02, 0x00, 0x5e, 0x10, 0x00, 0x00, 0x00, 0x01,
35
+ },
36
+ "",
37
+ },
38
+ {
39
+ "00-00-00-00-fe-80-00-00-00-00-00-00-02-00-5e-10-00-00-00-01",
40
+ HardwareAddr{
41
+ 0x00, 0x00, 0x00, 0x00,
42
+ 0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
43
+ 0x02, 0x00, 0x5e, 0x10, 0x00, 0x00, 0x00, 0x01,
44
+ },
45
+ "",
46
+ },
47
+ {
48
+ "0000.0000.fe80.0000.0000.0000.0200.5e10.0000.0001",
49
+ HardwareAddr{
50
+ 0x00, 0x00, 0x00, 0x00,
51
+ 0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
52
+ 0x02, 0x00, 0x5e, 0x10, 0x00, 0x00, 0x00, 0x01,
53
+ },
54
+ "",
55
+ },
56
+
57
+ {"ab:cd:ef:AB:CD:EF", HardwareAddr{0xab, 0xcd, 0xef, 0xab, 0xcd, 0xef}, ""},
58
+ {"ab:cd:ef:AB:CD:EF:ab:cd", HardwareAddr{0xab, 0xcd, 0xef, 0xab, 0xcd, 0xef, 0xab, 0xcd}, ""},
59
+ {
60
+ "ab:cd:ef:AB:CD:EF:ab:cd:ef:AB:CD:EF:ab:cd:ef:AB:CD:EF:ab:cd",
61
+ HardwareAddr{
62
+ 0xab, 0xcd, 0xef, 0xab,
63
+ 0xcd, 0xef, 0xab, 0xcd, 0xef, 0xab, 0xcd, 0xef,
64
+ 0xab, 0xcd, 0xef, 0xab, 0xcd, 0xef, 0xab, 0xcd,
65
+ },
66
+ "",
67
+ },
68
+
69
+ {"01.02.03.04.05.06", nil, "invalid MAC address"},
70
+ {"01:02:03:04:05:06:", nil, "invalid MAC address"},
71
+ {"x1:02:03:04:05:06", nil, "invalid MAC address"},
72
+ {"01002:03:04:05:06", nil, "invalid MAC address"},
73
+ {"01:02003:04:05:06", nil, "invalid MAC address"},
74
+ {"01:02:03004:05:06", nil, "invalid MAC address"},
75
+ {"01:02:03:04005:06", nil, "invalid MAC address"},
76
+ {"01:02:03:04:05006", nil, "invalid MAC address"},
77
+ {"01-02:03:04:05:06", nil, "invalid MAC address"},
78
+ {"01:02-03-04-05-06", nil, "invalid MAC address"},
79
+ {"0123:4567:89AF", nil, "invalid MAC address"},
80
+ {"0123-4567-89AF", nil, "invalid MAC address"},
81
+ }
82
+
83
+ func TestParseMAC(t *testing.T) {
84
+ match := func(err error, s string) bool {
85
+ if s == "" {
86
+ return err == nil
87
+ }
88
+ return err != nil && strings.Contains(err.Error(), s)
89
+ }
90
+
91
+ for i, tt := range parseMACTests {
92
+ out, err := ParseMAC(tt.in)
93
+ if !reflect.DeepEqual(out, tt.out) || !match(err, tt.err) {
94
+ t.Errorf("ParseMAC(%q) = %v, %v, want %v, %v", tt.in, out, err, tt.out, tt.err)
95
+ }
96
+ if tt.err == "" {
97
+ // Verify that serialization works too, and that it round-trips.
98
+ s := out.String()
99
+ out2, err := ParseMAC(s)
100
+ if err != nil {
101
+ t.Errorf("%d. ParseMAC(%q) = %v", i, s, err)
102
+ continue
103
+ }
104
+ if !reflect.DeepEqual(out2, out) {
105
+ t.Errorf("%d. ParseMAC(%q) = %v, want %v", i, s, out2, out)
106
+ }
107
+ }
108
+ }
109
+ }
platform/dbops/binaries/go/go/src/net/main_cloexec_test.go ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2015 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 dragonfly || freebsd || linux || netbsd || openbsd || solaris
6
+
7
+ package net
8
+
9
+ import "internal/poll"
10
+
11
+ func init() {
12
+ extraTestHookInstallers = append(extraTestHookInstallers, installAccept4TestHook)
13
+ extraTestHookUninstallers = append(extraTestHookUninstallers, uninstallAccept4TestHook)
14
+ }
15
+
16
+ var (
17
+ // Placeholders for saving original socket system calls.
18
+ origAccept4 = poll.Accept4Func
19
+ )
20
+
21
+ func installAccept4TestHook() {
22
+ poll.Accept4Func = sw.Accept4
23
+ }
24
+
25
+ func uninstallAccept4TestHook() {
26
+ poll.Accept4Func = origAccept4
27
+ }
platform/dbops/binaries/go/go/src/net/main_conf_test.go ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2015 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 !plan9
6
+
7
+ package net
8
+
9
+ import "testing"
10
+
11
+ // forceGoDNS forces the resolver configuration to use the pure Go resolver
12
+ // and returns a fixup function to restore the old settings.
13
+ func forceGoDNS() func() {
14
+ c := systemConf()
15
+ oldGo := c.netGo
16
+ oldCgo := c.netCgo
17
+ fixup := func() {
18
+ c.netGo = oldGo
19
+ c.netCgo = oldCgo
20
+ }
21
+ c.netGo = true
22
+ c.netCgo = false
23
+ return fixup
24
+ }
25
+
26
+ // forceCgoDNS forces the resolver configuration to use the cgo resolver
27
+ // and returns a fixup function to restore the old settings.
28
+ // (On non-Unix systems forceCgoDNS returns nil.)
29
+ func forceCgoDNS() func() {
30
+ c := systemConf()
31
+ oldGo := c.netGo
32
+ oldCgo := c.netCgo
33
+ fixup := func() {
34
+ c.netGo = oldGo
35
+ c.netCgo = oldCgo
36
+ }
37
+ c.netGo = false
38
+ c.netCgo = true
39
+ return fixup
40
+ }
41
+
42
+ func TestForceCgoDNS(t *testing.T) {
43
+ if !cgoAvailable {
44
+ t.Skip("cgo resolver not available")
45
+ }
46
+ defer forceCgoDNS()()
47
+ order, _ := systemConf().hostLookupOrder(nil, "go.dev")
48
+ if order != hostLookupCgo {
49
+ t.Fatalf("hostLookupOrder returned: %v, want cgo", order)
50
+ }
51
+ }
52
+
53
+ func TestForceGoDNS(t *testing.T) {
54
+ defer forceGoDNS()()
55
+ order, _ := systemConf().hostLookupOrder(nil, "go.dev")
56
+ if order == hostLookupCgo {
57
+ t.Fatalf("hostLookupOrder returned: %v, want go resolver order", order)
58
+ }
59
+ }
platform/dbops/binaries/go/go/src/net/main_noconf_test.go ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2015 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 plan9
6
+
7
+ package net
8
+
9
+ import "runtime"
10
+
11
+ // See main_conf_test.go for what these (don't) do.
12
+ func forceGoDNS() func() {
13
+ switch runtime.GOOS {
14
+ case "plan9":
15
+ return func() {}
16
+ default:
17
+ return nil
18
+ }
19
+ }
20
+
21
+ // See main_conf_test.go for what these (don't) do.
22
+ func forceCgoDNS() func() { return nil }
platform/dbops/binaries/go/go/src/net/main_plan9_test.go ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2015 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 installTestHooks() {}
8
+
9
+ func uninstallTestHooks() {}
10
+
11
+ // forceCloseSockets must be called only from TestMain.
12
+ func forceCloseSockets() {}
13
+
14
+ func enableSocketConnect() {}
15
+
16
+ func disableSocketConnect(network string) {}
platform/dbops/binaries/go/go/src/net/main_posix_test.go ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2015 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 !plan9
6
+
7
+ package net
8
+
9
+ import (
10
+ "net/internal/socktest"
11
+ "strings"
12
+ "syscall"
13
+ )
14
+
15
+ func enableSocketConnect() {
16
+ sw.Set(socktest.FilterConnect, nil)
17
+ }
18
+
19
+ func disableSocketConnect(network string) {
20
+ net, _, _ := strings.Cut(network, ":")
21
+ sw.Set(socktest.FilterConnect, func(so *socktest.Status) (socktest.AfterFilter, error) {
22
+ switch net {
23
+ case "tcp4":
24
+ if so.Cookie.Family() == syscall.AF_INET && so.Cookie.Type() == syscall.SOCK_STREAM {
25
+ return nil, syscall.EHOSTUNREACH
26
+ }
27
+ case "udp4":
28
+ if so.Cookie.Family() == syscall.AF_INET && so.Cookie.Type() == syscall.SOCK_DGRAM {
29
+ return nil, syscall.EHOSTUNREACH
30
+ }
31
+ case "ip4":
32
+ if so.Cookie.Family() == syscall.AF_INET && so.Cookie.Type() == syscall.SOCK_RAW {
33
+ return nil, syscall.EHOSTUNREACH
34
+ }
35
+ case "tcp6":
36
+ if so.Cookie.Family() == syscall.AF_INET6 && so.Cookie.Type() == syscall.SOCK_STREAM {
37
+ return nil, syscall.EHOSTUNREACH
38
+ }
39
+ case "udp6":
40
+ if so.Cookie.Family() == syscall.AF_INET6 && so.Cookie.Type() == syscall.SOCK_DGRAM {
41
+ return nil, syscall.EHOSTUNREACH
42
+ }
43
+ case "ip6":
44
+ if so.Cookie.Family() == syscall.AF_INET6 && so.Cookie.Type() == syscall.SOCK_RAW {
45
+ return nil, syscall.EHOSTUNREACH
46
+ }
47
+ }
48
+ return nil, nil
49
+ })
50
+ }
platform/dbops/binaries/go/go/src/net/main_test.go ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2015 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
+ "flag"
9
+ "fmt"
10
+ "net/internal/socktest"
11
+ "os"
12
+ "runtime"
13
+ "sort"
14
+ "strings"
15
+ "sync"
16
+ "testing"
17
+ "time"
18
+ )
19
+
20
+ var (
21
+ sw socktest.Switch
22
+
23
+ // uninstallTestHooks runs just before a run of benchmarks.
24
+ testHookUninstaller sync.Once
25
+ )
26
+
27
+ var (
28
+ testTCPBig = flag.Bool("tcpbig", false, "whether to test massive size of data per read or write call on TCP connection")
29
+
30
+ testDNSFlood = flag.Bool("dnsflood", false, "whether to test DNS query flooding")
31
+
32
+ // If external IPv4 connectivity exists, we can try dialing
33
+ // non-node/interface local scope IPv4 addresses.
34
+ // On Windows, Lookup APIs may not return IPv4-related
35
+ // resource records when a node has no external IPv4
36
+ // connectivity.
37
+ testIPv4 = flag.Bool("ipv4", true, "assume external IPv4 connectivity exists")
38
+
39
+ // If external IPv6 connectivity exists, we can try dialing
40
+ // non-node/interface local scope IPv6 addresses.
41
+ // On Windows, Lookup APIs may not return IPv6-related
42
+ // resource records when a node has no external IPv6
43
+ // connectivity.
44
+ testIPv6 = flag.Bool("ipv6", false, "assume external IPv6 connectivity exists")
45
+ )
46
+
47
+ func TestMain(m *testing.M) {
48
+ setupTestData()
49
+ installTestHooks()
50
+
51
+ st := m.Run()
52
+
53
+ testHookUninstaller.Do(uninstallTestHooks)
54
+ if testing.Verbose() {
55
+ printRunningGoroutines()
56
+ printInflightSockets()
57
+ printSocketStats()
58
+ }
59
+ forceCloseSockets()
60
+ os.Exit(st)
61
+ }
62
+
63
+ // mustSetDeadline calls the bound method m to set a deadline on a Conn.
64
+ // If the call fails, mustSetDeadline skips t if the current GOOS is believed
65
+ // not to support deadlines, or fails the test otherwise.
66
+ func mustSetDeadline(t testing.TB, m func(time.Time) error, d time.Duration) {
67
+ err := m(time.Now().Add(d))
68
+ if err != nil {
69
+ t.Helper()
70
+ if runtime.GOOS == "plan9" {
71
+ t.Skipf("skipping: %s does not support deadlines", runtime.GOOS)
72
+ }
73
+ t.Fatal(err)
74
+ }
75
+ }
76
+
77
+ type ipv6LinkLocalUnicastTest struct {
78
+ network, address string
79
+ nameLookup bool
80
+ }
81
+
82
+ var (
83
+ ipv6LinkLocalUnicastTCPTests []ipv6LinkLocalUnicastTest
84
+ ipv6LinkLocalUnicastUDPTests []ipv6LinkLocalUnicastTest
85
+ )
86
+
87
+ func setupTestData() {
88
+ if supportsIPv4() {
89
+ resolveTCPAddrTests = append(resolveTCPAddrTests, []resolveTCPAddrTest{
90
+ {"tcp", "localhost:1", &TCPAddr{IP: IPv4(127, 0, 0, 1), Port: 1}, nil},
91
+ {"tcp4", "localhost:2", &TCPAddr{IP: IPv4(127, 0, 0, 1), Port: 2}, nil},
92
+ }...)
93
+ resolveUDPAddrTests = append(resolveUDPAddrTests, []resolveUDPAddrTest{
94
+ {"udp", "localhost:1", &UDPAddr{IP: IPv4(127, 0, 0, 1), Port: 1}, nil},
95
+ {"udp4", "localhost:2", &UDPAddr{IP: IPv4(127, 0, 0, 1), Port: 2}, nil},
96
+ }...)
97
+ resolveIPAddrTests = append(resolveIPAddrTests, []resolveIPAddrTest{
98
+ {"ip", "localhost", &IPAddr{IP: IPv4(127, 0, 0, 1)}, nil},
99
+ {"ip4", "localhost", &IPAddr{IP: IPv4(127, 0, 0, 1)}, nil},
100
+ }...)
101
+ }
102
+
103
+ if supportsIPv6() {
104
+ resolveTCPAddrTests = append(resolveTCPAddrTests, resolveTCPAddrTest{"tcp6", "localhost:3", &TCPAddr{IP: IPv6loopback, Port: 3}, nil})
105
+ resolveUDPAddrTests = append(resolveUDPAddrTests, resolveUDPAddrTest{"udp6", "localhost:3", &UDPAddr{IP: IPv6loopback, Port: 3}, nil})
106
+ resolveIPAddrTests = append(resolveIPAddrTests, resolveIPAddrTest{"ip6", "localhost", &IPAddr{IP: IPv6loopback}, nil})
107
+
108
+ // Issue 20911: don't return IPv4 addresses for
109
+ // Resolve*Addr calls of the IPv6 unspecified address.
110
+ resolveTCPAddrTests = append(resolveTCPAddrTests, resolveTCPAddrTest{"tcp", "[::]:4", &TCPAddr{IP: IPv6unspecified, Port: 4}, nil})
111
+ resolveUDPAddrTests = append(resolveUDPAddrTests, resolveUDPAddrTest{"udp", "[::]:4", &UDPAddr{IP: IPv6unspecified, Port: 4}, nil})
112
+ resolveIPAddrTests = append(resolveIPAddrTests, resolveIPAddrTest{"ip", "::", &IPAddr{IP: IPv6unspecified}, nil})
113
+ }
114
+
115
+ ifi := loopbackInterface()
116
+ if ifi != nil {
117
+ index := fmt.Sprintf("%v", ifi.Index)
118
+ resolveTCPAddrTests = append(resolveTCPAddrTests, []resolveTCPAddrTest{
119
+ {"tcp6", "[fe80::1%" + ifi.Name + "]:1", &TCPAddr{IP: ParseIP("fe80::1"), Port: 1, Zone: zoneCache.name(ifi.Index)}, nil},
120
+ {"tcp6", "[fe80::1%" + index + "]:2", &TCPAddr{IP: ParseIP("fe80::1"), Port: 2, Zone: index}, nil},
121
+ }...)
122
+ resolveUDPAddrTests = append(resolveUDPAddrTests, []resolveUDPAddrTest{
123
+ {"udp6", "[fe80::1%" + ifi.Name + "]:1", &UDPAddr{IP: ParseIP("fe80::1"), Port: 1, Zone: zoneCache.name(ifi.Index)}, nil},
124
+ {"udp6", "[fe80::1%" + index + "]:2", &UDPAddr{IP: ParseIP("fe80::1"), Port: 2, Zone: index}, nil},
125
+ }...)
126
+ resolveIPAddrTests = append(resolveIPAddrTests, []resolveIPAddrTest{
127
+ {"ip6", "fe80::1%" + ifi.Name, &IPAddr{IP: ParseIP("fe80::1"), Zone: zoneCache.name(ifi.Index)}, nil},
128
+ {"ip6", "fe80::1%" + index, &IPAddr{IP: ParseIP("fe80::1"), Zone: index}, nil},
129
+ }...)
130
+ }
131
+
132
+ addr := ipv6LinkLocalUnicastAddr(ifi)
133
+ if addr != "" {
134
+ if runtime.GOOS != "dragonfly" {
135
+ ipv6LinkLocalUnicastTCPTests = append(ipv6LinkLocalUnicastTCPTests, []ipv6LinkLocalUnicastTest{
136
+ {"tcp", "[" + addr + "%" + ifi.Name + "]:0", false},
137
+ }...)
138
+ ipv6LinkLocalUnicastUDPTests = append(ipv6LinkLocalUnicastUDPTests, []ipv6LinkLocalUnicastTest{
139
+ {"udp", "[" + addr + "%" + ifi.Name + "]:0", false},
140
+ }...)
141
+ }
142
+ ipv6LinkLocalUnicastTCPTests = append(ipv6LinkLocalUnicastTCPTests, []ipv6LinkLocalUnicastTest{
143
+ {"tcp6", "[" + addr + "%" + ifi.Name + "]:0", false},
144
+ }...)
145
+ ipv6LinkLocalUnicastUDPTests = append(ipv6LinkLocalUnicastUDPTests, []ipv6LinkLocalUnicastTest{
146
+ {"udp6", "[" + addr + "%" + ifi.Name + "]:0", false},
147
+ }...)
148
+ switch runtime.GOOS {
149
+ case "darwin", "ios", "dragonfly", "freebsd", "openbsd", "netbsd":
150
+ ipv6LinkLocalUnicastTCPTests = append(ipv6LinkLocalUnicastTCPTests, []ipv6LinkLocalUnicastTest{
151
+ {"tcp", "[localhost%" + ifi.Name + "]:0", true},
152
+ {"tcp6", "[localhost%" + ifi.Name + "]:0", true},
153
+ }...)
154
+ ipv6LinkLocalUnicastUDPTests = append(ipv6LinkLocalUnicastUDPTests, []ipv6LinkLocalUnicastTest{
155
+ {"udp", "[localhost%" + ifi.Name + "]:0", true},
156
+ {"udp6", "[localhost%" + ifi.Name + "]:0", true},
157
+ }...)
158
+ case "linux":
159
+ ipv6LinkLocalUnicastTCPTests = append(ipv6LinkLocalUnicastTCPTests, []ipv6LinkLocalUnicastTest{
160
+ {"tcp", "[ip6-localhost%" + ifi.Name + "]:0", true},
161
+ {"tcp6", "[ip6-localhost%" + ifi.Name + "]:0", true},
162
+ }...)
163
+ ipv6LinkLocalUnicastUDPTests = append(ipv6LinkLocalUnicastUDPTests, []ipv6LinkLocalUnicastTest{
164
+ {"udp", "[ip6-localhost%" + ifi.Name + "]:0", true},
165
+ {"udp6", "[ip6-localhost%" + ifi.Name + "]:0", true},
166
+ }...)
167
+ }
168
+ }
169
+ }
170
+
171
+ func printRunningGoroutines() {
172
+ gss := runningGoroutines()
173
+ if len(gss) == 0 {
174
+ return
175
+ }
176
+ fmt.Fprintf(os.Stderr, "Running goroutines:\n")
177
+ for _, gs := range gss {
178
+ fmt.Fprintf(os.Stderr, "%v\n", gs)
179
+ }
180
+ fmt.Fprintf(os.Stderr, "\n")
181
+ }
182
+
183
+ // runningGoroutines returns a list of remaining goroutines.
184
+ func runningGoroutines() []string {
185
+ var gss []string
186
+ b := make([]byte, 2<<20)
187
+ b = b[:runtime.Stack(b, true)]
188
+ for _, s := range strings.Split(string(b), "\n\n") {
189
+ _, stack, _ := strings.Cut(s, "\n")
190
+ stack = strings.TrimSpace(stack)
191
+ if !strings.Contains(stack, "created by net") {
192
+ continue
193
+ }
194
+ gss = append(gss, stack)
195
+ }
196
+ sort.Strings(gss)
197
+ return gss
198
+ }
199
+
200
+ func printInflightSockets() {
201
+ sos := sw.Sockets()
202
+ if len(sos) == 0 {
203
+ return
204
+ }
205
+ fmt.Fprintf(os.Stderr, "Inflight sockets:\n")
206
+ for s, so := range sos {
207
+ fmt.Fprintf(os.Stderr, "%v: %v\n", s, so)
208
+ }
209
+ fmt.Fprintf(os.Stderr, "\n")
210
+ }
211
+
212
+ func printSocketStats() {
213
+ sts := sw.Stats()
214
+ if len(sts) == 0 {
215
+ return
216
+ }
217
+ fmt.Fprintf(os.Stderr, "Socket statistical information:\n")
218
+ for _, st := range sts {
219
+ fmt.Fprintf(os.Stderr, "%v\n", st)
220
+ }
221
+ fmt.Fprintf(os.Stderr, "\n")
222
+ }
platform/dbops/binaries/go/go/src/net/main_unix_test.go ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2015 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 "internal/poll"
10
+
11
+ var (
12
+ // Placeholders for saving original socket system calls.
13
+ origSocket = socketFunc
14
+ origClose = poll.CloseFunc
15
+ origConnect = connectFunc
16
+ origListen = listenFunc
17
+ origAccept = poll.AcceptFunc
18
+ origGetsockoptInt = getsockoptIntFunc
19
+
20
+ extraTestHookInstallers []func()
21
+ extraTestHookUninstallers []func()
22
+ )
23
+
24
+ func installTestHooks() {
25
+ socketFunc = sw.Socket
26
+ poll.CloseFunc = sw.Close
27
+ connectFunc = sw.Connect
28
+ listenFunc = sw.Listen
29
+ poll.AcceptFunc = sw.Accept
30
+ getsockoptIntFunc = sw.GetsockoptInt
31
+
32
+ for _, fn := range extraTestHookInstallers {
33
+ fn()
34
+ }
35
+ }
36
+
37
+ func uninstallTestHooks() {
38
+ socketFunc = origSocket
39
+ poll.CloseFunc = origClose
40
+ connectFunc = origConnect
41
+ listenFunc = origListen
42
+ poll.AcceptFunc = origAccept
43
+ getsockoptIntFunc = origGetsockoptInt
44
+
45
+ for _, fn := range extraTestHookUninstallers {
46
+ fn()
47
+ }
48
+ }
49
+
50
+ // forceCloseSockets must be called only from TestMain.
51
+ func forceCloseSockets() {
52
+ for s := range sw.Sockets() {
53
+ poll.CloseFunc(s)
54
+ }
55
+ }
platform/dbops/binaries/go/go/src/net/main_wasm_test.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 wasip1 || js
6
+
7
+ package net
8
+
9
+ func installTestHooks() {}
10
+
11
+ func uninstallTestHooks() {}
12
+
13
+ func forceCloseSockets() {}
platform/dbops/binaries/go/go/src/net/main_windows_test.go ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2015 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/poll"
8
+
9
+ var (
10
+ // Placeholders for saving original socket system calls.
11
+ origWSASocket = wsaSocketFunc
12
+ origClosesocket = poll.CloseFunc
13
+ origConnect = connectFunc
14
+ origConnectEx = poll.ConnectExFunc
15
+ origListen = listenFunc
16
+ origAccept = poll.AcceptFunc
17
+ )
18
+
19
+ func installTestHooks() {
20
+ wsaSocketFunc = sw.WSASocket
21
+ poll.CloseFunc = sw.Closesocket
22
+ connectFunc = sw.Connect
23
+ poll.ConnectExFunc = sw.ConnectEx
24
+ listenFunc = sw.Listen
25
+ poll.AcceptFunc = sw.AcceptEx
26
+ }
27
+
28
+ func uninstallTestHooks() {
29
+ wsaSocketFunc = origWSASocket
30
+ poll.CloseFunc = origClosesocket
31
+ connectFunc = origConnect
32
+ poll.ConnectExFunc = origConnectEx
33
+ listenFunc = origListen
34
+ poll.AcceptFunc = origAccept
35
+ }
36
+
37
+ // forceCloseSockets must be called only from TestMain.
38
+ func forceCloseSockets() {
39
+ for s := range sw.Sockets() {
40
+ poll.CloseFunc(s)
41
+ }
42
+ }
platform/dbops/binaries/go/go/src/net/mockserver_test.go ADDED
@@ -0,0 +1,508 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import (
8
+ "context"
9
+ "errors"
10
+ "fmt"
11
+ "os"
12
+ "path/filepath"
13
+ "sync"
14
+ "testing"
15
+ "time"
16
+ )
17
+
18
+ // testUnixAddr uses os.MkdirTemp to get a name that is unique.
19
+ func testUnixAddr(t testing.TB) string {
20
+ // Pass an empty pattern to get a directory name that is as short as possible.
21
+ // If we end up with a name longer than the sun_path field in the sockaddr_un
22
+ // struct, we won't be able to make the syscall to open the socket.
23
+ d, err := os.MkdirTemp("", "")
24
+ if err != nil {
25
+ t.Fatal(err)
26
+ }
27
+ t.Cleanup(func() {
28
+ if err := os.RemoveAll(d); err != nil {
29
+ t.Error(err)
30
+ }
31
+ })
32
+ return filepath.Join(d, "sock")
33
+ }
34
+
35
+ func newLocalListener(t testing.TB, network string, lcOpt ...*ListenConfig) Listener {
36
+ var lc *ListenConfig
37
+ switch len(lcOpt) {
38
+ case 0:
39
+ lc = new(ListenConfig)
40
+ case 1:
41
+ lc = lcOpt[0]
42
+ default:
43
+ t.Helper()
44
+ t.Fatal("too many ListenConfigs passed to newLocalListener: want 0 or 1")
45
+ }
46
+
47
+ listen := func(net, addr string) Listener {
48
+ ln, err := lc.Listen(context.Background(), net, addr)
49
+ if err != nil {
50
+ t.Helper()
51
+ t.Fatal(err)
52
+ }
53
+ return ln
54
+ }
55
+
56
+ switch network {
57
+ case "tcp":
58
+ if supportsIPv4() {
59
+ if !supportsIPv6() {
60
+ return listen("tcp4", "127.0.0.1:0")
61
+ }
62
+ if ln, err := Listen("tcp4", "127.0.0.1:0"); err == nil {
63
+ return ln
64
+ }
65
+ }
66
+ if supportsIPv6() {
67
+ return listen("tcp6", "[::1]:0")
68
+ }
69
+ case "tcp4":
70
+ if supportsIPv4() {
71
+ return listen("tcp4", "127.0.0.1:0")
72
+ }
73
+ case "tcp6":
74
+ if supportsIPv6() {
75
+ return listen("tcp6", "[::1]:0")
76
+ }
77
+ case "unix", "unixpacket":
78
+ return listen(network, testUnixAddr(t))
79
+ }
80
+
81
+ t.Helper()
82
+ t.Fatalf("%s is not supported", network)
83
+ return nil
84
+ }
85
+
86
+ func newDualStackListener() (lns []*TCPListener, err error) {
87
+ var args = []struct {
88
+ network string
89
+ TCPAddr
90
+ }{
91
+ {"tcp4", TCPAddr{IP: IPv4(127, 0, 0, 1)}},
92
+ {"tcp6", TCPAddr{IP: IPv6loopback}},
93
+ }
94
+ for i := 0; i < 64; i++ {
95
+ var port int
96
+ var lns []*TCPListener
97
+ for _, arg := range args {
98
+ arg.TCPAddr.Port = port
99
+ ln, err := ListenTCP(arg.network, &arg.TCPAddr)
100
+ if err != nil {
101
+ continue
102
+ }
103
+ port = ln.Addr().(*TCPAddr).Port
104
+ lns = append(lns, ln)
105
+ }
106
+ if len(lns) != len(args) {
107
+ for _, ln := range lns {
108
+ ln.Close()
109
+ }
110
+ continue
111
+ }
112
+ return lns, nil
113
+ }
114
+ return nil, errors.New("no dualstack port available")
115
+ }
116
+
117
+ type localServer struct {
118
+ lnmu sync.RWMutex
119
+ Listener
120
+ done chan bool // signal that indicates server stopped
121
+ cl []Conn // accepted connection list
122
+ }
123
+
124
+ func (ls *localServer) buildup(handler func(*localServer, Listener)) error {
125
+ go func() {
126
+ handler(ls, ls.Listener)
127
+ close(ls.done)
128
+ }()
129
+ return nil
130
+ }
131
+
132
+ func (ls *localServer) teardown() error {
133
+ ls.lnmu.Lock()
134
+ defer ls.lnmu.Unlock()
135
+ if ls.Listener != nil {
136
+ network := ls.Listener.Addr().Network()
137
+ address := ls.Listener.Addr().String()
138
+ ls.Listener.Close()
139
+ for _, c := range ls.cl {
140
+ if err := c.Close(); err != nil {
141
+ return err
142
+ }
143
+ }
144
+ <-ls.done
145
+ ls.Listener = nil
146
+ switch network {
147
+ case "unix", "unixpacket":
148
+ os.Remove(address)
149
+ }
150
+ }
151
+ return nil
152
+ }
153
+
154
+ func newLocalServer(t testing.TB, network string) *localServer {
155
+ t.Helper()
156
+ ln := newLocalListener(t, network)
157
+ return &localServer{Listener: ln, done: make(chan bool)}
158
+ }
159
+
160
+ type streamListener struct {
161
+ network, address string
162
+ Listener
163
+ done chan bool // signal that indicates server stopped
164
+ }
165
+
166
+ func (sl *streamListener) newLocalServer() *localServer {
167
+ return &localServer{Listener: sl.Listener, done: make(chan bool)}
168
+ }
169
+
170
+ type dualStackServer struct {
171
+ lnmu sync.RWMutex
172
+ lns []streamListener
173
+ port string
174
+
175
+ cmu sync.RWMutex
176
+ cs []Conn // established connections at the passive open side
177
+ }
178
+
179
+ func (dss *dualStackServer) buildup(handler func(*dualStackServer, Listener)) error {
180
+ for i := range dss.lns {
181
+ go func(i int) {
182
+ handler(dss, dss.lns[i].Listener)
183
+ close(dss.lns[i].done)
184
+ }(i)
185
+ }
186
+ return nil
187
+ }
188
+
189
+ func (dss *dualStackServer) teardownNetwork(network string) error {
190
+ dss.lnmu.Lock()
191
+ for i := range dss.lns {
192
+ if network == dss.lns[i].network && dss.lns[i].Listener != nil {
193
+ dss.lns[i].Listener.Close()
194
+ <-dss.lns[i].done
195
+ dss.lns[i].Listener = nil
196
+ }
197
+ }
198
+ dss.lnmu.Unlock()
199
+ return nil
200
+ }
201
+
202
+ func (dss *dualStackServer) teardown() error {
203
+ dss.lnmu.Lock()
204
+ for i := range dss.lns {
205
+ if dss.lns[i].Listener != nil {
206
+ dss.lns[i].Listener.Close()
207
+ <-dss.lns[i].done
208
+ }
209
+ }
210
+ dss.lns = dss.lns[:0]
211
+ dss.lnmu.Unlock()
212
+ dss.cmu.Lock()
213
+ for _, c := range dss.cs {
214
+ c.Close()
215
+ }
216
+ dss.cs = dss.cs[:0]
217
+ dss.cmu.Unlock()
218
+ return nil
219
+ }
220
+
221
+ func newDualStackServer() (*dualStackServer, error) {
222
+ lns, err := newDualStackListener()
223
+ if err != nil {
224
+ return nil, err
225
+ }
226
+ _, port, err := SplitHostPort(lns[0].Addr().String())
227
+ if err != nil {
228
+ lns[0].Close()
229
+ lns[1].Close()
230
+ return nil, err
231
+ }
232
+ return &dualStackServer{
233
+ lns: []streamListener{
234
+ {network: "tcp4", address: lns[0].Addr().String(), Listener: lns[0], done: make(chan bool)},
235
+ {network: "tcp6", address: lns[1].Addr().String(), Listener: lns[1], done: make(chan bool)},
236
+ },
237
+ port: port,
238
+ }, nil
239
+ }
240
+
241
+ func (ls *localServer) transponder(ln Listener, ch chan<- error) {
242
+ defer close(ch)
243
+
244
+ switch ln := ln.(type) {
245
+ case *TCPListener:
246
+ ln.SetDeadline(time.Now().Add(someTimeout))
247
+ case *UnixListener:
248
+ ln.SetDeadline(time.Now().Add(someTimeout))
249
+ }
250
+ c, err := ln.Accept()
251
+ if err != nil {
252
+ if perr := parseAcceptError(err); perr != nil {
253
+ ch <- perr
254
+ }
255
+ ch <- err
256
+ return
257
+ }
258
+ ls.cl = append(ls.cl, c)
259
+
260
+ network := ln.Addr().Network()
261
+ if c.LocalAddr().Network() != network || c.RemoteAddr().Network() != network {
262
+ ch <- fmt.Errorf("got %v->%v; expected %v->%v", c.LocalAddr().Network(), c.RemoteAddr().Network(), network, network)
263
+ return
264
+ }
265
+ c.SetDeadline(time.Now().Add(someTimeout))
266
+ c.SetReadDeadline(time.Now().Add(someTimeout))
267
+ c.SetWriteDeadline(time.Now().Add(someTimeout))
268
+
269
+ b := make([]byte, 256)
270
+ n, err := c.Read(b)
271
+ if err != nil {
272
+ if perr := parseReadError(err); perr != nil {
273
+ ch <- perr
274
+ }
275
+ ch <- err
276
+ return
277
+ }
278
+ if _, err := c.Write(b[:n]); err != nil {
279
+ if perr := parseWriteError(err); perr != nil {
280
+ ch <- perr
281
+ }
282
+ ch <- err
283
+ return
284
+ }
285
+ }
286
+
287
+ func transceiver(c Conn, wb []byte, ch chan<- error) {
288
+ defer close(ch)
289
+
290
+ c.SetDeadline(time.Now().Add(someTimeout))
291
+ c.SetReadDeadline(time.Now().Add(someTimeout))
292
+ c.SetWriteDeadline(time.Now().Add(someTimeout))
293
+
294
+ n, err := c.Write(wb)
295
+ if err != nil {
296
+ if perr := parseWriteError(err); perr != nil {
297
+ ch <- perr
298
+ }
299
+ ch <- err
300
+ return
301
+ }
302
+ if n != len(wb) {
303
+ ch <- fmt.Errorf("wrote %d; want %d", n, len(wb))
304
+ }
305
+ rb := make([]byte, len(wb))
306
+ n, err = c.Read(rb)
307
+ if err != nil {
308
+ if perr := parseReadError(err); perr != nil {
309
+ ch <- perr
310
+ }
311
+ ch <- err
312
+ return
313
+ }
314
+ if n != len(wb) {
315
+ ch <- fmt.Errorf("read %d; want %d", n, len(wb))
316
+ }
317
+ }
318
+
319
+ func newLocalPacketListener(t testing.TB, network string, lcOpt ...*ListenConfig) PacketConn {
320
+ var lc *ListenConfig
321
+ switch len(lcOpt) {
322
+ case 0:
323
+ lc = new(ListenConfig)
324
+ case 1:
325
+ lc = lcOpt[0]
326
+ default:
327
+ t.Helper()
328
+ t.Fatal("too many ListenConfigs passed to newLocalListener: want 0 or 1")
329
+ }
330
+
331
+ listenPacket := func(net, addr string) PacketConn {
332
+ c, err := lc.ListenPacket(context.Background(), net, addr)
333
+ if err != nil {
334
+ t.Helper()
335
+ t.Fatal(err)
336
+ }
337
+ return c
338
+ }
339
+
340
+ t.Helper()
341
+ switch network {
342
+ case "udp":
343
+ if supportsIPv4() {
344
+ return listenPacket("udp4", "127.0.0.1:0")
345
+ }
346
+ if supportsIPv6() {
347
+ return listenPacket("udp6", "[::1]:0")
348
+ }
349
+ case "udp4":
350
+ if supportsIPv4() {
351
+ return listenPacket("udp4", "127.0.0.1:0")
352
+ }
353
+ case "udp6":
354
+ if supportsIPv6() {
355
+ return listenPacket("udp6", "[::1]:0")
356
+ }
357
+ case "unixgram":
358
+ return listenPacket(network, testUnixAddr(t))
359
+ }
360
+
361
+ t.Fatalf("%s is not supported", network)
362
+ return nil
363
+ }
364
+
365
+ func newDualStackPacketListener() (cs []*UDPConn, err error) {
366
+ var args = []struct {
367
+ network string
368
+ UDPAddr
369
+ }{
370
+ {"udp4", UDPAddr{IP: IPv4(127, 0, 0, 1)}},
371
+ {"udp6", UDPAddr{IP: IPv6loopback}},
372
+ }
373
+ for i := 0; i < 64; i++ {
374
+ var port int
375
+ var cs []*UDPConn
376
+ for _, arg := range args {
377
+ arg.UDPAddr.Port = port
378
+ c, err := ListenUDP(arg.network, &arg.UDPAddr)
379
+ if err != nil {
380
+ continue
381
+ }
382
+ port = c.LocalAddr().(*UDPAddr).Port
383
+ cs = append(cs, c)
384
+ }
385
+ if len(cs) != len(args) {
386
+ for _, c := range cs {
387
+ c.Close()
388
+ }
389
+ continue
390
+ }
391
+ return cs, nil
392
+ }
393
+ return nil, errors.New("no dualstack port available")
394
+ }
395
+
396
+ type localPacketServer struct {
397
+ pcmu sync.RWMutex
398
+ PacketConn
399
+ done chan bool // signal that indicates server stopped
400
+ }
401
+
402
+ func (ls *localPacketServer) buildup(handler func(*localPacketServer, PacketConn)) error {
403
+ go func() {
404
+ handler(ls, ls.PacketConn)
405
+ close(ls.done)
406
+ }()
407
+ return nil
408
+ }
409
+
410
+ func (ls *localPacketServer) teardown() error {
411
+ ls.pcmu.Lock()
412
+ if ls.PacketConn != nil {
413
+ network := ls.PacketConn.LocalAddr().Network()
414
+ address := ls.PacketConn.LocalAddr().String()
415
+ ls.PacketConn.Close()
416
+ <-ls.done
417
+ ls.PacketConn = nil
418
+ switch network {
419
+ case "unixgram":
420
+ os.Remove(address)
421
+ }
422
+ }
423
+ ls.pcmu.Unlock()
424
+ return nil
425
+ }
426
+
427
+ func newLocalPacketServer(t testing.TB, network string) *localPacketServer {
428
+ t.Helper()
429
+ c := newLocalPacketListener(t, network)
430
+ return &localPacketServer{PacketConn: c, done: make(chan bool)}
431
+ }
432
+
433
+ type packetListener struct {
434
+ PacketConn
435
+ }
436
+
437
+ func (pl *packetListener) newLocalServer() *localPacketServer {
438
+ return &localPacketServer{PacketConn: pl.PacketConn, done: make(chan bool)}
439
+ }
440
+
441
+ func packetTransponder(c PacketConn, ch chan<- error) {
442
+ defer close(ch)
443
+
444
+ c.SetDeadline(time.Now().Add(someTimeout))
445
+ c.SetReadDeadline(time.Now().Add(someTimeout))
446
+ c.SetWriteDeadline(time.Now().Add(someTimeout))
447
+
448
+ b := make([]byte, 256)
449
+ n, peer, err := c.ReadFrom(b)
450
+ if err != nil {
451
+ if perr := parseReadError(err); perr != nil {
452
+ ch <- perr
453
+ }
454
+ ch <- err
455
+ return
456
+ }
457
+ if peer == nil { // for connected-mode sockets
458
+ switch c.LocalAddr().Network() {
459
+ case "udp":
460
+ peer, err = ResolveUDPAddr("udp", string(b[:n]))
461
+ case "unixgram":
462
+ peer, err = ResolveUnixAddr("unixgram", string(b[:n]))
463
+ }
464
+ if err != nil {
465
+ ch <- err
466
+ return
467
+ }
468
+ }
469
+ if _, err := c.WriteTo(b[:n], peer); err != nil {
470
+ if perr := parseWriteError(err); perr != nil {
471
+ ch <- perr
472
+ }
473
+ ch <- err
474
+ return
475
+ }
476
+ }
477
+
478
+ func packetTransceiver(c PacketConn, wb []byte, dst Addr, ch chan<- error) {
479
+ defer close(ch)
480
+
481
+ c.SetDeadline(time.Now().Add(someTimeout))
482
+ c.SetReadDeadline(time.Now().Add(someTimeout))
483
+ c.SetWriteDeadline(time.Now().Add(someTimeout))
484
+
485
+ n, err := c.WriteTo(wb, dst)
486
+ if err != nil {
487
+ if perr := parseWriteError(err); perr != nil {
488
+ ch <- perr
489
+ }
490
+ ch <- err
491
+ return
492
+ }
493
+ if n != len(wb) {
494
+ ch <- fmt.Errorf("wrote %d; want %d", n, len(wb))
495
+ }
496
+ rb := make([]byte, len(wb))
497
+ n, _, err = c.ReadFrom(rb)
498
+ if err != nil {
499
+ if perr := parseReadError(err); perr != nil {
500
+ ch <- perr
501
+ }
502
+ ch <- err
503
+ return
504
+ }
505
+ if n != len(wb) {
506
+ ch <- fmt.Errorf("read %d; want %d", n, len(wb))
507
+ }
508
+ }
platform/dbops/binaries/go/go/src/net/mptcpsock_linux.go ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ package net
6
+
7
+ import (
8
+ "context"
9
+ "errors"
10
+ "internal/poll"
11
+ "internal/syscall/unix"
12
+ "sync"
13
+ "syscall"
14
+ )
15
+
16
+ var (
17
+ mptcpOnce sync.Once
18
+ mptcpAvailable bool
19
+ hasSOLMPTCP bool
20
+ )
21
+
22
+ // These constants aren't in the syscall package, which is frozen
23
+ const (
24
+ _IPPROTO_MPTCP = 0x106
25
+ _SOL_MPTCP = 0x11c
26
+ _MPTCP_INFO = 0x1
27
+ )
28
+
29
+ func supportsMultipathTCP() bool {
30
+ mptcpOnce.Do(initMPTCPavailable)
31
+ return mptcpAvailable
32
+ }
33
+
34
+ // Check that MPTCP is supported by attempting to create an MPTCP socket and by
35
+ // looking at the returned error if any.
36
+ func initMPTCPavailable() {
37
+ s, err := sysSocket(syscall.AF_INET, syscall.SOCK_STREAM, _IPPROTO_MPTCP)
38
+ switch {
39
+ case errors.Is(err, syscall.EPROTONOSUPPORT): // Not supported: >= v5.6
40
+ case errors.Is(err, syscall.EINVAL): // Not supported: < v5.6
41
+ case err == nil: // Supported and no error
42
+ poll.CloseFunc(s)
43
+ fallthrough
44
+ default:
45
+ // another error: MPTCP was not available but it might be later
46
+ mptcpAvailable = true
47
+ }
48
+
49
+ major, minor := unix.KernelVersion()
50
+ // SOL_MPTCP only supported from kernel 5.16
51
+ hasSOLMPTCP = major > 5 || (major == 5 && minor >= 16)
52
+ }
53
+
54
+ func (sd *sysDialer) dialMPTCP(ctx context.Context, laddr, raddr *TCPAddr) (*TCPConn, error) {
55
+ if supportsMultipathTCP() {
56
+ if conn, err := sd.doDialTCPProto(ctx, laddr, raddr, _IPPROTO_MPTCP); err == nil {
57
+ return conn, nil
58
+ }
59
+ }
60
+
61
+ // Fallback to dialTCP if Multipath TCP isn't supported on this operating
62
+ // system. But also fallback in case of any error with MPTCP.
63
+ //
64
+ // Possible MPTCP specific error: ENOPROTOOPT (sysctl net.mptcp.enabled=0)
65
+ // But just in case MPTCP is blocked differently (SELinux, etc.), just
66
+ // retry with "plain" TCP.
67
+ return sd.dialTCP(ctx, laddr, raddr)
68
+ }
69
+
70
+ func (sl *sysListener) listenMPTCP(ctx context.Context, laddr *TCPAddr) (*TCPListener, error) {
71
+ if supportsMultipathTCP() {
72
+ if dial, err := sl.listenTCPProto(ctx, laddr, _IPPROTO_MPTCP); err == nil {
73
+ return dial, nil
74
+ }
75
+ }
76
+
77
+ // Fallback to listenTCP if Multipath TCP isn't supported on this operating
78
+ // system. But also fallback in case of any error with MPTCP.
79
+ //
80
+ // Possible MPTCP specific error: ENOPROTOOPT (sysctl net.mptcp.enabled=0)
81
+ // But just in case MPTCP is blocked differently (SELinux, etc.), just
82
+ // retry with "plain" TCP.
83
+ return sl.listenTCP(ctx, laddr)
84
+ }
85
+
86
+ // hasFallenBack reports whether the MPTCP connection has fallen back to "plain"
87
+ // TCP.
88
+ //
89
+ // A connection can fallback to TCP for different reasons, e.g. the other peer
90
+ // doesn't support it, a middle box "accidentally" drops the option, etc.
91
+ //
92
+ // If the MPTCP protocol has not been requested when creating the socket, this
93
+ // method will return true: MPTCP is not being used.
94
+ //
95
+ // Kernel >= 5.16 returns EOPNOTSUPP/ENOPROTOOPT in case of fallback.
96
+ // Older kernels will always return them even if MPTCP is used: not usable.
97
+ func hasFallenBack(fd *netFD) bool {
98
+ _, err := fd.pfd.GetsockoptInt(_SOL_MPTCP, _MPTCP_INFO)
99
+
100
+ // 2 expected errors in case of fallback depending on the address family
101
+ // - AF_INET: EOPNOTSUPP
102
+ // - AF_INET6: ENOPROTOOPT
103
+ return err == syscall.EOPNOTSUPP || err == syscall.ENOPROTOOPT
104
+ }
105
+
106
+ // isUsingMPTCPProto reports whether the socket protocol is MPTCP.
107
+ //
108
+ // Compared to hasFallenBack method, here only the socket protocol being used is
109
+ // checked: it can be MPTCP but it doesn't mean MPTCP is used on the wire, maybe
110
+ // a fallback to TCP has been done.
111
+ func isUsingMPTCPProto(fd *netFD) bool {
112
+ proto, _ := fd.pfd.GetsockoptInt(syscall.SOL_SOCKET, syscall.SO_PROTOCOL)
113
+
114
+ return proto == _IPPROTO_MPTCP
115
+ }
116
+
117
+ // isUsingMultipathTCP reports whether MPTCP is still being used.
118
+ //
119
+ // Please look at the description of hasFallenBack (kernel >=5.16) and
120
+ // isUsingMPTCPProto methods for more details about what is being checked here.
121
+ func isUsingMultipathTCP(fd *netFD) bool {
122
+ if hasSOLMPTCP {
123
+ return !hasFallenBack(fd)
124
+ }
125
+
126
+ return isUsingMPTCPProto(fd)
127
+ }
platform/dbops/binaries/go/go/src/net/mptcpsock_linux_test.go ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ package net
6
+
7
+ import (
8
+ "bytes"
9
+ "context"
10
+ "errors"
11
+ "syscall"
12
+ "testing"
13
+ )
14
+
15
+ func newLocalListenerMPTCP(t *testing.T, envVar bool) Listener {
16
+ lc := &ListenConfig{}
17
+
18
+ if envVar {
19
+ if !lc.MultipathTCP() {
20
+ t.Fatal("MultipathTCP Listen is not on despite GODEBUG=multipathtcp=1")
21
+ }
22
+ } else {
23
+ if lc.MultipathTCP() {
24
+ t.Error("MultipathTCP should be off by default")
25
+ }
26
+
27
+ lc.SetMultipathTCP(true)
28
+ if !lc.MultipathTCP() {
29
+ t.Fatal("MultipathTCP is not on after having been forced to on")
30
+ }
31
+ }
32
+
33
+ ln, err := lc.Listen(context.Background(), "tcp", "127.0.0.1:0")
34
+ if err != nil {
35
+ t.Fatal(err)
36
+ }
37
+ return ln
38
+ }
39
+
40
+ func postAcceptMPTCP(ls *localServer, ch chan<- error) {
41
+ defer close(ch)
42
+
43
+ if len(ls.cl) == 0 {
44
+ ch <- errors.New("no accepted stream")
45
+ return
46
+ }
47
+
48
+ c := ls.cl[0]
49
+
50
+ tcp, ok := c.(*TCPConn)
51
+ if !ok {
52
+ ch <- errors.New("struct is not a TCPConn")
53
+ return
54
+ }
55
+
56
+ mptcp, err := tcp.MultipathTCP()
57
+ if err != nil {
58
+ ch <- err
59
+ return
60
+ }
61
+
62
+ if !mptcp {
63
+ ch <- errors.New("incoming connection is not with MPTCP")
64
+ return
65
+ }
66
+
67
+ // Also check the method for the older kernels if not tested before
68
+ if hasSOLMPTCP && !isUsingMPTCPProto(tcp.fd) {
69
+ ch <- errors.New("incoming connection is not an MPTCP proto")
70
+ return
71
+ }
72
+ }
73
+
74
+ func dialerMPTCP(t *testing.T, addr string, envVar bool) {
75
+ d := &Dialer{}
76
+
77
+ if envVar {
78
+ if !d.MultipathTCP() {
79
+ t.Fatal("MultipathTCP Dialer is not on despite GODEBUG=multipathtcp=1")
80
+ }
81
+ } else {
82
+ if d.MultipathTCP() {
83
+ t.Error("MultipathTCP should be off by default")
84
+ }
85
+
86
+ d.SetMultipathTCP(true)
87
+ if !d.MultipathTCP() {
88
+ t.Fatal("MultipathTCP is not on after having been forced to on")
89
+ }
90
+ }
91
+
92
+ c, err := d.Dial("tcp", addr)
93
+ if err != nil {
94
+ t.Fatal(err)
95
+ }
96
+ defer c.Close()
97
+
98
+ tcp, ok := c.(*TCPConn)
99
+ if !ok {
100
+ t.Fatal("struct is not a TCPConn")
101
+ }
102
+
103
+ // Transfer a bit of data to make sure everything is still OK
104
+ snt := []byte("MPTCP TEST")
105
+ if _, err := c.Write(snt); err != nil {
106
+ t.Fatal(err)
107
+ }
108
+ b := make([]byte, len(snt))
109
+ if _, err := c.Read(b); err != nil {
110
+ t.Fatal(err)
111
+ }
112
+ if !bytes.Equal(snt, b) {
113
+ t.Errorf("sent bytes (%s) are different from received ones (%s)", snt, b)
114
+ }
115
+
116
+ mptcp, err := tcp.MultipathTCP()
117
+ if err != nil {
118
+ t.Fatal(err)
119
+ }
120
+
121
+ t.Logf("outgoing connection from %s with mptcp: %t", addr, mptcp)
122
+
123
+ if !mptcp {
124
+ t.Error("outgoing connection is not with MPTCP")
125
+ }
126
+
127
+ // Also check the method for the older kernels if not tested before
128
+ if hasSOLMPTCP && !isUsingMPTCPProto(tcp.fd) {
129
+ t.Error("outgoing connection is not an MPTCP proto")
130
+ }
131
+ }
132
+
133
+ func canCreateMPTCPSocket() bool {
134
+ // We want to know if we can create an MPTCP socket, not just if it is
135
+ // available (mptcpAvailable()): it could be blocked by the admin
136
+ fd, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_STREAM, _IPPROTO_MPTCP)
137
+ if err != nil {
138
+ return false
139
+ }
140
+
141
+ syscall.Close(fd)
142
+ return true
143
+ }
144
+
145
+ func testMultiPathTCP(t *testing.T, envVar bool) {
146
+ if envVar {
147
+ t.Log("Test with GODEBUG=multipathtcp=1")
148
+ t.Setenv("GODEBUG", "multipathtcp=1")
149
+ } else {
150
+ t.Log("Test with GODEBUG=multipathtcp=0")
151
+ t.Setenv("GODEBUG", "multipathtcp=0")
152
+ }
153
+
154
+ ln := newLocalListenerMPTCP(t, envVar)
155
+
156
+ // similar to tcpsock_test:TestIPv6LinkLocalUnicastTCP
157
+ ls := (&streamListener{Listener: ln}).newLocalServer()
158
+ defer ls.teardown()
159
+
160
+ if g, w := ls.Listener.Addr().Network(), "tcp"; g != w {
161
+ t.Fatalf("Network type mismatch: got %q, want %q", g, w)
162
+ }
163
+
164
+ genericCh := make(chan error)
165
+ mptcpCh := make(chan error)
166
+ handler := func(ls *localServer, ln Listener) {
167
+ ls.transponder(ln, genericCh)
168
+ postAcceptMPTCP(ls, mptcpCh)
169
+ }
170
+ if err := ls.buildup(handler); err != nil {
171
+ t.Fatal(err)
172
+ }
173
+
174
+ dialerMPTCP(t, ln.Addr().String(), envVar)
175
+
176
+ if err := <-genericCh; err != nil {
177
+ t.Error(err)
178
+ }
179
+ if err := <-mptcpCh; err != nil {
180
+ t.Error(err)
181
+ }
182
+ }
183
+
184
+ func TestMultiPathTCP(t *testing.T) {
185
+ if !canCreateMPTCPSocket() {
186
+ t.Skip("Cannot create MPTCP sockets")
187
+ }
188
+
189
+ for _, envVar := range []bool{false, true} {
190
+ testMultiPathTCP(t, envVar)
191
+ }
192
+ }
platform/dbops/binaries/go/go/src/net/mptcpsock_stub.go ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 !linux
6
+
7
+ package net
8
+
9
+ import (
10
+ "context"
11
+ )
12
+
13
+ func (sd *sysDialer) dialMPTCP(ctx context.Context, laddr, raddr *TCPAddr) (*TCPConn, error) {
14
+ return sd.dialTCP(ctx, laddr, raddr)
15
+ }
16
+
17
+ func (sl *sysListener) listenMPTCP(ctx context.Context, laddr *TCPAddr) (*TCPListener, error) {
18
+ return sl.listenTCP(ctx, laddr)
19
+ }
20
+
21
+ func isUsingMultipathTCP(fd *netFD) bool {
22
+ return false
23
+ }
platform/dbops/binaries/go/go/src/net/net.go ADDED
@@ -0,0 +1,815 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ /*
6
+ Package net provides a portable interface for network I/O, including
7
+ TCP/IP, UDP, domain name resolution, and Unix domain sockets.
8
+
9
+ Although the package provides access to low-level networking
10
+ primitives, most clients will need only the basic interface provided
11
+ by the [Dial], [Listen], and Accept functions and the associated
12
+ [Conn] and [Listener] interfaces. The crypto/tls package uses
13
+ the same interfaces and similar Dial and Listen functions.
14
+
15
+ The Dial function connects to a server:
16
+
17
+ conn, err := net.Dial("tcp", "golang.org:80")
18
+ if err != nil {
19
+ // handle error
20
+ }
21
+ fmt.Fprintf(conn, "GET / HTTP/1.0\r\n\r\n")
22
+ status, err := bufio.NewReader(conn).ReadString('\n')
23
+ // ...
24
+
25
+ The Listen function creates servers:
26
+
27
+ ln, err := net.Listen("tcp", ":8080")
28
+ if err != nil {
29
+ // handle error
30
+ }
31
+ for {
32
+ conn, err := ln.Accept()
33
+ if err != nil {
34
+ // handle error
35
+ }
36
+ go handleConnection(conn)
37
+ }
38
+
39
+ # Name Resolution
40
+
41
+ The method for resolving domain names, whether indirectly with functions like Dial
42
+ or directly with functions like [LookupHost] and [LookupAddr], varies by operating system.
43
+
44
+ On Unix systems, the resolver has two options for resolving names.
45
+ It can use a pure Go resolver that sends DNS requests directly to the servers
46
+ listed in /etc/resolv.conf, or it can use a cgo-based resolver that calls C
47
+ library routines such as getaddrinfo and getnameinfo.
48
+
49
+ By default the pure Go resolver is used, because a blocked DNS request consumes
50
+ only a goroutine, while a blocked C call consumes an operating system thread.
51
+ When cgo is available, the cgo-based resolver is used instead under a variety of
52
+ conditions: on systems that do not let programs make direct DNS requests (OS X),
53
+ when the LOCALDOMAIN environment variable is present (even if empty),
54
+ when the RES_OPTIONS or HOSTALIASES environment variable is non-empty,
55
+ when the ASR_CONFIG environment variable is non-empty (OpenBSD only),
56
+ when /etc/resolv.conf or /etc/nsswitch.conf specify the use of features that the
57
+ Go resolver does not implement, and when the name being looked up ends in .local
58
+ or is an mDNS name.
59
+
60
+ The resolver decision can be overridden by setting the netdns value of the
61
+ GODEBUG environment variable (see package runtime) to go or cgo, as in:
62
+
63
+ export GODEBUG=netdns=go # force pure Go resolver
64
+ export GODEBUG=netdns=cgo # force native resolver (cgo, win32)
65
+
66
+ The decision can also be forced while building the Go source tree
67
+ by setting the netgo or netcgo build tag.
68
+
69
+ A numeric netdns setting, as in GODEBUG=netdns=1, causes the resolver
70
+ to print debugging information about its decisions.
71
+ To force a particular resolver while also printing debugging information,
72
+ join the two settings by a plus sign, as in GODEBUG=netdns=go+1.
73
+
74
+ The Go resolver will send an EDNS0 additional header with a DNS request,
75
+ to signal a willingness to accept a larger DNS packet size.
76
+ This can reportedly cause sporadic failures with the DNS server run
77
+ by some modems and routers. Setting GODEBUG=netedns0=0 will disable
78
+ sending the additional header.
79
+
80
+ On macOS, if Go code that uses the net package is built with
81
+ -buildmode=c-archive, linking the resulting archive into a C program
82
+ requires passing -lresolv when linking the C code.
83
+
84
+ On Plan 9, the resolver always accesses /net/cs and /net/dns.
85
+
86
+ On Windows, in Go 1.18.x and earlier, the resolver always used C
87
+ library functions, such as GetAddrInfo and DnsQuery.
88
+ */
89
+ package net
90
+
91
+ import (
92
+ "context"
93
+ "errors"
94
+ "internal/poll"
95
+ "io"
96
+ "os"
97
+ "sync"
98
+ "syscall"
99
+ "time"
100
+ )
101
+
102
+ // Addr represents a network end point address.
103
+ //
104
+ // The two methods [Addr.Network] and [Addr.String] conventionally return strings
105
+ // that can be passed as the arguments to [Dial], but the exact form
106
+ // and meaning of the strings is up to the implementation.
107
+ type Addr interface {
108
+ Network() string // name of the network (for example, "tcp", "udp")
109
+ String() string // string form of address (for example, "192.0.2.1:25", "[2001:db8::1]:80")
110
+ }
111
+
112
+ // Conn is a generic stream-oriented network connection.
113
+ //
114
+ // Multiple goroutines may invoke methods on a Conn simultaneously.
115
+ type Conn interface {
116
+ // Read reads data from the connection.
117
+ // Read can be made to time out and return an error after a fixed
118
+ // time limit; see SetDeadline and SetReadDeadline.
119
+ Read(b []byte) (n int, err error)
120
+
121
+ // Write writes data to the connection.
122
+ // Write can be made to time out and return an error after a fixed
123
+ // time limit; see SetDeadline and SetWriteDeadline.
124
+ Write(b []byte) (n int, err error)
125
+
126
+ // Close closes the connection.
127
+ // Any blocked Read or Write operations will be unblocked and return errors.
128
+ Close() error
129
+
130
+ // LocalAddr returns the local network address, if known.
131
+ LocalAddr() Addr
132
+
133
+ // RemoteAddr returns the remote network address, if known.
134
+ RemoteAddr() Addr
135
+
136
+ // SetDeadline sets the read and write deadlines associated
137
+ // with the connection. It is equivalent to calling both
138
+ // SetReadDeadline and SetWriteDeadline.
139
+ //
140
+ // A deadline is an absolute time after which I/O operations
141
+ // fail instead of blocking. The deadline applies to all future
142
+ // and pending I/O, not just the immediately following call to
143
+ // Read or Write. After a deadline has been exceeded, the
144
+ // connection can be refreshed by setting a deadline in the future.
145
+ //
146
+ // If the deadline is exceeded a call to Read or Write or to other
147
+ // I/O methods will return an error that wraps os.ErrDeadlineExceeded.
148
+ // This can be tested using errors.Is(err, os.ErrDeadlineExceeded).
149
+ // The error's Timeout method will return true, but note that there
150
+ // are other possible errors for which the Timeout method will
151
+ // return true even if the deadline has not been exceeded.
152
+ //
153
+ // An idle timeout can be implemented by repeatedly extending
154
+ // the deadline after successful Read or Write calls.
155
+ //
156
+ // A zero value for t means I/O operations will not time out.
157
+ SetDeadline(t time.Time) error
158
+
159
+ // SetReadDeadline sets the deadline for future Read calls
160
+ // and any currently-blocked Read call.
161
+ // A zero value for t means Read will not time out.
162
+ SetReadDeadline(t time.Time) error
163
+
164
+ // SetWriteDeadline sets the deadline for future Write calls
165
+ // and any currently-blocked Write call.
166
+ // Even if write times out, it may return n > 0, indicating that
167
+ // some of the data was successfully written.
168
+ // A zero value for t means Write will not time out.
169
+ SetWriteDeadline(t time.Time) error
170
+ }
171
+
172
+ type conn struct {
173
+ fd *netFD
174
+ }
175
+
176
+ func (c *conn) ok() bool { return c != nil && c.fd != nil }
177
+
178
+ // Implementation of the Conn interface.
179
+
180
+ // Read implements the Conn Read method.
181
+ func (c *conn) Read(b []byte) (int, error) {
182
+ if !c.ok() {
183
+ return 0, syscall.EINVAL
184
+ }
185
+ n, err := c.fd.Read(b)
186
+ if err != nil && err != io.EOF {
187
+ err = &OpError{Op: "read", Net: c.fd.net, Source: c.fd.laddr, Addr: c.fd.raddr, Err: err}
188
+ }
189
+ return n, err
190
+ }
191
+
192
+ // Write implements the Conn Write method.
193
+ func (c *conn) Write(b []byte) (int, error) {
194
+ if !c.ok() {
195
+ return 0, syscall.EINVAL
196
+ }
197
+ n, err := c.fd.Write(b)
198
+ if err != nil {
199
+ err = &OpError{Op: "write", Net: c.fd.net, Source: c.fd.laddr, Addr: c.fd.raddr, Err: err}
200
+ }
201
+ return n, err
202
+ }
203
+
204
+ // Close closes the connection.
205
+ func (c *conn) Close() error {
206
+ if !c.ok() {
207
+ return syscall.EINVAL
208
+ }
209
+ err := c.fd.Close()
210
+ if err != nil {
211
+ err = &OpError{Op: "close", Net: c.fd.net, Source: c.fd.laddr, Addr: c.fd.raddr, Err: err}
212
+ }
213
+ return err
214
+ }
215
+
216
+ // LocalAddr returns the local network address.
217
+ // The Addr returned is shared by all invocations of LocalAddr, so
218
+ // do not modify it.
219
+ func (c *conn) LocalAddr() Addr {
220
+ if !c.ok() {
221
+ return nil
222
+ }
223
+ return c.fd.laddr
224
+ }
225
+
226
+ // RemoteAddr returns the remote network address.
227
+ // The Addr returned is shared by all invocations of RemoteAddr, so
228
+ // do not modify it.
229
+ func (c *conn) RemoteAddr() Addr {
230
+ if !c.ok() {
231
+ return nil
232
+ }
233
+ return c.fd.raddr
234
+ }
235
+
236
+ // SetDeadline implements the Conn SetDeadline method.
237
+ func (c *conn) SetDeadline(t time.Time) error {
238
+ if !c.ok() {
239
+ return syscall.EINVAL
240
+ }
241
+ if err := c.fd.SetDeadline(t); err != nil {
242
+ return &OpError{Op: "set", Net: c.fd.net, Source: nil, Addr: c.fd.laddr, Err: err}
243
+ }
244
+ return nil
245
+ }
246
+
247
+ // SetReadDeadline implements the Conn SetReadDeadline method.
248
+ func (c *conn) SetReadDeadline(t time.Time) error {
249
+ if !c.ok() {
250
+ return syscall.EINVAL
251
+ }
252
+ if err := c.fd.SetReadDeadline(t); err != nil {
253
+ return &OpError{Op: "set", Net: c.fd.net, Source: nil, Addr: c.fd.laddr, Err: err}
254
+ }
255
+ return nil
256
+ }
257
+
258
+ // SetWriteDeadline implements the Conn SetWriteDeadline method.
259
+ func (c *conn) SetWriteDeadline(t time.Time) error {
260
+ if !c.ok() {
261
+ return syscall.EINVAL
262
+ }
263
+ if err := c.fd.SetWriteDeadline(t); err != nil {
264
+ return &OpError{Op: "set", Net: c.fd.net, Source: nil, Addr: c.fd.laddr, Err: err}
265
+ }
266
+ return nil
267
+ }
268
+
269
+ // SetReadBuffer sets the size of the operating system's
270
+ // receive buffer associated with the connection.
271
+ func (c *conn) SetReadBuffer(bytes int) error {
272
+ if !c.ok() {
273
+ return syscall.EINVAL
274
+ }
275
+ if err := setReadBuffer(c.fd, bytes); err != nil {
276
+ return &OpError{Op: "set", Net: c.fd.net, Source: nil, Addr: c.fd.laddr, Err: err}
277
+ }
278
+ return nil
279
+ }
280
+
281
+ // SetWriteBuffer sets the size of the operating system's
282
+ // transmit buffer associated with the connection.
283
+ func (c *conn) SetWriteBuffer(bytes int) error {
284
+ if !c.ok() {
285
+ return syscall.EINVAL
286
+ }
287
+ if err := setWriteBuffer(c.fd, bytes); err != nil {
288
+ return &OpError{Op: "set", Net: c.fd.net, Source: nil, Addr: c.fd.laddr, Err: err}
289
+ }
290
+ return nil
291
+ }
292
+
293
+ // File returns a copy of the underlying [os.File].
294
+ // It is the caller's responsibility to close f when finished.
295
+ // Closing c does not affect f, and closing f does not affect c.
296
+ //
297
+ // The returned os.File's file descriptor is different from the connection's.
298
+ // Attempting to change properties of the original using this duplicate
299
+ // may or may not have the desired effect.
300
+ func (c *conn) File() (f *os.File, err error) {
301
+ f, err = c.fd.dup()
302
+ if err != nil {
303
+ err = &OpError{Op: "file", Net: c.fd.net, Source: c.fd.laddr, Addr: c.fd.raddr, Err: err}
304
+ }
305
+ return
306
+ }
307
+
308
+ // PacketConn is a generic packet-oriented network connection.
309
+ //
310
+ // Multiple goroutines may invoke methods on a PacketConn simultaneously.
311
+ type PacketConn interface {
312
+ // ReadFrom reads a packet from the connection,
313
+ // copying the payload into p. It returns the number of
314
+ // bytes copied into p and the return address that
315
+ // was on the packet.
316
+ // It returns the number of bytes read (0 <= n <= len(p))
317
+ // and any error encountered. Callers should always process
318
+ // the n > 0 bytes returned before considering the error err.
319
+ // ReadFrom can be made to time out and return an error after a
320
+ // fixed time limit; see SetDeadline and SetReadDeadline.
321
+ ReadFrom(p []byte) (n int, addr Addr, err error)
322
+
323
+ // WriteTo writes a packet with payload p to addr.
324
+ // WriteTo can be made to time out and return an Error after a
325
+ // fixed time limit; see SetDeadline and SetWriteDeadline.
326
+ // On packet-oriented connections, write timeouts are rare.
327
+ WriteTo(p []byte, addr Addr) (n int, err error)
328
+
329
+ // Close closes the connection.
330
+ // Any blocked ReadFrom or WriteTo operations will be unblocked and return errors.
331
+ Close() error
332
+
333
+ // LocalAddr returns the local network address, if known.
334
+ LocalAddr() Addr
335
+
336
+ // SetDeadline sets the read and write deadlines associated
337
+ // with the connection. It is equivalent to calling both
338
+ // SetReadDeadline and SetWriteDeadline.
339
+ //
340
+ // A deadline is an absolute time after which I/O operations
341
+ // fail instead of blocking. The deadline applies to all future
342
+ // and pending I/O, not just the immediately following call to
343
+ // Read or Write. After a deadline has been exceeded, the
344
+ // connection can be refreshed by setting a deadline in the future.
345
+ //
346
+ // If the deadline is exceeded a call to Read or Write or to other
347
+ // I/O methods will return an error that wraps os.ErrDeadlineExceeded.
348
+ // This can be tested using errors.Is(err, os.ErrDeadlineExceeded).
349
+ // The error's Timeout method will return true, but note that there
350
+ // are other possible errors for which the Timeout method will
351
+ // return true even if the deadline has not been exceeded.
352
+ //
353
+ // An idle timeout can be implemented by repeatedly extending
354
+ // the deadline after successful ReadFrom or WriteTo calls.
355
+ //
356
+ // A zero value for t means I/O operations will not time out.
357
+ SetDeadline(t time.Time) error
358
+
359
+ // SetReadDeadline sets the deadline for future ReadFrom calls
360
+ // and any currently-blocked ReadFrom call.
361
+ // A zero value for t means ReadFrom will not time out.
362
+ SetReadDeadline(t time.Time) error
363
+
364
+ // SetWriteDeadline sets the deadline for future WriteTo calls
365
+ // and any currently-blocked WriteTo call.
366
+ // Even if write times out, it may return n > 0, indicating that
367
+ // some of the data was successfully written.
368
+ // A zero value for t means WriteTo will not time out.
369
+ SetWriteDeadline(t time.Time) error
370
+ }
371
+
372
+ var listenerBacklogCache struct {
373
+ sync.Once
374
+ val int
375
+ }
376
+
377
+ // listenerBacklog is a caching wrapper around maxListenerBacklog.
378
+ func listenerBacklog() int {
379
+ listenerBacklogCache.Do(func() { listenerBacklogCache.val = maxListenerBacklog() })
380
+ return listenerBacklogCache.val
381
+ }
382
+
383
+ // A Listener is a generic network listener for stream-oriented protocols.
384
+ //
385
+ // Multiple goroutines may invoke methods on a Listener simultaneously.
386
+ type Listener interface {
387
+ // Accept waits for and returns the next connection to the listener.
388
+ Accept() (Conn, error)
389
+
390
+ // Close closes the listener.
391
+ // Any blocked Accept operations will be unblocked and return errors.
392
+ Close() error
393
+
394
+ // Addr returns the listener's network address.
395
+ Addr() Addr
396
+ }
397
+
398
+ // An Error represents a network error.
399
+ type Error interface {
400
+ error
401
+ Timeout() bool // Is the error a timeout?
402
+
403
+ // Deprecated: Temporary errors are not well-defined.
404
+ // Most "temporary" errors are timeouts, and the few exceptions are surprising.
405
+ // Do not use this method.
406
+ Temporary() bool
407
+ }
408
+
409
+ // Various errors contained in OpError.
410
+ var (
411
+ // For connection setup operations.
412
+ errNoSuitableAddress = errors.New("no suitable address found")
413
+
414
+ // For connection setup and write operations.
415
+ errMissingAddress = errors.New("missing address")
416
+
417
+ // For both read and write operations.
418
+ errCanceled = canceledError{}
419
+ ErrWriteToConnected = errors.New("use of WriteTo with pre-connected connection")
420
+ )
421
+
422
+ // canceledError lets us return the same error string we have always
423
+ // returned, while still being Is context.Canceled.
424
+ type canceledError struct{}
425
+
426
+ func (canceledError) Error() string { return "operation was canceled" }
427
+
428
+ func (canceledError) Is(err error) bool { return err == context.Canceled }
429
+
430
+ // mapErr maps from the context errors to the historical internal net
431
+ // error values.
432
+ func mapErr(err error) error {
433
+ switch err {
434
+ case context.Canceled:
435
+ return errCanceled
436
+ case context.DeadlineExceeded:
437
+ return errTimeout
438
+ default:
439
+ return err
440
+ }
441
+ }
442
+
443
+ // OpError is the error type usually returned by functions in the net
444
+ // package. It describes the operation, network type, and address of
445
+ // an error.
446
+ type OpError struct {
447
+ // Op is the operation which caused the error, such as
448
+ // "read" or "write".
449
+ Op string
450
+
451
+ // Net is the network type on which this error occurred,
452
+ // such as "tcp" or "udp6".
453
+ Net string
454
+
455
+ // For operations involving a remote network connection, like
456
+ // Dial, Read, or Write, Source is the corresponding local
457
+ // network address.
458
+ Source Addr
459
+
460
+ // Addr is the network address for which this error occurred.
461
+ // For local operations, like Listen or SetDeadline, Addr is
462
+ // the address of the local endpoint being manipulated.
463
+ // For operations involving a remote network connection, like
464
+ // Dial, Read, or Write, Addr is the remote address of that
465
+ // connection.
466
+ Addr Addr
467
+
468
+ // Err is the error that occurred during the operation.
469
+ // The Error method panics if the error is nil.
470
+ Err error
471
+ }
472
+
473
+ func (e *OpError) Unwrap() error { return e.Err }
474
+
475
+ func (e *OpError) Error() string {
476
+ if e == nil {
477
+ return "<nil>"
478
+ }
479
+ s := e.Op
480
+ if e.Net != "" {
481
+ s += " " + e.Net
482
+ }
483
+ if e.Source != nil {
484
+ s += " " + e.Source.String()
485
+ }
486
+ if e.Addr != nil {
487
+ if e.Source != nil {
488
+ s += "->"
489
+ } else {
490
+ s += " "
491
+ }
492
+ s += e.Addr.String()
493
+ }
494
+ s += ": " + e.Err.Error()
495
+ return s
496
+ }
497
+
498
+ var (
499
+ // aLongTimeAgo is a non-zero time, far in the past, used for
500
+ // immediate cancellation of dials.
501
+ aLongTimeAgo = time.Unix(1, 0)
502
+
503
+ // noDeadline and noCancel are just zero values for
504
+ // readability with functions taking too many parameters.
505
+ noDeadline = time.Time{}
506
+ noCancel = (chan struct{})(nil)
507
+ )
508
+
509
+ type timeout interface {
510
+ Timeout() bool
511
+ }
512
+
513
+ func (e *OpError) Timeout() bool {
514
+ if ne, ok := e.Err.(*os.SyscallError); ok {
515
+ t, ok := ne.Err.(timeout)
516
+ return ok && t.Timeout()
517
+ }
518
+ t, ok := e.Err.(timeout)
519
+ return ok && t.Timeout()
520
+ }
521
+
522
+ type temporary interface {
523
+ Temporary() bool
524
+ }
525
+
526
+ func (e *OpError) Temporary() bool {
527
+ // Treat ECONNRESET and ECONNABORTED as temporary errors when
528
+ // they come from calling accept. See issue 6163.
529
+ if e.Op == "accept" && isConnError(e.Err) {
530
+ return true
531
+ }
532
+
533
+ if ne, ok := e.Err.(*os.SyscallError); ok {
534
+ t, ok := ne.Err.(temporary)
535
+ return ok && t.Temporary()
536
+ }
537
+ t, ok := e.Err.(temporary)
538
+ return ok && t.Temporary()
539
+ }
540
+
541
+ // A ParseError is the error type of literal network address parsers.
542
+ type ParseError struct {
543
+ // Type is the type of string that was expected, such as
544
+ // "IP address", "CIDR address".
545
+ Type string
546
+
547
+ // Text is the malformed text string.
548
+ Text string
549
+ }
550
+
551
+ func (e *ParseError) Error() string { return "invalid " + e.Type + ": " + e.Text }
552
+
553
+ func (e *ParseError) Timeout() bool { return false }
554
+ func (e *ParseError) Temporary() bool { return false }
555
+
556
+ type AddrError struct {
557
+ Err string
558
+ Addr string
559
+ }
560
+
561
+ func (e *AddrError) Error() string {
562
+ if e == nil {
563
+ return "<nil>"
564
+ }
565
+ s := e.Err
566
+ if e.Addr != "" {
567
+ s = "address " + e.Addr + ": " + s
568
+ }
569
+ return s
570
+ }
571
+
572
+ func (e *AddrError) Timeout() bool { return false }
573
+ func (e *AddrError) Temporary() bool { return false }
574
+
575
+ type UnknownNetworkError string
576
+
577
+ func (e UnknownNetworkError) Error() string { return "unknown network " + string(e) }
578
+ func (e UnknownNetworkError) Timeout() bool { return false }
579
+ func (e UnknownNetworkError) Temporary() bool { return false }
580
+
581
+ type InvalidAddrError string
582
+
583
+ func (e InvalidAddrError) Error() string { return string(e) }
584
+ func (e InvalidAddrError) Timeout() bool { return false }
585
+ func (e InvalidAddrError) Temporary() bool { return false }
586
+
587
+ // errTimeout exists to return the historical "i/o timeout" string
588
+ // for context.DeadlineExceeded. See mapErr.
589
+ // It is also used when Dialer.Deadline is exceeded.
590
+ // error.Is(errTimeout, context.DeadlineExceeded) returns true.
591
+ //
592
+ // TODO(iant): We could consider changing this to os.ErrDeadlineExceeded
593
+ // in the future, if we make
594
+ //
595
+ // errors.Is(os.ErrDeadlineExceeded, context.DeadlineExceeded)
596
+ //
597
+ // return true.
598
+ var errTimeout error = &timeoutError{}
599
+
600
+ type timeoutError struct{}
601
+
602
+ func (e *timeoutError) Error() string { return "i/o timeout" }
603
+ func (e *timeoutError) Timeout() bool { return true }
604
+ func (e *timeoutError) Temporary() bool { return true }
605
+
606
+ func (e *timeoutError) Is(err error) bool {
607
+ return err == context.DeadlineExceeded
608
+ }
609
+
610
+ // DNSConfigError represents an error reading the machine's DNS configuration.
611
+ // (No longer used; kept for compatibility.)
612
+ type DNSConfigError struct {
613
+ Err error
614
+ }
615
+
616
+ func (e *DNSConfigError) Unwrap() error { return e.Err }
617
+ func (e *DNSConfigError) Error() string { return "error reading DNS config: " + e.Err.Error() }
618
+ func (e *DNSConfigError) Timeout() bool { return false }
619
+ func (e *DNSConfigError) Temporary() bool { return false }
620
+
621
+ // Various errors contained in DNSError.
622
+ var (
623
+ errNoSuchHost = errors.New("no such host")
624
+ )
625
+
626
+ // DNSError represents a DNS lookup error.
627
+ type DNSError struct {
628
+ Err string // description of the error
629
+ Name string // name looked for
630
+ Server string // server used
631
+ IsTimeout bool // if true, timed out; not all timeouts set this
632
+ IsTemporary bool // if true, error is temporary; not all errors set this
633
+
634
+ // IsNotFound is set to true when the requested name does not
635
+ // contain any records of the requested type (data not found),
636
+ // or the name itself was not found (NXDOMAIN).
637
+ IsNotFound bool
638
+ }
639
+
640
+ func (e *DNSError) Error() string {
641
+ if e == nil {
642
+ return "<nil>"
643
+ }
644
+ s := "lookup " + e.Name
645
+ if e.Server != "" {
646
+ s += " on " + e.Server
647
+ }
648
+ s += ": " + e.Err
649
+ return s
650
+ }
651
+
652
+ // Timeout reports whether the DNS lookup is known to have timed out.
653
+ // This is not always known; a DNS lookup may fail due to a timeout
654
+ // and return a [DNSError] for which Timeout returns false.
655
+ func (e *DNSError) Timeout() bool { return e.IsTimeout }
656
+
657
+ // Temporary reports whether the DNS error is known to be temporary.
658
+ // This is not always known; a DNS lookup may fail due to a temporary
659
+ // error and return a [DNSError] for which Temporary returns false.
660
+ func (e *DNSError) Temporary() bool { return e.IsTimeout || e.IsTemporary }
661
+
662
+ // errClosed exists just so that the docs for ErrClosed don't mention
663
+ // the internal package poll.
664
+ var errClosed = poll.ErrNetClosing
665
+
666
+ // ErrClosed is the error returned by an I/O call on a network
667
+ // connection that has already been closed, or that is closed by
668
+ // another goroutine before the I/O is completed. This may be wrapped
669
+ // in another error, and should normally be tested using
670
+ // errors.Is(err, net.ErrClosed).
671
+ var ErrClosed error = errClosed
672
+
673
+ // noReadFrom can be embedded alongside another type to
674
+ // hide the ReadFrom method of that other type.
675
+ type noReadFrom struct{}
676
+
677
+ // ReadFrom hides another ReadFrom method.
678
+ // It should never be called.
679
+ func (noReadFrom) ReadFrom(io.Reader) (int64, error) {
680
+ panic("can't happen")
681
+ }
682
+
683
+ // tcpConnWithoutReadFrom implements all the methods of *TCPConn other
684
+ // than ReadFrom. This is used to permit ReadFrom to call io.Copy
685
+ // without leading to a recursive call to ReadFrom.
686
+ type tcpConnWithoutReadFrom struct {
687
+ noReadFrom
688
+ *TCPConn
689
+ }
690
+
691
+ // Fallback implementation of io.ReaderFrom's ReadFrom, when sendfile isn't
692
+ // applicable.
693
+ func genericReadFrom(c *TCPConn, r io.Reader) (n int64, err error) {
694
+ // Use wrapper to hide existing r.ReadFrom from io.Copy.
695
+ return io.Copy(tcpConnWithoutReadFrom{TCPConn: c}, r)
696
+ }
697
+
698
+ // noWriteTo can be embedded alongside another type to
699
+ // hide the WriteTo method of that other type.
700
+ type noWriteTo struct{}
701
+
702
+ // WriteTo hides another WriteTo method.
703
+ // It should never be called.
704
+ func (noWriteTo) WriteTo(io.Writer) (int64, error) {
705
+ panic("can't happen")
706
+ }
707
+
708
+ // tcpConnWithoutWriteTo implements all the methods of *TCPConn other
709
+ // than WriteTo. This is used to permit WriteTo to call io.Copy
710
+ // without leading to a recursive call to WriteTo.
711
+ type tcpConnWithoutWriteTo struct {
712
+ noWriteTo
713
+ *TCPConn
714
+ }
715
+
716
+ // Fallback implementation of io.WriterTo's WriteTo, when zero-copy isn't applicable.
717
+ func genericWriteTo(c *TCPConn, w io.Writer) (n int64, err error) {
718
+ // Use wrapper to hide existing w.WriteTo from io.Copy.
719
+ return io.Copy(w, tcpConnWithoutWriteTo{TCPConn: c})
720
+ }
721
+
722
+ // Limit the number of concurrent cgo-using goroutines, because
723
+ // each will block an entire operating system thread. The usual culprit
724
+ // is resolving many DNS names in separate goroutines but the DNS
725
+ // server is not responding. Then the many lookups each use a different
726
+ // thread, and the system or the program runs out of threads.
727
+
728
+ var threadLimit chan struct{}
729
+
730
+ var threadOnce sync.Once
731
+
732
+ func acquireThread() {
733
+ threadOnce.Do(func() {
734
+ threadLimit = make(chan struct{}, concurrentThreadsLimit())
735
+ })
736
+ threadLimit <- struct{}{}
737
+ }
738
+
739
+ func releaseThread() {
740
+ <-threadLimit
741
+ }
742
+
743
+ // buffersWriter is the interface implemented by Conns that support a
744
+ // "writev"-like batch write optimization.
745
+ // writeBuffers should fully consume and write all chunks from the
746
+ // provided Buffers, else it should report a non-nil error.
747
+ type buffersWriter interface {
748
+ writeBuffers(*Buffers) (int64, error)
749
+ }
750
+
751
+ // Buffers contains zero or more runs of bytes to write.
752
+ //
753
+ // On certain machines, for certain types of connections, this is
754
+ // optimized into an OS-specific batch write operation (such as
755
+ // "writev").
756
+ type Buffers [][]byte
757
+
758
+ var (
759
+ _ io.WriterTo = (*Buffers)(nil)
760
+ _ io.Reader = (*Buffers)(nil)
761
+ )
762
+
763
+ // WriteTo writes contents of the buffers to w.
764
+ //
765
+ // WriteTo implements [io.WriterTo] for [Buffers].
766
+ //
767
+ // WriteTo modifies the slice v as well as v[i] for 0 <= i < len(v),
768
+ // but does not modify v[i][j] for any i, j.
769
+ func (v *Buffers) WriteTo(w io.Writer) (n int64, err error) {
770
+ if wv, ok := w.(buffersWriter); ok {
771
+ return wv.writeBuffers(v)
772
+ }
773
+ for _, b := range *v {
774
+ nb, err := w.Write(b)
775
+ n += int64(nb)
776
+ if err != nil {
777
+ v.consume(n)
778
+ return n, err
779
+ }
780
+ }
781
+ v.consume(n)
782
+ return n, nil
783
+ }
784
+
785
+ // Read from the buffers.
786
+ //
787
+ // Read implements [io.Reader] for [Buffers].
788
+ //
789
+ // Read modifies the slice v as well as v[i] for 0 <= i < len(v),
790
+ // but does not modify v[i][j] for any i, j.
791
+ func (v *Buffers) Read(p []byte) (n int, err error) {
792
+ for len(p) > 0 && len(*v) > 0 {
793
+ n0 := copy(p, (*v)[0])
794
+ v.consume(int64(n0))
795
+ p = p[n0:]
796
+ n += n0
797
+ }
798
+ if len(*v) == 0 {
799
+ err = io.EOF
800
+ }
801
+ return
802
+ }
803
+
804
+ func (v *Buffers) consume(n int64) {
805
+ for len(*v) > 0 {
806
+ ln0 := int64(len((*v)[0]))
807
+ if ln0 > n {
808
+ (*v)[0] = (*v)[0][n:]
809
+ return
810
+ }
811
+ n -= ln0
812
+ (*v)[0] = nil
813
+ *v = (*v)[1:]
814
+ }
815
+ }
platform/dbops/binaries/go/go/src/net/net_fake.go ADDED
@@ -0,0 +1,1170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ // Fake networking for js/wasm and wasip1/wasm.
6
+ // It is intended to allow tests of other package to pass.
7
+
8
+ //go:build js || wasip1
9
+
10
+ package net
11
+
12
+ import (
13
+ "context"
14
+ "errors"
15
+ "io"
16
+ "os"
17
+ "runtime"
18
+ "sync"
19
+ "sync/atomic"
20
+ "syscall"
21
+ "time"
22
+ )
23
+
24
+ var (
25
+ sockets sync.Map // fakeSockAddr → *netFD
26
+ fakeSocketIDs sync.Map // fakeNetFD.id → *netFD
27
+ fakePorts sync.Map // int (port #) → *netFD
28
+ nextPortCounter atomic.Int32
29
+ )
30
+
31
+ const defaultBuffer = 65535
32
+
33
+ type fakeSockAddr struct {
34
+ family int
35
+ address string
36
+ }
37
+
38
+ func fakeAddr(sa sockaddr) fakeSockAddr {
39
+ return fakeSockAddr{
40
+ family: sa.family(),
41
+ address: sa.String(),
42
+ }
43
+ }
44
+
45
+ // socket returns a network file descriptor that is ready for
46
+ // I/O using the fake network.
47
+ 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) (*netFD, error) {
48
+ if raddr != nil && ctrlCtxFn != nil {
49
+ return nil, os.NewSyscallError("socket", syscall.ENOTSUP)
50
+ }
51
+ switch sotype {
52
+ case syscall.SOCK_STREAM, syscall.SOCK_SEQPACKET, syscall.SOCK_DGRAM:
53
+ default:
54
+ return nil, os.NewSyscallError("socket", syscall.ENOTSUP)
55
+ }
56
+
57
+ fd := &netFD{
58
+ family: family,
59
+ sotype: sotype,
60
+ net: net,
61
+ }
62
+ fd.fakeNetFD = newFakeNetFD(fd)
63
+
64
+ if raddr == nil {
65
+ if err := fakeListen(fd, laddr); err != nil {
66
+ fd.Close()
67
+ return nil, err
68
+ }
69
+ return fd, nil
70
+ }
71
+
72
+ if err := fakeConnect(ctx, fd, laddr, raddr); err != nil {
73
+ fd.Close()
74
+ return nil, err
75
+ }
76
+ return fd, nil
77
+ }
78
+
79
+ func validateResolvedAddr(net string, family int, sa sockaddr) error {
80
+ validateIP := func(ip IP) error {
81
+ switch family {
82
+ case syscall.AF_INET:
83
+ if len(ip) != 4 {
84
+ return &AddrError{
85
+ Err: "non-IPv4 address",
86
+ Addr: ip.String(),
87
+ }
88
+ }
89
+ case syscall.AF_INET6:
90
+ if len(ip) != 16 {
91
+ return &AddrError{
92
+ Err: "non-IPv6 address",
93
+ Addr: ip.String(),
94
+ }
95
+ }
96
+ default:
97
+ panic("net: unexpected address family in validateResolvedAddr")
98
+ }
99
+ return nil
100
+ }
101
+
102
+ switch net {
103
+ case "tcp", "tcp4", "tcp6":
104
+ sa, ok := sa.(*TCPAddr)
105
+ if !ok {
106
+ return &AddrError{
107
+ Err: "non-TCP address for " + net + " network",
108
+ Addr: sa.String(),
109
+ }
110
+ }
111
+ if err := validateIP(sa.IP); err != nil {
112
+ return err
113
+ }
114
+ if sa.Port <= 0 || sa.Port >= 1<<16 {
115
+ return &AddrError{
116
+ Err: "port out of range",
117
+ Addr: sa.String(),
118
+ }
119
+ }
120
+ return nil
121
+
122
+ case "udp", "udp4", "udp6":
123
+ sa, ok := sa.(*UDPAddr)
124
+ if !ok {
125
+ return &AddrError{
126
+ Err: "non-UDP address for " + net + " network",
127
+ Addr: sa.String(),
128
+ }
129
+ }
130
+ if err := validateIP(sa.IP); err != nil {
131
+ return err
132
+ }
133
+ if sa.Port <= 0 || sa.Port >= 1<<16 {
134
+ return &AddrError{
135
+ Err: "port out of range",
136
+ Addr: sa.String(),
137
+ }
138
+ }
139
+ return nil
140
+
141
+ case "unix", "unixgram", "unixpacket":
142
+ sa, ok := sa.(*UnixAddr)
143
+ if !ok {
144
+ return &AddrError{
145
+ Err: "non-Unix address for " + net + " network",
146
+ Addr: sa.String(),
147
+ }
148
+ }
149
+ if sa.Name != "" {
150
+ i := len(sa.Name) - 1
151
+ for i > 0 && !os.IsPathSeparator(sa.Name[i]) {
152
+ i--
153
+ }
154
+ for i > 0 && os.IsPathSeparator(sa.Name[i]) {
155
+ i--
156
+ }
157
+ if i <= 0 {
158
+ return &AddrError{
159
+ Err: "unix socket name missing path component",
160
+ Addr: sa.Name,
161
+ }
162
+ }
163
+ if _, err := os.Stat(sa.Name[:i+1]); err != nil {
164
+ return &AddrError{
165
+ Err: err.Error(),
166
+ Addr: sa.Name,
167
+ }
168
+ }
169
+ }
170
+ return nil
171
+
172
+ default:
173
+ return &AddrError{
174
+ Err: syscall.EAFNOSUPPORT.Error(),
175
+ Addr: sa.String(),
176
+ }
177
+ }
178
+ }
179
+
180
+ func matchIPFamily(family int, addr sockaddr) sockaddr {
181
+ convertIP := func(ip IP) IP {
182
+ switch family {
183
+ case syscall.AF_INET:
184
+ return ip.To4()
185
+ case syscall.AF_INET6:
186
+ return ip.To16()
187
+ default:
188
+ return ip
189
+ }
190
+ }
191
+
192
+ switch addr := addr.(type) {
193
+ case *TCPAddr:
194
+ ip := convertIP(addr.IP)
195
+ if ip == nil || len(ip) == len(addr.IP) {
196
+ return addr
197
+ }
198
+ return &TCPAddr{IP: ip, Port: addr.Port, Zone: addr.Zone}
199
+ case *UDPAddr:
200
+ ip := convertIP(addr.IP)
201
+ if ip == nil || len(ip) == len(addr.IP) {
202
+ return addr
203
+ }
204
+ return &UDPAddr{IP: ip, Port: addr.Port, Zone: addr.Zone}
205
+ default:
206
+ return addr
207
+ }
208
+ }
209
+
210
+ type fakeNetFD struct {
211
+ fd *netFD
212
+ assignedPort int // 0 if no port has been assigned for this socket
213
+
214
+ queue *packetQueue // incoming packets
215
+ peer *netFD // connected peer (for outgoing packets); nil for listeners and PacketConns
216
+ readDeadline atomic.Pointer[deadlineTimer]
217
+ writeDeadline atomic.Pointer[deadlineTimer]
218
+
219
+ fakeAddr fakeSockAddr // cached fakeSockAddr equivalent of fd.laddr
220
+
221
+ // The incoming channels hold incoming connections that have not yet been accepted.
222
+ // All of these channels are 1-buffered.
223
+ incoming chan []*netFD // holds the queue when it has >0 but <SOMAXCONN pending connections; closed when the Listener is closed
224
+ incomingFull chan []*netFD // holds the queue when it has SOMAXCONN pending connections
225
+ incomingEmpty chan bool // holds true when the incoming queue is empty
226
+ }
227
+
228
+ func newFakeNetFD(fd *netFD) *fakeNetFD {
229
+ ffd := &fakeNetFD{fd: fd}
230
+ ffd.readDeadline.Store(newDeadlineTimer(noDeadline))
231
+ ffd.writeDeadline.Store(newDeadlineTimer(noDeadline))
232
+ return ffd
233
+ }
234
+
235
+ func (ffd *fakeNetFD) Read(p []byte) (n int, err error) {
236
+ n, _, err = ffd.queue.recvfrom(ffd.readDeadline.Load(), p, false, nil)
237
+ return n, err
238
+ }
239
+
240
+ func (ffd *fakeNetFD) Write(p []byte) (nn int, err error) {
241
+ peer := ffd.peer
242
+ if peer == nil {
243
+ if ffd.fd.raddr == nil {
244
+ return 0, os.NewSyscallError("write", syscall.ENOTCONN)
245
+ }
246
+ peeri, _ := sockets.Load(fakeAddr(ffd.fd.raddr.(sockaddr)))
247
+ if peeri == nil {
248
+ return 0, os.NewSyscallError("write", syscall.ECONNRESET)
249
+ }
250
+ peer = peeri.(*netFD)
251
+ if peer.queue == nil {
252
+ return 0, os.NewSyscallError("write", syscall.ECONNRESET)
253
+ }
254
+ }
255
+
256
+ if peer.fakeNetFD == nil {
257
+ return 0, os.NewSyscallError("write", syscall.EINVAL)
258
+ }
259
+ return peer.queue.write(ffd.writeDeadline.Load(), p, ffd.fd.laddr.(sockaddr))
260
+ }
261
+
262
+ func (ffd *fakeNetFD) Close() (err error) {
263
+ if ffd.fakeAddr != (fakeSockAddr{}) {
264
+ sockets.CompareAndDelete(ffd.fakeAddr, ffd.fd)
265
+ }
266
+
267
+ if ffd.queue != nil {
268
+ if closeErr := ffd.queue.closeRead(); err == nil {
269
+ err = closeErr
270
+ }
271
+ }
272
+ if ffd.peer != nil {
273
+ if closeErr := ffd.peer.queue.closeWrite(); err == nil {
274
+ err = closeErr
275
+ }
276
+ }
277
+ ffd.readDeadline.Load().Reset(noDeadline)
278
+ ffd.writeDeadline.Load().Reset(noDeadline)
279
+
280
+ if ffd.incoming != nil {
281
+ var (
282
+ incoming []*netFD
283
+ ok bool
284
+ )
285
+ select {
286
+ case _, ok = <-ffd.incomingEmpty:
287
+ case incoming, ok = <-ffd.incoming:
288
+ case incoming, ok = <-ffd.incomingFull:
289
+ }
290
+ if ok {
291
+ // Sends on ffd.incoming require a receive first.
292
+ // Since we successfully received, no other goroutine may
293
+ // send on it at this point, and we may safely close it.
294
+ close(ffd.incoming)
295
+
296
+ for _, c := range incoming {
297
+ c.Close()
298
+ }
299
+ }
300
+ }
301
+
302
+ if ffd.assignedPort != 0 {
303
+ fakePorts.CompareAndDelete(ffd.assignedPort, ffd.fd)
304
+ }
305
+
306
+ return err
307
+ }
308
+
309
+ func (ffd *fakeNetFD) closeRead() error {
310
+ return ffd.queue.closeRead()
311
+ }
312
+
313
+ func (ffd *fakeNetFD) closeWrite() error {
314
+ if ffd.peer == nil {
315
+ return os.NewSyscallError("closeWrite", syscall.ENOTCONN)
316
+ }
317
+ return ffd.peer.queue.closeWrite()
318
+ }
319
+
320
+ func (ffd *fakeNetFD) accept(laddr Addr) (*netFD, error) {
321
+ if ffd.incoming == nil {
322
+ return nil, os.NewSyscallError("accept", syscall.EINVAL)
323
+ }
324
+
325
+ var (
326
+ incoming []*netFD
327
+ ok bool
328
+ )
329
+ select {
330
+ case <-ffd.readDeadline.Load().expired:
331
+ return nil, os.ErrDeadlineExceeded
332
+ case incoming, ok = <-ffd.incoming:
333
+ if !ok {
334
+ return nil, ErrClosed
335
+ }
336
+ case incoming, ok = <-ffd.incomingFull:
337
+ }
338
+
339
+ peer := incoming[0]
340
+ incoming = incoming[1:]
341
+ if len(incoming) == 0 {
342
+ ffd.incomingEmpty <- true
343
+ } else {
344
+ ffd.incoming <- incoming
345
+ }
346
+ return peer, nil
347
+ }
348
+
349
+ func (ffd *fakeNetFD) SetDeadline(t time.Time) error {
350
+ err1 := ffd.SetReadDeadline(t)
351
+ err2 := ffd.SetWriteDeadline(t)
352
+ if err1 != nil {
353
+ return err1
354
+ }
355
+ return err2
356
+ }
357
+
358
+ func (ffd *fakeNetFD) SetReadDeadline(t time.Time) error {
359
+ dt := ffd.readDeadline.Load()
360
+ if !dt.Reset(t) {
361
+ ffd.readDeadline.Store(newDeadlineTimer(t))
362
+ }
363
+ return nil
364
+ }
365
+
366
+ func (ffd *fakeNetFD) SetWriteDeadline(t time.Time) error {
367
+ dt := ffd.writeDeadline.Load()
368
+ if !dt.Reset(t) {
369
+ ffd.writeDeadline.Store(newDeadlineTimer(t))
370
+ }
371
+ return nil
372
+ }
373
+
374
+ const maxPacketSize = 65535
375
+
376
+ type packet struct {
377
+ buf []byte
378
+ bufOffset int
379
+ next *packet
380
+ from sockaddr
381
+ }
382
+
383
+ func (p *packet) clear() {
384
+ p.buf = p.buf[:0]
385
+ p.bufOffset = 0
386
+ p.next = nil
387
+ p.from = nil
388
+ }
389
+
390
+ var packetPool = sync.Pool{
391
+ New: func() any { return new(packet) },
392
+ }
393
+
394
+ type packetQueueState struct {
395
+ head, tail *packet // unqueued packets
396
+ nBytes int // number of bytes enqueued in the packet buffers starting from head
397
+ readBufferBytes int // soft limit on nbytes; no more packets may be enqueued when the limit is exceeded
398
+ readClosed bool // true if the reader of the queue has stopped reading
399
+ writeClosed bool // true if the writer of the queue has stopped writing; the reader sees either io.EOF or syscall.ECONNRESET when they have read all buffered packets
400
+ noLinger bool // if true, the reader sees ECONNRESET instead of EOF
401
+ }
402
+
403
+ // A packetQueue is a set of 1-buffered channels implementing a FIFO queue
404
+ // of packets.
405
+ type packetQueue struct {
406
+ empty chan packetQueueState // contains configuration parameters when the queue is empty and not closed
407
+ ready chan packetQueueState // contains the packets when non-empty or closed
408
+ full chan packetQueueState // contains the packets when buffer is full and not closed
409
+ }
410
+
411
+ func newPacketQueue(readBufferBytes int) *packetQueue {
412
+ pq := &packetQueue{
413
+ empty: make(chan packetQueueState, 1),
414
+ ready: make(chan packetQueueState, 1),
415
+ full: make(chan packetQueueState, 1),
416
+ }
417
+ pq.put(packetQueueState{
418
+ readBufferBytes: readBufferBytes,
419
+ })
420
+ return pq
421
+ }
422
+
423
+ func (pq *packetQueue) get() packetQueueState {
424
+ var q packetQueueState
425
+ select {
426
+ case q = <-pq.empty:
427
+ case q = <-pq.ready:
428
+ case q = <-pq.full:
429
+ }
430
+ return q
431
+ }
432
+
433
+ func (pq *packetQueue) put(q packetQueueState) {
434
+ switch {
435
+ case q.readClosed || q.writeClosed:
436
+ pq.ready <- q
437
+ case q.nBytes >= q.readBufferBytes:
438
+ pq.full <- q
439
+ case q.head == nil:
440
+ if q.nBytes > 0 {
441
+ defer panic("net: put with nil packet list and nonzero nBytes")
442
+ }
443
+ pq.empty <- q
444
+ default:
445
+ pq.ready <- q
446
+ }
447
+ }
448
+
449
+ func (pq *packetQueue) closeRead() error {
450
+ q := pq.get()
451
+
452
+ // Discard any unread packets.
453
+ for q.head != nil {
454
+ p := q.head
455
+ q.head = p.next
456
+ p.clear()
457
+ packetPool.Put(p)
458
+ }
459
+ q.nBytes = 0
460
+
461
+ q.readClosed = true
462
+ pq.put(q)
463
+ return nil
464
+ }
465
+
466
+ func (pq *packetQueue) closeWrite() error {
467
+ q := pq.get()
468
+ q.writeClosed = true
469
+ pq.put(q)
470
+ return nil
471
+ }
472
+
473
+ func (pq *packetQueue) setLinger(linger bool) error {
474
+ q := pq.get()
475
+ defer func() { pq.put(q) }()
476
+
477
+ if q.writeClosed {
478
+ return ErrClosed
479
+ }
480
+ q.noLinger = !linger
481
+ return nil
482
+ }
483
+
484
+ func (pq *packetQueue) write(dt *deadlineTimer, b []byte, from sockaddr) (n int, err error) {
485
+ for {
486
+ dn := len(b)
487
+ if dn > maxPacketSize {
488
+ dn = maxPacketSize
489
+ }
490
+
491
+ dn, err = pq.send(dt, b[:dn], from, true)
492
+ n += dn
493
+ if err != nil {
494
+ return n, err
495
+ }
496
+
497
+ b = b[dn:]
498
+ if len(b) == 0 {
499
+ return n, nil
500
+ }
501
+ }
502
+ }
503
+
504
+ func (pq *packetQueue) send(dt *deadlineTimer, b []byte, from sockaddr, block bool) (n int, err error) {
505
+ if from == nil {
506
+ return 0, os.NewSyscallError("send", syscall.EINVAL)
507
+ }
508
+ if len(b) > maxPacketSize {
509
+ return 0, os.NewSyscallError("send", syscall.EMSGSIZE)
510
+ }
511
+
512
+ var q packetQueueState
513
+ var full chan packetQueueState
514
+ if !block {
515
+ full = pq.full
516
+ }
517
+
518
+ // Before we check dt.expired, yield to other goroutines.
519
+ // This may help to prevent starvation of the goroutine that runs the
520
+ // deadlineTimer's time.After callback.
521
+ //
522
+ // TODO(#65178): Remove this when the runtime scheduler no longer starves
523
+ // runnable goroutines.
524
+ runtime.Gosched()
525
+
526
+ select {
527
+ case <-dt.expired:
528
+ return 0, os.ErrDeadlineExceeded
529
+
530
+ case q = <-full:
531
+ pq.put(q)
532
+ return 0, os.NewSyscallError("send", syscall.ENOBUFS)
533
+
534
+ case q = <-pq.empty:
535
+ case q = <-pq.ready:
536
+ }
537
+ defer func() { pq.put(q) }()
538
+
539
+ // Don't allow a packet to be sent if the deadline has expired,
540
+ // even if the select above chose a different branch.
541
+ select {
542
+ case <-dt.expired:
543
+ return 0, os.ErrDeadlineExceeded
544
+ default:
545
+ }
546
+ if q.writeClosed {
547
+ return 0, ErrClosed
548
+ } else if q.readClosed {
549
+ return 0, os.NewSyscallError("send", syscall.ECONNRESET)
550
+ }
551
+
552
+ p := packetPool.Get().(*packet)
553
+ p.buf = append(p.buf[:0], b...)
554
+ p.from = from
555
+
556
+ if q.head == nil {
557
+ q.head = p
558
+ } else {
559
+ q.tail.next = p
560
+ }
561
+ q.tail = p
562
+ q.nBytes += len(p.buf)
563
+
564
+ return len(b), nil
565
+ }
566
+
567
+ func (pq *packetQueue) recvfrom(dt *deadlineTimer, b []byte, wholePacket bool, checkFrom func(sockaddr) error) (n int, from sockaddr, err error) {
568
+ var q packetQueueState
569
+ var empty chan packetQueueState
570
+ if len(b) == 0 {
571
+ // For consistency with the implementation on Unix platforms,
572
+ // allow a zero-length Read to proceed if the queue is empty.
573
+ // (Without this, TestZeroByteRead deadlocks.)
574
+ empty = pq.empty
575
+ }
576
+
577
+ // Before we check dt.expired, yield to other goroutines.
578
+ // This may help to prevent starvation of the goroutine that runs the
579
+ // deadlineTimer's time.After callback.
580
+ //
581
+ // TODO(#65178): Remove this when the runtime scheduler no longer starves
582
+ // runnable goroutines.
583
+ runtime.Gosched()
584
+
585
+ select {
586
+ case <-dt.expired:
587
+ return 0, nil, os.ErrDeadlineExceeded
588
+ case q = <-empty:
589
+ case q = <-pq.ready:
590
+ case q = <-pq.full:
591
+ }
592
+ defer func() { pq.put(q) }()
593
+
594
+ p := q.head
595
+ if p == nil {
596
+ switch {
597
+ case q.readClosed:
598
+ return 0, nil, ErrClosed
599
+ case q.writeClosed:
600
+ if q.noLinger {
601
+ return 0, nil, os.NewSyscallError("recvfrom", syscall.ECONNRESET)
602
+ }
603
+ return 0, nil, io.EOF
604
+ case len(b) == 0:
605
+ return 0, nil, nil
606
+ default:
607
+ // This should be impossible: pq.full should only contain a non-empty list,
608
+ // pq.ready should either contain a non-empty list or indicate that the
609
+ // connection is closed, and we should only receive from pq.empty if
610
+ // len(b) == 0.
611
+ panic("net: nil packet list from non-closed packetQueue")
612
+ }
613
+ }
614
+
615
+ select {
616
+ case <-dt.expired:
617
+ return 0, nil, os.ErrDeadlineExceeded
618
+ default:
619
+ }
620
+
621
+ if checkFrom != nil {
622
+ if err := checkFrom(p.from); err != nil {
623
+ return 0, nil, err
624
+ }
625
+ }
626
+
627
+ n = copy(b, p.buf[p.bufOffset:])
628
+ from = p.from
629
+ if wholePacket || p.bufOffset+n == len(p.buf) {
630
+ q.head = p.next
631
+ q.nBytes -= len(p.buf)
632
+ p.clear()
633
+ packetPool.Put(p)
634
+ } else {
635
+ p.bufOffset += n
636
+ }
637
+
638
+ return n, from, nil
639
+ }
640
+
641
+ // setReadBuffer sets a soft limit on the number of bytes available to read
642
+ // from the pipe.
643
+ func (pq *packetQueue) setReadBuffer(bytes int) error {
644
+ if bytes <= 0 {
645
+ return os.NewSyscallError("setReadBuffer", syscall.EINVAL)
646
+ }
647
+ q := pq.get() // Use the queue as a lock.
648
+ q.readBufferBytes = bytes
649
+ pq.put(q)
650
+ return nil
651
+ }
652
+
653
+ type deadlineTimer struct {
654
+ timer chan *time.Timer
655
+ expired chan struct{}
656
+ }
657
+
658
+ func newDeadlineTimer(deadline time.Time) *deadlineTimer {
659
+ dt := &deadlineTimer{
660
+ timer: make(chan *time.Timer, 1),
661
+ expired: make(chan struct{}),
662
+ }
663
+ dt.timer <- nil
664
+ dt.Reset(deadline)
665
+ return dt
666
+ }
667
+
668
+ // Reset attempts to reset the timer.
669
+ // If the timer has already expired, Reset returns false.
670
+ func (dt *deadlineTimer) Reset(deadline time.Time) bool {
671
+ timer := <-dt.timer
672
+ defer func() { dt.timer <- timer }()
673
+
674
+ if deadline.Equal(noDeadline) {
675
+ if timer != nil && timer.Stop() {
676
+ timer = nil
677
+ }
678
+ return timer == nil
679
+ }
680
+
681
+ d := time.Until(deadline)
682
+ if d < 0 {
683
+ // Ensure that a deadline in the past takes effect immediately.
684
+ defer func() { <-dt.expired }()
685
+ }
686
+
687
+ if timer == nil {
688
+ timer = time.AfterFunc(d, func() { close(dt.expired) })
689
+ return true
690
+ }
691
+ if !timer.Stop() {
692
+ return false
693
+ }
694
+ timer.Reset(d)
695
+ return true
696
+ }
697
+
698
+ func sysSocket(family, sotype, proto int) (int, error) {
699
+ return 0, os.NewSyscallError("sysSocket", syscall.ENOSYS)
700
+ }
701
+
702
+ func fakeListen(fd *netFD, laddr sockaddr) (err error) {
703
+ wrapErr := func(err error) error {
704
+ if errno, ok := err.(syscall.Errno); ok {
705
+ err = os.NewSyscallError("listen", errno)
706
+ }
707
+ if errors.Is(err, syscall.EADDRINUSE) {
708
+ return err
709
+ }
710
+ if laddr != nil {
711
+ if _, ok := err.(*AddrError); !ok {
712
+ err = &AddrError{
713
+ Err: err.Error(),
714
+ Addr: laddr.String(),
715
+ }
716
+ }
717
+ }
718
+ return err
719
+ }
720
+
721
+ ffd := newFakeNetFD(fd)
722
+ defer func() {
723
+ if fd.fakeNetFD != ffd {
724
+ // Failed to register listener; clean up.
725
+ ffd.Close()
726
+ }
727
+ }()
728
+
729
+ if err := ffd.assignFakeAddr(matchIPFamily(fd.family, laddr)); err != nil {
730
+ return wrapErr(err)
731
+ }
732
+
733
+ ffd.fakeAddr = fakeAddr(fd.laddr.(sockaddr))
734
+ switch fd.sotype {
735
+ case syscall.SOCK_STREAM, syscall.SOCK_SEQPACKET:
736
+ ffd.incoming = make(chan []*netFD, 1)
737
+ ffd.incomingFull = make(chan []*netFD, 1)
738
+ ffd.incomingEmpty = make(chan bool, 1)
739
+ ffd.incomingEmpty <- true
740
+ case syscall.SOCK_DGRAM:
741
+ ffd.queue = newPacketQueue(defaultBuffer)
742
+ default:
743
+ return wrapErr(syscall.EINVAL)
744
+ }
745
+
746
+ fd.fakeNetFD = ffd
747
+ if _, dup := sockets.LoadOrStore(ffd.fakeAddr, fd); dup {
748
+ fd.fakeNetFD = nil
749
+ return wrapErr(syscall.EADDRINUSE)
750
+ }
751
+
752
+ return nil
753
+ }
754
+
755
+ func fakeConnect(ctx context.Context, fd *netFD, laddr, raddr sockaddr) error {
756
+ wrapErr := func(err error) error {
757
+ if errno, ok := err.(syscall.Errno); ok {
758
+ err = os.NewSyscallError("connect", errno)
759
+ }
760
+ if errors.Is(err, syscall.EADDRINUSE) {
761
+ return err
762
+ }
763
+ if terr, ok := err.(interface{ Timeout() bool }); !ok || !terr.Timeout() {
764
+ // For consistency with the net implementation on other platforms,
765
+ // if we don't need to preserve the Timeout-ness of err we should
766
+ // wrap it in an AddrError. (Unfortunately we can't wrap errors
767
+ // that convey structured information, because AddrError reduces
768
+ // the wrapped Err to a flat string.)
769
+ if _, ok := err.(*AddrError); !ok {
770
+ err = &AddrError{
771
+ Err: err.Error(),
772
+ Addr: raddr.String(),
773
+ }
774
+ }
775
+ }
776
+ return err
777
+ }
778
+
779
+ if fd.isConnected {
780
+ return wrapErr(syscall.EISCONN)
781
+ }
782
+ if ctx.Err() != nil {
783
+ return wrapErr(syscall.ETIMEDOUT)
784
+ }
785
+
786
+ fd.raddr = matchIPFamily(fd.family, raddr)
787
+ if err := validateResolvedAddr(fd.net, fd.family, fd.raddr.(sockaddr)); err != nil {
788
+ return wrapErr(err)
789
+ }
790
+
791
+ if err := fd.fakeNetFD.assignFakeAddr(laddr); err != nil {
792
+ return wrapErr(err)
793
+ }
794
+ fd.fakeNetFD.queue = newPacketQueue(defaultBuffer)
795
+
796
+ switch fd.sotype {
797
+ case syscall.SOCK_DGRAM:
798
+ if ua, ok := fd.laddr.(*UnixAddr); !ok || ua.Name != "" {
799
+ fd.fakeNetFD.fakeAddr = fakeAddr(fd.laddr.(sockaddr))
800
+ if _, dup := sockets.LoadOrStore(fd.fakeNetFD.fakeAddr, fd); dup {
801
+ return wrapErr(syscall.EADDRINUSE)
802
+ }
803
+ }
804
+ fd.isConnected = true
805
+ return nil
806
+
807
+ case syscall.SOCK_STREAM, syscall.SOCK_SEQPACKET:
808
+ default:
809
+ return wrapErr(syscall.EINVAL)
810
+ }
811
+
812
+ fa := fakeAddr(raddr)
813
+ lni, ok := sockets.Load(fa)
814
+ if !ok {
815
+ return wrapErr(syscall.ECONNREFUSED)
816
+ }
817
+ ln := lni.(*netFD)
818
+ if ln.sotype != fd.sotype {
819
+ return wrapErr(syscall.EPROTOTYPE)
820
+ }
821
+ if ln.incoming == nil {
822
+ return wrapErr(syscall.ECONNREFUSED)
823
+ }
824
+
825
+ peer := &netFD{
826
+ family: ln.family,
827
+ sotype: ln.sotype,
828
+ net: ln.net,
829
+ laddr: ln.laddr,
830
+ raddr: fd.laddr,
831
+ isConnected: true,
832
+ }
833
+ peer.fakeNetFD = newFakeNetFD(fd)
834
+ peer.fakeNetFD.queue = newPacketQueue(defaultBuffer)
835
+ defer func() {
836
+ if fd.peer != peer {
837
+ // Failed to connect; clean up.
838
+ peer.Close()
839
+ }
840
+ }()
841
+
842
+ var incoming []*netFD
843
+ select {
844
+ case <-ctx.Done():
845
+ return wrapErr(syscall.ETIMEDOUT)
846
+ case ok = <-ln.incomingEmpty:
847
+ case incoming, ok = <-ln.incoming:
848
+ }
849
+ if !ok {
850
+ return wrapErr(syscall.ECONNREFUSED)
851
+ }
852
+
853
+ fd.isConnected = true
854
+ fd.peer = peer
855
+ peer.peer = fd
856
+
857
+ incoming = append(incoming, peer)
858
+ if len(incoming) >= listenerBacklog() {
859
+ ln.incomingFull <- incoming
860
+ } else {
861
+ ln.incoming <- incoming
862
+ }
863
+ return nil
864
+ }
865
+
866
+ func (ffd *fakeNetFD) assignFakeAddr(addr sockaddr) error {
867
+ validate := func(sa sockaddr) error {
868
+ if err := validateResolvedAddr(ffd.fd.net, ffd.fd.family, sa); err != nil {
869
+ return err
870
+ }
871
+ ffd.fd.laddr = sa
872
+ return nil
873
+ }
874
+
875
+ assignIP := func(addr sockaddr) error {
876
+ var (
877
+ ip IP
878
+ port int
879
+ zone string
880
+ )
881
+ switch addr := addr.(type) {
882
+ case *TCPAddr:
883
+ if addr != nil {
884
+ ip = addr.IP
885
+ port = addr.Port
886
+ zone = addr.Zone
887
+ }
888
+ case *UDPAddr:
889
+ if addr != nil {
890
+ ip = addr.IP
891
+ port = addr.Port
892
+ zone = addr.Zone
893
+ }
894
+ default:
895
+ return validate(addr)
896
+ }
897
+
898
+ if ip == nil {
899
+ ip = IPv4(127, 0, 0, 1)
900
+ }
901
+ switch ffd.fd.family {
902
+ case syscall.AF_INET:
903
+ if ip4 := ip.To4(); ip4 != nil {
904
+ ip = ip4
905
+ }
906
+ case syscall.AF_INET6:
907
+ if ip16 := ip.To16(); ip16 != nil {
908
+ ip = ip16
909
+ }
910
+ }
911
+ if ip == nil {
912
+ return syscall.EINVAL
913
+ }
914
+
915
+ if port == 0 {
916
+ var prevPort int32
917
+ portWrapped := false
918
+ nextPort := func() (int, bool) {
919
+ for {
920
+ port := nextPortCounter.Add(1)
921
+ if port <= 0 || port >= 1<<16 {
922
+ // nextPortCounter ran off the end of the port space.
923
+ // Bump it back into range.
924
+ for {
925
+ if nextPortCounter.CompareAndSwap(port, 0) {
926
+ break
927
+ }
928
+ if port = nextPortCounter.Load(); port >= 0 && port < 1<<16 {
929
+ break
930
+ }
931
+ }
932
+ if portWrapped {
933
+ // This is the second wraparound, so we've scanned the whole port space
934
+ // at least once already and it's time to give up.
935
+ return 0, false
936
+ }
937
+ portWrapped = true
938
+ prevPort = 0
939
+ continue
940
+ }
941
+
942
+ if port <= prevPort {
943
+ // nextPortCounter has wrapped around since the last time we read it.
944
+ if portWrapped {
945
+ // This is the second wraparound, so we've scanned the whole port space
946
+ // at least once already and it's time to give up.
947
+ return 0, false
948
+ } else {
949
+ portWrapped = true
950
+ }
951
+ }
952
+
953
+ prevPort = port
954
+ return int(port), true
955
+ }
956
+ }
957
+
958
+ for {
959
+ var ok bool
960
+ port, ok = nextPort()
961
+ if !ok {
962
+ ffd.assignedPort = 0
963
+ return syscall.EADDRINUSE
964
+ }
965
+
966
+ ffd.assignedPort = int(port)
967
+ if _, dup := fakePorts.LoadOrStore(ffd.assignedPort, ffd.fd); !dup {
968
+ break
969
+ }
970
+ }
971
+ }
972
+
973
+ switch addr.(type) {
974
+ case *TCPAddr:
975
+ return validate(&TCPAddr{IP: ip, Port: port, Zone: zone})
976
+ case *UDPAddr:
977
+ return validate(&UDPAddr{IP: ip, Port: port, Zone: zone})
978
+ default:
979
+ panic("unreachable")
980
+ }
981
+ }
982
+
983
+ switch ffd.fd.net {
984
+ case "tcp", "tcp4", "tcp6":
985
+ if addr == nil {
986
+ return assignIP(new(TCPAddr))
987
+ }
988
+ return assignIP(addr)
989
+
990
+ case "udp", "udp4", "udp6":
991
+ if addr == nil {
992
+ return assignIP(new(UDPAddr))
993
+ }
994
+ return assignIP(addr)
995
+
996
+ case "unix", "unixgram", "unixpacket":
997
+ uaddr, ok := addr.(*UnixAddr)
998
+ if !ok && addr != nil {
999
+ return &AddrError{
1000
+ Err: "non-Unix address for " + ffd.fd.net + " network",
1001
+ Addr: addr.String(),
1002
+ }
1003
+ }
1004
+ if uaddr == nil {
1005
+ return validate(&UnixAddr{Net: ffd.fd.net})
1006
+ }
1007
+ return validate(&UnixAddr{Net: ffd.fd.net, Name: uaddr.Name})
1008
+
1009
+ default:
1010
+ return &AddrError{
1011
+ Err: syscall.EAFNOSUPPORT.Error(),
1012
+ Addr: addr.String(),
1013
+ }
1014
+ }
1015
+ }
1016
+
1017
+ func (ffd *fakeNetFD) readFrom(p []byte) (n int, sa syscall.Sockaddr, err error) {
1018
+ if ffd.queue == nil {
1019
+ return 0, nil, os.NewSyscallError("readFrom", syscall.EINVAL)
1020
+ }
1021
+
1022
+ n, from, err := ffd.queue.recvfrom(ffd.readDeadline.Load(), p, true, nil)
1023
+
1024
+ if from != nil {
1025
+ // Convert the net.sockaddr to a syscall.Sockaddr type.
1026
+ var saErr error
1027
+ sa, saErr = from.sockaddr(ffd.fd.family)
1028
+ if err == nil {
1029
+ err = saErr
1030
+ }
1031
+ }
1032
+
1033
+ return n, sa, err
1034
+ }
1035
+
1036
+ func (ffd *fakeNetFD) readFromInet4(p []byte, sa *syscall.SockaddrInet4) (n int, err error) {
1037
+ n, _, err = ffd.queue.recvfrom(ffd.readDeadline.Load(), p, true, func(from sockaddr) error {
1038
+ fromSA, err := from.sockaddr(syscall.AF_INET)
1039
+ if err != nil {
1040
+ return err
1041
+ }
1042
+ if fromSA == nil {
1043
+ return os.NewSyscallError("readFromInet4", syscall.EINVAL)
1044
+ }
1045
+ *sa = *(fromSA.(*syscall.SockaddrInet4))
1046
+ return nil
1047
+ })
1048
+ return n, err
1049
+ }
1050
+
1051
+ func (ffd *fakeNetFD) readFromInet6(p []byte, sa *syscall.SockaddrInet6) (n int, err error) {
1052
+ n, _, err = ffd.queue.recvfrom(ffd.readDeadline.Load(), p, true, func(from sockaddr) error {
1053
+ fromSA, err := from.sockaddr(syscall.AF_INET6)
1054
+ if err != nil {
1055
+ return err
1056
+ }
1057
+ if fromSA == nil {
1058
+ return os.NewSyscallError("readFromInet6", syscall.EINVAL)
1059
+ }
1060
+ *sa = *(fromSA.(*syscall.SockaddrInet6))
1061
+ return nil
1062
+ })
1063
+ return n, err
1064
+ }
1065
+
1066
+ func (ffd *fakeNetFD) readMsg(p []byte, oob []byte, flags int) (n, oobn, retflags int, sa syscall.Sockaddr, err error) {
1067
+ if flags != 0 {
1068
+ return 0, 0, 0, nil, os.NewSyscallError("readMsg", syscall.ENOTSUP)
1069
+ }
1070
+ n, sa, err = ffd.readFrom(p)
1071
+ return n, 0, 0, sa, err
1072
+ }
1073
+
1074
+ func (ffd *fakeNetFD) readMsgInet4(p []byte, oob []byte, flags int, sa *syscall.SockaddrInet4) (n, oobn, retflags int, err error) {
1075
+ if flags != 0 {
1076
+ return 0, 0, 0, os.NewSyscallError("readMsgInet4", syscall.ENOTSUP)
1077
+ }
1078
+ n, err = ffd.readFromInet4(p, sa)
1079
+ return n, 0, 0, err
1080
+ }
1081
+
1082
+ func (ffd *fakeNetFD) readMsgInet6(p []byte, oob []byte, flags int, sa *syscall.SockaddrInet6) (n, oobn, retflags int, err error) {
1083
+ if flags != 0 {
1084
+ return 0, 0, 0, os.NewSyscallError("readMsgInet6", syscall.ENOTSUP)
1085
+ }
1086
+ n, err = ffd.readFromInet6(p, sa)
1087
+ return n, 0, 0, err
1088
+ }
1089
+
1090
+ func (ffd *fakeNetFD) writeMsg(p []byte, oob []byte, sa syscall.Sockaddr) (n int, oobn int, err error) {
1091
+ if len(oob) > 0 {
1092
+ return 0, 0, os.NewSyscallError("writeMsg", syscall.ENOTSUP)
1093
+ }
1094
+ n, err = ffd.writeTo(p, sa)
1095
+ return n, 0, err
1096
+ }
1097
+
1098
+ func (ffd *fakeNetFD) writeMsgInet4(p []byte, oob []byte, sa *syscall.SockaddrInet4) (n int, oobn int, err error) {
1099
+ return ffd.writeMsg(p, oob, sa)
1100
+ }
1101
+
1102
+ func (ffd *fakeNetFD) writeMsgInet6(p []byte, oob []byte, sa *syscall.SockaddrInet6) (n int, oobn int, err error) {
1103
+ return ffd.writeMsg(p, oob, sa)
1104
+ }
1105
+
1106
+ func (ffd *fakeNetFD) writeTo(p []byte, sa syscall.Sockaddr) (n int, err error) {
1107
+ raddr := ffd.fd.raddr
1108
+ if sa != nil {
1109
+ if ffd.fd.isConnected {
1110
+ return 0, os.NewSyscallError("writeTo", syscall.EISCONN)
1111
+ }
1112
+ raddr = ffd.fd.addrFunc()(sa)
1113
+ }
1114
+ if raddr == nil {
1115
+ return 0, os.NewSyscallError("writeTo", syscall.EINVAL)
1116
+ }
1117
+
1118
+ peeri, _ := sockets.Load(fakeAddr(raddr.(sockaddr)))
1119
+ if peeri == nil {
1120
+ if len(ffd.fd.net) >= 3 && ffd.fd.net[:3] == "udp" {
1121
+ return len(p), nil
1122
+ }
1123
+ return 0, os.NewSyscallError("writeTo", syscall.ECONNRESET)
1124
+ }
1125
+ peer := peeri.(*netFD)
1126
+ if peer.queue == nil {
1127
+ if len(ffd.fd.net) >= 3 && ffd.fd.net[:3] == "udp" {
1128
+ return len(p), nil
1129
+ }
1130
+ return 0, os.NewSyscallError("writeTo", syscall.ECONNRESET)
1131
+ }
1132
+
1133
+ block := true
1134
+ if len(ffd.fd.net) >= 3 && ffd.fd.net[:3] == "udp" {
1135
+ block = false
1136
+ }
1137
+ return peer.queue.send(ffd.writeDeadline.Load(), p, ffd.fd.laddr.(sockaddr), block)
1138
+ }
1139
+
1140
+ func (ffd *fakeNetFD) writeToInet4(p []byte, sa *syscall.SockaddrInet4) (n int, err error) {
1141
+ return ffd.writeTo(p, sa)
1142
+ }
1143
+
1144
+ func (ffd *fakeNetFD) writeToInet6(p []byte, sa *syscall.SockaddrInet6) (n int, err error) {
1145
+ return ffd.writeTo(p, sa)
1146
+ }
1147
+
1148
+ func (ffd *fakeNetFD) dup() (f *os.File, err error) {
1149
+ return nil, os.NewSyscallError("dup", syscall.ENOSYS)
1150
+ }
1151
+
1152
+ func (ffd *fakeNetFD) setReadBuffer(bytes int) error {
1153
+ if ffd.queue == nil {
1154
+ return os.NewSyscallError("setReadBuffer", syscall.EINVAL)
1155
+ }
1156
+ ffd.queue.setReadBuffer(bytes)
1157
+ return nil
1158
+ }
1159
+
1160
+ func (ffd *fakeNetFD) setWriteBuffer(bytes int) error {
1161
+ return os.NewSyscallError("setWriteBuffer", syscall.ENOTSUP)
1162
+ }
1163
+
1164
+ func (ffd *fakeNetFD) setLinger(sec int) error {
1165
+ if sec < 0 || ffd.peer == nil {
1166
+ return os.NewSyscallError("setLinger", syscall.EINVAL)
1167
+ }
1168
+ ffd.peer.queue.setLinger(sec > 0)
1169
+ return nil
1170
+ }
platform/dbops/binaries/go/go/src/net/net_fake_test.go ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 || wasip1
6
+
7
+ package net
8
+
9
+ // GOOS=js and GOOS=wasip1 do not have typical socket networking capabilities
10
+ // found on other platforms. To help run test suites of the stdlib packages,
11
+ // an in-memory "fake network" facility is implemented.
12
+ //
13
+ // The tests in this files are intended to validate the behavior of the fake
14
+ // network stack on these platforms.
15
+
16
+ import (
17
+ "errors"
18
+ "syscall"
19
+ "testing"
20
+ )
21
+
22
+ func TestFakePortExhaustion(t *testing.T) {
23
+ if testing.Short() {
24
+ t.Skipf("skipping test that opens 1<<16 connections")
25
+ }
26
+
27
+ ln := newLocalListener(t, "tcp")
28
+ done := make(chan struct{})
29
+ go func() {
30
+ var accepted []Conn
31
+ defer func() {
32
+ for _, c := range accepted {
33
+ c.Close()
34
+ }
35
+ close(done)
36
+ }()
37
+
38
+ for {
39
+ c, err := ln.Accept()
40
+ if err != nil {
41
+ return
42
+ }
43
+ accepted = append(accepted, c)
44
+ }
45
+ }()
46
+
47
+ var dialed []Conn
48
+ defer func() {
49
+ ln.Close()
50
+ for _, c := range dialed {
51
+ c.Close()
52
+ }
53
+ <-done
54
+ }()
55
+
56
+ // Since this test is not running in parallel, we expect to be able to open
57
+ // all 65535 valid (fake) ports. The listener is already using one, so
58
+ // we should be able to Dial the remaining 65534.
59
+ for len(dialed) < (1<<16)-2 {
60
+ c, err := Dial(ln.Addr().Network(), ln.Addr().String())
61
+ if err != nil {
62
+ t.Fatalf("unexpected error from Dial with %v connections: %v", len(dialed), err)
63
+ }
64
+ dialed = append(dialed, c)
65
+ if testing.Verbose() && len(dialed)%(1<<12) == 0 {
66
+ t.Logf("dialed %d connections", len(dialed))
67
+ }
68
+ }
69
+ t.Logf("dialed %d connections", len(dialed))
70
+
71
+ // Now that all of the ports are in use, dialing another should fail due
72
+ // to port exhaustion, which (for POSIX-like socket APIs) should return
73
+ // an EADDRINUSE error.
74
+ c, err := Dial(ln.Addr().Network(), ln.Addr().String())
75
+ if err == nil {
76
+ c.Close()
77
+ }
78
+ if errors.Is(err, syscall.EADDRINUSE) {
79
+ t.Logf("Dial returned expected error: %v", err)
80
+ } else {
81
+ t.Errorf("unexpected error from Dial: %v\nwant: %v", err, syscall.EADDRINUSE)
82
+ }
83
+
84
+ // Opening a Listener should fail at this point too.
85
+ ln2, err := Listen("tcp", "localhost:0")
86
+ if err == nil {
87
+ ln2.Close()
88
+ }
89
+ if errors.Is(err, syscall.EADDRINUSE) {
90
+ t.Logf("Listen returned expected error: %v", err)
91
+ } else {
92
+ t.Errorf("unexpected error from Listen: %v\nwant: %v", err, syscall.EADDRINUSE)
93
+ }
94
+
95
+ // When we close an arbitrary connection, we should be able to reuse its port
96
+ // even if the server hasn't yet seen the ECONNRESET for the connection.
97
+ dialed[0].Close()
98
+ dialed = dialed[1:]
99
+ t.Logf("closed one connection")
100
+ c, err = Dial(ln.Addr().Network(), ln.Addr().String())
101
+ if err == nil {
102
+ c.Close()
103
+ t.Logf("Dial succeeded")
104
+ } else {
105
+ t.Errorf("unexpected error from Dial: %v", err)
106
+ }
107
+ }
platform/dbops/binaries/go/go/src/net/net_test.go ADDED
@@ -0,0 +1,601 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "errors"
9
+ "fmt"
10
+ "io"
11
+ "net/internal/socktest"
12
+ "os"
13
+ "runtime"
14
+ "testing"
15
+ "time"
16
+ )
17
+
18
+ func TestCloseRead(t *testing.T) {
19
+ switch runtime.GOOS {
20
+ case "plan9":
21
+ t.Skipf("not supported on %s", runtime.GOOS)
22
+ }
23
+ t.Parallel()
24
+
25
+ for _, network := range []string{"tcp", "unix", "unixpacket"} {
26
+ network := network
27
+ t.Run(network, func(t *testing.T) {
28
+ if !testableNetwork(network) {
29
+ t.Skipf("network %s is not testable on the current platform", network)
30
+ }
31
+ t.Parallel()
32
+
33
+ ln := newLocalListener(t, network)
34
+ switch network {
35
+ case "unix", "unixpacket":
36
+ defer os.Remove(ln.Addr().String())
37
+ }
38
+ defer ln.Close()
39
+
40
+ c, err := Dial(ln.Addr().Network(), ln.Addr().String())
41
+ if err != nil {
42
+ t.Fatal(err)
43
+ }
44
+ switch network {
45
+ case "unix", "unixpacket":
46
+ defer os.Remove(c.LocalAddr().String())
47
+ }
48
+ defer c.Close()
49
+
50
+ switch c := c.(type) {
51
+ case *TCPConn:
52
+ err = c.CloseRead()
53
+ case *UnixConn:
54
+ err = c.CloseRead()
55
+ }
56
+ if err != nil {
57
+ if perr := parseCloseError(err, true); perr != nil {
58
+ t.Error(perr)
59
+ }
60
+ t.Fatal(err)
61
+ }
62
+ var b [1]byte
63
+ n, err := c.Read(b[:])
64
+ if n != 0 || err == nil {
65
+ t.Fatalf("got (%d, %v); want (0, error)", n, err)
66
+ }
67
+ })
68
+ }
69
+ }
70
+
71
+ func TestCloseWrite(t *testing.T) {
72
+ switch runtime.GOOS {
73
+ case "plan9":
74
+ t.Skipf("not supported on %s", runtime.GOOS)
75
+ }
76
+
77
+ t.Parallel()
78
+ deadline, _ := t.Deadline()
79
+ if !deadline.IsZero() {
80
+ // Leave 10% headroom on the deadline to report errors and clean up.
81
+ deadline = deadline.Add(-time.Until(deadline) / 10)
82
+ }
83
+
84
+ for _, network := range []string{"tcp", "unix", "unixpacket"} {
85
+ network := network
86
+ t.Run(network, func(t *testing.T) {
87
+ if !testableNetwork(network) {
88
+ t.Skipf("network %s is not testable on the current platform", network)
89
+ }
90
+ t.Parallel()
91
+
92
+ handler := func(ls *localServer, ln Listener) {
93
+ c, err := ln.Accept()
94
+ if err != nil {
95
+ t.Error(err)
96
+ return
97
+ }
98
+
99
+ // Workaround for https://go.dev/issue/49352.
100
+ // On arm64 macOS (current as of macOS 12.4),
101
+ // reading from a socket at the same time as the client
102
+ // is closing it occasionally hangs for 60 seconds before
103
+ // returning ECONNRESET. Sleep for a bit to give the
104
+ // socket time to close before trying to read from it.
105
+ if runtime.GOOS == "darwin" && runtime.GOARCH == "arm64" {
106
+ time.Sleep(10 * time.Millisecond)
107
+ }
108
+
109
+ if !deadline.IsZero() {
110
+ c.SetDeadline(deadline)
111
+ }
112
+ defer c.Close()
113
+
114
+ var b [1]byte
115
+ n, err := c.Read(b[:])
116
+ if n != 0 || err != io.EOF {
117
+ t.Errorf("got (%d, %v); want (0, io.EOF)", n, err)
118
+ return
119
+ }
120
+ switch c := c.(type) {
121
+ case *TCPConn:
122
+ err = c.CloseWrite()
123
+ case *UnixConn:
124
+ err = c.CloseWrite()
125
+ }
126
+ if err != nil {
127
+ if perr := parseCloseError(err, true); perr != nil {
128
+ t.Error(perr)
129
+ }
130
+ t.Error(err)
131
+ return
132
+ }
133
+ n, err = c.Write(b[:])
134
+ if err == nil {
135
+ t.Errorf("got (%d, %v); want (any, error)", n, err)
136
+ return
137
+ }
138
+ }
139
+
140
+ ls := newLocalServer(t, network)
141
+ defer ls.teardown()
142
+ if err := ls.buildup(handler); err != nil {
143
+ t.Fatal(err)
144
+ }
145
+
146
+ c, err := Dial(ls.Listener.Addr().Network(), ls.Listener.Addr().String())
147
+ if err != nil {
148
+ t.Fatal(err)
149
+ }
150
+ if !deadline.IsZero() {
151
+ c.SetDeadline(deadline)
152
+ }
153
+ switch network {
154
+ case "unix", "unixpacket":
155
+ defer os.Remove(c.LocalAddr().String())
156
+ }
157
+ defer c.Close()
158
+
159
+ switch c := c.(type) {
160
+ case *TCPConn:
161
+ err = c.CloseWrite()
162
+ case *UnixConn:
163
+ err = c.CloseWrite()
164
+ }
165
+ if err != nil {
166
+ if perr := parseCloseError(err, true); perr != nil {
167
+ t.Error(perr)
168
+ }
169
+ t.Fatal(err)
170
+ }
171
+ var b [1]byte
172
+ n, err := c.Read(b[:])
173
+ if n != 0 || err != io.EOF {
174
+ t.Fatalf("got (%d, %v); want (0, io.EOF)", n, err)
175
+ }
176
+ n, err = c.Write(b[:])
177
+ if err == nil {
178
+ t.Fatalf("got (%d, %v); want (any, error)", n, err)
179
+ }
180
+ })
181
+ }
182
+ }
183
+
184
+ func TestConnClose(t *testing.T) {
185
+ t.Parallel()
186
+ for _, network := range []string{"tcp", "unix", "unixpacket"} {
187
+ network := network
188
+ t.Run(network, func(t *testing.T) {
189
+ if !testableNetwork(network) {
190
+ t.Skipf("network %s is not testable on the current platform", network)
191
+ }
192
+ t.Parallel()
193
+
194
+ ln := newLocalListener(t, network)
195
+ switch network {
196
+ case "unix", "unixpacket":
197
+ defer os.Remove(ln.Addr().String())
198
+ }
199
+ defer ln.Close()
200
+
201
+ c, err := Dial(ln.Addr().Network(), ln.Addr().String())
202
+ if err != nil {
203
+ t.Fatal(err)
204
+ }
205
+ switch network {
206
+ case "unix", "unixpacket":
207
+ defer os.Remove(c.LocalAddr().String())
208
+ }
209
+ defer c.Close()
210
+
211
+ if err := c.Close(); err != nil {
212
+ if perr := parseCloseError(err, false); perr != nil {
213
+ t.Error(perr)
214
+ }
215
+ t.Fatal(err)
216
+ }
217
+ var b [1]byte
218
+ n, err := c.Read(b[:])
219
+ if n != 0 || err == nil {
220
+ t.Fatalf("got (%d, %v); want (0, error)", n, err)
221
+ }
222
+ })
223
+ }
224
+ }
225
+
226
+ func TestListenerClose(t *testing.T) {
227
+ t.Parallel()
228
+ for _, network := range []string{"tcp", "unix", "unixpacket"} {
229
+ network := network
230
+ t.Run(network, func(t *testing.T) {
231
+ if !testableNetwork(network) {
232
+ t.Skipf("network %s is not testable on the current platform", network)
233
+ }
234
+ t.Parallel()
235
+
236
+ ln := newLocalListener(t, network)
237
+ switch network {
238
+ case "unix", "unixpacket":
239
+ defer os.Remove(ln.Addr().String())
240
+ }
241
+
242
+ if err := ln.Close(); err != nil {
243
+ if perr := parseCloseError(err, false); perr != nil {
244
+ t.Error(perr)
245
+ }
246
+ t.Fatal(err)
247
+ }
248
+ c, err := ln.Accept()
249
+ if err == nil {
250
+ c.Close()
251
+ t.Fatal("should fail")
252
+ }
253
+
254
+ // Note: we cannot ensure that a subsequent Dial does not succeed, because
255
+ // we do not in general have any guarantee that ln.Addr is not immediately
256
+ // reused. (TCP sockets enter a TIME_WAIT state when closed, but that only
257
+ // applies to existing connections for the port — it does not prevent the
258
+ // port itself from being used for entirely new connections in the
259
+ // meantime.)
260
+ })
261
+ }
262
+ }
263
+
264
+ func TestPacketConnClose(t *testing.T) {
265
+ t.Parallel()
266
+ for _, network := range []string{"udp", "unixgram"} {
267
+ network := network
268
+ t.Run(network, func(t *testing.T) {
269
+ if !testableNetwork(network) {
270
+ t.Skipf("network %s is not testable on the current platform", network)
271
+ }
272
+ t.Parallel()
273
+
274
+ c := newLocalPacketListener(t, network)
275
+ switch network {
276
+ case "unixgram":
277
+ defer os.Remove(c.LocalAddr().String())
278
+ }
279
+ defer c.Close()
280
+
281
+ if err := c.Close(); err != nil {
282
+ if perr := parseCloseError(err, false); perr != nil {
283
+ t.Error(perr)
284
+ }
285
+ t.Fatal(err)
286
+ }
287
+ var b [1]byte
288
+ n, _, err := c.ReadFrom(b[:])
289
+ if n != 0 || err == nil {
290
+ t.Fatalf("got (%d, %v); want (0, error)", n, err)
291
+ }
292
+ })
293
+ }
294
+ }
295
+
296
+ func TestListenCloseListen(t *testing.T) {
297
+ const maxTries = 10
298
+ for tries := 0; tries < maxTries; tries++ {
299
+ ln := newLocalListener(t, "tcp")
300
+ addr := ln.Addr().String()
301
+ // TODO: This is racy. The selected address could be reused in between this
302
+ // Close and the subsequent Listen.
303
+ if err := ln.Close(); err != nil {
304
+ if perr := parseCloseError(err, false); perr != nil {
305
+ t.Error(perr)
306
+ }
307
+ t.Fatal(err)
308
+ }
309
+ ln, err := Listen("tcp", addr)
310
+ if err == nil {
311
+ // Success. (This test didn't always make it here earlier.)
312
+ ln.Close()
313
+ return
314
+ }
315
+ t.Errorf("failed on try %d/%d: %v", tries+1, maxTries, err)
316
+ }
317
+ t.Fatalf("failed to listen/close/listen on same address after %d tries", maxTries)
318
+ }
319
+
320
+ // See golang.org/issue/6163, golang.org/issue/6987.
321
+ func TestAcceptIgnoreAbortedConnRequest(t *testing.T) {
322
+ switch runtime.GOOS {
323
+ case "plan9":
324
+ t.Skipf("%s does not have full support of socktest", runtime.GOOS)
325
+ }
326
+
327
+ syserr := make(chan error)
328
+ go func() {
329
+ defer close(syserr)
330
+ for _, err := range abortedConnRequestErrors {
331
+ syserr <- err
332
+ }
333
+ }()
334
+ sw.Set(socktest.FilterAccept, func(so *socktest.Status) (socktest.AfterFilter, error) {
335
+ if err, ok := <-syserr; ok {
336
+ return nil, err
337
+ }
338
+ return nil, nil
339
+ })
340
+ defer sw.Set(socktest.FilterAccept, nil)
341
+
342
+ operr := make(chan error, 1)
343
+ handler := func(ls *localServer, ln Listener) {
344
+ defer close(operr)
345
+ c, err := ln.Accept()
346
+ if err != nil {
347
+ if perr := parseAcceptError(err); perr != nil {
348
+ operr <- perr
349
+ }
350
+ operr <- err
351
+ return
352
+ }
353
+ c.Close()
354
+ }
355
+ ls := newLocalServer(t, "tcp")
356
+ defer ls.teardown()
357
+ if err := ls.buildup(handler); err != nil {
358
+ t.Fatal(err)
359
+ }
360
+
361
+ c, err := Dial(ls.Listener.Addr().Network(), ls.Listener.Addr().String())
362
+ if err != nil {
363
+ t.Fatal(err)
364
+ }
365
+ c.Close()
366
+
367
+ for err := range operr {
368
+ t.Error(err)
369
+ }
370
+ }
371
+
372
+ func TestZeroByteRead(t *testing.T) {
373
+ t.Parallel()
374
+ for _, network := range []string{"tcp", "unix", "unixpacket"} {
375
+ network := network
376
+ t.Run(network, func(t *testing.T) {
377
+ if !testableNetwork(network) {
378
+ t.Skipf("network %s is not testable on the current platform", network)
379
+ }
380
+ t.Parallel()
381
+
382
+ ln := newLocalListener(t, network)
383
+ connc := make(chan Conn, 1)
384
+ defer func() {
385
+ ln.Close()
386
+ for c := range connc {
387
+ if c != nil {
388
+ c.Close()
389
+ }
390
+ }
391
+ }()
392
+ go func() {
393
+ defer close(connc)
394
+ c, err := ln.Accept()
395
+ if err != nil {
396
+ t.Error(err)
397
+ }
398
+ connc <- c // might be nil
399
+ }()
400
+ c, err := Dial(network, ln.Addr().String())
401
+ if err != nil {
402
+ t.Fatal(err)
403
+ }
404
+ defer c.Close()
405
+ sc := <-connc
406
+ if sc == nil {
407
+ return
408
+ }
409
+ defer sc.Close()
410
+
411
+ if runtime.GOOS == "windows" {
412
+ // A zero byte read on Windows caused a wait for readability first.
413
+ // Rather than change that behavior, satisfy it in this test.
414
+ // See Issue 15735.
415
+ go io.WriteString(sc, "a")
416
+ }
417
+
418
+ n, err := c.Read(nil)
419
+ if n != 0 || err != nil {
420
+ t.Errorf("%s: zero byte client read = %v, %v; want 0, nil", network, n, err)
421
+ }
422
+
423
+ if runtime.GOOS == "windows" {
424
+ // Same as comment above.
425
+ go io.WriteString(c, "a")
426
+ }
427
+ n, err = sc.Read(nil)
428
+ if n != 0 || err != nil {
429
+ t.Errorf("%s: zero byte server read = %v, %v; want 0, nil", network, n, err)
430
+ }
431
+ })
432
+ }
433
+ }
434
+
435
+ // withTCPConnPair sets up a TCP connection between two peers, then
436
+ // runs peer1 and peer2 concurrently. withTCPConnPair returns when
437
+ // both have completed.
438
+ func withTCPConnPair(t *testing.T, peer1, peer2 func(c *TCPConn) error) {
439
+ t.Helper()
440
+ ln := newLocalListener(t, "tcp")
441
+ defer ln.Close()
442
+ errc := make(chan error, 2)
443
+ go func() {
444
+ c1, err := ln.Accept()
445
+ if err != nil {
446
+ errc <- err
447
+ return
448
+ }
449
+ err = peer1(c1.(*TCPConn))
450
+ c1.Close()
451
+ errc <- err
452
+ }()
453
+ go func() {
454
+ c2, err := Dial("tcp", ln.Addr().String())
455
+ if err != nil {
456
+ errc <- err
457
+ return
458
+ }
459
+ err = peer2(c2.(*TCPConn))
460
+ c2.Close()
461
+ errc <- err
462
+ }()
463
+ for i := 0; i < 2; i++ {
464
+ if err := <-errc; err != nil {
465
+ t.Error(err)
466
+ }
467
+ }
468
+ }
469
+
470
+ // Tests that a blocked Read is interrupted by a concurrent SetReadDeadline
471
+ // modifying that Conn's read deadline to the past.
472
+ // See golang.org/cl/30164 which documented this. The net/http package
473
+ // depends on this.
474
+ func TestReadTimeoutUnblocksRead(t *testing.T) {
475
+ serverDone := make(chan struct{})
476
+ server := func(cs *TCPConn) error {
477
+ defer close(serverDone)
478
+ errc := make(chan error, 1)
479
+ go func() {
480
+ defer close(errc)
481
+ go func() {
482
+ // TODO: find a better way to wait
483
+ // until we're blocked in the cs.Read
484
+ // call below. Sleep is lame.
485
+ time.Sleep(100 * time.Millisecond)
486
+
487
+ // Interrupt the upcoming Read, unblocking it:
488
+ cs.SetReadDeadline(time.Unix(123, 0)) // time in the past
489
+ }()
490
+ var buf [1]byte
491
+ n, err := cs.Read(buf[:1])
492
+ if n != 0 || err == nil {
493
+ errc <- fmt.Errorf("Read = %v, %v; want 0, non-nil", n, err)
494
+ }
495
+ }()
496
+ select {
497
+ case err := <-errc:
498
+ return err
499
+ case <-time.After(5 * time.Second):
500
+ buf := make([]byte, 2<<20)
501
+ buf = buf[:runtime.Stack(buf, true)]
502
+ println("Stacks at timeout:\n", string(buf))
503
+ return errors.New("timeout waiting for Read to finish")
504
+ }
505
+
506
+ }
507
+ // Do nothing in the client. Never write. Just wait for the
508
+ // server's half to be done.
509
+ client := func(*TCPConn) error {
510
+ <-serverDone
511
+ return nil
512
+ }
513
+ withTCPConnPair(t, client, server)
514
+ }
515
+
516
+ // Issue 17695: verify that a blocked Read is woken up by a Close.
517
+ func TestCloseUnblocksRead(t *testing.T) {
518
+ t.Parallel()
519
+ server := func(cs *TCPConn) error {
520
+ // Give the client time to get stuck in a Read:
521
+ time.Sleep(20 * time.Millisecond)
522
+ cs.Close()
523
+ return nil
524
+ }
525
+ client := func(ss *TCPConn) error {
526
+ n, err := ss.Read([]byte{0})
527
+ if n != 0 || err != io.EOF {
528
+ return fmt.Errorf("Read = %v, %v; want 0, EOF", n, err)
529
+ }
530
+ return nil
531
+ }
532
+ withTCPConnPair(t, client, server)
533
+ }
534
+
535
+ // Issue 24808: verify that ECONNRESET is not temporary for read.
536
+ func TestNotTemporaryRead(t *testing.T) {
537
+ t.Parallel()
538
+
539
+ ln := newLocalListener(t, "tcp")
540
+ serverDone := make(chan struct{})
541
+ dialed := make(chan struct{})
542
+ go func() {
543
+ defer close(serverDone)
544
+
545
+ cs, err := ln.Accept()
546
+ if err != nil {
547
+ return
548
+ }
549
+ <-dialed
550
+ cs.(*TCPConn).SetLinger(0)
551
+ cs.Close()
552
+ }()
553
+ defer func() {
554
+ ln.Close()
555
+ <-serverDone
556
+ }()
557
+
558
+ ss, err := Dial("tcp", ln.Addr().String())
559
+ close(dialed)
560
+ if err != nil {
561
+ t.Fatal(err)
562
+ }
563
+ defer ss.Close()
564
+
565
+ _, err = ss.Read([]byte{0})
566
+ if err == nil {
567
+ t.Fatal("Read succeeded unexpectedly")
568
+ } else if err == io.EOF {
569
+ // This happens on Plan 9, but for some reason (prior to CL 385314) it was
570
+ // accepted everywhere else too.
571
+ if runtime.GOOS == "plan9" {
572
+ return
573
+ }
574
+ t.Fatal("Read unexpectedly returned io.EOF after socket was abruptly closed")
575
+ }
576
+ if ne, ok := err.(Error); !ok {
577
+ t.Errorf("Read error does not implement net.Error: %v", err)
578
+ } else if ne.Temporary() {
579
+ t.Errorf("Read error is unexpectedly temporary: %v", err)
580
+ }
581
+ }
582
+
583
+ // The various errors should implement the Error interface.
584
+ func TestErrors(t *testing.T) {
585
+ var (
586
+ _ Error = &OpError{}
587
+ _ Error = &ParseError{}
588
+ _ Error = &AddrError{}
589
+ _ Error = UnknownNetworkError("")
590
+ _ Error = InvalidAddrError("")
591
+ _ Error = &timeoutError{}
592
+ _ Error = &DNSConfigError{}
593
+ _ Error = &DNSError{}
594
+ )
595
+
596
+ // ErrClosed was introduced as type error, so we can't check
597
+ // it using a declaration.
598
+ if _, ok := ErrClosed.(Error); !ok {
599
+ t.Fatal("ErrClosed does not implement Error")
600
+ }
601
+ }
platform/dbops/binaries/go/go/src/net/net_windows_test.go ADDED
@@ -0,0 +1,631 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 (
8
+ "bufio"
9
+ "bytes"
10
+ "fmt"
11
+ "internal/testenv"
12
+ "io"
13
+ "os"
14
+ "os/exec"
15
+ "regexp"
16
+ "sort"
17
+ "strings"
18
+ "syscall"
19
+ "testing"
20
+ "time"
21
+ )
22
+
23
+ func toErrno(err error) (syscall.Errno, bool) {
24
+ operr, ok := err.(*OpError)
25
+ if !ok {
26
+ return 0, false
27
+ }
28
+ syserr, ok := operr.Err.(*os.SyscallError)
29
+ if !ok {
30
+ return 0, false
31
+ }
32
+ errno, ok := syserr.Err.(syscall.Errno)
33
+ if !ok {
34
+ return 0, false
35
+ }
36
+ return errno, true
37
+ }
38
+
39
+ // TestAcceptIgnoreSomeErrors tests that windows TCPListener.AcceptTCP
40
+ // handles broken connections. It verifies that broken connections do
41
+ // not affect future connections.
42
+ func TestAcceptIgnoreSomeErrors(t *testing.T) {
43
+ recv := func(ln Listener, ignoreSomeReadErrors bool) (string, error) {
44
+ c, err := ln.Accept()
45
+ if err != nil {
46
+ // Display windows errno in error message.
47
+ errno, ok := toErrno(err)
48
+ if !ok {
49
+ return "", err
50
+ }
51
+ return "", fmt.Errorf("%v (windows errno=%d)", err, errno)
52
+ }
53
+ defer c.Close()
54
+
55
+ b := make([]byte, 100)
56
+ n, err := c.Read(b)
57
+ if err == nil || err == io.EOF {
58
+ return string(b[:n]), nil
59
+ }
60
+ errno, ok := toErrno(err)
61
+ if ok && ignoreSomeReadErrors && (errno == syscall.ERROR_NETNAME_DELETED || errno == syscall.WSAECONNRESET) {
62
+ return "", nil
63
+ }
64
+ return "", err
65
+ }
66
+
67
+ send := func(addr string, data string) error {
68
+ c, err := Dial("tcp", addr)
69
+ if err != nil {
70
+ return err
71
+ }
72
+ defer c.Close()
73
+
74
+ b := []byte(data)
75
+ n, err := c.Write(b)
76
+ if err != nil {
77
+ return err
78
+ }
79
+ if n != len(b) {
80
+ return fmt.Errorf(`Only %d chars of string "%s" sent`, n, data)
81
+ }
82
+ return nil
83
+ }
84
+
85
+ if envaddr := os.Getenv("GOTEST_DIAL_ADDR"); envaddr != "" {
86
+ // In child process.
87
+ c, err := Dial("tcp", envaddr)
88
+ if err != nil {
89
+ t.Fatal(err)
90
+ }
91
+ fmt.Printf("sleeping\n")
92
+ time.Sleep(time.Minute) // process will be killed here
93
+ c.Close()
94
+ }
95
+
96
+ ln, err := Listen("tcp", "127.0.0.1:0")
97
+ if err != nil {
98
+ t.Fatal(err)
99
+ }
100
+ defer ln.Close()
101
+
102
+ // Start child process that connects to our listener.
103
+ cmd := exec.Command(os.Args[0], "-test.run=TestAcceptIgnoreSomeErrors")
104
+ cmd.Env = append(os.Environ(), "GOTEST_DIAL_ADDR="+ln.Addr().String())
105
+ stdout, err := cmd.StdoutPipe()
106
+ if err != nil {
107
+ t.Fatalf("cmd.StdoutPipe failed: %v", err)
108
+ }
109
+ err = cmd.Start()
110
+ if err != nil {
111
+ t.Fatalf("cmd.Start failed: %v\n", err)
112
+ }
113
+ outReader := bufio.NewReader(stdout)
114
+ for {
115
+ s, err := outReader.ReadString('\n')
116
+ if err != nil {
117
+ t.Fatalf("reading stdout failed: %v", err)
118
+ }
119
+ if s == "sleeping\n" {
120
+ break
121
+ }
122
+ }
123
+ defer cmd.Wait() // ignore error - we know it is getting killed
124
+
125
+ const alittle = 100 * time.Millisecond
126
+ time.Sleep(alittle)
127
+ cmd.Process.Kill() // the only way to trigger the errors
128
+ time.Sleep(alittle)
129
+
130
+ // Send second connection data (with delay in a separate goroutine).
131
+ result := make(chan error)
132
+ go func() {
133
+ time.Sleep(alittle)
134
+ err := send(ln.Addr().String(), "abc")
135
+ if err != nil {
136
+ result <- err
137
+ }
138
+ result <- nil
139
+ }()
140
+ defer func() {
141
+ err := <-result
142
+ if err != nil {
143
+ t.Fatalf("send failed: %v", err)
144
+ }
145
+ }()
146
+
147
+ // Receive first or second connection.
148
+ s, err := recv(ln, true)
149
+ if err != nil {
150
+ t.Fatalf("recv failed: %v", err)
151
+ }
152
+ switch s {
153
+ case "":
154
+ // First connection data is received, let's get second connection data.
155
+ case "abc":
156
+ // First connection is lost forever, but that is ok.
157
+ return
158
+ default:
159
+ t.Fatalf(`"%s" received from recv, but "" or "abc" expected`, s)
160
+ }
161
+
162
+ // Get second connection data.
163
+ s, err = recv(ln, false)
164
+ if err != nil {
165
+ t.Fatalf("recv failed: %v", err)
166
+ }
167
+ if s != "abc" {
168
+ t.Fatalf(`"%s" received from recv, but "abc" expected`, s)
169
+ }
170
+ }
171
+
172
+ func runCmd(args ...string) ([]byte, error) {
173
+ removeUTF8BOM := func(b []byte) []byte {
174
+ if len(b) >= 3 && b[0] == 0xEF && b[1] == 0xBB && b[2] == 0xBF {
175
+ return b[3:]
176
+ }
177
+ return b
178
+ }
179
+ f, err := os.CreateTemp("", "netcmd")
180
+ if err != nil {
181
+ return nil, err
182
+ }
183
+ f.Close()
184
+ defer os.Remove(f.Name())
185
+ cmd := fmt.Sprintf(`%s | Out-File "%s" -encoding UTF8`, strings.Join(args, " "), f.Name())
186
+ out, err := exec.Command("powershell", "-Command", cmd).CombinedOutput()
187
+ if err != nil {
188
+ if len(out) != 0 {
189
+ return nil, fmt.Errorf("%s failed: %v: %q", args[0], err, string(removeUTF8BOM(out)))
190
+ }
191
+ var err2 error
192
+ out, err2 = os.ReadFile(f.Name())
193
+ if err2 != nil {
194
+ return nil, err2
195
+ }
196
+ if len(out) != 0 {
197
+ return nil, fmt.Errorf("%s failed: %v: %q", args[0], err, string(removeUTF8BOM(out)))
198
+ }
199
+ return nil, fmt.Errorf("%s failed: %v", args[0], err)
200
+ }
201
+ out, err = os.ReadFile(f.Name())
202
+ if err != nil {
203
+ return nil, err
204
+ }
205
+ return removeUTF8BOM(out), nil
206
+ }
207
+
208
+ func checkNetsh(t *testing.T) {
209
+ if testenv.Builder() == "windows-arm64-10" {
210
+ // netsh was observed to sometimes hang on this builder.
211
+ // We have not observed failures on windows-arm64-11, so for the
212
+ // moment we are leaving the test enabled elsewhere on the theory
213
+ // that it may have been a platform bug fixed in Windows 11.
214
+ testenv.SkipFlaky(t, 52082)
215
+ }
216
+ out, err := runCmd("netsh", "help")
217
+ if err != nil {
218
+ t.Fatal(err)
219
+ }
220
+ if bytes.Contains(out, []byte("The following helper DLL cannot be loaded")) {
221
+ t.Skipf("powershell failure:\n%s", err)
222
+ }
223
+ if !bytes.Contains(out, []byte("The following commands are available:")) {
224
+ t.Skipf("powershell does not speak English:\n%s", out)
225
+ }
226
+ }
227
+
228
+ func netshInterfaceIPShowInterface(ipver string, ifaces map[string]bool) error {
229
+ out, err := runCmd("netsh", "interface", ipver, "show", "interface", "level=verbose")
230
+ if err != nil {
231
+ return err
232
+ }
233
+ // interface information is listed like:
234
+ //
235
+ //Interface Local Area Connection Parameters
236
+ //----------------------------------------------
237
+ //IfLuid : ethernet_6
238
+ //IfIndex : 11
239
+ //State : connected
240
+ //Metric : 10
241
+ //...
242
+ var name string
243
+ lines := bytes.Split(out, []byte{'\r', '\n'})
244
+ for _, line := range lines {
245
+ if bytes.HasPrefix(line, []byte("Interface ")) && bytes.HasSuffix(line, []byte(" Parameters")) {
246
+ f := line[len("Interface "):]
247
+ f = f[:len(f)-len(" Parameters")]
248
+ name = string(f)
249
+ continue
250
+ }
251
+ var isup bool
252
+ switch string(line) {
253
+ case "State : connected":
254
+ isup = true
255
+ case "State : disconnected":
256
+ isup = false
257
+ default:
258
+ continue
259
+ }
260
+ if name != "" {
261
+ if v, ok := ifaces[name]; ok && v != isup {
262
+ return fmt.Errorf("%s:%s isup=%v: ipv4 and ipv6 report different interface state", ipver, name, isup)
263
+ }
264
+ ifaces[name] = isup
265
+ name = ""
266
+ }
267
+ }
268
+ return nil
269
+ }
270
+
271
+ func TestInterfacesWithNetsh(t *testing.T) {
272
+ checkNetsh(t)
273
+
274
+ toString := func(name string, isup bool) string {
275
+ if isup {
276
+ return name + ":up"
277
+ }
278
+ return name + ":down"
279
+ }
280
+
281
+ ift, err := Interfaces()
282
+ if err != nil {
283
+ t.Fatal(err)
284
+ }
285
+ have := make([]string, 0)
286
+ for _, ifi := range ift {
287
+ have = append(have, toString(ifi.Name, ifi.Flags&FlagUp != 0))
288
+ }
289
+ sort.Strings(have)
290
+
291
+ ifaces := make(map[string]bool)
292
+ err = netshInterfaceIPShowInterface("ipv6", ifaces)
293
+ if err != nil {
294
+ t.Fatal(err)
295
+ }
296
+ err = netshInterfaceIPShowInterface("ipv4", ifaces)
297
+ if err != nil {
298
+ t.Fatal(err)
299
+ }
300
+ want := make([]string, 0)
301
+ for name, isup := range ifaces {
302
+ want = append(want, toString(name, isup))
303
+ }
304
+ sort.Strings(want)
305
+
306
+ if strings.Join(want, "/") != strings.Join(have, "/") {
307
+ t.Fatalf("unexpected interface list %q, want %q", have, want)
308
+ }
309
+ }
310
+
311
+ func netshInterfaceIPv4ShowAddress(name string, netshOutput []byte) []string {
312
+ // Address information is listed like:
313
+ //
314
+ //Configuration for interface "Local Area Connection"
315
+ // DHCP enabled: Yes
316
+ // IP Address: 10.0.0.2
317
+ // Subnet Prefix: 10.0.0.0/24 (mask 255.255.255.0)
318
+ // IP Address: 10.0.0.3
319
+ // Subnet Prefix: 10.0.0.0/24 (mask 255.255.255.0)
320
+ // Default Gateway: 10.0.0.254
321
+ // Gateway Metric: 0
322
+ // InterfaceMetric: 10
323
+ //
324
+ //Configuration for interface "Loopback Pseudo-Interface 1"
325
+ // DHCP enabled: No
326
+ // IP Address: 127.0.0.1
327
+ // Subnet Prefix: 127.0.0.0/8 (mask 255.0.0.0)
328
+ // InterfaceMetric: 50
329
+ //
330
+ addrs := make([]string, 0)
331
+ var addr, subnetprefix string
332
+ var processingOurInterface bool
333
+ lines := bytes.Split(netshOutput, []byte{'\r', '\n'})
334
+ for _, line := range lines {
335
+ if !processingOurInterface {
336
+ if !bytes.HasPrefix(line, []byte("Configuration for interface")) {
337
+ continue
338
+ }
339
+ if !bytes.Contains(line, []byte(`"`+name+`"`)) {
340
+ continue
341
+ }
342
+ processingOurInterface = true
343
+ continue
344
+ }
345
+ if len(line) == 0 {
346
+ break
347
+ }
348
+ if bytes.Contains(line, []byte("Subnet Prefix:")) {
349
+ f := bytes.Split(line, []byte{':'})
350
+ if len(f) == 2 {
351
+ f = bytes.Split(f[1], []byte{'('})
352
+ if len(f) == 2 {
353
+ f = bytes.Split(f[0], []byte{'/'})
354
+ if len(f) == 2 {
355
+ subnetprefix = string(bytes.TrimSpace(f[1]))
356
+ if addr != "" && subnetprefix != "" {
357
+ addrs = append(addrs, addr+"/"+subnetprefix)
358
+ }
359
+ }
360
+ }
361
+ }
362
+ }
363
+ addr = ""
364
+ if bytes.Contains(line, []byte("IP Address:")) {
365
+ f := bytes.Split(line, []byte{':'})
366
+ if len(f) == 2 {
367
+ addr = string(bytes.TrimSpace(f[1]))
368
+ }
369
+ }
370
+ }
371
+ return addrs
372
+ }
373
+
374
+ func netshInterfaceIPv6ShowAddress(name string, netshOutput []byte) []string {
375
+ // Address information is listed like:
376
+ //
377
+ //Address ::1 Parameters
378
+ //---------------------------------------------------------
379
+ //Interface Luid : Loopback Pseudo-Interface 1
380
+ //Scope Id : 0.0
381
+ //Valid Lifetime : infinite
382
+ //Preferred Lifetime : infinite
383
+ //DAD State : Preferred
384
+ //Address Type : Other
385
+ //Skip as Source : false
386
+ //
387
+ //Address XXXX::XXXX:XXXX:XXXX:XXXX%11 Parameters
388
+ //---------------------------------------------------------
389
+ //Interface Luid : Local Area Connection
390
+ //Scope Id : 0.11
391
+ //Valid Lifetime : infinite
392
+ //Preferred Lifetime : infinite
393
+ //DAD State : Preferred
394
+ //Address Type : Other
395
+ //Skip as Source : false
396
+ //
397
+
398
+ // TODO: need to test ipv6 netmask too, but netsh does not outputs it
399
+ var addr string
400
+ addrs := make([]string, 0)
401
+ lines := bytes.Split(netshOutput, []byte{'\r', '\n'})
402
+ for _, line := range lines {
403
+ if addr != "" {
404
+ if len(line) == 0 {
405
+ addr = ""
406
+ continue
407
+ }
408
+ if string(line) != "Interface Luid : "+name {
409
+ continue
410
+ }
411
+ addrs = append(addrs, addr)
412
+ addr = ""
413
+ continue
414
+ }
415
+ if !bytes.HasPrefix(line, []byte("Address")) {
416
+ continue
417
+ }
418
+ if !bytes.HasSuffix(line, []byte("Parameters")) {
419
+ continue
420
+ }
421
+ f := bytes.Split(line, []byte{' '})
422
+ if len(f) != 3 {
423
+ continue
424
+ }
425
+ // remove scope ID if present
426
+ f = bytes.Split(f[1], []byte{'%'})
427
+
428
+ // netsh can create IPv4-embedded IPv6 addresses, like fe80::5efe:192.168.140.1.
429
+ // Convert these to all hexadecimal fe80::5efe:c0a8:8c01 for later string comparisons.
430
+ ipv4Tail := regexp.MustCompile(`:\d+\.\d+\.\d+\.\d+$`)
431
+ if ipv4Tail.Match(f[0]) {
432
+ f[0] = []byte(ParseIP(string(f[0])).String())
433
+ }
434
+
435
+ addr = string(bytes.ToLower(bytes.TrimSpace(f[0])))
436
+ }
437
+ return addrs
438
+ }
439
+
440
+ func TestInterfaceAddrsWithNetsh(t *testing.T) {
441
+ checkNetsh(t)
442
+
443
+ outIPV4, err := runCmd("netsh", "interface", "ipv4", "show", "address")
444
+ if err != nil {
445
+ t.Fatal(err)
446
+ }
447
+ outIPV6, err := runCmd("netsh", "interface", "ipv6", "show", "address", "level=verbose")
448
+ if err != nil {
449
+ t.Fatal(err)
450
+ }
451
+
452
+ ift, err := Interfaces()
453
+ if err != nil {
454
+ t.Fatal(err)
455
+ }
456
+ for _, ifi := range ift {
457
+ // Skip the interface if it's down.
458
+ if (ifi.Flags & FlagUp) == 0 {
459
+ continue
460
+ }
461
+ have := make([]string, 0)
462
+ addrs, err := ifi.Addrs()
463
+ if err != nil {
464
+ t.Fatal(err)
465
+ }
466
+ for _, addr := range addrs {
467
+ switch addr := addr.(type) {
468
+ case *IPNet:
469
+ if addr.IP.To4() != nil {
470
+ have = append(have, addr.String())
471
+ }
472
+ if addr.IP.To16() != nil && addr.IP.To4() == nil {
473
+ // netsh does not output netmask for ipv6, so ignore ipv6 mask
474
+ have = append(have, addr.IP.String())
475
+ }
476
+ case *IPAddr:
477
+ if addr.IP.To4() != nil {
478
+ have = append(have, addr.String())
479
+ }
480
+ if addr.IP.To16() != nil && addr.IP.To4() == nil {
481
+ // netsh does not output netmask for ipv6, so ignore ipv6 mask
482
+ have = append(have, addr.IP.String())
483
+ }
484
+ }
485
+ }
486
+ sort.Strings(have)
487
+
488
+ want := netshInterfaceIPv4ShowAddress(ifi.Name, outIPV4)
489
+ wantIPv6 := netshInterfaceIPv6ShowAddress(ifi.Name, outIPV6)
490
+ want = append(want, wantIPv6...)
491
+ sort.Strings(want)
492
+
493
+ if strings.Join(want, "/") != strings.Join(have, "/") {
494
+ t.Errorf("%s: unexpected addresses list %q, want %q", ifi.Name, have, want)
495
+ }
496
+ }
497
+ }
498
+
499
+ // check that getmac exists as a powershell command, and that it
500
+ // speaks English.
501
+ func checkGetmac(t *testing.T) {
502
+ out, err := runCmd("getmac", "/?")
503
+ if err != nil {
504
+ if strings.Contains(err.Error(), "term 'getmac' is not recognized as the name of a cmdlet") {
505
+ t.Skipf("getmac not available")
506
+ }
507
+ t.Fatal(err)
508
+ }
509
+ if !bytes.Contains(out, []byte("network adapters on a system")) {
510
+ t.Skipf("skipping test on non-English system")
511
+ }
512
+ }
513
+
514
+ func TestInterfaceHardwareAddrWithGetmac(t *testing.T) {
515
+ checkGetmac(t)
516
+
517
+ ift, err := Interfaces()
518
+ if err != nil {
519
+ t.Fatal(err)
520
+ }
521
+ have := make(map[string]string)
522
+ for _, ifi := range ift {
523
+ if ifi.Flags&FlagLoopback != 0 {
524
+ // no MAC address for loopback interfaces
525
+ continue
526
+ }
527
+ have[ifi.Name] = ifi.HardwareAddr.String()
528
+ }
529
+
530
+ out, err := runCmd("getmac", "/fo", "list", "/v")
531
+ if err != nil {
532
+ t.Fatal(err)
533
+ }
534
+ // getmac output looks like:
535
+ //
536
+ //Connection Name: Local Area Connection
537
+ //Network Adapter: Intel Gigabit Network Connection
538
+ //Physical Address: XX-XX-XX-XX-XX-XX
539
+ //Transport Name: \Device\Tcpip_{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}
540
+ //
541
+ //Connection Name: Wireless Network Connection
542
+ //Network Adapter: Wireles WLAN Card
543
+ //Physical Address: XX-XX-XX-XX-XX-XX
544
+ //Transport Name: Media disconnected
545
+ //
546
+ //Connection Name: Bluetooth Network Connection
547
+ //Network Adapter: Bluetooth Device (Personal Area Network)
548
+ //Physical Address: N/A
549
+ //Transport Name: Hardware not present
550
+ //
551
+ //Connection Name: VMware Network Adapter VMnet8
552
+ //Network Adapter: VMware Virtual Ethernet Adapter for VMnet8
553
+ //Physical Address: Disabled
554
+ //Transport Name: Disconnected
555
+ //
556
+ want := make(map[string]string)
557
+ group := make(map[string]string) // name / values for single adapter
558
+ getValue := func(name string) string {
559
+ value, found := group[name]
560
+ if !found {
561
+ t.Fatalf("%q has no %q line in it", group, name)
562
+ }
563
+ if value == "" {
564
+ t.Fatalf("%q has empty %q value", group, name)
565
+ }
566
+ return value
567
+ }
568
+ processGroup := func() {
569
+ if len(group) == 0 {
570
+ return
571
+ }
572
+ tname := strings.ToLower(getValue("Transport Name"))
573
+ if tname == "n/a" {
574
+ // skip these
575
+ return
576
+ }
577
+ addr := strings.ToLower(getValue("Physical Address"))
578
+ if addr == "disabled" || addr == "n/a" {
579
+ // skip these
580
+ return
581
+ }
582
+ addr = strings.ReplaceAll(addr, "-", ":")
583
+ cname := getValue("Connection Name")
584
+ want[cname] = addr
585
+ group = make(map[string]string)
586
+ }
587
+ lines := bytes.Split(out, []byte{'\r', '\n'})
588
+ for _, line := range lines {
589
+ if len(line) == 0 {
590
+ processGroup()
591
+ continue
592
+ }
593
+ i := bytes.IndexByte(line, ':')
594
+ if i == -1 {
595
+ t.Fatalf("line %q has no : in it", line)
596
+ }
597
+ group[string(line[:i])] = string(bytes.TrimSpace(line[i+1:]))
598
+ }
599
+ processGroup()
600
+
601
+ dups := make(map[string][]string)
602
+ for name, addr := range want {
603
+ if _, ok := dups[addr]; !ok {
604
+ dups[addr] = make([]string, 0)
605
+ }
606
+ dups[addr] = append(dups[addr], name)
607
+ }
608
+
609
+ nextWant:
610
+ for name, wantAddr := range want {
611
+ if haveAddr, ok := have[name]; ok {
612
+ if haveAddr != wantAddr {
613
+ t.Errorf("unexpected MAC address for %q - %v, want %v", name, haveAddr, wantAddr)
614
+ }
615
+ continue
616
+ }
617
+ // We could not find the interface in getmac output by name.
618
+ // But sometimes getmac lists many interface names
619
+ // for the same MAC address. If that is the case here,
620
+ // and we can match at least one of those names,
621
+ // let's ignore the other names.
622
+ if dupNames, ok := dups[wantAddr]; ok && len(dupNames) > 1 {
623
+ for _, dupName := range dupNames {
624
+ if haveAddr, ok := have[dupName]; ok && haveAddr == wantAddr {
625
+ continue nextWant
626
+ }
627
+ }
628
+ }
629
+ t.Errorf("getmac lists %q, but it could not be found among Go interfaces %v", name, have)
630
+ }
631
+ }
platform/dbops/binaries/go/go/src/net/netcgo_off.go ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
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 !netcgo
6
+
7
+ package net
8
+
9
+ const netCgoBuildTag = false
platform/dbops/binaries/go/go/src/net/netcgo_on.go ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
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 netcgo
6
+
7
+ package net
8
+
9
+ const netCgoBuildTag = true
platform/dbops/binaries/go/go/src/net/netgo_netcgo.go ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 netgo && netcgo
6
+
7
+ package net
8
+
9
+ func init() {
10
+ // This will give a compile time error about the unused constant.
11
+ // The advantage of this approach is that the gc compiler
12
+ // actually prints the constant, making the problem obvious.
13
+ "Do not use both netgo and netcgo build tags."
14
+ }
platform/dbops/binaries/go/go/src/net/netgo_off.go ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
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 !netgo
6
+
7
+ package net
8
+
9
+ const netGoBuildTag = false
platform/dbops/binaries/go/go/src/net/netgo_on.go ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
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 netgo
6
+
7
+ package net
8
+
9
+ const netGoBuildTag = true
platform/dbops/binaries/go/go/src/net/nss.go ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2015 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
+ "errors"
9
+ "internal/bytealg"
10
+ "os"
11
+ "sync"
12
+ "time"
13
+ )
14
+
15
+ const (
16
+ nssConfigPath = "/etc/nsswitch.conf"
17
+ )
18
+
19
+ var nssConfig nsswitchConfig
20
+
21
+ type nsswitchConfig struct {
22
+ initOnce sync.Once // guards init of nsswitchConfig
23
+
24
+ // ch is used as a semaphore that only allows one lookup at a
25
+ // time to recheck nsswitch.conf
26
+ ch chan struct{} // guards lastChecked and modTime
27
+ lastChecked time.Time // last time nsswitch.conf was checked
28
+
29
+ mu sync.Mutex // protects nssConf
30
+ nssConf *nssConf
31
+ }
32
+
33
+ func getSystemNSS() *nssConf {
34
+ nssConfig.tryUpdate()
35
+ nssConfig.mu.Lock()
36
+ conf := nssConfig.nssConf
37
+ nssConfig.mu.Unlock()
38
+ return conf
39
+ }
40
+
41
+ // init initializes conf and is only called via conf.initOnce.
42
+ func (conf *nsswitchConfig) init() {
43
+ conf.nssConf = parseNSSConfFile("/etc/nsswitch.conf")
44
+ conf.lastChecked = time.Now()
45
+ conf.ch = make(chan struct{}, 1)
46
+ }
47
+
48
+ // tryUpdate tries to update conf.
49
+ func (conf *nsswitchConfig) tryUpdate() {
50
+ conf.initOnce.Do(conf.init)
51
+
52
+ // Ensure only one update at a time checks nsswitch.conf
53
+ if !conf.tryAcquireSema() {
54
+ return
55
+ }
56
+ defer conf.releaseSema()
57
+
58
+ now := time.Now()
59
+ if conf.lastChecked.After(now.Add(-5 * time.Second)) {
60
+ return
61
+ }
62
+ conf.lastChecked = now
63
+
64
+ var mtime time.Time
65
+ if fi, err := os.Stat(nssConfigPath); err == nil {
66
+ mtime = fi.ModTime()
67
+ }
68
+ if mtime.Equal(conf.nssConf.mtime) {
69
+ return
70
+ }
71
+
72
+ nssConf := parseNSSConfFile(nssConfigPath)
73
+ conf.mu.Lock()
74
+ conf.nssConf = nssConf
75
+ conf.mu.Unlock()
76
+ }
77
+
78
+ func (conf *nsswitchConfig) acquireSema() {
79
+ conf.ch <- struct{}{}
80
+ }
81
+
82
+ func (conf *nsswitchConfig) tryAcquireSema() bool {
83
+ select {
84
+ case conf.ch <- struct{}{}:
85
+ return true
86
+ default:
87
+ return false
88
+ }
89
+ }
90
+
91
+ func (conf *nsswitchConfig) releaseSema() {
92
+ <-conf.ch
93
+ }
94
+
95
+ // nssConf represents the state of the machine's /etc/nsswitch.conf file.
96
+ type nssConf struct {
97
+ mtime time.Time // time of nsswitch.conf modification
98
+ err error // any error encountered opening or parsing the file
99
+ sources map[string][]nssSource // keyed by database (e.g. "hosts")
100
+ }
101
+
102
+ type nssSource struct {
103
+ source string // e.g. "compat", "files", "mdns4_minimal"
104
+ criteria []nssCriterion
105
+ }
106
+
107
+ // standardCriteria reports all specified criteria have the default
108
+ // status actions.
109
+ func (s nssSource) standardCriteria() bool {
110
+ for i, crit := range s.criteria {
111
+ if !crit.standardStatusAction(i == len(s.criteria)-1) {
112
+ return false
113
+ }
114
+ }
115
+ return true
116
+ }
117
+
118
+ // nssCriterion is the parsed structure of one of the criteria in brackets
119
+ // after an NSS source name.
120
+ type nssCriterion struct {
121
+ negate bool // if "!" was present
122
+ status string // e.g. "success", "unavail" (lowercase)
123
+ action string // e.g. "return", "continue" (lowercase)
124
+ }
125
+
126
+ // standardStatusAction reports whether c is equivalent to not
127
+ // specifying the criterion at all. last is whether this criteria is the
128
+ // last in the list.
129
+ func (c nssCriterion) standardStatusAction(last bool) bool {
130
+ if c.negate {
131
+ return false
132
+ }
133
+ var def string
134
+ switch c.status {
135
+ case "success":
136
+ def = "return"
137
+ case "notfound", "unavail", "tryagain":
138
+ def = "continue"
139
+ default:
140
+ // Unknown status
141
+ return false
142
+ }
143
+ if last && c.action == "return" {
144
+ return true
145
+ }
146
+ return c.action == def
147
+ }
148
+
149
+ func parseNSSConfFile(file string) *nssConf {
150
+ f, err := open(file)
151
+ if err != nil {
152
+ return &nssConf{err: err}
153
+ }
154
+ defer f.close()
155
+ mtime, _, err := f.stat()
156
+ if err != nil {
157
+ return &nssConf{err: err}
158
+ }
159
+
160
+ conf := parseNSSConf(f)
161
+ conf.mtime = mtime
162
+ return conf
163
+ }
164
+
165
+ func parseNSSConf(f *file) *nssConf {
166
+ conf := new(nssConf)
167
+ for line, ok := f.readLine(); ok; line, ok = f.readLine() {
168
+ line = trimSpace(removeComment(line))
169
+ if len(line) == 0 {
170
+ continue
171
+ }
172
+ colon := bytealg.IndexByteString(line, ':')
173
+ if colon == -1 {
174
+ conf.err = errors.New("no colon on line")
175
+ return conf
176
+ }
177
+ db := trimSpace(line[:colon])
178
+ srcs := line[colon+1:]
179
+ for {
180
+ srcs = trimSpace(srcs)
181
+ if len(srcs) == 0 {
182
+ break
183
+ }
184
+ sp := bytealg.IndexByteString(srcs, ' ')
185
+ var src string
186
+ if sp == -1 {
187
+ src = srcs
188
+ srcs = "" // done
189
+ } else {
190
+ src = srcs[:sp]
191
+ srcs = trimSpace(srcs[sp+1:])
192
+ }
193
+ var criteria []nssCriterion
194
+ // See if there's a criteria block in brackets.
195
+ if len(srcs) > 0 && srcs[0] == '[' {
196
+ bclose := bytealg.IndexByteString(srcs, ']')
197
+ if bclose == -1 {
198
+ conf.err = errors.New("unclosed criterion bracket")
199
+ return conf
200
+ }
201
+ var err error
202
+ criteria, err = parseCriteria(srcs[1:bclose])
203
+ if err != nil {
204
+ conf.err = errors.New("invalid criteria: " + srcs[1:bclose])
205
+ return conf
206
+ }
207
+ srcs = srcs[bclose+1:]
208
+ }
209
+ if conf.sources == nil {
210
+ conf.sources = make(map[string][]nssSource)
211
+ }
212
+ conf.sources[db] = append(conf.sources[db], nssSource{
213
+ source: src,
214
+ criteria: criteria,
215
+ })
216
+ }
217
+ }
218
+ return conf
219
+ }
220
+
221
+ // parses "foo=bar !foo=bar"
222
+ func parseCriteria(x string) (c []nssCriterion, err error) {
223
+ err = foreachField(x, func(f string) error {
224
+ not := false
225
+ if len(f) > 0 && f[0] == '!' {
226
+ not = true
227
+ f = f[1:]
228
+ }
229
+ if len(f) < 3 {
230
+ return errors.New("criterion too short")
231
+ }
232
+ eq := bytealg.IndexByteString(f, '=')
233
+ if eq == -1 {
234
+ return errors.New("criterion lacks equal sign")
235
+ }
236
+ if hasUpperCase(f) {
237
+ lower := []byte(f)
238
+ lowerASCIIBytes(lower)
239
+ f = string(lower)
240
+ }
241
+ c = append(c, nssCriterion{
242
+ negate: not,
243
+ status: f[:eq],
244
+ action: f[eq+1:],
245
+ })
246
+ return nil
247
+ })
248
+ return
249
+ }
platform/dbops/binaries/go/go/src/net/nss_test.go ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2015 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 || linux || netbsd || openbsd || solaris
6
+
7
+ package net
8
+
9
+ import (
10
+ "reflect"
11
+ "testing"
12
+ "time"
13
+ )
14
+
15
+ const ubuntuTrustyAvahi = `# /etc/nsswitch.conf
16
+ #
17
+ # Example configuration of GNU Name Service Switch functionality.
18
+ # If you have the libc-doc-reference' and nfo' packages installed, try:
19
+ # nfo libc "Name Service Switch"' for information about this file.
20
+
21
+ passwd: compat
22
+ group: compat
23
+ shadow: compat
24
+
25
+ hosts: files mdns4_minimal [NOTFOUND=return] dns mdns4
26
+ networks: files
27
+
28
+ protocols: db files
29
+ services: db files
30
+ ethers: db files
31
+ rpc: db files
32
+
33
+ netgroup: nis
34
+ `
35
+
36
+ func TestParseNSSConf(t *testing.T) {
37
+ t.Parallel()
38
+
39
+ tests := []struct {
40
+ name string
41
+ in string
42
+ want *nssConf
43
+ }{
44
+ {
45
+ name: "no_newline",
46
+ in: "foo: a b",
47
+ want: &nssConf{
48
+ sources: map[string][]nssSource{
49
+ "foo": {{source: "a"}, {source: "b"}},
50
+ },
51
+ },
52
+ },
53
+ {
54
+ name: "newline",
55
+ in: "foo: a b\n",
56
+ want: &nssConf{
57
+ sources: map[string][]nssSource{
58
+ "foo": {{source: "a"}, {source: "b"}},
59
+ },
60
+ },
61
+ },
62
+ {
63
+ name: "whitespace",
64
+ in: " foo:a b \n",
65
+ want: &nssConf{
66
+ sources: map[string][]nssSource{
67
+ "foo": {{source: "a"}, {source: "b"}},
68
+ },
69
+ },
70
+ },
71
+ {
72
+ name: "comment1",
73
+ in: " foo:a b#c\n",
74
+ want: &nssConf{
75
+ sources: map[string][]nssSource{
76
+ "foo": {{source: "a"}, {source: "b"}},
77
+ },
78
+ },
79
+ },
80
+ {
81
+ name: "comment2",
82
+ in: " foo:a b #c \n",
83
+ want: &nssConf{
84
+ sources: map[string][]nssSource{
85
+ "foo": {{source: "a"}, {source: "b"}},
86
+ },
87
+ },
88
+ },
89
+ {
90
+ name: "crit",
91
+ in: " foo:a b [!a=b X=Y ] c#d \n",
92
+ want: &nssConf{
93
+ sources: map[string][]nssSource{
94
+ "foo": {
95
+ {source: "a"},
96
+ {
97
+ source: "b",
98
+ criteria: []nssCriterion{
99
+ {
100
+ negate: true,
101
+ status: "a",
102
+ action: "b",
103
+ },
104
+ {
105
+ status: "x",
106
+ action: "y",
107
+ },
108
+ },
109
+ },
110
+ {source: "c"},
111
+ },
112
+ },
113
+ },
114
+ },
115
+
116
+ // Ubuntu Trusty w/ avahi-daemon, libavahi-* etc installed.
117
+ {
118
+ name: "ubuntu_trusty_avahi",
119
+ in: ubuntuTrustyAvahi,
120
+ want: &nssConf{
121
+ sources: map[string][]nssSource{
122
+ "passwd": {{source: "compat"}},
123
+ "group": {{source: "compat"}},
124
+ "shadow": {{source: "compat"}},
125
+ "hosts": {
126
+ {source: "files"},
127
+ {
128
+ source: "mdns4_minimal",
129
+ criteria: []nssCriterion{
130
+ {
131
+ negate: false,
132
+ status: "notfound",
133
+ action: "return",
134
+ },
135
+ },
136
+ },
137
+ {source: "dns"},
138
+ {source: "mdns4"},
139
+ },
140
+ "networks": {{source: "files"}},
141
+ "protocols": {
142
+ {source: "db"},
143
+ {source: "files"},
144
+ },
145
+ "services": {
146
+ {source: "db"},
147
+ {source: "files"},
148
+ },
149
+ "ethers": {
150
+ {source: "db"},
151
+ {source: "files"},
152
+ },
153
+ "rpc": {
154
+ {source: "db"},
155
+ {source: "files"},
156
+ },
157
+ "netgroup": {
158
+ {source: "nis"},
159
+ },
160
+ },
161
+ },
162
+ },
163
+ }
164
+
165
+ for _, tt := range tests {
166
+ gotConf := nssStr(t, tt.in)
167
+ gotConf.mtime = time.Time{} // ignore mtime in comparison
168
+ if !reflect.DeepEqual(gotConf, tt.want) {
169
+ t.Errorf("%s: mismatch\n got %#v\nwant %#v", tt.name, gotConf, tt.want)
170
+ }
171
+ }
172
+ }
platform/dbops/binaries/go/go/src/net/packetconn_test.go ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2012 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 API tests across platforms and should never have a build
6
+ // constraint.
7
+
8
+ package net
9
+
10
+ import (
11
+ "os"
12
+ "testing"
13
+ )
14
+
15
+ // The full stack test cases for IPConn have been moved to the
16
+ // following:
17
+ // golang.org/x/net/ipv4
18
+ // golang.org/x/net/ipv6
19
+ // golang.org/x/net/icmp
20
+
21
+ func packetConnTestData(t *testing.T, network string) ([]byte, func()) {
22
+ if !testableNetwork(network) {
23
+ return nil, func() { t.Logf("skipping %s test", network) }
24
+ }
25
+ return []byte("PACKETCONN TEST"), nil
26
+ }
27
+
28
+ func TestPacketConn(t *testing.T) {
29
+ var packetConnTests = []struct {
30
+ net string
31
+ addr1 string
32
+ addr2 string
33
+ }{
34
+ {"udp", "127.0.0.1:0", "127.0.0.1:0"},
35
+ {"unixgram", testUnixAddr(t), testUnixAddr(t)},
36
+ }
37
+
38
+ closer := func(c PacketConn, net, addr1, addr2 string) {
39
+ c.Close()
40
+ switch net {
41
+ case "unixgram":
42
+ os.Remove(addr1)
43
+ os.Remove(addr2)
44
+ }
45
+ }
46
+
47
+ for _, tt := range packetConnTests {
48
+ wb, skipOrFatalFn := packetConnTestData(t, tt.net)
49
+ if skipOrFatalFn != nil {
50
+ skipOrFatalFn()
51
+ continue
52
+ }
53
+
54
+ c1, err := ListenPacket(tt.net, tt.addr1)
55
+ if err != nil {
56
+ t.Fatal(err)
57
+ }
58
+ defer closer(c1, tt.net, tt.addr1, tt.addr2)
59
+ c1.LocalAddr()
60
+
61
+ c2, err := ListenPacket(tt.net, tt.addr2)
62
+ if err != nil {
63
+ t.Fatal(err)
64
+ }
65
+ defer closer(c2, tt.net, tt.addr1, tt.addr2)
66
+ c2.LocalAddr()
67
+ rb2 := make([]byte, 128)
68
+
69
+ if _, err := c1.WriteTo(wb, c2.LocalAddr()); err != nil {
70
+ t.Fatal(err)
71
+ }
72
+ if _, _, err := c2.ReadFrom(rb2); err != nil {
73
+ t.Fatal(err)
74
+ }
75
+ if _, err := c2.WriteTo(wb, c1.LocalAddr()); err != nil {
76
+ t.Fatal(err)
77
+ }
78
+ rb1 := make([]byte, 128)
79
+ if _, _, err := c1.ReadFrom(rb1); err != nil {
80
+ t.Fatal(err)
81
+ }
82
+ }
83
+ }
84
+
85
+ func TestConnAndPacketConn(t *testing.T) {
86
+ var packetConnTests = []struct {
87
+ net string
88
+ addr1 string
89
+ addr2 string
90
+ }{
91
+ {"udp", "127.0.0.1:0", "127.0.0.1:0"},
92
+ {"unixgram", testUnixAddr(t), testUnixAddr(t)},
93
+ }
94
+
95
+ closer := func(c PacketConn, net, addr1, addr2 string) {
96
+ c.Close()
97
+ switch net {
98
+ case "unixgram":
99
+ os.Remove(addr1)
100
+ os.Remove(addr2)
101
+ }
102
+ }
103
+
104
+ for _, tt := range packetConnTests {
105
+ var wb []byte
106
+ wb, skipOrFatalFn := packetConnTestData(t, tt.net)
107
+ if skipOrFatalFn != nil {
108
+ skipOrFatalFn()
109
+ continue
110
+ }
111
+
112
+ c1, err := ListenPacket(tt.net, tt.addr1)
113
+ if err != nil {
114
+ t.Fatal(err)
115
+ }
116
+ defer closer(c1, tt.net, tt.addr1, tt.addr2)
117
+ c1.LocalAddr()
118
+
119
+ c2, err := Dial(tt.net, c1.LocalAddr().String())
120
+ if err != nil {
121
+ t.Fatal(err)
122
+ }
123
+ defer c2.Close()
124
+ c2.LocalAddr()
125
+ c2.RemoteAddr()
126
+
127
+ if _, err := c2.Write(wb); err != nil {
128
+ t.Fatal(err)
129
+ }
130
+ rb1 := make([]byte, 128)
131
+ if _, _, err := c1.ReadFrom(rb1); err != nil {
132
+ t.Fatal(err)
133
+ }
134
+ var dst Addr
135
+ switch tt.net {
136
+ case "unixgram":
137
+ continue
138
+ default:
139
+ dst = c2.LocalAddr()
140
+ }
141
+ if _, err := c1.WriteTo(wb, dst); err != nil {
142
+ t.Fatal(err)
143
+ }
144
+ rb2 := make([]byte, 128)
145
+ if _, err := c2.Read(rb2); err != nil {
146
+ t.Fatal(err)
147
+ }
148
+ }
149
+ }
platform/dbops/binaries/go/go/src/net/parse.go ADDED
@@ -0,0 +1,283 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ // Simple file i/o and string manipulation, to avoid
6
+ // depending on strconv and bufio and strings.
7
+
8
+ package net
9
+
10
+ import (
11
+ "internal/bytealg"
12
+ "io"
13
+ "os"
14
+ "time"
15
+ )
16
+
17
+ type file struct {
18
+ file *os.File
19
+ data []byte
20
+ atEOF bool
21
+ }
22
+
23
+ func (f *file) close() { f.file.Close() }
24
+
25
+ func (f *file) getLineFromData() (s string, ok bool) {
26
+ data := f.data
27
+ i := 0
28
+ for i = 0; i < len(data); i++ {
29
+ if data[i] == '\n' {
30
+ s = string(data[0:i])
31
+ ok = true
32
+ // move data
33
+ i++
34
+ n := len(data) - i
35
+ copy(data[0:], data[i:])
36
+ f.data = data[0:n]
37
+ return
38
+ }
39
+ }
40
+ if f.atEOF && len(f.data) > 0 {
41
+ // EOF, return all we have
42
+ s = string(data)
43
+ f.data = f.data[0:0]
44
+ ok = true
45
+ }
46
+ return
47
+ }
48
+
49
+ func (f *file) readLine() (s string, ok bool) {
50
+ if s, ok = f.getLineFromData(); ok {
51
+ return
52
+ }
53
+ if len(f.data) < cap(f.data) {
54
+ ln := len(f.data)
55
+ n, err := io.ReadFull(f.file, f.data[ln:cap(f.data)])
56
+ if n >= 0 {
57
+ f.data = f.data[0 : ln+n]
58
+ }
59
+ if err == io.EOF || err == io.ErrUnexpectedEOF {
60
+ f.atEOF = true
61
+ }
62
+ }
63
+ s, ok = f.getLineFromData()
64
+ return
65
+ }
66
+
67
+ func (f *file) stat() (mtime time.Time, size int64, err error) {
68
+ st, err := f.file.Stat()
69
+ if err != nil {
70
+ return time.Time{}, 0, err
71
+ }
72
+ return st.ModTime(), st.Size(), nil
73
+ }
74
+
75
+ func open(name string) (*file, error) {
76
+ fd, err := os.Open(name)
77
+ if err != nil {
78
+ return nil, err
79
+ }
80
+ return &file{fd, make([]byte, 0, 64*1024), false}, nil
81
+ }
82
+
83
+ func stat(name string) (mtime time.Time, size int64, err error) {
84
+ st, err := os.Stat(name)
85
+ if err != nil {
86
+ return time.Time{}, 0, err
87
+ }
88
+ return st.ModTime(), st.Size(), nil
89
+ }
90
+
91
+ // Count occurrences in s of any bytes in t.
92
+ func countAnyByte(s string, t string) int {
93
+ n := 0
94
+ for i := 0; i < len(s); i++ {
95
+ if bytealg.IndexByteString(t, s[i]) >= 0 {
96
+ n++
97
+ }
98
+ }
99
+ return n
100
+ }
101
+
102
+ // Split s at any bytes in t.
103
+ func splitAtBytes(s string, t string) []string {
104
+ a := make([]string, 1+countAnyByte(s, t))
105
+ n := 0
106
+ last := 0
107
+ for i := 0; i < len(s); i++ {
108
+ if bytealg.IndexByteString(t, s[i]) >= 0 {
109
+ if last < i {
110
+ a[n] = s[last:i]
111
+ n++
112
+ }
113
+ last = i + 1
114
+ }
115
+ }
116
+ if last < len(s) {
117
+ a[n] = s[last:]
118
+ n++
119
+ }
120
+ return a[0:n]
121
+ }
122
+
123
+ func getFields(s string) []string { return splitAtBytes(s, " \r\t\n") }
124
+
125
+ // Bigger than we need, not too big to worry about overflow
126
+ const big = 0xFFFFFF
127
+
128
+ // Decimal to integer.
129
+ // Returns number, characters consumed, success.
130
+ func dtoi(s string) (n int, i int, ok bool) {
131
+ n = 0
132
+ for i = 0; i < len(s) && '0' <= s[i] && s[i] <= '9'; i++ {
133
+ n = n*10 + int(s[i]-'0')
134
+ if n >= big {
135
+ return big, i, false
136
+ }
137
+ }
138
+ if i == 0 {
139
+ return 0, 0, false
140
+ }
141
+ return n, i, true
142
+ }
143
+
144
+ // Hexadecimal to integer.
145
+ // Returns number, characters consumed, success.
146
+ func xtoi(s string) (n int, i int, ok bool) {
147
+ n = 0
148
+ for i = 0; i < len(s); i++ {
149
+ if '0' <= s[i] && s[i] <= '9' {
150
+ n *= 16
151
+ n += int(s[i] - '0')
152
+ } else if 'a' <= s[i] && s[i] <= 'f' {
153
+ n *= 16
154
+ n += int(s[i]-'a') + 10
155
+ } else if 'A' <= s[i] && s[i] <= 'F' {
156
+ n *= 16
157
+ n += int(s[i]-'A') + 10
158
+ } else {
159
+ break
160
+ }
161
+ if n >= big {
162
+ return 0, i, false
163
+ }
164
+ }
165
+ if i == 0 {
166
+ return 0, i, false
167
+ }
168
+ return n, i, true
169
+ }
170
+
171
+ // xtoi2 converts the next two hex digits of s into a byte.
172
+ // If s is longer than 2 bytes then the third byte must be e.
173
+ // If the first two bytes of s are not hex digits or the third byte
174
+ // does not match e, false is returned.
175
+ func xtoi2(s string, e byte) (byte, bool) {
176
+ if len(s) > 2 && s[2] != e {
177
+ return 0, false
178
+ }
179
+ n, ei, ok := xtoi(s[:2])
180
+ return byte(n), ok && ei == 2
181
+ }
182
+
183
+ // hasUpperCase tells whether the given string contains at least one upper-case.
184
+ func hasUpperCase(s string) bool {
185
+ for i := range s {
186
+ if 'A' <= s[i] && s[i] <= 'Z' {
187
+ return true
188
+ }
189
+ }
190
+ return false
191
+ }
192
+
193
+ // lowerASCIIBytes makes x ASCII lowercase in-place.
194
+ func lowerASCIIBytes(x []byte) {
195
+ for i, b := range x {
196
+ if 'A' <= b && b <= 'Z' {
197
+ x[i] += 'a' - 'A'
198
+ }
199
+ }
200
+ }
201
+
202
+ // lowerASCII returns the ASCII lowercase version of b.
203
+ func lowerASCII(b byte) byte {
204
+ if 'A' <= b && b <= 'Z' {
205
+ return b + ('a' - 'A')
206
+ }
207
+ return b
208
+ }
209
+
210
+ // trimSpace returns x without any leading or trailing ASCII whitespace.
211
+ func trimSpace(x string) string {
212
+ for len(x) > 0 && isSpace(x[0]) {
213
+ x = x[1:]
214
+ }
215
+ for len(x) > 0 && isSpace(x[len(x)-1]) {
216
+ x = x[:len(x)-1]
217
+ }
218
+ return x
219
+ }
220
+
221
+ // isSpace reports whether b is an ASCII space character.
222
+ func isSpace(b byte) bool {
223
+ return b == ' ' || b == '\t' || b == '\n' || b == '\r'
224
+ }
225
+
226
+ // removeComment returns line, removing any '#' byte and any following
227
+ // bytes.
228
+ func removeComment(line string) string {
229
+ if i := bytealg.IndexByteString(line, '#'); i != -1 {
230
+ return line[:i]
231
+ }
232
+ return line
233
+ }
234
+
235
+ // foreachField runs fn on each non-empty run of non-space bytes in x.
236
+ // It returns the first non-nil error returned by fn.
237
+ func foreachField(x string, fn func(field string) error) error {
238
+ x = trimSpace(x)
239
+ for len(x) > 0 {
240
+ sp := bytealg.IndexByteString(x, ' ')
241
+ if sp == -1 {
242
+ return fn(x)
243
+ }
244
+ if field := trimSpace(x[:sp]); len(field) > 0 {
245
+ if err := fn(field); err != nil {
246
+ return err
247
+ }
248
+ }
249
+ x = trimSpace(x[sp+1:])
250
+ }
251
+ return nil
252
+ }
253
+
254
+ // stringsHasSuffix is strings.HasSuffix. It reports whether s ends in
255
+ // suffix.
256
+ func stringsHasSuffix(s, suffix string) bool {
257
+ return len(s) >= len(suffix) && s[len(s)-len(suffix):] == suffix
258
+ }
259
+
260
+ // stringsHasSuffixFold reports whether s ends in suffix,
261
+ // ASCII-case-insensitively.
262
+ func stringsHasSuffixFold(s, suffix string) bool {
263
+ return len(s) >= len(suffix) && stringsEqualFold(s[len(s)-len(suffix):], suffix)
264
+ }
265
+
266
+ // stringsHasPrefix is strings.HasPrefix. It reports whether s begins with prefix.
267
+ func stringsHasPrefix(s, prefix string) bool {
268
+ return len(s) >= len(prefix) && s[:len(prefix)] == prefix
269
+ }
270
+
271
+ // stringsEqualFold is strings.EqualFold, ASCII only. It reports whether s and t
272
+ // are equal, ASCII-case-insensitively.
273
+ func stringsEqualFold(s, t string) bool {
274
+ if len(s) != len(t) {
275
+ return false
276
+ }
277
+ for i := 0; i < len(s); i++ {
278
+ if lowerASCII(s[i]) != lowerASCII(t[i]) {
279
+ return false
280
+ }
281
+ }
282
+ return true
283
+ }
platform/dbops/binaries/go/go/src/net/parse_test.go ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "bufio"
9
+ "os"
10
+ "runtime"
11
+ "testing"
12
+ )
13
+
14
+ func TestReadLine(t *testing.T) {
15
+ // /etc/services file does not exist on android, plan9, windows, or wasip1
16
+ // where it would be required to be mounted from the host file system.
17
+ switch runtime.GOOS {
18
+ case "android", "plan9", "windows", "wasip1":
19
+ t.Skipf("not supported on %s", runtime.GOOS)
20
+ }
21
+ filename := "/etc/services" // a nice big file
22
+
23
+ fd, err := os.Open(filename)
24
+ if err != nil {
25
+ t.Fatal(err)
26
+ }
27
+ defer fd.Close()
28
+ br := bufio.NewReader(fd)
29
+
30
+ file, err := open(filename)
31
+ if file == nil {
32
+ t.Fatal(err)
33
+ }
34
+ defer file.close()
35
+
36
+ lineno := 1
37
+ byteno := 0
38
+ for {
39
+ bline, berr := br.ReadString('\n')
40
+ if n := len(bline); n > 0 {
41
+ bline = bline[0 : n-1]
42
+ }
43
+ line, ok := file.readLine()
44
+ if (berr != nil) != !ok || bline != line {
45
+ t.Fatalf("%s:%d (#%d)\nbufio => %q, %v\nnet => %q, %v", filename, lineno, byteno, bline, berr, line, ok)
46
+ }
47
+ if !ok {
48
+ break
49
+ }
50
+ lineno++
51
+ byteno += len(line) + 1
52
+ }
53
+ }
54
+
55
+ func TestDtoi(t *testing.T) {
56
+ for _, tt := range []struct {
57
+ in string
58
+ out int
59
+ off int
60
+ ok bool
61
+ }{
62
+ {"", 0, 0, false},
63
+ {"0", 0, 1, true},
64
+ {"65536", 65536, 5, true},
65
+ {"123456789", big, 8, false},
66
+ {"-0", 0, 0, false},
67
+ {"-1234", 0, 0, false},
68
+ } {
69
+ n, i, ok := dtoi(tt.in)
70
+ if n != tt.out || i != tt.off || ok != tt.ok {
71
+ t.Errorf("got %d, %d, %v; want %d, %d, %v", n, i, ok, tt.out, tt.off, tt.ok)
72
+ }
73
+ }
74
+ }
platform/dbops/binaries/go/go/src/net/pipe.go ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2010 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
+ "io"
9
+ "os"
10
+ "sync"
11
+ "time"
12
+ )
13
+
14
+ // pipeDeadline is an abstraction for handling timeouts.
15
+ type pipeDeadline struct {
16
+ mu sync.Mutex // Guards timer and cancel
17
+ timer *time.Timer
18
+ cancel chan struct{} // Must be non-nil
19
+ }
20
+
21
+ func makePipeDeadline() pipeDeadline {
22
+ return pipeDeadline{cancel: make(chan struct{})}
23
+ }
24
+
25
+ // set sets the point in time when the deadline will time out.
26
+ // A timeout event is signaled by closing the channel returned by waiter.
27
+ // Once a timeout has occurred, the deadline can be refreshed by specifying a
28
+ // t value in the future.
29
+ //
30
+ // A zero value for t prevents timeout.
31
+ func (d *pipeDeadline) set(t time.Time) {
32
+ d.mu.Lock()
33
+ defer d.mu.Unlock()
34
+
35
+ if d.timer != nil && !d.timer.Stop() {
36
+ <-d.cancel // Wait for the timer callback to finish and close cancel
37
+ }
38
+ d.timer = nil
39
+
40
+ // Time is zero, then there is no deadline.
41
+ closed := isClosedChan(d.cancel)
42
+ if t.IsZero() {
43
+ if closed {
44
+ d.cancel = make(chan struct{})
45
+ }
46
+ return
47
+ }
48
+
49
+ // Time in the future, setup a timer to cancel in the future.
50
+ if dur := time.Until(t); dur > 0 {
51
+ if closed {
52
+ d.cancel = make(chan struct{})
53
+ }
54
+ d.timer = time.AfterFunc(dur, func() {
55
+ close(d.cancel)
56
+ })
57
+ return
58
+ }
59
+
60
+ // Time in the past, so close immediately.
61
+ if !closed {
62
+ close(d.cancel)
63
+ }
64
+ }
65
+
66
+ // wait returns a channel that is closed when the deadline is exceeded.
67
+ func (d *pipeDeadline) wait() chan struct{} {
68
+ d.mu.Lock()
69
+ defer d.mu.Unlock()
70
+ return d.cancel
71
+ }
72
+
73
+ func isClosedChan(c <-chan struct{}) bool {
74
+ select {
75
+ case <-c:
76
+ return true
77
+ default:
78
+ return false
79
+ }
80
+ }
81
+
82
+ type pipeAddr struct{}
83
+
84
+ func (pipeAddr) Network() string { return "pipe" }
85
+ func (pipeAddr) String() string { return "pipe" }
86
+
87
+ type pipe struct {
88
+ wrMu sync.Mutex // Serialize Write operations
89
+
90
+ // Used by local Read to interact with remote Write.
91
+ // Successful receive on rdRx is always followed by send on rdTx.
92
+ rdRx <-chan []byte
93
+ rdTx chan<- int
94
+
95
+ // Used by local Write to interact with remote Read.
96
+ // Successful send on wrTx is always followed by receive on wrRx.
97
+ wrTx chan<- []byte
98
+ wrRx <-chan int
99
+
100
+ once sync.Once // Protects closing localDone
101
+ localDone chan struct{}
102
+ remoteDone <-chan struct{}
103
+
104
+ readDeadline pipeDeadline
105
+ writeDeadline pipeDeadline
106
+ }
107
+
108
+ // Pipe creates a synchronous, in-memory, full duplex
109
+ // network connection; both ends implement the [Conn] interface.
110
+ // Reads on one end are matched with writes on the other,
111
+ // copying data directly between the two; there is no internal
112
+ // buffering.
113
+ func Pipe() (Conn, Conn) {
114
+ cb1 := make(chan []byte)
115
+ cb2 := make(chan []byte)
116
+ cn1 := make(chan int)
117
+ cn2 := make(chan int)
118
+ done1 := make(chan struct{})
119
+ done2 := make(chan struct{})
120
+
121
+ p1 := &pipe{
122
+ rdRx: cb1, rdTx: cn1,
123
+ wrTx: cb2, wrRx: cn2,
124
+ localDone: done1, remoteDone: done2,
125
+ readDeadline: makePipeDeadline(),
126
+ writeDeadline: makePipeDeadline(),
127
+ }
128
+ p2 := &pipe{
129
+ rdRx: cb2, rdTx: cn2,
130
+ wrTx: cb1, wrRx: cn1,
131
+ localDone: done2, remoteDone: done1,
132
+ readDeadline: makePipeDeadline(),
133
+ writeDeadline: makePipeDeadline(),
134
+ }
135
+ return p1, p2
136
+ }
137
+
138
+ func (*pipe) LocalAddr() Addr { return pipeAddr{} }
139
+ func (*pipe) RemoteAddr() Addr { return pipeAddr{} }
140
+
141
+ func (p *pipe) Read(b []byte) (int, error) {
142
+ n, err := p.read(b)
143
+ if err != nil && err != io.EOF && err != io.ErrClosedPipe {
144
+ err = &OpError{Op: "read", Net: "pipe", Err: err}
145
+ }
146
+ return n, err
147
+ }
148
+
149
+ func (p *pipe) read(b []byte) (n int, err error) {
150
+ switch {
151
+ case isClosedChan(p.localDone):
152
+ return 0, io.ErrClosedPipe
153
+ case isClosedChan(p.remoteDone):
154
+ return 0, io.EOF
155
+ case isClosedChan(p.readDeadline.wait()):
156
+ return 0, os.ErrDeadlineExceeded
157
+ }
158
+
159
+ select {
160
+ case bw := <-p.rdRx:
161
+ nr := copy(b, bw)
162
+ p.rdTx <- nr
163
+ return nr, nil
164
+ case <-p.localDone:
165
+ return 0, io.ErrClosedPipe
166
+ case <-p.remoteDone:
167
+ return 0, io.EOF
168
+ case <-p.readDeadline.wait():
169
+ return 0, os.ErrDeadlineExceeded
170
+ }
171
+ }
172
+
173
+ func (p *pipe) Write(b []byte) (int, error) {
174
+ n, err := p.write(b)
175
+ if err != nil && err != io.ErrClosedPipe {
176
+ err = &OpError{Op: "write", Net: "pipe", Err: err}
177
+ }
178
+ return n, err
179
+ }
180
+
181
+ func (p *pipe) write(b []byte) (n int, err error) {
182
+ switch {
183
+ case isClosedChan(p.localDone):
184
+ return 0, io.ErrClosedPipe
185
+ case isClosedChan(p.remoteDone):
186
+ return 0, io.ErrClosedPipe
187
+ case isClosedChan(p.writeDeadline.wait()):
188
+ return 0, os.ErrDeadlineExceeded
189
+ }
190
+
191
+ p.wrMu.Lock() // Ensure entirety of b is written together
192
+ defer p.wrMu.Unlock()
193
+ for once := true; once || len(b) > 0; once = false {
194
+ select {
195
+ case p.wrTx <- b:
196
+ nw := <-p.wrRx
197
+ b = b[nw:]
198
+ n += nw
199
+ case <-p.localDone:
200
+ return n, io.ErrClosedPipe
201
+ case <-p.remoteDone:
202
+ return n, io.ErrClosedPipe
203
+ case <-p.writeDeadline.wait():
204
+ return n, os.ErrDeadlineExceeded
205
+ }
206
+ }
207
+ return n, nil
208
+ }
209
+
210
+ func (p *pipe) SetDeadline(t time.Time) error {
211
+ if isClosedChan(p.localDone) || isClosedChan(p.remoteDone) {
212
+ return io.ErrClosedPipe
213
+ }
214
+ p.readDeadline.set(t)
215
+ p.writeDeadline.set(t)
216
+ return nil
217
+ }
218
+
219
+ func (p *pipe) SetReadDeadline(t time.Time) error {
220
+ if isClosedChan(p.localDone) || isClosedChan(p.remoteDone) {
221
+ return io.ErrClosedPipe
222
+ }
223
+ p.readDeadline.set(t)
224
+ return nil
225
+ }
226
+
227
+ func (p *pipe) SetWriteDeadline(t time.Time) error {
228
+ if isClosedChan(p.localDone) || isClosedChan(p.remoteDone) {
229
+ return io.ErrClosedPipe
230
+ }
231
+ p.writeDeadline.set(t)
232
+ return nil
233
+ }
234
+
235
+ func (p *pipe) Close() error {
236
+ p.once.Do(func() { close(p.localDone) })
237
+ return nil
238
+ }
platform/dbops/binaries/go/go/src/net/pipe_test.go ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2010 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_test
6
+
7
+ import (
8
+ "io"
9
+ "net"
10
+ "testing"
11
+ "time"
12
+
13
+ "golang.org/x/net/nettest"
14
+ )
15
+
16
+ func TestPipe(t *testing.T) {
17
+ nettest.TestConn(t, func() (c1, c2 net.Conn, stop func(), err error) {
18
+ c1, c2 = net.Pipe()
19
+ stop = func() {
20
+ c1.Close()
21
+ c2.Close()
22
+ }
23
+ return
24
+ })
25
+ }
26
+
27
+ func TestPipeCloseError(t *testing.T) {
28
+ c1, c2 := net.Pipe()
29
+ c1.Close()
30
+
31
+ if _, err := c1.Read(nil); err != io.ErrClosedPipe {
32
+ t.Errorf("c1.Read() = %v, want io.ErrClosedPipe", err)
33
+ }
34
+ if _, err := c1.Write(nil); err != io.ErrClosedPipe {
35
+ t.Errorf("c1.Write() = %v, want io.ErrClosedPipe", err)
36
+ }
37
+ if err := c1.SetDeadline(time.Time{}); err != io.ErrClosedPipe {
38
+ t.Errorf("c1.SetDeadline() = %v, want io.ErrClosedPipe", err)
39
+ }
40
+ if _, err := c2.Read(nil); err != io.EOF {
41
+ t.Errorf("c2.Read() = %v, want io.EOF", err)
42
+ }
43
+ if _, err := c2.Write(nil); err != io.ErrClosedPipe {
44
+ t.Errorf("c2.Write() = %v, want io.ErrClosedPipe", err)
45
+ }
46
+ if err := c2.SetDeadline(time.Time{}); err != io.ErrClosedPipe {
47
+ t.Errorf("c2.SetDeadline() = %v, want io.ErrClosedPipe", err)
48
+ }
49
+ }
platform/dbops/binaries/go/go/src/net/platform_test.go ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2015 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/testenv"
9
+ "os"
10
+ "os/exec"
11
+ "runtime"
12
+ "strconv"
13
+ "strings"
14
+ "testing"
15
+ )
16
+
17
+ var unixEnabledOnAIX bool
18
+
19
+ func init() {
20
+ if runtime.GOOS == "aix" {
21
+ // Unix network isn't properly working on AIX 7.2 with
22
+ // Technical Level < 2.
23
+ // The information is retrieved only once in this init()
24
+ // instead of everytime testableNetwork is called.
25
+ out, _ := exec.Command("oslevel", "-s").Output()
26
+ if len(out) >= len("7200-XX-ZZ-YYMM") { // AIX 7.2, Tech Level XX, Service Pack ZZ, date YYMM
27
+ aixVer := string(out[:4])
28
+ tl, _ := strconv.Atoi(string(out[5:7]))
29
+ unixEnabledOnAIX = aixVer > "7200" || (aixVer == "7200" && tl >= 2)
30
+ }
31
+ }
32
+ }
33
+
34
+ // testableNetwork reports whether network is testable on the current
35
+ // platform configuration.
36
+ func testableNetwork(network string) bool {
37
+ net, _, _ := strings.Cut(network, ":")
38
+ switch net {
39
+ case "ip+nopriv":
40
+ case "ip", "ip4", "ip6":
41
+ switch runtime.GOOS {
42
+ case "plan9":
43
+ return false
44
+ default:
45
+ if os.Getuid() != 0 {
46
+ return false
47
+ }
48
+ }
49
+ case "unix", "unixgram":
50
+ switch runtime.GOOS {
51
+ case "android", "ios", "plan9", "windows":
52
+ return false
53
+ case "aix":
54
+ return unixEnabledOnAIX
55
+ }
56
+ case "unixpacket":
57
+ switch runtime.GOOS {
58
+ case "aix", "android", "darwin", "ios", "plan9", "windows":
59
+ return false
60
+ }
61
+ }
62
+ switch net {
63
+ case "tcp4", "udp4", "ip4":
64
+ if !supportsIPv4() {
65
+ return false
66
+ }
67
+ case "tcp6", "udp6", "ip6":
68
+ if !supportsIPv6() {
69
+ return false
70
+ }
71
+ }
72
+ return true
73
+ }
74
+
75
+ // testableAddress reports whether address of network is testable on
76
+ // the current platform configuration.
77
+ func testableAddress(network, address string) bool {
78
+ switch net, _, _ := strings.Cut(network, ":"); net {
79
+ case "unix", "unixgram", "unixpacket":
80
+ // Abstract unix domain sockets, a Linux-ism.
81
+ if address[0] == '@' && runtime.GOOS != "linux" {
82
+ return false
83
+ }
84
+ }
85
+ return true
86
+ }
87
+
88
+ // testableListenArgs reports whether arguments are testable on the
89
+ // current platform configuration.
90
+ func testableListenArgs(network, address, client string) bool {
91
+ if !testableNetwork(network) || !testableAddress(network, address) {
92
+ return false
93
+ }
94
+
95
+ var err error
96
+ var addr Addr
97
+ switch net, _, _ := strings.Cut(network, ":"); net {
98
+ case "tcp", "tcp4", "tcp6":
99
+ addr, err = ResolveTCPAddr("tcp", address)
100
+ case "udp", "udp4", "udp6":
101
+ addr, err = ResolveUDPAddr("udp", address)
102
+ case "ip", "ip4", "ip6":
103
+ addr, err = ResolveIPAddr("ip", address)
104
+ default:
105
+ return true
106
+ }
107
+ if err != nil {
108
+ return false
109
+ }
110
+ var ip IP
111
+ var wildcard bool
112
+ switch addr := addr.(type) {
113
+ case *TCPAddr:
114
+ ip = addr.IP
115
+ wildcard = addr.isWildcard()
116
+ case *UDPAddr:
117
+ ip = addr.IP
118
+ wildcard = addr.isWildcard()
119
+ case *IPAddr:
120
+ ip = addr.IP
121
+ wildcard = addr.isWildcard()
122
+ }
123
+
124
+ // Test wildcard IP addresses.
125
+ if wildcard && !testenv.HasExternalNetwork() {
126
+ return false
127
+ }
128
+
129
+ // Test functionality of IPv4 communication using AF_INET and
130
+ // IPv6 communication using AF_INET6 sockets.
131
+ if !supportsIPv4() && ip.To4() != nil {
132
+ return false
133
+ }
134
+ if !supportsIPv6() && ip.To16() != nil && ip.To4() == nil {
135
+ return false
136
+ }
137
+ cip := ParseIP(client)
138
+ if cip != nil {
139
+ if !supportsIPv4() && cip.To4() != nil {
140
+ return false
141
+ }
142
+ if !supportsIPv6() && cip.To16() != nil && cip.To4() == nil {
143
+ return false
144
+ }
145
+ }
146
+
147
+ // Test functionality of IPv4 communication using AF_INET6
148
+ // sockets.
149
+ if !supportsIPv4map() && supportsIPv4() && (network == "tcp" || network == "udp" || network == "ip") && wildcard {
150
+ // At this point, we prefer IPv4 when ip is nil.
151
+ // See favoriteAddrFamily for further information.
152
+ if ip.To16() != nil && ip.To4() == nil && cip.To4() != nil { // a pair of IPv6 server and IPv4 client
153
+ return false
154
+ }
155
+ if (ip.To4() != nil || ip == nil) && cip.To16() != nil && cip.To4() == nil { // a pair of IPv4 server and IPv6 client
156
+ return false
157
+ }
158
+ }
159
+
160
+ return true
161
+ }
162
+
163
+ func condFatalf(t *testing.T, network string, format string, args ...any) {
164
+ t.Helper()
165
+ // A few APIs like File and Read/WriteMsg{UDP,IP} are not
166
+ // fully implemented yet on Plan 9 and Windows.
167
+ switch runtime.GOOS {
168
+ case "windows", "js", "wasip1":
169
+ if network == "file+net" {
170
+ t.Logf(format, args...)
171
+ return
172
+ }
173
+ case "plan9":
174
+ t.Logf(format, args...)
175
+ return
176
+ }
177
+ t.Fatalf(format, args...)
178
+ }