github.com/robhaswell/grandperspective-scan@v0.1.0/test/go-go1.7.1/src/net/dnsclient_unix.go (about) 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 // +build darwin dragonfly freebsd linux netbsd openbsd solaris 6 7 // DNS client: see RFC 1035. 8 // Has to be linked into package net for Dial. 9 10 // TODO(rsc): 11 // Could potentially handle many outstanding lookups faster. 12 // Could have a small cache. 13 // Random UDP source port (net.Dial should do that for us). 14 // Random request IDs. 15 16 package net 17 18 import ( 19 "context" 20 "errors" 21 "io" 22 "math/rand" 23 "os" 24 "sync" 25 "time" 26 ) 27 28 // A dnsDialer provides dialing suitable for DNS queries. 29 type dnsDialer interface { 30 dialDNS(ctx context.Context, network, addr string) (dnsConn, error) 31 } 32 33 var testHookDNSDialer = func() dnsDialer { return &Dialer{} } 34 35 // A dnsConn represents a DNS transport endpoint. 36 type dnsConn interface { 37 io.Closer 38 39 SetDeadline(time.Time) error 40 41 // dnsRoundTrip executes a single DNS transaction, returning a 42 // DNS response message for the provided DNS query message. 43 dnsRoundTrip(query *dnsMsg) (*dnsMsg, error) 44 } 45 46 func (c *UDPConn) dnsRoundTrip(query *dnsMsg) (*dnsMsg, error) { 47 return dnsRoundTripUDP(c, query) 48 } 49 50 // dnsRoundTripUDP implements the dnsRoundTrip interface for RFC 1035's 51 // "UDP usage" transport mechanism. c should be a packet-oriented connection, 52 // such as a *UDPConn. 53 func dnsRoundTripUDP(c io.ReadWriter, query *dnsMsg) (*dnsMsg, error) { 54 b, ok := query.Pack() 55 if !ok { 56 return nil, errors.New("cannot marshal DNS message") 57 } 58 if _, err := c.Write(b); err != nil { 59 return nil, err 60 } 61 62 b = make([]byte, 512) // see RFC 1035 63 for { 64 n, err := c.Read(b) 65 if err != nil { 66 return nil, err 67 } 68 resp := &dnsMsg{} 69 if !resp.Unpack(b[:n]) || !resp.IsResponseTo(query) { 70 // Ignore invalid responses as they may be malicious 71 // forgery attempts. Instead continue waiting until 72 // timeout. See golang.org/issue/13281. 73 continue 74 } 75 return resp, nil 76 } 77 } 78 79 func (c *TCPConn) dnsRoundTrip(out *dnsMsg) (*dnsMsg, error) { 80 return dnsRoundTripTCP(c, out) 81 } 82 83 // dnsRoundTripTCP implements the dnsRoundTrip interface for RFC 1035's 84 // "TCP usage" transport mechanism. c should be a stream-oriented connection, 85 // such as a *TCPConn. 86 func dnsRoundTripTCP(c io.ReadWriter, query *dnsMsg) (*dnsMsg, error) { 87 b, ok := query.Pack() 88 if !ok { 89 return nil, errors.New("cannot marshal DNS message") 90 } 91 l := len(b) 92 b = append([]byte{byte(l >> 8), byte(l)}, b...) 93 if _, err := c.Write(b); err != nil { 94 return nil, err 95 } 96 97 b = make([]byte, 1280) // 1280 is a reasonable initial size for IP over Ethernet, see RFC 4035 98 if _, err := io.ReadFull(c, b[:2]); err != nil { 99 return nil, err 100 } 101 l = int(b[0])<<8 | int(b[1]) 102 if l > len(b) { 103 b = make([]byte, l) 104 } 105 n, err := io.ReadFull(c, b[:l]) 106 if err != nil { 107 return nil, err 108 } 109 resp := &dnsMsg{} 110 if !resp.Unpack(b[:n]) { 111 return nil, errors.New("cannot unmarshal DNS message") 112 } 113 if !resp.IsResponseTo(query) { 114 return nil, errors.New("invalid DNS response") 115 } 116 return resp, nil 117 } 118 119 func (d *Dialer) dialDNS(ctx context.Context, network, server string) (dnsConn, error) { 120 switch network { 121 case "tcp", "tcp4", "tcp6", "udp", "udp4", "udp6": 122 default: 123 return nil, UnknownNetworkError(network) 124 } 125 // Calling Dial here is scary -- we have to be sure not to 126 // dial a name that will require a DNS lookup, or Dial will 127 // call back here to translate it. The DNS config parser has 128 // already checked that all the cfg.servers[i] are IP 129 // addresses, which Dial will use without a DNS lookup. 130 c, err := d.DialContext(ctx, network, server) 131 if err != nil { 132 return nil, mapErr(err) 133 } 134 switch network { 135 case "tcp", "tcp4", "tcp6": 136 return c.(*TCPConn), nil 137 case "udp", "udp4", "udp6": 138 return c.(*UDPConn), nil 139 } 140 panic("unreachable") 141 } 142 143 // exchange sends a query on the connection and hopes for a response. 144 func exchange(ctx context.Context, server, name string, qtype uint16, timeout time.Duration) (*dnsMsg, error) { 145 d := testHookDNSDialer() 146 out := dnsMsg{ 147 dnsMsgHdr: dnsMsgHdr{ 148 recursion_desired: true, 149 }, 150 question: []dnsQuestion{ 151 {name, qtype, dnsClassINET}, 152 }, 153 } 154 for _, network := range []string{"udp", "tcp"} { 155 // TODO(mdempsky): Refactor so defers from UDP-based 156 // exchanges happen before TCP-based exchange. 157 158 ctx, cancel := context.WithDeadline(ctx, time.Now().Add(timeout)) 159 defer cancel() 160 161 c, err := d.dialDNS(ctx, network, server) 162 if err != nil { 163 return nil, err 164 } 165 defer c.Close() 166 if d, ok := ctx.Deadline(); ok && !d.IsZero() { 167 c.SetDeadline(d) 168 } 169 out.id = uint16(rand.Int()) ^ uint16(time.Now().UnixNano()) 170 in, err := c.dnsRoundTrip(&out) 171 if err != nil { 172 return nil, mapErr(err) 173 } 174 if in.truncated { // see RFC 5966 175 continue 176 } 177 return in, nil 178 } 179 return nil, errors.New("no answer from DNS server") 180 } 181 182 // Do a lookup for a single name, which must be rooted 183 // (otherwise answer will not find the answers). 184 func tryOneName(ctx context.Context, cfg *dnsConfig, name string, qtype uint16) (string, []dnsRR, error) { 185 if len(cfg.servers) == 0 { 186 return "", nil, &DNSError{Err: "no DNS servers", Name: name} 187 } 188 189 var lastErr error 190 for i := 0; i < cfg.attempts; i++ { 191 for _, server := range cfg.servers { 192 msg, err := exchange(ctx, server, name, qtype, cfg.timeout) 193 if err != nil { 194 lastErr = &DNSError{ 195 Err: err.Error(), 196 Name: name, 197 Server: server, 198 } 199 if nerr, ok := err.(Error); ok && nerr.Timeout() { 200 lastErr.(*DNSError).IsTimeout = true 201 } 202 continue 203 } 204 // libresolv continues to the next server when it receives 205 // an invalid referral response. See golang.org/issue/15434. 206 if msg.rcode == dnsRcodeSuccess && !msg.authoritative && !msg.recursion_available && len(msg.answer) == 0 && len(msg.extra) == 0 { 207 lastErr = &DNSError{Err: "lame referral", Name: name, Server: server} 208 continue 209 } 210 cname, rrs, err := answer(name, server, msg, qtype) 211 // If answer errored for rcodes dnsRcodeSuccess or dnsRcodeNameError, 212 // it means the response in msg was not useful and trying another 213 // server probably won't help. Return now in those cases. 214 // TODO: indicate this in a more obvious way, such as a field on DNSError? 215 if err == nil || msg.rcode == dnsRcodeSuccess || msg.rcode == dnsRcodeNameError { 216 return cname, rrs, err 217 } 218 lastErr = err 219 } 220 } 221 return "", nil, lastErr 222 } 223 224 // addrRecordList converts and returns a list of IP addresses from DNS 225 // address records (both A and AAAA). Other record types are ignored. 226 func addrRecordList(rrs []dnsRR) []IPAddr { 227 addrs := make([]IPAddr, 0, 4) 228 for _, rr := range rrs { 229 switch rr := rr.(type) { 230 case *dnsRR_A: 231 addrs = append(addrs, IPAddr{IP: IPv4(byte(rr.A>>24), byte(rr.A>>16), byte(rr.A>>8), byte(rr.A))}) 232 case *dnsRR_AAAA: 233 ip := make(IP, IPv6len) 234 copy(ip, rr.AAAA[:]) 235 addrs = append(addrs, IPAddr{IP: ip}) 236 } 237 } 238 return addrs 239 } 240 241 // A resolverConfig represents a DNS stub resolver configuration. 242 type resolverConfig struct { 243 initOnce sync.Once // guards init of resolverConfig 244 245 // ch is used as a semaphore that only allows one lookup at a 246 // time to recheck resolv.conf. 247 ch chan struct{} // guards lastChecked and modTime 248 lastChecked time.Time // last time resolv.conf was checked 249 250 mu sync.RWMutex // protects dnsConfig 251 dnsConfig *dnsConfig // parsed resolv.conf structure used in lookups 252 } 253 254 var resolvConf resolverConfig 255 256 // init initializes conf and is only called via conf.initOnce. 257 func (conf *resolverConfig) init() { 258 // Set dnsConfig and lastChecked so we don't parse 259 // resolv.conf twice the first time. 260 conf.dnsConfig = systemConf().resolv 261 if conf.dnsConfig == nil { 262 conf.dnsConfig = dnsReadConfig("/etc/resolv.conf") 263 } 264 conf.lastChecked = time.Now() 265 266 // Prepare ch so that only one update of resolverConfig may 267 // run at once. 268 conf.ch = make(chan struct{}, 1) 269 } 270 271 // tryUpdate tries to update conf with the named resolv.conf file. 272 // The name variable only exists for testing. It is otherwise always 273 // "/etc/resolv.conf". 274 func (conf *resolverConfig) tryUpdate(name string) { 275 conf.initOnce.Do(conf.init) 276 277 // Ensure only one update at a time checks resolv.conf. 278 if !conf.tryAcquireSema() { 279 return 280 } 281 defer conf.releaseSema() 282 283 now := time.Now() 284 if conf.lastChecked.After(now.Add(-5 * time.Second)) { 285 return 286 } 287 conf.lastChecked = now 288 289 var mtime time.Time 290 if fi, err := os.Stat(name); err == nil { 291 mtime = fi.ModTime() 292 } 293 if mtime.Equal(conf.dnsConfig.mtime) { 294 return 295 } 296 297 dnsConf := dnsReadConfig(name) 298 conf.mu.Lock() 299 conf.dnsConfig = dnsConf 300 conf.mu.Unlock() 301 } 302 303 func (conf *resolverConfig) tryAcquireSema() bool { 304 select { 305 case conf.ch <- struct{}{}: 306 return true 307 default: 308 return false 309 } 310 } 311 312 func (conf *resolverConfig) releaseSema() { 313 <-conf.ch 314 } 315 316 func lookup(ctx context.Context, name string, qtype uint16) (cname string, rrs []dnsRR, err error) { 317 if !isDomainName(name) { 318 return "", nil, &DNSError{Err: "invalid domain name", Name: name} 319 } 320 resolvConf.tryUpdate("/etc/resolv.conf") 321 resolvConf.mu.RLock() 322 conf := resolvConf.dnsConfig 323 resolvConf.mu.RUnlock() 324 for _, fqdn := range conf.nameList(name) { 325 cname, rrs, err = tryOneName(ctx, conf, fqdn, qtype) 326 if err == nil { 327 break 328 } 329 } 330 if err, ok := err.(*DNSError); ok { 331 // Show original name passed to lookup, not suffixed one. 332 // In general we might have tried many suffixes; showing 333 // just one is misleading. See also golang.org/issue/6324. 334 err.Name = name 335 } 336 return 337 } 338 339 // avoidDNS reports whether this is a hostname for which we should not 340 // use DNS. Currently this includes only .onion, per RFC 7686. See 341 // golang.org/issue/13705. Does not cover .local names (RFC 6762), 342 // see golang.org/issue/16739. 343 func avoidDNS(name string) bool { 344 if name == "" { 345 return true 346 } 347 if name[len(name)-1] == '.' { 348 name = name[:len(name)-1] 349 } 350 return stringsHasSuffixFold(name, ".onion") 351 } 352 353 // nameList returns a list of names for sequential DNS queries. 354 func (conf *dnsConfig) nameList(name string) []string { 355 if avoidDNS(name) { 356 return nil 357 } 358 359 // If name is rooted (trailing dot), try only that name. 360 rooted := len(name) > 0 && name[len(name)-1] == '.' 361 if rooted { 362 return []string{name} 363 } 364 365 hasNdots := count(name, '.') >= conf.ndots 366 name += "." 367 368 // Build list of search choices. 369 names := make([]string, 0, 1+len(conf.search)) 370 // If name has enough dots, try unsuffixed first. 371 if hasNdots { 372 names = append(names, name) 373 } 374 // Try suffixes. 375 for _, suffix := range conf.search { 376 names = append(names, name+suffix) 377 } 378 // Try unsuffixed, if not tried first above. 379 if !hasNdots { 380 names = append(names, name) 381 } 382 return names 383 } 384 385 // hostLookupOrder specifies the order of LookupHost lookup strategies. 386 // It is basically a simplified representation of nsswitch.conf. 387 // "files" means /etc/hosts. 388 type hostLookupOrder int 389 390 const ( 391 // hostLookupCgo means defer to cgo. 392 hostLookupCgo hostLookupOrder = iota 393 hostLookupFilesDNS // files first 394 hostLookupDNSFiles // dns first 395 hostLookupFiles // only files 396 hostLookupDNS // only DNS 397 ) 398 399 var lookupOrderName = map[hostLookupOrder]string{ 400 hostLookupCgo: "cgo", 401 hostLookupFilesDNS: "files,dns", 402 hostLookupDNSFiles: "dns,files", 403 hostLookupFiles: "files", 404 hostLookupDNS: "dns", 405 } 406 407 func (o hostLookupOrder) String() string { 408 if s, ok := lookupOrderName[o]; ok { 409 return s 410 } 411 return "hostLookupOrder=" + itoa(int(o)) + "??" 412 } 413 414 // goLookupHost is the native Go implementation of LookupHost. 415 // Used only if cgoLookupHost refuses to handle the request 416 // (that is, only if cgoLookupHost is the stub in cgo_stub.go). 417 // Normally we let cgo use the C library resolver instead of 418 // depending on our lookup code, so that Go and C get the same 419 // answers. 420 func goLookupHost(ctx context.Context, name string) (addrs []string, err error) { 421 return goLookupHostOrder(ctx, name, hostLookupFilesDNS) 422 } 423 424 func goLookupHostOrder(ctx context.Context, name string, order hostLookupOrder) (addrs []string, err error) { 425 if order == hostLookupFilesDNS || order == hostLookupFiles { 426 // Use entries from /etc/hosts if they match. 427 addrs = lookupStaticHost(name) 428 if len(addrs) > 0 || order == hostLookupFiles { 429 return 430 } 431 } 432 ips, err := goLookupIPOrder(ctx, name, order) 433 if err != nil { 434 return 435 } 436 addrs = make([]string, 0, len(ips)) 437 for _, ip := range ips { 438 addrs = append(addrs, ip.String()) 439 } 440 return 441 } 442 443 // lookup entries from /etc/hosts 444 func goLookupIPFiles(name string) (addrs []IPAddr) { 445 for _, haddr := range lookupStaticHost(name) { 446 haddr, zone := splitHostZone(haddr) 447 if ip := ParseIP(haddr); ip != nil { 448 addr := IPAddr{IP: ip, Zone: zone} 449 addrs = append(addrs, addr) 450 } 451 } 452 sortByRFC6724(addrs) 453 return 454 } 455 456 // goLookupIP is the native Go implementation of LookupIP. 457 // The libc versions are in cgo_*.go. 458 func goLookupIP(ctx context.Context, name string) (addrs []IPAddr, err error) { 459 return goLookupIPOrder(ctx, name, hostLookupFilesDNS) 460 } 461 462 func goLookupIPOrder(ctx context.Context, name string, order hostLookupOrder) (addrs []IPAddr, err error) { 463 if order == hostLookupFilesDNS || order == hostLookupFiles { 464 addrs = goLookupIPFiles(name) 465 if len(addrs) > 0 || order == hostLookupFiles { 466 return addrs, nil 467 } 468 } 469 if !isDomainName(name) { 470 return nil, &DNSError{Err: "invalid domain name", Name: name} 471 } 472 resolvConf.tryUpdate("/etc/resolv.conf") 473 resolvConf.mu.RLock() 474 conf := resolvConf.dnsConfig 475 resolvConf.mu.RUnlock() 476 type racer struct { 477 fqdn string 478 rrs []dnsRR 479 error 480 } 481 lane := make(chan racer, 1) 482 qtypes := [...]uint16{dnsTypeA, dnsTypeAAAA} 483 var lastErr error 484 for _, fqdn := range conf.nameList(name) { 485 for _, qtype := range qtypes { 486 go func(qtype uint16) { 487 _, rrs, err := tryOneName(ctx, conf, fqdn, qtype) 488 lane <- racer{fqdn, rrs, err} 489 }(qtype) 490 } 491 for range qtypes { 492 racer := <-lane 493 if racer.error != nil { 494 // Prefer error for original name. 495 if lastErr == nil || racer.fqdn == name+"." { 496 lastErr = racer.error 497 } 498 continue 499 } 500 addrs = append(addrs, addrRecordList(racer.rrs)...) 501 } 502 if len(addrs) > 0 { 503 break 504 } 505 } 506 if lastErr, ok := lastErr.(*DNSError); ok { 507 // Show original name passed to lookup, not suffixed one. 508 // In general we might have tried many suffixes; showing 509 // just one is misleading. See also golang.org/issue/6324. 510 lastErr.Name = name 511 } 512 sortByRFC6724(addrs) 513 if len(addrs) == 0 { 514 if order == hostLookupDNSFiles { 515 addrs = goLookupIPFiles(name) 516 } 517 if len(addrs) == 0 && lastErr != nil { 518 return nil, lastErr 519 } 520 } 521 return addrs, nil 522 } 523 524 // goLookupCNAME is the native Go implementation of LookupCNAME. 525 // Used only if cgoLookupCNAME refuses to handle the request 526 // (that is, only if cgoLookupCNAME is the stub in cgo_stub.go). 527 // Normally we let cgo use the C library resolver instead of 528 // depending on our lookup code, so that Go and C get the same 529 // answers. 530 func goLookupCNAME(ctx context.Context, name string) (cname string, err error) { 531 _, rrs, err := lookup(ctx, name, dnsTypeCNAME) 532 if err != nil { 533 return 534 } 535 cname = rrs[0].(*dnsRR_CNAME).Cname 536 return 537 } 538 539 // goLookupPTR is the native Go implementation of LookupAddr. 540 // Used only if cgoLookupPTR refuses to handle the request (that is, 541 // only if cgoLookupPTR is the stub in cgo_stub.go). 542 // Normally we let cgo use the C library resolver instead of depending 543 // on our lookup code, so that Go and C get the same answers. 544 func goLookupPTR(ctx context.Context, addr string) ([]string, error) { 545 names := lookupStaticAddr(addr) 546 if len(names) > 0 { 547 return names, nil 548 } 549 arpa, err := reverseaddr(addr) 550 if err != nil { 551 return nil, err 552 } 553 _, rrs, err := lookup(ctx, arpa, dnsTypePTR) 554 if err != nil { 555 return nil, err 556 } 557 ptrs := make([]string, len(rrs)) 558 for i, rr := range rrs { 559 ptrs[i] = rr.(*dnsRR_PTR).Ptr 560 } 561 return ptrs, nil 562 }