...
Run Format

Source file src/net/cgo_unix.go

Documentation: net

     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  // +build cgo,!netgo
     6  // +build darwin dragonfly freebsd linux netbsd openbsd solaris
     7  
     8  package net
     9  
    10  /*
    11  #include <sys/types.h>
    12  #include <sys/socket.h>
    13  #include <netinet/in.h>
    14  #include <netdb.h>
    15  #include <unistd.h>
    16  #include <string.h>
    17  */
    18  import "C"
    19  
    20  import (
    21  	"context"
    22  	"syscall"
    23  	"unsafe"
    24  )
    25  
    26  // An addrinfoErrno represents a getaddrinfo, getnameinfo-specific
    27  // error number. It's a signed number and a zero value is a non-error
    28  // by convention.
    29  type addrinfoErrno int
    30  
    31  func (eai addrinfoErrno) Error() string   { return C.GoString(C.gai_strerror(C.int(eai))) }
    32  func (eai addrinfoErrno) Temporary() bool { return eai == C.EAI_AGAIN }
    33  func (eai addrinfoErrno) Timeout() bool   { return false }
    34  
    35  type portLookupResult struct {
    36  	port int
    37  	err  error
    38  }
    39  
    40  type ipLookupResult struct {
    41  	addrs []IPAddr
    42  	cname string
    43  	err   error
    44  }
    45  
    46  type reverseLookupResult struct {
    47  	names []string
    48  	err   error
    49  }
    50  
    51  func cgoLookupHost(ctx context.Context, name string) (hosts []string, err error, completed bool) {
    52  	addrs, err, completed := cgoLookupIP(ctx, "ip", name)
    53  	for _, addr := range addrs {
    54  		hosts = append(hosts, addr.String())
    55  	}
    56  	return
    57  }
    58  
    59  func cgoLookupPort(ctx context.Context, network, service string) (port int, err error, completed bool) {
    60  	var hints C.struct_addrinfo
    61  	switch network {
    62  	case "": // no hints
    63  	case "tcp", "tcp4", "tcp6":
    64  		hints.ai_socktype = C.SOCK_STREAM
    65  		hints.ai_protocol = C.IPPROTO_TCP
    66  	case "udp", "udp4", "udp6":
    67  		hints.ai_socktype = C.SOCK_DGRAM
    68  		hints.ai_protocol = C.IPPROTO_UDP
    69  	default:
    70  		return 0, &DNSError{Err: "unknown network", Name: network + "/" + service}, true
    71  	}
    72  	switch ipVersion(network) {
    73  	case '4':
    74  		hints.ai_family = C.AF_INET
    75  	case '6':
    76  		hints.ai_family = C.AF_INET6
    77  	}
    78  	if ctx.Done() == nil {
    79  		port, err := cgoLookupServicePort(&hints, network, service)
    80  		return port, err, true
    81  	}
    82  	result := make(chan portLookupResult, 1)
    83  	go cgoPortLookup(result, &hints, network, service)
    84  	select {
    85  	case r := <-result:
    86  		return r.port, r.err, true
    87  	case <-ctx.Done():
    88  		// Since there isn't a portable way to cancel the lookup,
    89  		// we just let it finish and write to the buffered channel.
    90  		return 0, mapErr(ctx.Err()), false
    91  	}
    92  }
    93  
    94  func cgoLookupServicePort(hints *C.struct_addrinfo, network, service string) (port int, err error) {
    95  	cservice := make([]byte, len(service)+1)
    96  	copy(cservice, service)
    97  	// Lowercase the C service name.
    98  	for i, b := range cservice[:len(service)] {
    99  		cservice[i] = lowerASCII(b)
   100  	}
   101  	var res *C.struct_addrinfo
   102  	gerrno, err := C.getaddrinfo(nil, (*C.char)(unsafe.Pointer(&cservice[0])), hints, &res)
   103  	if gerrno != 0 {
   104  		switch gerrno {
   105  		case C.EAI_SYSTEM:
   106  			if err == nil { // see golang.org/issue/6232
   107  				err = syscall.EMFILE
   108  			}
   109  		default:
   110  			err = addrinfoErrno(gerrno)
   111  		}
   112  		return 0, &DNSError{Err: err.Error(), Name: network + "/" + service}
   113  	}
   114  	defer C.freeaddrinfo(res)
   115  
   116  	for r := res; r != nil; r = r.ai_next {
   117  		switch r.ai_family {
   118  		case C.AF_INET:
   119  			sa := (*syscall.RawSockaddrInet4)(unsafe.Pointer(r.ai_addr))
   120  			p := (*[2]byte)(unsafe.Pointer(&sa.Port))
   121  			return int(p[0])<<8 | int(p[1]), nil
   122  		case C.AF_INET6:
   123  			sa := (*syscall.RawSockaddrInet6)(unsafe.Pointer(r.ai_addr))
   124  			p := (*[2]byte)(unsafe.Pointer(&sa.Port))
   125  			return int(p[0])<<8 | int(p[1]), nil
   126  		}
   127  	}
   128  	return 0, &DNSError{Err: "unknown port", Name: network + "/" + service}
   129  }
   130  
   131  func cgoPortLookup(result chan<- portLookupResult, hints *C.struct_addrinfo, network, service string) {
   132  	port, err := cgoLookupServicePort(hints, network, service)
   133  	result <- portLookupResult{port, err}
   134  }
   135  
   136  func cgoLookupIPCNAME(network, name string) (addrs []IPAddr, cname string, err error) {
   137  	acquireThread()
   138  	defer releaseThread()
   139  
   140  	var hints C.struct_addrinfo
   141  	hints.ai_flags = cgoAddrInfoFlags
   142  	hints.ai_socktype = C.SOCK_STREAM
   143  	hints.ai_family = C.AF_UNSPEC
   144  	switch ipVersion(network) {
   145  	case '4':
   146  		hints.ai_family = C.AF_INET
   147  	case '6':
   148  		hints.ai_family = C.AF_INET6
   149  	}
   150  
   151  	h := make([]byte, len(name)+1)
   152  	copy(h, name)
   153  	var res *C.struct_addrinfo
   154  	gerrno, err := C.getaddrinfo((*C.char)(unsafe.Pointer(&h[0])), nil, &hints, &res)
   155  	if gerrno != 0 {
   156  		switch gerrno {
   157  		case C.EAI_SYSTEM:
   158  			if err == nil {
   159  				// err should not be nil, but sometimes getaddrinfo returns
   160  				// gerrno == C.EAI_SYSTEM with err == nil on Linux.
   161  				// The report claims that it happens when we have too many
   162  				// open files, so use syscall.EMFILE (too many open files in system).
   163  				// Most system calls would return ENFILE (too many open files),
   164  				// so at the least EMFILE should be easy to recognize if this
   165  				// comes up again. golang.org/issue/6232.
   166  				err = syscall.EMFILE
   167  			}
   168  		case C.EAI_NONAME:
   169  			err = errNoSuchHost
   170  		default:
   171  			err = addrinfoErrno(gerrno)
   172  		}
   173  		return nil, "", &DNSError{Err: err.Error(), Name: name}
   174  	}
   175  	defer C.freeaddrinfo(res)
   176  
   177  	if res != nil {
   178  		cname = C.GoString(res.ai_canonname)
   179  		if cname == "" {
   180  			cname = name
   181  		}
   182  		if len(cname) > 0 && cname[len(cname)-1] != '.' {
   183  			cname += "."
   184  		}
   185  	}
   186  	for r := res; r != nil; r = r.ai_next {
   187  		// We only asked for SOCK_STREAM, but check anyhow.
   188  		if r.ai_socktype != C.SOCK_STREAM {
   189  			continue
   190  		}
   191  		switch r.ai_family {
   192  		case C.AF_INET:
   193  			sa := (*syscall.RawSockaddrInet4)(unsafe.Pointer(r.ai_addr))
   194  			addr := IPAddr{IP: copyIP(sa.Addr[:])}
   195  			addrs = append(addrs, addr)
   196  		case C.AF_INET6:
   197  			sa := (*syscall.RawSockaddrInet6)(unsafe.Pointer(r.ai_addr))
   198  			addr := IPAddr{IP: copyIP(sa.Addr[:]), Zone: zoneCache.name(int(sa.Scope_id))}
   199  			addrs = append(addrs, addr)
   200  		}
   201  	}
   202  	return addrs, cname, nil
   203  }
   204  
   205  func cgoIPLookup(result chan<- ipLookupResult, network, name string) {
   206  	addrs, cname, err := cgoLookupIPCNAME(network, name)
   207  	result <- ipLookupResult{addrs, cname, err}
   208  }
   209  
   210  func cgoLookupIP(ctx context.Context, network, name string) (addrs []IPAddr, err error, completed bool) {
   211  	if ctx.Done() == nil {
   212  		addrs, _, err = cgoLookupIPCNAME(network, name)
   213  		return addrs, err, true
   214  	}
   215  	result := make(chan ipLookupResult, 1)
   216  	go cgoIPLookup(result, network, name)
   217  	select {
   218  	case r := <-result:
   219  		return r.addrs, r.err, true
   220  	case <-ctx.Done():
   221  		return nil, mapErr(ctx.Err()), false
   222  	}
   223  }
   224  
   225  func cgoLookupCNAME(ctx context.Context, name string) (cname string, err error, completed bool) {
   226  	if ctx.Done() == nil {
   227  		_, cname, err = cgoLookupIPCNAME("ip", name)
   228  		return cname, err, true
   229  	}
   230  	result := make(chan ipLookupResult, 1)
   231  	go cgoIPLookup(result, "ip", name)
   232  	select {
   233  	case r := <-result:
   234  		return r.cname, r.err, true
   235  	case <-ctx.Done():
   236  		return "", mapErr(ctx.Err()), false
   237  	}
   238  }
   239  
   240  // These are roughly enough for the following:
   241  //
   242  // Source		Encoding			Maximum length of single name entry
   243  // Unicast DNS		ASCII or			<=253 + a NUL terminator
   244  //			Unicode in RFC 5892		252 * total number of labels + delimiters + a NUL terminator
   245  // Multicast DNS	UTF-8 in RFC 5198 or		<=253 + a NUL terminator
   246  //			the same as unicast DNS ASCII	<=253 + a NUL terminator
   247  // Local database	various				depends on implementation
   248  const (
   249  	nameinfoLen    = 64
   250  	maxNameinfoLen = 4096
   251  )
   252  
   253  func cgoLookupPTR(ctx context.Context, addr string) (names []string, err error, completed bool) {
   254  	var zone string
   255  	ip := parseIPv4(addr)
   256  	if ip == nil {
   257  		ip, zone = parseIPv6Zone(addr)
   258  	}
   259  	if ip == nil {
   260  		return nil, &DNSError{Err: "invalid address", Name: addr}, true
   261  	}
   262  	sa, salen := cgoSockaddr(ip, zone)
   263  	if sa == nil {
   264  		return nil, &DNSError{Err: "invalid address " + ip.String(), Name: addr}, true
   265  	}
   266  	if ctx.Done() == nil {
   267  		names, err := cgoLookupAddrPTR(addr, sa, salen)
   268  		return names, err, true
   269  	}
   270  	result := make(chan reverseLookupResult, 1)
   271  	go cgoReverseLookup(result, addr, sa, salen)
   272  	select {
   273  	case r := <-result:
   274  		return r.names, r.err, true
   275  	case <-ctx.Done():
   276  		return nil, mapErr(ctx.Err()), false
   277  	}
   278  }
   279  
   280  func cgoLookupAddrPTR(addr string, sa *C.struct_sockaddr, salen C.socklen_t) (names []string, err error) {
   281  	acquireThread()
   282  	defer releaseThread()
   283  
   284  	var gerrno int
   285  	var b []byte
   286  	for l := nameinfoLen; l <= maxNameinfoLen; l *= 2 {
   287  		b = make([]byte, l)
   288  		gerrno, err = cgoNameinfoPTR(b, sa, salen)
   289  		if gerrno == 0 || gerrno != C.EAI_OVERFLOW {
   290  			break
   291  		}
   292  	}
   293  	if gerrno != 0 {
   294  		switch gerrno {
   295  		case C.EAI_SYSTEM:
   296  			if err == nil { // see golang.org/issue/6232
   297  				err = syscall.EMFILE
   298  			}
   299  		default:
   300  			err = addrinfoErrno(gerrno)
   301  		}
   302  		return nil, &DNSError{Err: err.Error(), Name: addr}
   303  	}
   304  	for i := 0; i < len(b); i++ {
   305  		if b[i] == 0 {
   306  			b = b[:i]
   307  			break
   308  		}
   309  	}
   310  	return []string{absDomainName(b)}, nil
   311  }
   312  
   313  func cgoReverseLookup(result chan<- reverseLookupResult, addr string, sa *C.struct_sockaddr, salen C.socklen_t) {
   314  	names, err := cgoLookupAddrPTR(addr, sa, salen)
   315  	result <- reverseLookupResult{names, err}
   316  }
   317  
   318  func cgoSockaddr(ip IP, zone string) (*C.struct_sockaddr, C.socklen_t) {
   319  	if ip4 := ip.To4(); ip4 != nil {
   320  		return cgoSockaddrInet4(ip4), C.socklen_t(syscall.SizeofSockaddrInet4)
   321  	}
   322  	if ip6 := ip.To16(); ip6 != nil {
   323  		return cgoSockaddrInet6(ip6, zoneCache.index(zone)), C.socklen_t(syscall.SizeofSockaddrInet6)
   324  	}
   325  	return nil, 0
   326  }
   327  
   328  func copyIP(x IP) IP {
   329  	if len(x) < 16 {
   330  		return x.To16()
   331  	}
   332  	y := make(IP, len(x))
   333  	copy(y, x)
   334  	return y
   335  }
   336  

View as plain text