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.
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
10 //go:build !netgo && ((cgo && unix) || darwin)
21 "golang.org/x/net/dns/dnsmessage"
24 // cgoAvailable set to true to indicate that the cgo resolver
25 // is available on this system.
26 const cgoAvailable = true
28 // An addrinfoErrno represents a getaddrinfo, getnameinfo-specific
29 // error number. It's a signed number and a zero value is a non-error
31 type addrinfoErrno int
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 }
37 // isAddrinfoErrno is just for testing purposes.
38 func (eai addrinfoErrno) isAddrinfoErrno() {}
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 {
53 res := make(chan result, 1)
56 r.res, r.err = blocking()
65 return zero, mapErr(ctx.Err())
69 func cgoLookupHost(ctx context.Context, name string) (hosts []string, err error) {
70 addrs, err := cgoLookupIP(ctx, "ip", name)
74 for _, addr := range addrs {
75 hosts = append(hosts, addr.String())
80 func cgoLookupPort(ctx context.Context, network, service string) (port int, err error) {
81 var hints _C_struct_addrinfo
83 case "ip": // 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
91 return 0, &DNSError{Err: "unknown network", Name: network + "/" + service}
93 switch ipVersion(network) {
95 *_C_ai_family(&hints) = _C_AF_INET
97 *_C_ai_family(&hints) = _C_AF_INET6
100 return doBlockingWithCtx(ctx, func() (int, error) {
101 return cgoLookupServicePort(&hints, network, service)
105 func cgoLookupServicePort(hints *_C_struct_addrinfo, network, service string) (port int, err error) {
106 cservice, err := syscall.ByteSliceFromString(service)
108 return 0, &DNSError{Err: err.Error(), Name: network + "/" + service}
110 // Lowercase the C service name.
111 for i, b := range cservice[:len(service)] {
112 cservice[i] = lowerASCII(b)
114 var res *_C_struct_addrinfo
115 gerrno, err := _C_getaddrinfo(nil, (*_C_char)(unsafe.Pointer(&cservice[0])), hints, &res)
120 if err == nil { // see golang.org/issue/6232
123 case _C_EAI_SERVICE, _C_EAI_NONAME: // Darwin returns EAI_NONAME.
124 return 0, &DNSError{Err: "unknown port", Name: network + "/" + service, IsNotFound: true}
126 err = addrinfoErrno(gerrno)
127 isTemporary = addrinfoErrno(gerrno).Temporary()
129 return 0, &DNSError{Err: err.Error(), Name: network + "/" + service, IsTemporary: isTemporary}
131 defer _C_freeaddrinfo(res)
133 for r := res; r != nil; r = *_C_ai_next(r) {
134 switch *_C_ai_family(r) {
136 sa := (*syscall.RawSockaddrInet4)(unsafe.Pointer(*_C_ai_addr(r)))
137 p := (*[2]byte)(unsafe.Pointer(&sa.Port))
138 return int(p[0])<<8 | int(p[1]), nil
140 sa := (*syscall.RawSockaddrInet6)(unsafe.Pointer(*_C_ai_addr(r)))
141 p := (*[2]byte)(unsafe.Pointer(&sa.Port))
142 return int(p[0])<<8 | int(p[1]), nil
145 return 0, &DNSError{Err: "unknown port", Name: network + "/" + service, IsNotFound: true}
148 func cgoLookupHostIP(network, name string) (addrs []IPAddr, err error) {
150 defer releaseThread()
152 var hints _C_struct_addrinfo
153 *_C_ai_flags(&hints) = cgoAddrInfoFlags
154 *_C_ai_socktype(&hints) = _C_SOCK_STREAM
155 *_C_ai_family(&hints) = _C_AF_UNSPEC
156 switch ipVersion(network) {
158 *_C_ai_family(&hints) = _C_AF_INET
160 *_C_ai_family(&hints) = _C_AF_INET6
163 h, err := syscall.BytePtrFromString(name)
165 return nil, &DNSError{Err: err.Error(), Name: name}
167 var res *_C_struct_addrinfo
168 gerrno, err := _C_getaddrinfo((*_C_char)(unsafe.Pointer(h)), nil, &hints, &res)
170 isErrorNoSuchHost := false
175 // err should not be nil, but sometimes getaddrinfo returns
176 // gerrno == _C_EAI_SYSTEM with err == nil on Linux.
177 // The report claims that it happens when we have too many
178 // open files, so use syscall.EMFILE (too many open files in system).
179 // Most system calls would return ENFILE (too many open files),
180 // so at the least EMFILE should be easy to recognize if this
181 // comes up again. golang.org/issue/6232.
184 case _C_EAI_NONAME, _C_EAI_NODATA:
186 isErrorNoSuchHost = true
188 err = addrinfoErrno(gerrno)
189 isTemporary = addrinfoErrno(gerrno).Temporary()
192 return nil, &DNSError{Err: err.Error(), Name: name, IsNotFound: isErrorNoSuchHost, IsTemporary: isTemporary}
194 defer _C_freeaddrinfo(res)
196 for r := res; r != nil; r = *_C_ai_next(r) {
197 // We only asked for SOCK_STREAM, but check anyhow.
198 if *_C_ai_socktype(r) != _C_SOCK_STREAM {
201 switch *_C_ai_family(r) {
203 sa := (*syscall.RawSockaddrInet4)(unsafe.Pointer(*_C_ai_addr(r)))
204 addr := IPAddr{IP: copyIP(sa.Addr[:])}
205 addrs = append(addrs, addr)
207 sa := (*syscall.RawSockaddrInet6)(unsafe.Pointer(*_C_ai_addr(r)))
208 addr := IPAddr{IP: copyIP(sa.Addr[:]), Zone: zoneCache.name(int(sa.Scope_id))}
209 addrs = append(addrs, addr)
215 func cgoLookupIP(ctx context.Context, network, name string) (addrs []IPAddr, err error) {
216 return doBlockingWithCtx(ctx, func() ([]IPAddr, error) {
217 return cgoLookupHostIP(network, name)
221 // These are roughly enough for the following:
223 // Source Encoding Maximum length of single name entry
224 // Unicast DNS ASCII or <=253 + a NUL terminator
225 // Unicode in RFC 5892 252 * total number of labels + delimiters + a NUL terminator
226 // Multicast DNS UTF-8 in RFC 5198 or <=253 + a NUL terminator
227 // the same as unicast DNS ASCII <=253 + a NUL terminator
228 // Local database various depends on implementation
231 maxNameinfoLen = 4096
234 func cgoLookupPTR(ctx context.Context, addr string) (names []string, err error) {
235 ip, err := netip.ParseAddr(addr)
237 return nil, &DNSError{Err: "invalid address", Name: addr}
239 sa, salen := cgoSockaddr(IP(ip.AsSlice()), ip.Zone())
241 return nil, &DNSError{Err: "invalid address " + ip.String(), Name: addr}
244 return doBlockingWithCtx(ctx, func() ([]string, error) {
245 return cgoLookupAddrPTR(addr, sa, salen)
249 func cgoLookupAddrPTR(addr string, sa *_C_struct_sockaddr, salen _C_socklen_t) (names []string, err error) {
251 defer releaseThread()
255 for l := nameinfoLen; l <= maxNameinfoLen; l *= 2 {
257 gerrno, err = cgoNameinfoPTR(b, sa, salen)
258 if gerrno == 0 || gerrno != _C_EAI_OVERFLOW {
263 isErrorNoSuchHost := false
267 if err == nil { // see golang.org/issue/6232
272 isErrorNoSuchHost = true
274 err = addrinfoErrno(gerrno)
275 isTemporary = addrinfoErrno(gerrno).Temporary()
277 return nil, &DNSError{Err: err.Error(), Name: addr, IsTemporary: isTemporary, IsNotFound: isErrorNoSuchHost}
279 for i := 0; i < len(b); i++ {
285 return []string{absDomainName(string(b))}, nil
288 func cgoSockaddr(ip IP, zone string) (*_C_struct_sockaddr, _C_socklen_t) {
289 if ip4 := ip.To4(); ip4 != nil {
290 return cgoSockaddrInet4(ip4), _C_socklen_t(syscall.SizeofSockaddrInet4)
292 if ip6 := ip.To16(); ip6 != nil {
293 return cgoSockaddrInet6(ip6, zoneCache.index(zone)), _C_socklen_t(syscall.SizeofSockaddrInet6)
298 func cgoLookupCNAME(ctx context.Context, name string) (cname string, err error, completed bool) {
299 resources, err := resSearch(ctx, name, int(dnsmessage.TypeCNAME), int(dnsmessage.ClassINET))
303 cname, err = parseCNAMEFromResources(resources)
305 return "", err, false
307 return cname, nil, true
310 // resSearch will make a call to the 'res_nsearch' routine in the C library
311 // and parse the output as a slice of DNS resources.
312 func resSearch(ctx context.Context, hostname string, rtype, class int) ([]dnsmessage.Resource, error) {
313 return doBlockingWithCtx(ctx, func() ([]dnsmessage.Resource, error) {
314 return cgoResSearch(hostname, rtype, class)
318 func cgoResSearch(hostname string, rtype, class int) ([]dnsmessage.Resource, error) {
320 defer releaseThread()
322 resStateSize := unsafe.Sizeof(_C_struct___res_state{})
323 var state *_C_struct___res_state
324 if resStateSize > 0 {
325 mem := _C_malloc(resStateSize)
327 memSlice := unsafe.Slice((*byte)(mem), resStateSize)
329 state = (*_C_struct___res_state)(unsafe.Pointer(&memSlice[0]))
331 if err := _C_res_ninit(state); err != nil {
332 return nil, errors.New("res_ninit failure: " + err.Error())
334 defer _C_res_nclose(state)
336 // Some res_nsearch implementations (like macOS) do not set errno.
337 // They set h_errno, which is not per-thread and useless to us.
338 // res_nsearch returns the size of the DNS response packet.
339 // But if the DNS response packet contains failure-like response codes,
340 // res_search returns -1 even though it has copied the packet into buf,
341 // giving us no way to find out how big the packet is.
342 // For now, we are willing to take res_search's word that there's nothing
343 // useful in the response, even though there *is* a response.
344 bufSize := maxDNSPacketSize
345 buf := (*_C_uchar)(_C_malloc(uintptr(bufSize)))
346 defer _C_free(unsafe.Pointer(buf))
348 s, err := syscall.BytePtrFromString(hostname)
355 size, _ = _C_res_nsearch(state, (*_C_char)(unsafe.Pointer(s)), class, rtype, buf, bufSize)
356 if size <= 0 || size > 0xffff {
357 return nil, errors.New("res_nsearch failure")
363 // Allocate a bigger buffer to fit the entire msg.
364 _C_free(unsafe.Pointer(buf))
366 buf = (*_C_uchar)(_C_malloc(uintptr(bufSize)))
369 var p dnsmessage.Parser
370 if _, err := p.Start(unsafe.Slice((*byte)(unsafe.Pointer(buf)), size)); err != nil {
374 resources, err := p.AllAnswers()
378 return resources, nil