github.com/mh-cbon/go@v0.0.0-20160603070303-9e112a3fe4c0/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) (*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 c, err := d.dialDNS(ctx, network, server) 156 if err != nil { 157 return nil, err 158 } 159 defer c.Close() 160 if d, ok := ctx.Deadline(); ok && !d.IsZero() { 161 c.SetDeadline(d) 162 } 163 out.id = uint16(rand.Int()) ^ uint16(time.Now().UnixNano()) 164 in, err := c.dnsRoundTrip(&out) 165 if err != nil { 166 return nil, mapErr(err) 167 } 168 if in.truncated { // see RFC 5966 169 continue 170 } 171 return in, nil 172 } 173 return nil, errors.New("no answer from DNS server") 174 } 175 176 // Do a lookup for a single name, which must be rooted 177 // (otherwise answer will not find the answers). 178 func tryOneName(ctx context.Context, cfg *dnsConfig, name string, qtype uint16) (string, []dnsRR, error) { 179 if len(cfg.servers) == 0 { 180 return "", nil, &DNSError{Err: "no DNS servers", Name: name} 181 } 182 183 deadline := time.Now().Add(cfg.timeout) 184 if old, ok := ctx.Deadline(); !ok || deadline.Before(old) { 185 var cancel context.CancelFunc 186 ctx, cancel = context.WithDeadline(ctx, deadline) 187 defer cancel() 188 } 189 190 var lastErr error 191 for i := 0; i < cfg.attempts; i++ { 192 for _, server := range cfg.servers { 193 msg, err := exchange(ctx, server, name, qtype) 194 if err != nil { 195 lastErr = &DNSError{ 196 Err: err.Error(), 197 Name: name, 198 Server: server, 199 } 200 if nerr, ok := err.(Error); ok && nerr.Timeout() { 201 lastErr.(*DNSError).IsTimeout = true 202 } 203 continue 204 } 205 // libresolv continues to the next server when it receives 206 // an invalid referral response. See golang.org/issue/15434. 207 if msg.rcode == dnsRcodeSuccess && !msg.authoritative && !msg.recursion_available && len(msg.answer) == 0 && len(msg.extra) == 0 { 208 lastErr = &DNSError{Err: "lame referral", Name: name, Server: server} 209 continue 210 } 211 cname, rrs, err := answer(name, server, msg, qtype) 212 // If answer errored for rcodes dnsRcodeSuccess or dnsRcodeNameError, 213 // it means the response in msg was not useful and trying another 214 // server probably won't help. Return now in those cases. 215 // TODO: indicate this in a more obvious way, such as a field on DNSError? 216 if err == nil || msg.rcode == dnsRcodeSuccess || msg.rcode == dnsRcodeNameError { 217 return cname, rrs, err 218 } 219 lastErr = err 220 } 221 } 222 return "", nil, lastErr 223 } 224 225 // addrRecordList converts and returns a list of IP addresses from DNS 226 // address records (both A and AAAA). Other record types are ignored. 227 func addrRecordList(rrs []dnsRR) []IPAddr { 228 addrs := make([]IPAddr, 0, 4) 229 for _, rr := range rrs { 230 switch rr := rr.(type) { 231 case *dnsRR_A: 232 addrs = append(addrs, IPAddr{IP: IPv4(byte(rr.A>>24), byte(rr.A>>16), byte(rr.A>>8), byte(rr.A))}) 233 case *dnsRR_AAAA: 234 ip := make(IP, IPv6len) 235 copy(ip, rr.AAAA[:]) 236 addrs = append(addrs, IPAddr{IP: ip}) 237 } 238 } 239 return addrs 240 } 241 242 // A resolverConfig represents a DNS stub resolver configuration. 243 type resolverConfig struct { 244 initOnce sync.Once // guards init of resolverConfig 245 246 // ch is used as a semaphore that only allows one lookup at a 247 // time to recheck resolv.conf. 248 ch chan struct{} // guards lastChecked and modTime 249 lastChecked time.Time // last time resolv.conf was checked 250 251 mu sync.RWMutex // protects dnsConfig 252 dnsConfig *dnsConfig // parsed resolv.conf structure used in lookups 253 } 254 255 var resolvConf resolverConfig 256 257 // init initializes conf and is only called via conf.initOnce. 258 func (conf *resolverConfig) init() { 259 // Set dnsConfig and lastChecked so we don't parse 260 // resolv.conf twice the first time. 261 conf.dnsConfig = systemConf().resolv 262 if conf.dnsConfig == nil { 263 conf.dnsConfig = dnsReadConfig("/etc/resolv.conf") 264 } 265 conf.lastChecked = time.Now() 266 267 // Prepare ch so that only one update of resolverConfig may 268 // run at once. 269 conf.ch = make(chan struct{}, 1) 270 } 271 272 // tryUpdate tries to update conf with the named resolv.conf file. 273 // The name variable only exists for testing. It is otherwise always 274 // "/etc/resolv.conf". 275 func (conf *resolverConfig) tryUpdate(name string) { 276 conf.initOnce.Do(conf.init) 277 278 // Ensure only one update at a time checks resolv.conf. 279 if !conf.tryAcquireSema() { 280 return 281 } 282 defer conf.releaseSema() 283 284 now := time.Now() 285 if conf.lastChecked.After(now.Add(-5 * time.Second)) { 286 return 287 } 288 conf.lastChecked = now 289 290 var mtime time.Time 291 if fi, err := os.Stat(name); err == nil { 292 mtime = fi.ModTime() 293 } 294 if mtime.Equal(conf.dnsConfig.mtime) { 295 return 296 } 297 298 dnsConf := dnsReadConfig(name) 299 conf.mu.Lock() 300 conf.dnsConfig = dnsConf 301 conf.mu.Unlock() 302 } 303 304 func (conf *resolverConfig) tryAcquireSema() bool { 305 select { 306 case conf.ch <- struct{}{}: 307 return true 308 default: 309 return false 310 } 311 } 312 313 func (conf *resolverConfig) releaseSema() { 314 <-conf.ch 315 } 316 317 func lookup(ctx context.Context, name string, qtype uint16) (cname string, rrs []dnsRR, err error) { 318 if !isDomainName(name) { 319 return "", nil, &DNSError{Err: "invalid domain name", Name: name} 320 } 321 resolvConf.tryUpdate("/etc/resolv.conf") 322 resolvConf.mu.RLock() 323 conf := resolvConf.dnsConfig 324 resolvConf.mu.RUnlock() 325 for _, fqdn := range conf.nameList(name) { 326 cname, rrs, err = tryOneName(ctx, conf, fqdn, qtype) 327 if err == nil { 328 break 329 } 330 } 331 if err, ok := err.(*DNSError); ok { 332 // Show original name passed to lookup, not suffixed one. 333 // In general we might have tried many suffixes; showing 334 // just one is misleading. See also golang.org/issue/6324. 335 err.Name = name 336 } 337 return 338 } 339 340 // avoidDNS reports whether this is a hostname for which we should not 341 // use DNS. Currently this includes only .onion and .local names, 342 // per RFC 7686 and RFC 6762, respectively. See golang.org/issue/13705. 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") || stringsHasSuffixFold(name, ".local") 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 }