-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnative.go
More file actions
984 lines (886 loc) · 25.2 KB
/
Copy pathnative.go
File metadata and controls
984 lines (886 loc) · 25.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
package gonnect
import (
"context"
"fmt"
"net"
"net/netip"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
"syscall"
"time"
)
// Static type assertions
var (
_ Network = &NativeNetwork{}
_ Dial = (&NativeNetwork{}).Dial
_ Listen = (&NativeNetwork{}).Listen
_ LookupIP = (&NativeNetwork{}).LookupIP
_ LookupIPAddr = (&NativeNetwork{}).LookupIPAddr
_ LookupNetIP = (&NativeNetwork{}).LookupNetIP
_ LookupHost = (&NativeNetwork{}).LookupHost
_ LookupAddr = (&NativeNetwork{}).LookupAddr
_ LookupCNAME = (&NativeNetwork{}).LookupCNAME
_ LookupPort = (&NativeNetwork{}).LookupPort
_ LookupTXT = (&NativeNetwork{}).LookupTXT
_ LookupMX = (&NativeNetwork{}).LookupMX
_ LookupNS = (&NativeNetwork{}).LookupNS
_ LookupSRV = (&NativeNetwork{}).LookupSRV
)
const (
actionDial = iota
actionListen
actionLookup
)
// errForAction returns an appropriate error based on the action type.
// For lookup actions, it returns a NoSuchHost error; for listen actions,
// a ListenDeniedErr; and for dial actions, a ConnRefused error.
func errForAction(action int, network, address string) error {
if action == actionLookup {
err := nativeNoSuchHost(address, "rejectdns")
err.UnwrapErr = fmt.Errorf("rejected by filter")
return err
}
if action == actionListen {
return nativeListenDeniedErr(network, address)
}
return nativeConnRefused(network, address)
}
type nativeAddr struct {
network string
address string
}
func (a nativeAddr) Network() string { return a.network }
func (a nativeAddr) String() string { return a.address }
func nativeNoSuchHost(host, srv string) *net.DNSError {
return &net.DNSError{
Err: "no such host",
Name: host,
Server: srv,
IsTemporary: true,
IsNotFound: true,
}
}
func nativeConnRefused(network, address string) error {
return &net.OpError{
Op: "dial",
Net: network,
Source: nil,
Addr: nativeAddr{
network: network,
address: address,
},
Err: &os.SyscallError{
Syscall: "connect",
Err: syscall.ECONNREFUSED,
},
}
}
func nativeListenDeniedErr(network, address string) error {
return &net.OpError{
Op: "listen",
Net: network,
Source: nil,
Addr: nativeAddr{
network: network,
address: address,
},
Err: &os.SyscallError{
Syscall: "bind",
Err: syscall.EACCES,
},
}
}
func nativeJoinIPPort(ip net.IP, port int) string {
return net.JoinHostPort(ip.String(), strconv.Itoa(port))
}
func nativeFamilyFromNetwork(network string) string {
if strings.HasPrefix(network, "ip4") ||
strings.HasPrefix(network, "tcp4") ||
strings.HasPrefix(network, "udp4") {
return "ip4"
}
if strings.HasPrefix(network, "ip6") ||
strings.HasPrefix(network, "tcp6") ||
strings.HasPrefix(network, "udp6") {
return "ip6"
}
return "ip"
}
func nativePickIP(ips []net.IP, prefer int) net.IP {
if len(ips) == 0 {
return nil
}
if prefer != 4 && prefer != 6 {
return ips[0]
}
for _, ip := range ips {
if prefer == 4 && ip.To4() != nil {
return ip
}
if prefer == 6 && ip.To4() == nil {
return ip
}
}
return ips[0]
}
func nativeIPMatchesNetwork(ip netip.Addr, network string) bool {
family := nativeFamilyFromNetwork(network)
return family == "ip" ||
(family == "ip4" && ip.Is4()) ||
(family == "ip6" && ip.Is6())
}
func nativeIPLiteral(host, network string) (net.IP, bool, error) {
addr, err := netip.ParseAddr(host)
if err != nil {
return nil, false, nil // nolint
}
if !nativeIPMatchesNetwork(addr, network) {
return nil, true, nativeNoSuchHost(host, "local")
}
return net.IP(append([]byte(nil), addr.AsSlice()...)), true, nil
}
func nativePortNetwork(network string) string {
if strings.HasPrefix(network, "tcp") {
return "tcp"
}
if strings.HasPrefix(network, "udp") {
return "udp"
}
return network
}
func nativeHostsPaths() []string {
if runtime.GOOS != "windows" {
return []string{"/etc/hosts"}
}
var paths []string
for _, root := range []string{os.Getenv("SystemRoot"), os.Getenv("WINDIR")} {
if root != "" {
paths = append(
paths,
filepath.Join(root, "System32", "drivers", "etc", "hosts"),
)
}
}
return paths
}
func nativeAppendLocalhostIPs(ips []netip.Addr, network string) []netip.Addr {
if ip := netip.MustParseAddr(
"127.0.0.1",
); nativeIPMatchesNetwork(
ip,
network,
) {
ips = append(ips, ip)
}
if ip := netip.MustParseAddr("::1"); nativeIPMatchesNetwork(ip, network) {
ips = append(ips, ip)
}
return ips
}
func nativeLookupHostLocal(host, network string) []netip.Addr {
name := strings.TrimSuffix(strings.ToLower(host), ".")
var ips []netip.Addr
if name == "localhost" {
ips = nativeAppendLocalhostIPs(ips, network)
}
seen := make(map[netip.Addr]bool, len(ips))
for _, ip := range ips {
seen[ip] = true
}
for _, path := range nativeHostsPaths() {
data, err := os.ReadFile(path) //nolint
if err != nil {
continue
}
for line := range strings.SplitSeq(string(data), "\n") {
if i := strings.IndexByte(line, '#'); i >= 0 {
line = line[:i]
}
fields := strings.Fields(line)
if len(fields) < 2 {
continue
}
ip, err := netip.ParseAddr(fields[0])
if err != nil || !nativeIPMatchesNetwork(ip, network) {
continue
}
for _, alias := range fields[1:] {
if strings.TrimSuffix(strings.ToLower(alias), ".") != name {
continue
}
if !seen[ip] {
ips = append(ips, ip)
seen[ip] = true
}
break
}
}
}
return ips
}
// NativeConfig holds configuration options for building a Network.
type NativeConfig struct {
// Filter is an optional filter function that can reject network operations.
// It should return true to reject the operation.
//
// NOTE: filtering works only for connections establishing, unbinded DNS sockset can be used to bypass it
Filter Filter
// ResolverCfg configures the DNS resolver used by the Network.
// If nil, new one will be built.
ResolverCfg *ResolverCfg
// PreferIP specifies IP version preference:
// 4 for IPv4, 6 for IPv6, or 0 for no preference.
PreferIP int
// ListenCfg configures the listen operations. If nil, defaults are used.
ListenCfg *net.ListenConfig
// net.Dialer options
Timeout time.Duration
Deadline time.Time
LocalAddr net.Addr
FallbackDelay time.Duration
KeepAlive time.Duration
KeepAliveConfig net.KeepAliveConfig
Control func(network, address string, c syscall.RawConn) error
ControlContext func(ctx context.Context, network, address string, c syscall.RawConn) error
}
// Build creates and returns a new NativeNetwork instance from the configuration.
func (c NativeConfig) Build() *NativeNetwork {
n := &NativeNetwork{
filter: c.Filter,
preferIP: c.PreferIP,
listenCfg: c.ListenCfg,
}
rc := ResolverCfg{}
if c.ResolverCfg != nil {
rc = *c.ResolverCfg
}
r := rc.Build()
r.Dial = n.dialInternal
n.resolver = &r
n.dialer = net.Dialer{
Resolver: &r,
Timeout: c.Timeout,
Deadline: c.Deadline,
LocalAddr: c.LocalAddr,
FallbackDelay: c.FallbackDelay,
KeepAlive: c.KeepAlive,
KeepAliveConfig: c.KeepAliveConfig,
Control: c.Control,
ControlContext: c.ControlContext,
}
return n
}
// NativeNetwork is a filtered network provider that implements Network.
// It wraps Go's standard net package to provide controlled dialing,
// listening, and DNS resolution with optional filtering.
//
// NativeNetwork does not implement UpDown. Wrap it with DetachNetwork when an
// independently stoppable native network is needed:
//
// n := DetachNetwork(NativeConfig{}.Build(), nil, nil)
type NativeNetwork struct {
mu sync.RWMutex
// filter is an optional function to reject network operations.
filter Filter
// resolver is the DNS resolver used for lookups.
resolver Resolver
// dialer is used for establishing connections.
dialer net.Dialer
// listenCfg configures listen operations.
listenCfg *net.ListenConfig
// preferIP specifies IP version preference (4, 6, or 0).
preferIP int
}
func (n *NativeNetwork) IsNative() bool {
return true
}
// SetResolver replaces the resolver used for lookups. Passing nil restores the
// default resolver.
func (n *NativeNetwork) SetResolver(res Resolver) {
n.mu.Lock()
n.resolver = res
n.mu.Unlock()
}
// LookupIP looks up the host and returns a slice of its IPv4 and IPv6 addresses.
// The network parameter specifies the network type ("ip", "ip4", or "ip6").
// This method applies filtering before performing the lookup.
func (n *NativeNetwork) LookupIP(
ctx context.Context,
network, address string,
) ([]net.IP, error) {
err := n.doFilter(network, address, actionLookup)
if err != nil {
return nil, err
}
return n.getResolver().LookupIP(ctx, network, address)
}
// LookupIPAddr looks up the host and returns a slice of IPAddr structures.
// This method applies filtering before performing the lookup.
func (n *NativeNetwork) LookupIPAddr(
ctx context.Context,
host string,
) ([]net.IPAddr, error) {
err := n.doFilter("", host, actionLookup)
if err != nil {
return nil, err
}
return n.getResolver().LookupIPAddr(ctx, host)
}
// LookupNetIP looks up the host and returns a slice of netip.Addr values.
// The network parameter specifies the network type ("ip", "ip4", or "ip6").
// This method applies filtering before performing the lookup.
func (n *NativeNetwork) LookupNetIP(
ctx context.Context,
network, host string,
) ([]netip.Addr, error) {
err := n.doFilter(network, host, actionLookup)
if err != nil {
return nil, err
}
return n.getResolver().LookupNetIP(ctx, network, host)
}
// LookupHost looks up the host and returns a slice of IP address strings.
// This method applies filtering before performing the lookup.
func (n *NativeNetwork) LookupHost(
ctx context.Context,
host string,
) ([]string, error) {
err := n.doFilter("", host, actionLookup)
if err != nil {
return nil, err
}
return n.getResolver().LookupHost(ctx, host)
}
// LookupAddr performs a reverse lookup for the given address,
// returning a slice of names mapping to that address.
// This method applies filtering before performing the lookup.
func (n *NativeNetwork) LookupAddr(
ctx context.Context,
addr string,
) ([]string, error) {
err := n.doFilter("", addr, actionLookup)
if err != nil {
return nil, err
}
return n.getResolver().LookupAddr(ctx, addr)
}
// LookupCNAME returns the canonical name for the given host.
// This method applies filtering before performing the lookup.
func (n *NativeNetwork) LookupCNAME(
ctx context.Context,
host string,
) (string, error) {
err := n.doFilter("", host, actionLookup)
if err != nil {
return "", err
}
return n.getResolver().LookupCNAME(ctx, host)
}
// LookupPort looks up the port number for the given network and service.
// This method applies filtering before performing the lookup.
func (n *NativeNetwork) LookupPort(
ctx context.Context,
network, service string,
) (int, error) {
err := n.doFilter("", service, actionLookup)
if err != nil {
return 0, err
}
return n.getResolver().LookupPort(ctx, network, service)
}
// LookupTXT returns the DNS TXT records for the given domain name.
// This method applies filtering before performing the lookup.
func (n *NativeNetwork) LookupTXT(
ctx context.Context,
name string,
) ([]string, error) {
err := n.doFilter("", name, actionLookup)
if err != nil {
return nil, err
}
return n.getResolver().LookupTXT(ctx, name)
}
// LookupMX returns the DNS MX records for the given domain name,
// sorted by preference.
// This method applies filtering before performing the lookup.
func (n *NativeNetwork) LookupMX(
ctx context.Context,
name string,
) ([]*net.MX, error) {
err := n.doFilter("", name, actionLookup)
if err != nil {
return nil, err
}
return n.getResolver().LookupMX(ctx, name)
}
// LookupNS returns the DNS NS records for the given domain name.
// This method applies filtering before performing the lookup.
func (n *NativeNetwork) LookupNS(
ctx context.Context,
name string,
) ([]*net.NS, error) {
err := n.doFilter("", name, actionLookup)
if err != nil {
return nil, err
}
return n.getResolver().LookupNS(ctx, name)
}
// LookupSRV tries to resolve an SRV query for the given service, protocol, and domain name.
// The proto parameter is "tcp" or "udp".
// Returns the canonical host name and a slice of SRV records.
// This method applies filtering before performing the lookup.
func (n *NativeNetwork) LookupSRV(
ctx context.Context,
service, proto, name string,
) (string, []*net.SRV, error) {
err := n.doFilter(proto, name, actionLookup)
if err != nil {
return "", nil, err
}
return n.getResolver().LookupSRV(ctx, service, proto, name)
}
// LookupNetAddr resolves a network address string (e.g., "localhost:8080")
// into an IP address and port number.
// The network parameter specifies the network type (e.g., "tcp4", "udp6", "tcp").
// This method applies filtering before performing the resolution.
func (n *NativeNetwork) LookupNetAddr(
ctx context.Context,
network, addr string,
) (net.IP, int, error) {
return n.resolveAddr(ctx, network, addr, actionLookup)
}
// InterfaceAddrs returns the unicast interface addresses associated with the system.
// This method delegates to net.InterfaceAddrs.
func (n *NativeNetwork) InterfaceAddrs() ([]net.Addr, error) {
return net.InterfaceAddrs()
}
// InterfaceMulticastAddrs returns the multicast addresses associated with the system.
// This method delegates to each native interface's MulticastAddrs method.
func (n *NativeNetwork) InterfaceMulticastAddrs() ([]net.Addr, error) {
ifs, err := net.Interfaces()
if err != nil {
return nil, err
}
var ret []net.Addr
for _, iface := range ifs {
addrs, err := iface.MulticastAddrs()
if err != nil {
return nil, err
}
ret = append(ret, addrs...)
}
if ret == nil {
return []net.Addr{}, nil
}
return ret, nil
}
// Interfaces returns all network interfaces available on the system.
// This method delegates to net.Interfaces.
func (n *NativeNetwork) Interfaces() ([]NetworkInterface, error) {
ifs, err := net.Interfaces()
if err != nil {
return nil, err
}
return WrapNativeInterfaces(ifs), nil
}
// InterfacesByIndex returns the network interface with the given index.
// This method delegates to net.InterfaceByIndex.
func (n *NativeNetwork) InterfacesByIndex(
index int,
) ([]NetworkInterface, error) {
i, err := net.InterfaceByIndex(index)
if err != nil {
return nil, err
}
return []NetworkInterface{&NativeInterface{Iface: *i}}, nil
}
// InterfacesByName returns the network interface with the given name.
// This method delegates to net.InterfaceByName.
func (n *NativeNetwork) InterfacesByName(
name string,
) ([]NetworkInterface, error) {
i, err := net.InterfaceByName(name)
if err != nil {
return nil, err
}
return []NetworkInterface{&NativeInterface{Iface: *i}}, nil
}
// Dial establishes a connection to the address on the specified network.
// It applies filtering before dialing.
func (n *NativeNetwork) Dial(
ctx context.Context,
network, address string,
) (net.Conn, error) {
err := n.doFilter(network, address, actionDial)
if err != nil {
return nil, err
}
return n.dialer.DialContext(ctx, network, address)
}
// DialNoResolver establishes a connection like Dial, but it never performs DNS
// resolution. Raw IP:port addresses are dialed directly. Host names are only
// accepted when they can be resolved from local host data without network
// requests.
func (n *NativeNetwork) DialNoResolver(
ctx context.Context,
network, address string,
) (net.Conn, error) {
if _, err := netip.ParseAddrPort(address); err == nil {
return n.Dial(ctx, network, address)
}
err := n.doFilter(network, address, actionDial)
if err != nil {
return nil, err
}
host, serv, err := net.SplitHostPort(address)
if err != nil {
return nil, err
}
port, err := strconv.Atoi(serv)
if err != nil {
port, err = LookupPortOffline(nativePortNetwork(network), serv)
if err != nil {
return nil, err
}
}
ip, err := netip.ParseAddr(host)
if err == nil {
if !nativeIPMatchesNetwork(ip, network) {
return nil, nativeNoSuchHost(host, "local")
}
return n.Dial(
ctx,
network,
net.JoinHostPort(ip.String(), strconv.Itoa(port)),
)
}
ips := nativeLookupHostLocal(host, network)
if len(ips) == 0 {
return nil, nativeNoSuchHost(host, "local")
}
return n.Dial(
ctx,
network,
net.JoinHostPort(ips[0].String(), strconv.Itoa(port)),
)
}
// Listen announces on the specified network and address.
// It resolves the address, applies filtering, and creates a listener.
func (n *NativeNetwork) Listen(
ctx context.Context,
network, address string,
) (net.Listener, error) {
ip, port, err := n.resolveAddr(ctx, network, address, actionListen)
if err != nil {
return nil, err
}
address = nativeJoinIPPort(ip, port)
return n.getListenCfg().Listen(ctx, network, address)
}
// ListenPacket announces on the specified network and address for packet-oriented protocols.
// It resolves the address, applies filtering, and creates a packet connection.
func (n *NativeNetwork) ListenPacket(
ctx context.Context,
network, address string,
) (PacketConn, error) {
ip, port, err := n.resolveAddr(ctx, network, address, actionListen)
if err != nil {
return nil, err
}
address = nativeJoinIPPort(ip, port)
c, err := n.getListenCfg().ListenPacket(ctx, network, address)
if err != nil {
return nil, err
}
pc, ok := c.(PacketConn)
if ok {
return pc, nil
}
_ = c.Close()
return nil, nativeConnRefused(network, address)
}
// ListenPacketConfig announces on the specified network and address for
// packet-oriented protocols using the provided listen configuration.
// It resolves the address, applies filtering, and creates a packet connection.
func (n *NativeNetwork) ListenPacketConfig(
ctx context.Context,
lc *ListenConfig,
network, address string,
) (PacketConn, error) {
ip, port, err := n.resolveAddr(ctx, network, address, actionListen)
if err != nil {
return nil, err
}
address = nativeJoinIPPort(ip, port)
c, err := n.getListenCfgWith(lc).ListenPacket(ctx, network, address)
if err != nil {
return nil, err
}
pc, ok := c.(PacketConn)
if ok {
return pc, nil
}
_ = c.Close()
return nil, nativeConnRefused(network, address)
}
// DialTCP establishes a TCP connection to the remote address using the specified network.
// If laddr is not empty, it is used as the local address for the connection.
func (n *NativeNetwork) DialTCP(
ctx context.Context,
network, laddr, raddr string,
) (TCPConn, error) {
var laddrTCP *net.TCPAddr
var err error
if laddr != "" {
laddrTCP, err = n.resolveTCPAddr(ctx, network, laddr, actionDial)
if err != nil {
return nil, err
}
}
raddrTCP, err := n.resolveTCPAddr(ctx, network, raddr, actionDial)
if err != nil {
return nil, err
}
dialer := n.dialer
if laddrTCP != nil {
dialer.LocalAddr = laddrTCP
}
c, err := dialer.DialContext(ctx, network, raddrTCP.String())
if err != nil {
return nil, err
}
tc, ok := c.(*net.TCPConn)
if ok {
return tc, nil
}
_ = c.Close()
return nil, nativeConnRefused(network, raddrTCP.String())
}
// ListenTCP announces on the specified network and address for TCP connections.
// It resolves the address, applies filtering, and creates a TCP listener.
func (n *NativeNetwork) ListenTCP(
ctx context.Context,
network, laddr string,
) (TCPListener, error) {
laddrTCP, err := n.resolveTCPAddr(ctx, network, laddr, actionListen)
if err != nil {
return nil, err
}
l, err := n.getListenCfg().Listen(ctx, network, laddrTCP.String())
if err != nil {
return nil, err
}
tl, ok := l.(*net.TCPListener)
if ok {
return &NetTCPListener{
TCPListener: tl,
}, nil
}
_ = l.Close()
return nil, nativeListenDeniedErr(network, laddrTCP.String())
}
// PacketDial establishes a UDP connection to the remote address using the specified network.
func (n *NativeNetwork) PacketDial(
ctx context.Context, network, address string,
) (PacketConn, error) {
return n.DialUDP(ctx, network, "", address)
}
// DialUDP establishes a UDP connection to the remote address using the specified network.
// If laddr is not empty, it is used as the local address for the connection.
func (n *NativeNetwork) DialUDP(
ctx context.Context,
network, laddr, raddr string,
) (UDPConn, error) {
var laddrUDP *net.UDPAddr
var err error
if laddr != "" {
laddrUDP, err = n.resolveUDPAddr(ctx, network, laddr, actionDial)
if err != nil {
return nil, err
}
}
raddrUDP, err := n.resolveUDPAddr(ctx, network, raddr, actionDial)
if err != nil {
return nil, err
}
dialer := n.dialer
if laddrUDP != nil {
dialer.LocalAddr = laddrUDP
}
c, err := dialer.DialContext(ctx, network, raddrUDP.String())
if err != nil {
return nil, err
}
uc, ok := c.(UDPConn)
if ok {
return uc, nil
}
_ = c.Close()
return nil, nativeConnRefused(network, raddrUDP.String())
}
// ListenUDP announces on the specified network and address for UDP connections.
// It resolves the address, applies filtering, and creates a UDP connection.
func (n *NativeNetwork) ListenUDP(
ctx context.Context,
network, laddr string,
) (UDPConn, error) {
return n.ListenUDPConfig(ctx, nil, network, laddr)
}
// ListenUDPConfig announces on the specified network and address for UDP
// connections using the provided listen configuration. Since net.ListenConfig
// does not expose ListenUDP, this is implemented via ListenPacket and narrowed
// back to UDPConn.
func (n *NativeNetwork) ListenUDPConfig(
ctx context.Context,
lc *ListenConfig,
network, laddr string,
) (UDPConn, error) {
laddrUDP, err := n.resolveUDPAddr(ctx, network, laddr, actionListen)
if err != nil {
return nil, err
}
c, err := n.getListenCfgWith(lc).
ListenPacket(ctx, network, laddrUDP.String())
if err != nil {
return nil, err
}
uc, ok := c.(UDPConn)
if ok {
return uc, nil
}
_ = c.Close()
return nil, nativeConnRefused(network, laddrUDP.String())
}
// doFilter applies the filter function if set.
// It returns an error if the filter rejects the operation.
func (n *NativeNetwork) doFilter(network, address string, action int) error {
if n.filter == nil {
return nil
}
if n.filter(network, address) {
return errForAction(action, network, address)
}
return nil
}
// dialInternal is the internal dial function used by the resolver.
// It applies filtering before establishing the connection.
func (n *NativeNetwork) dialInternal(
ctx context.Context,
network, address string,
) (net.Conn, error) {
err := n.doFilter(network, address, actionDial)
if err != nil {
return nil, err
}
return n.dialer.DialContext(ctx, network, address)
}
// getResolver returns the configured resolver or net.DefaultResolver if none is set.
func (n *NativeNetwork) getResolver() Resolver {
n.mu.RLock()
defer n.mu.RUnlock()
if n.resolver == nil {
return net.DefaultResolver
}
return n.resolver
}
// getListenCfg returns the configured listen config or a default one if none is set.
func (n *NativeNetwork) getListenCfg() *net.ListenConfig {
cfg := &net.ListenConfig{}
if n.listenCfg == nil {
return cfg
}
cfg.Control = n.listenCfg.Control
cfg.KeepAlive = n.listenCfg.KeepAlive
cfg.KeepAliveConfig = n.listenCfg.KeepAliveConfig
return cfg
}
// getListenCfgWith returns a copy of the configured listen config with the
// provided ListenConfig merged into it.
func (n *NativeNetwork) getListenCfgWith(lc *ListenConfig) *net.ListenConfig {
cfg := *n.getListenCfg()
cfg.Control = lc.MergeNet(n.getListenCfg()).Control
return &cfg
}
// resolveAddr resolves a network address string into an IP and port.
// It applies filtering before and after resolution (if port lookup is needed).
func (n *NativeNetwork) resolveAddr(
ctx context.Context, network, addr string, action int,
) (net.IP, int, error) {
err := n.doFilter(network, addr, action)
if err != nil {
return nil, 0, err
}
host, serv, err := net.SplitHostPort(addr)
if err != nil {
return nil, 0, err
}
resolver := n.getResolver()
ipNet := nativeFamilyFromNetwork(network) // "ip","ip4" or "ip6"
ip, ok, err := nativeIPLiteral(host, ipNet)
if err != nil {
return nil, 0, err
}
if !ok {
ips, err := resolver.LookupIP(ctx, ipNet, host)
if err != nil {
return nil, 0, err
}
ip = nativePickIP(ips, n.preferIP)
}
port, err := strconv.Atoi(serv)
if err != nil {
// serv is not a port, lookup
port, err = resolver.LookupPort(ctx, network, serv)
if err != nil {
return nil, 0, err
}
err = n.doFilter(
network, net.JoinHostPort(ip.String(), strconv.Itoa(port)), action,
)
} else {
// serv is a port already
err = n.doFilter(network, net.JoinHostPort(ip.String(), serv), action)
}
if err != nil {
return nil, 0, err
}
return ip, port, nil
}
// resolveTCPAddr resolves a network address string into a TCPAddr.
// It applies filtering through resolveAddr before constructing the result.
func (n *NativeNetwork) resolveTCPAddr(
ctx context.Context,
network, addr string,
action int,
) (*net.TCPAddr, error) {
ip, port, err := n.resolveAddr(ctx, network, addr, action)
if err != nil {
return nil, err
}
addrTCP := &net.TCPAddr{
IP: ip,
Port: port,
}
return addrTCP, nil
}
// resolveUDPAddr resolves a network address string into a UDPAddr.
// It applies filtering through resolveAddr before constructing the result.
func (n *NativeNetwork) resolveUDPAddr(
ctx context.Context,
network, addr string,
action int,
) (*net.UDPAddr, error) {
ip, port, err := n.resolveAddr(ctx, network, addr, action)
if err != nil {
return nil, err
}
addrUDP := &net.UDPAddr{
IP: ip,
Port: port,
}
return addrUDP, nil
}