OSDN Git Service

Update to current Go library.
[pf3gnuchains/gcc-fork.git] / libgo / go / net / dnsclient.go
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 // DNS client: see RFC 1035.
6 // Has to be linked into package net for Dial.
7
8 // TODO(rsc):
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.
14
15 package net
16
17 import (
18         "bytes"
19         "fmt"
20         "os"
21         "rand"
22         "sync"
23         "time"
24 )
25
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
31         IsTimeout bool
32 }
33
34 func (e *DNSError) String() string {
35         if e == nil {
36                 return "<nil>"
37         }
38         s := "lookup " + e.Name
39         if e.Server != "" {
40                 s += " on " + e.Server
41         }
42         s += ": " + e.Error
43         return s
44 }
45
46 func (e *DNSError) Timeout() bool   { return e.IsTimeout }
47 func (e *DNSError) Temporary() bool { return e.IsTimeout }
48
49 const noSuchHost = "no such host"
50
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) {
54         if len(name) >= 256 {
55                 return nil, &DNSError{Error: "name too long", Name: name}
56         }
57         out := new(dnsMsg)
58         out.id = uint16(rand.Int()) ^ uint16(time.Nanoseconds())
59         out.question = []dnsQuestion{
60                 {name, qtype, dnsClassINET},
61         }
62         out.recursion_desired = true
63         msg, ok := out.Pack()
64         if !ok {
65                 return nil, &DNSError{Error: "internal error - cannot pack message", Name: name}
66         }
67
68         for attempt := 0; attempt < cfg.attempts; attempt++ {
69                 n, err := c.Write(msg)
70                 if err != nil {
71                         return nil, err
72                 }
73
74                 c.SetReadTimeout(int64(cfg.timeout) * 1e9) // nanoseconds
75
76                 buf := make([]byte, 2000) // More than enough.
77                 n, err = c.Read(buf)
78                 if err != nil {
79                         if e, ok := err.(Error); ok && e.Timeout() {
80                                 continue
81                         }
82                         return nil, err
83                 }
84                 buf = buf[0:n]
85                 in := new(dnsMsg)
86                 if !in.Unpack(buf) || in.id != out.id {
87                         continue
88                 }
89                 return in, nil
90         }
91         var server string
92         if a := c.RemoteAddr(); a != nil {
93                 server = a.String()
94         }
95         return nil, &DNSError{Error: "no answer from server", Name: name, Server: server, IsTimeout: true}
96 }
97
98
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))
103
104         if dns.rcode == dnsRcodeNameError && dns.recursion_available {
105                 return "", nil, &DNSError{Error: noSuchHost, Name: name}
106         }
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}
113         }
114
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.
120 Cname:
121         for cnameloop := 0; cnameloop < 10; cnameloop++ {
122                 addrs = addrs[0:0]
123                 for i := 0; i < len(dns.answer); i++ {
124                         rr := dns.answer[i]
125                         h := rr.Header()
126                         if h.Class == dnsClassINET && h.Name == name {
127                                 switch h.Rrtype {
128                                 case qtype:
129                                         n := len(addrs)
130                                         addrs = addrs[0 : n+1]
131                                         addrs[n] = rr
132                                 case dnsTypeCNAME:
133                                         // redirect to cname
134                                         name = rr.(*dnsRR_CNAME).Cname
135                                         continue Cname
136                                 }
137                         }
138                 }
139                 if len(addrs) == 0 {
140                         return "", nil, &DNSError{Error: noSuchHost, Name: name, Server: server}
141                 }
142                 return name, addrs, nil
143         }
144
145         return "", nil, &DNSError{Error: "too many redirects", Name: name, Server: server}
146 }
147
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}
153         }
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)
163                 if cerr != nil {
164                         err = cerr
165                         continue
166                 }
167                 msg, merr := exchange(cfg, c, name, qtype)
168                 c.Close()
169                 if merr != nil {
170                         err = merr
171                         continue
172                 }
173                 cname, addrs, err = answer(name, server, msg, qtype)
174                 if err == nil || err.(*DNSError).Error == noSuchHost {
175                         break
176                 }
177         }
178         return
179 }
180
181 func convertRR_A(records []dnsRR) []IP {
182         addrs := make([]IP, len(records))
183         for i := 0; i < len(records); i++ {
184                 rr := records[i]
185                 a := rr.(*dnsRR_A).A
186                 addrs[i] = IPv4(byte(a>>24), byte(a>>16), byte(a>>8), byte(a))
187         }
188         return addrs
189 }
190
191 func convertRR_AAAA(records []dnsRR) []IP {
192         addrs := make([]IP, len(records))
193         for i := 0; i < len(records); i++ {
194                 rr := records[i]
195                 a := make(IP, 16)
196                 copy(a, rr.(*dnsRR_AAAA).AAAA[:])
197                 addrs[i] = a
198         }
199         return addrs
200 }
201
202 var cfg *dnsConfig
203 var dnserr os.Error
204
205 func loadConfig() { cfg, dnserr = dnsReadConfig() }
206
207 func isDomainName(s string) bool {
208         // See RFC 1035, RFC 3696.
209         if len(s) == 0 {
210                 return false
211         }
212         if len(s) > 255 {
213                 return false
214         }
215         if s[len(s)-1] != '.' { // simplify checking loop: make name end in dot
216                 s += "."
217         }
218
219         last := byte('.')
220         ok := false // ok once we've seen a letter
221         partlen := 0
222         for i := 0; i < len(s); i++ {
223                 c := s[i]
224                 switch {
225                 default:
226                         return false
227                 case 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || c == '_':
228                         ok = true
229                         partlen++
230                 case '0' <= c && c <= '9':
231                         // fine
232                         partlen++
233                 case c == '-':
234                         // byte before dash cannot be dot
235                         if last == '.' {
236                                 return false
237                         }
238                         partlen++
239                 case c == '.':
240                         // byte before dot cannot be dot, dash
241                         if last == '.' || last == '-' {
242                                 return false
243                         }
244                         if partlen > 63 || partlen == 0 {
245                                 return false
246                         }
247                         partlen = 0
248                 }
249                 last = c
250         }
251
252         return ok
253 }
254
255 var onceLoadConfig sync.Once
256
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}
260         }
261         onceLoadConfig.Do(loadConfig)
262         if dnserr != nil || cfg == nil {
263                 err = dnserr
264                 return
265         }
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 {
270                 rname := name
271                 if !rooted {
272                         rname += "."
273                 }
274                 // Can try as ordinary name.
275                 cname, addrs, err = tryOneName(cfg, rname, qtype)
276                 if err == nil {
277                         return
278                 }
279         }
280         if rooted {
281                 return
282         }
283
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] != '.' {
288                         rname += "."
289                 }
290                 cname, addrs, err = tryOneName(cfg, rname, qtype)
291                 if err == nil {
292                         return
293                 }
294         }
295
296         // Last ditch effort: try unsuffixed.
297         rname := name
298         if !rooted {
299                 rname += "."
300         }
301         cname, addrs, err = tryOneName(cfg, rname, qtype)
302         if err == nil {
303                 return
304         }
305         return
306 }
307
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 {
312                 err = dnserr
313                 return
314         }
315         // Use entries from /etc/hosts if they match.
316         addrs = lookupStaticHost(name)
317         if len(addrs) > 0 {
318                 return
319         }
320         ips, err := goLookupIP(name)
321         if err != nil {
322                 return
323         }
324         addrs = make([]string, 0, len(ips))
325         for _, ip := range ips {
326                 addrs = append(addrs, ip.String())
327         }
328         return
329 }
330
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 {
335                 err = dnserr
336                 return
337         }
338         var records []dnsRR
339         var cname string
340         cname, records, err = lookup(name, dnsTypeA)
341         if err != nil {
342                 return
343         }
344         addrs = convertRR_A(records)
345         if cname != "" {
346                 name = cname
347         }
348         _, records, err = lookup(name, dnsTypeAAAA)
349         if err != nil && len(addrs) > 0 {
350                 // Ignore error because A lookup succeeded.
351                 err = nil
352         }
353         if err != nil {
354                 return
355         }
356         addrs = append(addrs, convertRR_AAAA(records)...)
357         return
358 }
359
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 {
367                 err = dnserr
368                 return
369         }
370         _, rr, err := lookup(name, dnsTypeCNAME)
371         if err != nil {
372                 return
373         }
374         if len(rr) >= 0 {
375                 cname = rr[0].(*dnsRR_CNAME).Cname
376         }
377         return
378 }
379
380 // An SRV represents a single DNS SRV record.
381 type SRV struct {
382         Target   string
383         Port     uint16
384         Priority uint16
385         Weight   uint16
386 }
387
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
391 // Addr.Network().
392 func LookupSRV(service, proto, name string) (cname string, addrs []*SRV, err os.Error) {
393         target := "_" + service + "._" + proto + "." + name
394         var records []dnsRR
395         cname, records, err = lookup(target, dnsTypeSRV)
396         if err != nil {
397                 return
398         }
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}
403         }
404         return
405 }
406
407 // An MX represents a single DNS MX record.
408 type MX struct {
409         Host string
410         Pref uint16
411 }
412
413 // LookupMX returns the DNS MX records associated with name.
414 func LookupMX(name string) (entries []*MX, err os.Error) {
415         var records []dnsRR
416         _, records, err = lookup(name, dnsTypeMX)
417         if err != nil {
418                 return
419         }
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}
424         }
425         return
426 }
427
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) {
432         ip := ParseIP(addr)
433         if ip == nil {
434                 return "", &DNSError{Error: "unrecognized address", Name: addr}
435         }
436         if ip.To4() != nil {
437                 return fmt.Sprintf("%d.%d.%d.%d.in-addr.arpa.", ip[15], ip[14], ip[13], ip[12]), nil
438         }
439         // Must be IPv6
440         var buf bytes.Buffer
441         // Add it, in reverse, to the buffer
442         for i := len(ip) - 1; i >= 0; i-- {
443                 s := fmt.Sprintf("%02x", ip[i])
444                 buf.WriteByte(s[1])
445                 buf.WriteByte('.')
446                 buf.WriteByte(s[0])
447                 buf.WriteByte('.')
448         }
449         // Append "ip6.arpa." and return (buf already has the final .)
450         return buf.String() + "ip6.arpa.", nil
451 }
452
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)
457         if len(name) > 0 {
458                 return
459         }
460         var arpa string
461         arpa, err = reverseaddr(addr)
462         if err != nil {
463                 return
464         }
465         var records []dnsRR
466         _, records, err = lookup(arpa, dnsTypePTR)
467         if err != nil {
468                 return
469         }
470         name = make([]string, len(records))
471         for i := range records {
472                 r := records[i].(*dnsRR_PTR)
473                 name[i] = r.Ptr
474         }
475         return
476 }