Source file src/net/cgo_unix.go

     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  // This file is called cgo_unix.go, but to allow syscalls-to-libc-based
     6  // implementations to share the code, it does not use cgo directly.
     7  // Instead of C.foo it uses _C_foo, which is defined in either
     8  // cgo_unix_cgo.go or cgo_unix_syscall.go
     9  
    10  //go:build !netgo && ((cgo && unix) || darwin)
    11  
    12  package net
    13  
    14  import (
    15  	"context"
    16  	"errors"
    17  	"net/netip"
    18  	"syscall"
    19  	"unsafe"
    20  
    21  	"golang.org/x/net/dns/dnsmessage"
    22  )
    23  
    24  // cgoAvailable set to true to indicate that the cgo resolver
    25  // is available on this system.
    26  const cgoAvailable = true
    27  
    28  // An addrinfoErrno represents a getaddrinfo, getnameinfo-specific
    29  // error number. It's a signed number and a zero value is a non-error
    30  // by convention.
    31  type addrinfoErrno int
    32  
    33  func (eai addrinfoErrno) Error() string   { return _C_gai_strerror(_C_int(eai)) }
    34  func (eai addrinfoErrno) Temporary() bool { return eai == _C_EAI_AGAIN }
    35  func (eai addrinfoErrno) Timeout() bool   { return false }
    36  
    37  // isAddrinfoErrno is just for testing purposes.
    38  func (eai addrinfoErrno) isAddrinfoErrno() {}
    39  
    40  // doBlockingWithCtx executes a blocking function in a separate goroutine when the provided
    41  // context is cancellable. It is intended for use with calls that don't support context
    42  // cancellation (cgo, syscalls). blocking func may still be running after this function finishes.
    43  func doBlockingWithCtx[T any](ctx context.Context, blocking func() (T, error)) (T, error) {
    44  	if ctx.Done() == nil {
    45  		return blocking()
    46  	}
    47  
    48  	type result struct {
    49  		res T
    50  		err error
    51  	}
    52  
    53  	res := make(chan result, 1)
    54  	go func() {
    55  		var r result
    56  		r.res, r.err = blocking()
    57  		res <- r
    58  	}()
    59  
    60  	select {
    61  	case r := <-res:
    62  		return r.res, r.err
    63  	case <-ctx.Done():
    64  		var zero T
    65  		return zero, mapErr(ctx.Err())
    66  	}
    67  }
    68  
    69  func cgoLookupHost(ctx context.Context, name string) (hosts []string, err error) {
    70  	addrs, err := cgoLookupIP(ctx, "ip", name)
    71  	if err != nil {
    72  		return nil, err
    73  	}
    74  	for _, addr := range addrs {
    75  		hosts = append(hosts, addr.String())
    76  	}
    77  	return hosts, nil
    78  }
    79  
    80  func cgoLookupPort(ctx context.Context, network, service string) (port int, err error) {
    81  	var hints _C_struct_addrinfo
    82  	switch network {
    83  	case "": // no hints
    84  	case "tcp", "tcp4", "tcp6":
    85  		*_C_ai_socktype(&hints) = _C_SOCK_STREAM
    86  		*_C_ai_protocol(&hints) = _C_IPPROTO_TCP
    87  	case "udp", "udp4", "udp6":
    88  		*_C_ai_socktype(&hints) = _C_SOCK_DGRAM
    89  		*_C_ai_protocol(&hints) = _C_IPPROTO_UDP
    90  	default:
    91  		return 0, &DNSError{Err: "unknown network", Name: network + "/" + service}
    92  	}
    93  	switch ipVersion(network) {
    94  	case '4':
    95  		*_C_ai_family(&hints) = _C_AF_INET
    96  	case '6':
    97  		*_C_ai_family(&hints) = _C_AF_INET6
    98  	}
    99  
   100  	return doBlockingWithCtx(ctx, func() (int, error) {
   101  		return cgoLookupServicePort(&hints, network, service)
   102  	})
   103  }
   104  
   105  func cgoLookupServicePort(hints *_C_struct_addrinfo, network, service string) (port int, err error) {
   106  	cservice, err := syscall.ByteSliceFromString(service)
   107  	if err != nil {
   108  		return 0, &DNSError{Err: err.Error(), Name: network + "/" + service}
   109  	}
   110  	// Lowercase the C service name.
   111  	for i, b := range cservice[:len(service)] {
   112  		cservice[i] = lowerASCII(b)
   113  	}
   114  	var res *_C_struct_addrinfo
   115  	gerrno, err := _C_getaddrinfo(nil, (*_C_char)(unsafe.Pointer(&cservice[0])), hints, &res)
   116  	if gerrno != 0 {
   117  		isTemporary := false
   118  		switch gerrno {
   119  		case _C_EAI_SYSTEM:
   120  			if err == nil { // see golang.org/issue/6232
   121  				err = syscall.EMFILE
   122  			}
   123  		default:
   124  			err = addrinfoErrno(gerrno)
   125  			isTemporary = addrinfoErrno(gerrno).Temporary()
   126  		}
   127  		return 0, &DNSError{Err: err.Error(), Name: network + "/" + service, IsTemporary: isTemporary}
   128  	}
   129  	defer _C_freeaddrinfo(res)
   130  
   131  	for r := res; r != nil; r = *_C_ai_next(r) {
   132  		switch *_C_ai_family(r) {
   133  		case _C_AF_INET:
   134  			sa := (*syscall.RawSockaddrInet4)(unsafe.Pointer(*_C_ai_addr(r)))
   135  			p := (*[2]byte)(unsafe.Pointer(&sa.Port))
   136  			return int(p[0])<<8 | int(p[1]), nil
   137  		case _C_AF_INET6:
   138  			sa := (*syscall.RawSockaddrInet6)(unsafe.Pointer(*_C_ai_addr(r)))
   139  			p := (*[2]byte)(unsafe.Pointer(&sa.Port))
   140  			return int(p[0])<<8 | int(p[1]), nil
   141  		}
   142  	}
   143  	return 0, &DNSError{Err: "unknown port", Name: network + "/" + service}
   144  }
   145  
   146  func cgoLookupHostIP(network, name string) (addrs []IPAddr, err error) {
   147  	acquireThread()
   148  	defer releaseThread()
   149  
   150  	var hints _C_struct_addrinfo
   151  	*_C_ai_flags(&hints) = cgoAddrInfoFlags
   152  	*_C_ai_socktype(&hints) = _C_SOCK_STREAM
   153  	*_C_ai_family(&hints) = _C_AF_UNSPEC
   154  	switch ipVersion(network) {
   155  	case '4':
   156  		*_C_ai_family(&hints) = _C_AF_INET
   157  	case '6':
   158  		*_C_ai_family(&hints) = _C_AF_INET6
   159  	}
   160  
   161  	h, err := syscall.BytePtrFromString(name)
   162  	if err != nil {
   163  		return nil, &DNSError{Err: err.Error(), Name: name}
   164  	}
   165  	var res *_C_struct_addrinfo
   166  	gerrno, err := _C_getaddrinfo((*_C_char)(unsafe.Pointer(h)), nil, &hints, &res)
   167  	if gerrno != 0 {
   168  		isErrorNoSuchHost := false
   169  		isTemporary := false
   170  		switch gerrno {
   171  		case _C_EAI_SYSTEM:
   172  			if err == nil {
   173  				// err should not be nil, but sometimes getaddrinfo returns
   174  				// gerrno == _C_EAI_SYSTEM with err == nil on Linux.
   175  				// The report claims that it happens when we have too many
   176  				// open files, so use syscall.EMFILE (too many open files in system).
   177  				// Most system calls would return ENFILE (too many open files),
   178  				// so at the least EMFILE should be easy to recognize if this
   179  				// comes up again. golang.org/issue/6232.
   180  				err = syscall.EMFILE
   181  			}
   182  		case _C_EAI_NONAME, _C_EAI_NODATA:
   183  			err = errNoSuchHost
   184  			isErrorNoSuchHost = true
   185  		default:
   186  			err = addrinfoErrno(gerrno)
   187  			isTemporary = addrinfoErrno(gerrno).Temporary()
   188  		}
   189  
   190  		return nil, &DNSError{Err: err.Error(), Name: name, IsNotFound: isErrorNoSuchHost, IsTemporary: isTemporary}
   191  	}
   192  	defer _C_freeaddrinfo(res)
   193  
   194  	for r := res; r != nil; r = *_C_ai_next(r) {
   195  		// We only asked for SOCK_STREAM, but check anyhow.
   196  		if *_C_ai_socktype(r) != _C_SOCK_STREAM {
   197  			continue
   198  		}
   199  		switch *_C_ai_family(r) {
   200  		case _C_AF_INET:
   201  			sa := (*syscall.RawSockaddrInet4)(unsafe.Pointer(*_C_ai_addr(r)))
   202  			addr := IPAddr{IP: copyIP(sa.Addr[:])}
   203  			addrs = append(addrs, addr)
   204  		case _C_AF_INET6:
   205  			sa := (*syscall.RawSockaddrInet6)(unsafe.Pointer(*_C_ai_addr(r)))
   206  			addr := IPAddr{IP: copyIP(sa.Addr[:]), Zone: zoneCache.name(int(sa.Scope_id))}
   207  			addrs = append(addrs, addr)
   208  		}
   209  	}
   210  	return addrs, nil
   211  }
   212  
   213  func cgoLookupIP(ctx context.Context, network, name string) (addrs []IPAddr, err error) {
   214  	return doBlockingWithCtx(ctx, func() ([]IPAddr, error) {
   215  		return cgoLookupHostIP(network, name)
   216  	})
   217  }
   218  
   219  // These are roughly enough for the following:
   220  //
   221  //	 Source		Encoding			Maximum length of single name entry
   222  //	 Unicast DNS		ASCII or			<=253 + a NUL terminator
   223  //				Unicode in RFC 5892		252 * total number of labels + delimiters + a NUL terminator
   224  //	 Multicast DNS	UTF-8 in RFC 5198 or		<=253 + a NUL terminator
   225  //				the same as unicast DNS ASCII	<=253 + a NUL terminator
   226  //	 Local database	various				depends on implementation
   227  const (
   228  	nameinfoLen    = 64
   229  	maxNameinfoLen = 4096
   230  )
   231  
   232  func cgoLookupPTR(ctx context.Context, addr string) (names []string, err error) {
   233  	ip, err := netip.ParseAddr(addr)
   234  	if err != nil {
   235  		return nil, &DNSError{Err: "invalid address", Name: addr}
   236  	}
   237  	sa, salen := cgoSockaddr(IP(ip.AsSlice()), ip.Zone())
   238  	if sa == nil {
   239  		return nil, &DNSError{Err: "invalid address " + ip.String(), Name: addr}
   240  	}
   241  
   242  	return doBlockingWithCtx(ctx, func() ([]string, error) {
   243  		return cgoLookupAddrPTR(addr, sa, salen)
   244  	})
   245  }
   246  
   247  func cgoLookupAddrPTR(addr string, sa *_C_struct_sockaddr, salen _C_socklen_t) (names []string, err error) {
   248  	acquireThread()
   249  	defer releaseThread()
   250  
   251  	var gerrno int
   252  	var b []byte
   253  	for l := nameinfoLen; l <= maxNameinfoLen; l *= 2 {
   254  		b = make([]byte, l)
   255  		gerrno, err = cgoNameinfoPTR(b, sa, salen)
   256  		if gerrno == 0 || gerrno != _C_EAI_OVERFLOW {
   257  			break
   258  		}
   259  	}
   260  	if gerrno != 0 {
   261  		isErrorNoSuchHost := false
   262  		isTemporary := false
   263  		switch gerrno {
   264  		case _C_EAI_SYSTEM:
   265  			if err == nil { // see golang.org/issue/6232
   266  				err = syscall.EMFILE
   267  			}
   268  		case _C_EAI_NONAME:
   269  			err = errNoSuchHost
   270  			isErrorNoSuchHost = true
   271  		default:
   272  			err = addrinfoErrno(gerrno)
   273  			isTemporary = addrinfoErrno(gerrno).Temporary()
   274  		}
   275  		return nil, &DNSError{Err: err.Error(), Name: addr, IsTemporary: isTemporary, IsNotFound: isErrorNoSuchHost}
   276  	}
   277  	for i := 0; i < len(b); i++ {
   278  		if b[i] == 0 {
   279  			b = b[:i]
   280  			break
   281  		}
   282  	}
   283  	return []string{absDomainName(string(b))}, nil
   284  }
   285  
   286  func cgoSockaddr(ip IP, zone string) (*_C_struct_sockaddr, _C_socklen_t) {
   287  	if ip4 := ip.To4(); ip4 != nil {
   288  		return cgoSockaddrInet4(ip4), _C_socklen_t(syscall.SizeofSockaddrInet4)
   289  	}
   290  	if ip6 := ip.To16(); ip6 != nil {
   291  		return cgoSockaddrInet6(ip6, zoneCache.index(zone)), _C_socklen_t(syscall.SizeofSockaddrInet6)
   292  	}
   293  	return nil, 0
   294  }
   295  
   296  func cgoLookupCNAME(ctx context.Context, name string) (cname string, err error, completed bool) {
   297  	resources, err := resSearch(ctx, name, int(dnsmessage.TypeCNAME), int(dnsmessage.ClassINET))
   298  	if err != nil {
   299  		return
   300  	}
   301  	cname, err = parseCNAMEFromResources(resources)
   302  	if err != nil {
   303  		return "", err, false
   304  	}
   305  	return cname, nil, true
   306  }
   307  
   308  // resSearch will make a call to the 'res_nsearch' routine in the C library
   309  // and parse the output as a slice of DNS resources.
   310  func resSearch(ctx context.Context, hostname string, rtype, class int) ([]dnsmessage.Resource, error) {
   311  	return doBlockingWithCtx(ctx, func() ([]dnsmessage.Resource, error) {
   312  		return cgoResSearch(hostname, rtype, class)
   313  	})
   314  }
   315  
   316  func cgoResSearch(hostname string, rtype, class int) ([]dnsmessage.Resource, error) {
   317  	acquireThread()
   318  	defer releaseThread()
   319  
   320  	state := (*_C_struct___res_state)(_C_malloc(unsafe.Sizeof(_C_struct___res_state{})))
   321  	defer _C_free(unsafe.Pointer(state))
   322  	if err := _C_res_ninit(state); err != nil {
   323  		return nil, errors.New("res_ninit failure: " + err.Error())
   324  	}
   325  	defer _C_res_nclose(state)
   326  
   327  	// Some res_nsearch implementations (like macOS) do not set errno.
   328  	// They set h_errno, which is not per-thread and useless to us.
   329  	// res_nsearch returns the size of the DNS response packet.
   330  	// But if the DNS response packet contains failure-like response codes,
   331  	// res_search returns -1 even though it has copied the packet into buf,
   332  	// giving us no way to find out how big the packet is.
   333  	// For now, we are willing to take res_search's word that there's nothing
   334  	// useful in the response, even though there *is* a response.
   335  	bufSize := maxDNSPacketSize
   336  	buf := (*_C_uchar)(_C_malloc(uintptr(bufSize)))
   337  	defer _C_free(unsafe.Pointer(buf))
   338  
   339  	s, err := syscall.BytePtrFromString(hostname)
   340  	if err != nil {
   341  		return nil, err
   342  	}
   343  
   344  	var size int
   345  	for {
   346  		size, _ = _C_res_nsearch(state, (*_C_char)(unsafe.Pointer(s)), class, rtype, buf, bufSize)
   347  		if size <= 0 || size > 0xffff {
   348  			return nil, errors.New("res_nsearch failure")
   349  		}
   350  		if size <= bufSize {
   351  			break
   352  		}
   353  
   354  		// Allocate a bigger buffer to fit the entire msg.
   355  		_C_free(unsafe.Pointer(buf))
   356  		bufSize = size
   357  		buf = (*_C_uchar)(_C_malloc(uintptr(bufSize)))
   358  	}
   359  
   360  	var p dnsmessage.Parser
   361  	if _, err := p.Start(unsafe.Slice((*byte)(unsafe.Pointer(buf)), size)); err != nil {
   362  		return nil, err
   363  	}
   364  	p.SkipAllQuestions()
   365  	resources, err := p.AllAnswers()
   366  	if err != nil {
   367  		return nil, err
   368  	}
   369  	return resources, nil
   370  }
   371  

View as plain text