]> Cypherpunks.ru repositories - gostls13.git/blob - src/net/cgo_unix.go
cmd/compile/internal/inline: score call sites exposed by inlines
[gostls13.git] / 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 "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
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                 case _C_EAI_SERVICE, _C_EAI_NONAME: // Darwin returns EAI_NONAME.
124                         return 0, &DNSError{Err: "unknown port", Name: network + "/" + service, IsNotFound: true}
125                 default:
126                         err = addrinfoErrno(gerrno)
127                         isTemporary = addrinfoErrno(gerrno).Temporary()
128                 }
129                 return 0, &DNSError{Err: err.Error(), Name: network + "/" + service, IsTemporary: isTemporary}
130         }
131         defer _C_freeaddrinfo(res)
132
133         for r := res; r != nil; r = *_C_ai_next(r) {
134                 switch *_C_ai_family(r) {
135                 case _C_AF_INET:
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
139                 case _C_AF_INET6:
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
143                 }
144         }
145         return 0, &DNSError{Err: "unknown port", Name: network + "/" + service, IsNotFound: true}
146 }
147
148 func cgoLookupHostIP(network, name string) (addrs []IPAddr, err error) {
149         acquireThread()
150         defer releaseThread()
151
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) {
157         case '4':
158                 *_C_ai_family(&hints) = _C_AF_INET
159         case '6':
160                 *_C_ai_family(&hints) = _C_AF_INET6
161         }
162
163         h, err := syscall.BytePtrFromString(name)
164         if err != nil {
165                 return nil, &DNSError{Err: err.Error(), Name: name}
166         }
167         var res *_C_struct_addrinfo
168         gerrno, err := _C_getaddrinfo((*_C_char)(unsafe.Pointer(h)), nil, &hints, &res)
169         if gerrno != 0 {
170                 isErrorNoSuchHost := false
171                 isTemporary := false
172                 switch gerrno {
173                 case _C_EAI_SYSTEM:
174                         if err == nil {
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.
182                                 err = syscall.EMFILE
183                         }
184                 case _C_EAI_NONAME, _C_EAI_NODATA:
185                         err = errNoSuchHost
186                         isErrorNoSuchHost = true
187                 default:
188                         err = addrinfoErrno(gerrno)
189                         isTemporary = addrinfoErrno(gerrno).Temporary()
190                 }
191
192                 return nil, &DNSError{Err: err.Error(), Name: name, IsNotFound: isErrorNoSuchHost, IsTemporary: isTemporary}
193         }
194         defer _C_freeaddrinfo(res)
195
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 {
199                         continue
200                 }
201                 switch *_C_ai_family(r) {
202                 case _C_AF_INET:
203                         sa := (*syscall.RawSockaddrInet4)(unsafe.Pointer(*_C_ai_addr(r)))
204                         addr := IPAddr{IP: copyIP(sa.Addr[:])}
205                         addrs = append(addrs, addr)
206                 case _C_AF_INET6:
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)
210                 }
211         }
212         return addrs, nil
213 }
214
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)
218         })
219 }
220
221 // These are roughly enough for the following:
222 //
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
229 const (
230         nameinfoLen    = 64
231         maxNameinfoLen = 4096
232 )
233
234 func cgoLookupPTR(ctx context.Context, addr string) (names []string, err error) {
235         ip, err := netip.ParseAddr(addr)
236         if err != nil {
237                 return nil, &DNSError{Err: "invalid address", Name: addr}
238         }
239         sa, salen := cgoSockaddr(IP(ip.AsSlice()), ip.Zone())
240         if sa == nil {
241                 return nil, &DNSError{Err: "invalid address " + ip.String(), Name: addr}
242         }
243
244         return doBlockingWithCtx(ctx, func() ([]string, error) {
245                 return cgoLookupAddrPTR(addr, sa, salen)
246         })
247 }
248
249 func cgoLookupAddrPTR(addr string, sa *_C_struct_sockaddr, salen _C_socklen_t) (names []string, err error) {
250         acquireThread()
251         defer releaseThread()
252
253         var gerrno int
254         var b []byte
255         for l := nameinfoLen; l <= maxNameinfoLen; l *= 2 {
256                 b = make([]byte, l)
257                 gerrno, err = cgoNameinfoPTR(b, sa, salen)
258                 if gerrno == 0 || gerrno != _C_EAI_OVERFLOW {
259                         break
260                 }
261         }
262         if gerrno != 0 {
263                 isErrorNoSuchHost := false
264                 isTemporary := false
265                 switch gerrno {
266                 case _C_EAI_SYSTEM:
267                         if err == nil { // see golang.org/issue/6232
268                                 err = syscall.EMFILE
269                         }
270                 case _C_EAI_NONAME:
271                         err = errNoSuchHost
272                         isErrorNoSuchHost = true
273                 default:
274                         err = addrinfoErrno(gerrno)
275                         isTemporary = addrinfoErrno(gerrno).Temporary()
276                 }
277                 return nil, &DNSError{Err: err.Error(), Name: addr, IsTemporary: isTemporary, IsNotFound: isErrorNoSuchHost}
278         }
279         for i := 0; i < len(b); i++ {
280                 if b[i] == 0 {
281                         b = b[:i]
282                         break
283                 }
284         }
285         return []string{absDomainName(string(b))}, nil
286 }
287
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)
291         }
292         if ip6 := ip.To16(); ip6 != nil {
293                 return cgoSockaddrInet6(ip6, zoneCache.index(zone)), _C_socklen_t(syscall.SizeofSockaddrInet6)
294         }
295         return nil, 0
296 }
297
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))
300         if err != nil {
301                 return
302         }
303         cname, err = parseCNAMEFromResources(resources)
304         if err != nil {
305                 return "", err, false
306         }
307         return cname, nil, true
308 }
309
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)
315         })
316 }
317
318 func cgoResSearch(hostname string, rtype, class int) ([]dnsmessage.Resource, error) {
319         acquireThread()
320         defer releaseThread()
321
322         resStateSize := unsafe.Sizeof(_C_struct___res_state{})
323         var state *_C_struct___res_state
324         if resStateSize > 0 {
325                 mem := _C_malloc(resStateSize)
326                 defer _C_free(mem)
327                 memSlice := unsafe.Slice((*byte)(mem), resStateSize)
328                 clear(memSlice)
329                 state = (*_C_struct___res_state)(unsafe.Pointer(&memSlice[0]))
330         }
331         if err := _C_res_ninit(state); err != nil {
332                 return nil, errors.New("res_ninit failure: " + err.Error())
333         }
334         defer _C_res_nclose(state)
335
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))
347
348         s, err := syscall.BytePtrFromString(hostname)
349         if err != nil {
350                 return nil, err
351         }
352
353         var size int
354         for {
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")
358                 }
359                 if size <= bufSize {
360                         break
361                 }
362
363                 // Allocate a bigger buffer to fit the entire msg.
364                 _C_free(unsafe.Pointer(buf))
365                 bufSize = size
366                 buf = (*_C_uchar)(_C_malloc(uintptr(bufSize)))
367         }
368
369         var p dnsmessage.Parser
370         if _, err := p.Start(unsafe.Slice((*byte)(unsafe.Pointer(buf)), size)); err != nil {
371                 return nil, err
372         }
373         p.SkipAllQuestions()
374         resources, err := p.AllAnswers()
375         if err != nil {
376                 return nil, err
377         }
378         return resources, nil
379 }