Source file src/net/ipsock_posix.go

     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  	_ "unsafe" // for linkname
    16  )
    17  
    18  // probe probes IPv4, IPv6 and IPv4-mapped IPv6 communication
    19  // capabilities which are controlled by the IPV6_V6ONLY socket option
    20  // and kernel configuration.
    21  //
    22  // Should we try to use the IPv4 socket interface if we're only
    23  // dealing with IPv4 sockets? As long as the host system understands
    24  // IPv4-mapped IPv6, it's okay to pass IPv4-mapped IPv6 addresses to
    25  // the IPv6 interface. That simplifies our code and is most
    26  // general. Unfortunately, we need to run on kernels built without
    27  // IPv6 support too. So probe the kernel to figure it out.
    28  func (p *ipStackCapabilities) probe() {
    29  	switch runtime.GOOS {
    30  	case "js", "wasip1":
    31  		// Both ipv4 and ipv6 are faked; see net_fake.go.
    32  		p.ipv4Enabled = true
    33  		p.ipv6Enabled = true
    34  		p.ipv4MappedIPv6Enabled = true
    35  		return
    36  	}
    37  
    38  	s, err := sysSocket(syscall.AF_INET, syscall.SOCK_STREAM, syscall.IPPROTO_TCP)
    39  	switch err {
    40  	case syscall.EAFNOSUPPORT, syscall.EPROTONOSUPPORT:
    41  	case nil:
    42  		poll.CloseFunc(s)
    43  		p.ipv4Enabled = true
    44  	}
    45  	var probes = []struct {
    46  		laddr TCPAddr
    47  		value int
    48  	}{
    49  		// IPv6 communication capability
    50  		{laddr: TCPAddr{IP: ParseIP("::1")}, value: 1},
    51  		// IPv4-mapped IPv6 address communication capability
    52  		{laddr: TCPAddr{IP: IPv4(127, 0, 0, 1)}, value: 0},
    53  	}
    54  	switch runtime.GOOS {
    55  	case "dragonfly", "openbsd":
    56  		// The latest DragonFly BSD and OpenBSD kernels don't
    57  		// support IPV6_V6ONLY=0. They always return an error
    58  		// and we don't need to probe the capability.
    59  		probes = probes[:1]
    60  	}
    61  	for i := range probes {
    62  		s, err := sysSocket(syscall.AF_INET6, syscall.SOCK_STREAM, syscall.IPPROTO_TCP)
    63  		if err != nil {
    64  			continue
    65  		}
    66  		defer poll.CloseFunc(s)
    67  		syscall.SetsockoptInt(s, syscall.IPPROTO_IPV6, syscall.IPV6_V6ONLY, probes[i].value)
    68  		sa, err := probes[i].laddr.sockaddr(syscall.AF_INET6)
    69  		if err != nil {
    70  			continue
    71  		}
    72  		if err := syscall.Bind(s, sa); err != nil {
    73  			// If the bind was denied by a security policy (BPF, seccomp,
    74  			// SELinux, etc.), the kernel still supports IPv6 — the socket
    75  			// was created and setsockopt succeeded. Only treat errors like
    76  			// EADDRNOTAVAIL as lack of support. See go.dev/issue/77430.
    77  			if err != syscall.EPERM && err != syscall.EACCES {
    78  				continue
    79  			}
    80  		}
    81  		if i == 0 {
    82  			p.ipv6Enabled = true
    83  		} else {
    84  			p.ipv4MappedIPv6Enabled = true
    85  		}
    86  	}
    87  }
    88  
    89  // favoriteAddrFamily returns the appropriate address family for the
    90  // given network, laddr, raddr and mode.
    91  //
    92  // If mode indicates "listen" and laddr is a wildcard, we assume that
    93  // the user wants to make a passive-open connection with a wildcard
    94  // address family, both AF_INET and AF_INET6, and a wildcard address
    95  // like the following:
    96  //
    97  //   - A listen for a wildcard communication domain, "tcp" or
    98  //     "udp", with a wildcard address: If the platform supports
    99  //     both IPv6 and IPv4-mapped IPv6 communication capabilities,
   100  //     or does not support IPv4, we use a dual stack, AF_INET6 and
   101  //     IPV6_V6ONLY=0, wildcard address listen. The dual stack
   102  //     wildcard address listen may fall back to an IPv6-only,
   103  //     AF_INET6 and IPV6_V6ONLY=1, wildcard address listen.
   104  //     Otherwise we prefer an IPv4-only, AF_INET, wildcard address
   105  //     listen.
   106  //
   107  //   - A listen for a wildcard communication domain, "tcp" or
   108  //     "udp", with an IPv4 wildcard address: same as above.
   109  //
   110  //   - A listen for a wildcard communication domain, "tcp" or
   111  //     "udp", with an IPv6 wildcard address: same as above.
   112  //
   113  //   - A listen for an IPv4 communication domain, "tcp4" or "udp4",
   114  //     with an IPv4 wildcard address: We use an IPv4-only, AF_INET,
   115  //     wildcard address listen.
   116  //
   117  //   - A listen for an IPv6 communication domain, "tcp6" or "udp6",
   118  //     with an IPv6 wildcard address: We use an IPv6-only, AF_INET6
   119  //     and IPV6_V6ONLY=1, wildcard address listen.
   120  //
   121  // Otherwise guess: If the addresses are IPv4 then returns AF_INET,
   122  // or else returns AF_INET6. It also returns a boolean value what
   123  // designates IPV6_V6ONLY option.
   124  //
   125  // Note that the latest DragonFly BSD and OpenBSD kernels allow
   126  // neither "net.inet6.ip6.v6only=1" change nor IPPROTO_IPV6 level
   127  // IPV6_V6ONLY socket option setting.
   128  //
   129  // favoriteAddrFamily should be an internal detail,
   130  // but widely used packages access it using linkname.
   131  // Notable members of the hall of shame include:
   132  //   - github.com/database64128/tfo-go/v2
   133  //   - github.com/metacubex/tfo-go
   134  //   - github.com/sagernet/tfo-go
   135  //
   136  // Do not remove or change the type signature.
   137  // See go.dev/issue/67401.
   138  //
   139  //go:linkname favoriteAddrFamily
   140  func favoriteAddrFamily(network string, laddr, raddr sockaddr, mode string) (family int, ipv6only bool) {
   141  	switch network[len(network)-1] {
   142  	case '4':
   143  		return syscall.AF_INET, false
   144  	case '6':
   145  		return syscall.AF_INET6, true
   146  	}
   147  
   148  	if mode == "listen" && (laddr == nil || laddr.isWildcard()) {
   149  		if supportsIPv4map() || !supportsIPv4() {
   150  			return syscall.AF_INET6, false
   151  		}
   152  		if laddr == nil {
   153  			return syscall.AF_INET, false
   154  		}
   155  		return laddr.family(), false
   156  	}
   157  
   158  	if (laddr == nil || laddr.family() == syscall.AF_INET) &&
   159  		(raddr == nil || raddr.family() == syscall.AF_INET) {
   160  		return syscall.AF_INET, false
   161  	}
   162  	return syscall.AF_INET6, false
   163  }
   164  
   165  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) {
   166  	switch runtime.GOOS {
   167  	case "aix", "freebsd", "windows", "openbsd", "js", "wasip1":
   168  		if mode == "dial" && raddr.isWildcard() {
   169  			raddr = raddr.toLocal(net)
   170  		}
   171  	}
   172  	family, ipv6only := favoriteAddrFamily(net, laddr, raddr, mode)
   173  	return socket(ctx, net, family, sotype, proto, ipv6only, laddr, raddr, ctrlCtxFn)
   174  }
   175  
   176  func ipToSockaddrInet4(ip IP, port int) (syscall.SockaddrInet4, error) {
   177  	if len(ip) == 0 {
   178  		ip = IPv4zero
   179  	}
   180  	ip4 := ip.To4()
   181  	if ip4 == nil {
   182  		return syscall.SockaddrInet4{}, &AddrError{Err: "non-IPv4 address", Addr: ip.String()}
   183  	}
   184  	sa := syscall.SockaddrInet4{Port: port}
   185  	copy(sa.Addr[:], ip4)
   186  	return sa, nil
   187  }
   188  
   189  func ipToSockaddrInet6(ip IP, port int, zone string) (syscall.SockaddrInet6, error) {
   190  	// In general, an IP wildcard address, which is either
   191  	// "0.0.0.0" or "::", means the entire IP addressing
   192  	// space. For some historical reason, it is used to
   193  	// specify "any available address" on some operations
   194  	// of IP node.
   195  	//
   196  	// When the IP node supports IPv4-mapped IPv6 address,
   197  	// we allow a listener to listen to the wildcard
   198  	// address of both IP addressing spaces by specifying
   199  	// IPv6 wildcard address.
   200  	if len(ip) == 0 || ip.Equal(IPv4zero) {
   201  		ip = IPv6zero
   202  	}
   203  	// We accept any IPv6 address including IPv4-mapped
   204  	// IPv6 address.
   205  	ip6 := ip.To16()
   206  	if ip6 == nil {
   207  		return syscall.SockaddrInet6{}, &AddrError{Err: "non-IPv6 address", Addr: ip.String()}
   208  	}
   209  	sa := syscall.SockaddrInet6{Port: port, ZoneId: uint32(zoneCache.index(zone))}
   210  	copy(sa.Addr[:], ip6)
   211  	return sa, nil
   212  }
   213  
   214  // ipToSockaddr should be an internal detail,
   215  // but widely used packages access it using linkname.
   216  // Notable members of the hall of shame include:
   217  //   - github.com/database64128/tfo-go/v2
   218  //   - github.com/metacubex/tfo-go
   219  //   - github.com/sagernet/tfo-go
   220  //
   221  // Do not remove or change the type signature.
   222  // See go.dev/issue/67401.
   223  //
   224  //go:linkname ipToSockaddr
   225  func ipToSockaddr(family int, ip IP, port int, zone string) (syscall.Sockaddr, error) {
   226  	switch family {
   227  	case syscall.AF_INET:
   228  		sa, err := ipToSockaddrInet4(ip, port)
   229  		if err != nil {
   230  			return nil, err
   231  		}
   232  		return &sa, nil
   233  	case syscall.AF_INET6:
   234  		sa, err := ipToSockaddrInet6(ip, port, zone)
   235  		if err != nil {
   236  			return nil, err
   237  		}
   238  		return &sa, nil
   239  	}
   240  	return nil, &AddrError{Err: "invalid address family", Addr: ip.String()}
   241  }
   242  
   243  func addrPortToSockaddrInet4(ap netip.AddrPort) (syscall.SockaddrInet4, error) {
   244  	// ipToSockaddrInet4 has special handling here for zero length slices.
   245  	// We do not, because netip has no concept of a generic zero IP address.
   246  	//
   247  	// addr is allowed to be an IPv4-mapped IPv6 address.
   248  	// As4 will unmap it to an IPv4 address.
   249  	// The error message is kept consistent with ipToSockaddrInet4.
   250  	addr := ap.Addr()
   251  	if !addr.Is4() && !addr.Is4In6() {
   252  		return syscall.SockaddrInet4{}, &AddrError{Err: "non-IPv4 address", Addr: addr.String()}
   253  	}
   254  	sa := syscall.SockaddrInet4{
   255  		Addr: addr.As4(),
   256  		Port: int(ap.Port()),
   257  	}
   258  	return sa, nil
   259  }
   260  
   261  func addrPortToSockaddrInet6(ap netip.AddrPort) (syscall.SockaddrInet6, error) {
   262  	// ipToSockaddrInet6 has special handling here for zero length slices.
   263  	// We do not, because netip has no concept of a generic zero IP address.
   264  	//
   265  	// addr is allowed to be an IPv4 address, because As16 will convert it
   266  	// to an IPv4-mapped IPv6 address.
   267  	// The error message is kept consistent with ipToSockaddrInet6.
   268  	addr := ap.Addr()
   269  	sa := syscall.SockaddrInet6{
   270  		Addr:   addr.As16(),
   271  		Port:   int(ap.Port()),
   272  		ZoneId: uint32(zoneCache.index(addr.Zone())),
   273  	}
   274  	return sa, nil
   275  }
   276  

View as plain text