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.
5 // DNS client: see RFC 1035.
6 // Has to be linked into package net for Dial.
9 // Check periodically whether /etc/resolv.conf has changed.
10 // Could potentially handle many outstanding lookups faster.
11 // Could have a small cache.
12 // Random UDP source port (net.Dial should do that for us).
13 // Random request IDs.
26 // DNSError represents a DNS lookup error.
27 type DNSError struct {
28 Error string // description of the error
29 Name string // name looked for
30 Server string // server used
34 func (e *DNSError) String() string {
38 s := "lookup " + e.Name
40 s += " on " + e.Server
46 func (e *DNSError) Timeout() bool { return e.IsTimeout }
47 func (e *DNSError) Temporary() bool { return e.IsTimeout }
49 const noSuchHost = "no such host"
51 // Send a request on the connection and hope for a reply.
52 // Up to cfg.attempts attempts.
53 func exchange(cfg *dnsConfig, c Conn, name string, qtype uint16) (*dnsMsg, os.Error) {
55 return nil, &DNSError{Error: "name too long", Name: name}
58 out.id = uint16(rand.Int()) ^ uint16(time.Nanoseconds())
59 out.question = []dnsQuestion{
60 {name, qtype, dnsClassINET},
62 out.recursion_desired = true
65 return nil, &DNSError{Error: "internal error - cannot pack message", Name: name}
68 for attempt := 0; attempt < cfg.attempts; attempt++ {
69 n, err := c.Write(msg)
74 c.SetReadTimeout(int64(cfg.timeout) * 1e9) // nanoseconds
76 buf := make([]byte, 2000) // More than enough.
79 if e, ok := err.(Error); ok && e.Timeout() {
86 if !in.Unpack(buf) || in.id != out.id {
92 if a := c.RemoteAddr(); a != nil {
95 return nil, &DNSError{Error: "no answer from server", Name: name, Server: server, IsTimeout: true}
99 // Find answer for name in dns message.
100 // On return, if err == nil, addrs != nil.
101 func answer(name, server string, dns *dnsMsg, qtype uint16) (cname string, addrs []dnsRR, err os.Error) {
102 addrs = make([]dnsRR, 0, len(dns.answer))
104 if dns.rcode == dnsRcodeNameError && dns.recursion_available {
105 return "", nil, &DNSError{Error: noSuchHost, Name: name}
107 if dns.rcode != dnsRcodeSuccess {
108 // None of the error codes make sense
109 // for the query we sent. If we didn't get
110 // a name error and we didn't get success,
111 // the server is behaving incorrectly.
112 return "", nil, &DNSError{Error: "server misbehaving", Name: name, Server: server}
115 // Look for the name.
116 // Presotto says it's okay to assume that servers listed in
117 // /etc/resolv.conf are recursive resolvers.
118 // We asked for recursion, so it should have included
119 // all the answers we need in this one packet.
121 for cnameloop := 0; cnameloop < 10; cnameloop++ {
123 for i := 0; i < len(dns.answer); i++ {
126 if h.Class == dnsClassINET && h.Name == name {
130 addrs = addrs[0 : n+1]
134 name = rr.(*dnsRR_CNAME).Cname
140 return "", nil, &DNSError{Error: noSuchHost, Name: name, Server: server}
142 return name, addrs, nil
145 return "", nil, &DNSError{Error: "too many redirects", Name: name, Server: server}
148 // Do a lookup for a single name, which must be rooted
149 // (otherwise answer will not find the answers).
150 func tryOneName(cfg *dnsConfig, name string, qtype uint16) (cname string, addrs []dnsRR, err os.Error) {
151 if len(cfg.servers) == 0 {
152 return "", nil, &DNSError{Error: "no DNS servers", Name: name}
154 for i := 0; i < len(cfg.servers); i++ {
155 // Calling Dial here is scary -- we have to be sure
156 // not to dial a name that will require a DNS lookup,
157 // or Dial will call back here to translate it.
158 // The DNS config parser has already checked that
159 // all the cfg.servers[i] are IP addresses, which
160 // Dial will use without a DNS lookup.
161 server := cfg.servers[i] + ":53"
162 c, cerr := Dial("udp", server)
167 msg, merr := exchange(cfg, c, name, qtype)
173 cname, addrs, err = answer(name, server, msg, qtype)
174 if err == nil || err.(*DNSError).Error == noSuchHost {
181 func convertRR_A(records []dnsRR) []IP {
182 addrs := make([]IP, len(records))
183 for i := 0; i < len(records); i++ {
186 addrs[i] = IPv4(byte(a>>24), byte(a>>16), byte(a>>8), byte(a))
191 func convertRR_AAAA(records []dnsRR) []IP {
192 addrs := make([]IP, len(records))
193 for i := 0; i < len(records); i++ {
196 copy(a, rr.(*dnsRR_AAAA).AAAA[:])
205 func loadConfig() { cfg, dnserr = dnsReadConfig() }
207 func isDomainName(s string) bool {
208 // See RFC 1035, RFC 3696.
215 if s[len(s)-1] != '.' { // simplify checking loop: make name end in dot
220 ok := false // ok once we've seen a letter
222 for i := 0; i < len(s); i++ {
227 case 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || c == '_':
230 case '0' <= c && c <= '9':
234 // byte before dash cannot be dot
240 // byte before dot cannot be dot, dash
241 if last == '.' || last == '-' {
244 if partlen > 63 || partlen == 0 {
255 var onceLoadConfig sync.Once
257 func lookup(name string, qtype uint16) (cname string, addrs []dnsRR, err os.Error) {
258 if !isDomainName(name) {
259 return name, nil, &DNSError{Error: "invalid domain name", Name: name}
261 onceLoadConfig.Do(loadConfig)
262 if dnserr != nil || cfg == nil {
266 // If name is rooted (trailing dot) or has enough dots,
267 // try it by itself first.
268 rooted := len(name) > 0 && name[len(name)-1] == '.'
269 if rooted || count(name, '.') >= cfg.ndots {
274 // Can try as ordinary name.
275 cname, addrs, err = tryOneName(cfg, rname, qtype)
284 // Otherwise, try suffixes.
285 for i := 0; i < len(cfg.search); i++ {
286 rname := name + "." + cfg.search[i]
287 if rname[len(rname)-1] != '.' {
290 cname, addrs, err = tryOneName(cfg, rname, qtype)
296 // Last ditch effort: try unsuffixed.
301 cname, addrs, err = tryOneName(cfg, rname, qtype)
308 // goLookupHost is the native Go implementation of LookupHost.
309 func goLookupHost(name string) (addrs []string, err os.Error) {
310 onceLoadConfig.Do(loadConfig)
311 if dnserr != nil || cfg == nil {
315 // Use entries from /etc/hosts if they match.
316 addrs = lookupStaticHost(name)
320 ips, err := goLookupIP(name)
324 addrs = make([]string, 0, len(ips))
325 for _, ip := range ips {
326 addrs = append(addrs, ip.String())
331 // goLookupIP is the native Go implementation of LookupIP.
332 func goLookupIP(name string) (addrs []IP, err os.Error) {
333 onceLoadConfig.Do(loadConfig)
334 if dnserr != nil || cfg == nil {
340 cname, records, err = lookup(name, dnsTypeA)
344 addrs = convertRR_A(records)
348 _, records, err = lookup(name, dnsTypeAAAA)
349 if err != nil && len(addrs) > 0 {
350 // Ignore error because A lookup succeeded.
356 addrs = append(addrs, convertRR_AAAA(records)...)
360 // LookupCNAME returns the canonical DNS host for the given name.
361 // Callers that do not care about the canonical name can call
362 // LookupHost or LookupIP directly; both take care of resolving
363 // the canonical name as part of the lookup.
364 func LookupCNAME(name string) (cname string, err os.Error) {
365 onceLoadConfig.Do(loadConfig)
366 if dnserr != nil || cfg == nil {
370 _, rr, err := lookup(name, dnsTypeCNAME)
375 cname = rr[0].(*dnsRR_CNAME).Cname
380 // An SRV represents a single DNS SRV record.
388 // LookupSRV tries to resolve an SRV query of the given service,
389 // protocol, and domain name, as specified in RFC 2782. In most cases
390 // the proto argument can be the same as the corresponding
392 func LookupSRV(service, proto, name string) (cname string, addrs []*SRV, err os.Error) {
393 target := "_" + service + "._" + proto + "." + name
395 cname, records, err = lookup(target, dnsTypeSRV)
399 addrs = make([]*SRV, len(records))
400 for i := 0; i < len(records); i++ {
401 r := records[i].(*dnsRR_SRV)
402 addrs[i] = &SRV{r.Target, r.Port, r.Priority, r.Weight}
407 // An MX represents a single DNS MX record.
413 // LookupMX returns the DNS MX records associated with name.
414 func LookupMX(name string) (entries []*MX, err os.Error) {
416 _, records, err = lookup(name, dnsTypeMX)
420 entries = make([]*MX, len(records))
421 for i := range records {
422 r := records[i].(*dnsRR_MX)
423 entries[i] = &MX{r.Mx, r.Pref}
428 // reverseaddr returns the in-addr.arpa. or ip6.arpa. hostname of the IP
429 // address addr suitable for rDNS (PTR) record lookup or an error if it fails
430 // to parse the IP address.
431 func reverseaddr(addr string) (arpa string, err os.Error) {
434 return "", &DNSError{Error: "unrecognized address", Name: addr}
437 return fmt.Sprintf("%d.%d.%d.%d.in-addr.arpa.", ip[15], ip[14], ip[13], ip[12]), nil
441 // Add it, in reverse, to the buffer
442 for i := len(ip) - 1; i >= 0; i-- {
443 s := fmt.Sprintf("%02x", ip[i])
449 // Append "ip6.arpa." and return (buf already has the final .)
450 return buf.String() + "ip6.arpa.", nil
453 // LookupAddr performs a reverse lookup for the given address, returning a list
454 // of names mapping to that address.
455 func LookupAddr(addr string) (name []string, err os.Error) {
456 name = lookupStaticAddr(addr)
461 arpa, err = reverseaddr(addr)
466 _, records, err = lookup(arpa, dnsTypePTR)
470 name = make([]string, len(records))
471 for i := range records {
472 r := records[i].(*dnsRR_PTR)