OSDN Git Service

Add Go frontend, libgo library, and Go testsuite.
[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         "os"
19         "rand"
20         "sync"
21         "time"
22 )
23
24 // DNSError represents a DNS lookup error.
25 type DNSError struct {
26         Error     string // description of the error
27         Name      string // name looked for
28         Server    string // server used
29         IsTimeout bool
30 }
31
32 func (e *DNSError) String() string {
33         if e == nil {
34                 return "<nil>"
35         }
36         s := "lookup " + e.Name
37         if e.Server != "" {
38                 s += " on " + e.Server
39         }
40         s += ": " + e.Error
41         return s
42 }
43
44 func (e *DNSError) Timeout() bool   { return e.IsTimeout }
45 func (e *DNSError) Temporary() bool { return e.IsTimeout }
46
47 const noSuchHost = "no such host"
48
49 // Send a request on the connection and hope for a reply.
50 // Up to cfg.attempts attempts.
51 func exchange(cfg *dnsConfig, c Conn, name string, qtype uint16) (*dnsMsg, os.Error) {
52         if len(name) >= 256 {
53                 return nil, &DNSError{Error: "name too long", Name: name}
54         }
55         out := new(dnsMsg)
56         out.id = uint16(rand.Int()) ^ uint16(time.Nanoseconds())
57         out.question = []dnsQuestion{
58                 {name, qtype, dnsClassINET},
59         }
60         out.recursion_desired = true
61         msg, ok := out.Pack()
62         if !ok {
63                 return nil, &DNSError{Error: "internal error - cannot pack message", Name: name}
64         }
65
66         for attempt := 0; attempt < cfg.attempts; attempt++ {
67                 n, err := c.Write(msg)
68                 if err != nil {
69                         return nil, err
70                 }
71
72                 c.SetReadTimeout(int64(cfg.timeout) * 1e9) // nanoseconds
73
74                 buf := make([]byte, 2000) // More than enough.
75                 n, err = c.Read(buf)
76                 if err != nil {
77                         if e, ok := err.(Error); ok && e.Timeout() {
78                                 continue
79                         }
80                         return nil, err
81                 }
82                 buf = buf[0:n]
83                 in := new(dnsMsg)
84                 if !in.Unpack(buf) || in.id != out.id {
85                         continue
86                 }
87                 return in, nil
88         }
89         var server string
90         if a := c.RemoteAddr(); a != nil {
91                 server = a.String()
92         }
93         return nil, &DNSError{Error: "no answer from server", Name: name, Server: server, IsTimeout: true}
94 }
95
96
97 // Find answer for name in dns message.
98 // On return, if err == nil, addrs != nil.
99 func answer(name, server string, dns *dnsMsg, qtype uint16) (addrs []dnsRR, err os.Error) {
100         addrs = make([]dnsRR, 0, len(dns.answer))
101
102         if dns.rcode == dnsRcodeNameError && dns.recursion_available {
103                 return nil, &DNSError{Error: noSuchHost, Name: name}
104         }
105         if dns.rcode != dnsRcodeSuccess {
106                 // None of the error codes make sense
107                 // for the query we sent.  If we didn't get
108                 // a name error and we didn't get success,
109                 // the server is behaving incorrectly.
110                 return nil, &DNSError{Error: "server misbehaving", Name: name, Server: server}
111         }
112
113         // Look for the name.
114         // Presotto says it's okay to assume that servers listed in
115         // /etc/resolv.conf are recursive resolvers.
116         // We asked for recursion, so it should have included
117         // all the answers we need in this one packet.
118 Cname:
119         for cnameloop := 0; cnameloop < 10; cnameloop++ {
120                 addrs = addrs[0:0]
121                 for i := 0; i < len(dns.answer); i++ {
122                         rr := dns.answer[i]
123                         h := rr.Header()
124                         if h.Class == dnsClassINET && h.Name == name {
125                                 switch h.Rrtype {
126                                 case qtype:
127                                         n := len(addrs)
128                                         addrs = addrs[0 : n+1]
129                                         addrs[n] = rr
130                                 case dnsTypeCNAME:
131                                         // redirect to cname
132                                         name = rr.(*dnsRR_CNAME).Cname
133                                         continue Cname
134                                 }
135                         }
136                 }
137                 if len(addrs) == 0 {
138                         return nil, &DNSError{Error: noSuchHost, Name: name, Server: server}
139                 }
140                 return addrs, nil
141         }
142
143         return nil, &DNSError{Error: "too many redirects", Name: name, Server: server}
144 }
145
146 // Do a lookup for a single name, which must be rooted
147 // (otherwise answer will not find the answers).
148 func tryOneName(cfg *dnsConfig, name string, qtype uint16) (addrs []dnsRR, err os.Error) {
149         if len(cfg.servers) == 0 {
150                 return nil, &DNSError{Error: "no DNS servers", Name: name}
151         }
152         for i := 0; i < len(cfg.servers); i++ {
153                 // Calling Dial here is scary -- we have to be sure
154                 // not to dial a name that will require a DNS lookup,
155                 // or Dial will call back here to translate it.
156                 // The DNS config parser has already checked that
157                 // all the cfg.servers[i] are IP addresses, which
158                 // Dial will use without a DNS lookup.
159                 server := cfg.servers[i] + ":53"
160                 c, cerr := Dial("udp", "", server)
161                 if cerr != nil {
162                         err = cerr
163                         continue
164                 }
165                 msg, merr := exchange(cfg, c, name, qtype)
166                 c.Close()
167                 if merr != nil {
168                         err = merr
169                         continue
170                 }
171                 addrs, err = answer(name, server, msg, qtype)
172                 if err == nil || err.(*DNSError).Error == noSuchHost {
173                         break
174                 }
175         }
176         return
177 }
178
179 func convertRR_A(records []dnsRR) []string {
180         addrs := make([]string, len(records))
181         for i := 0; i < len(records); i++ {
182                 rr := records[i]
183                 a := rr.(*dnsRR_A).A
184                 addrs[i] = IPv4(byte(a>>24), byte(a>>16), byte(a>>8), byte(a)).String()
185         }
186         return addrs
187 }
188
189 var cfg *dnsConfig
190 var dnserr os.Error
191
192 func loadConfig() { cfg, dnserr = dnsReadConfig() }
193
194 func isDomainName(s string) bool {
195         // See RFC 1035, RFC 3696.
196         if len(s) == 0 {
197                 return false
198         }
199         if len(s) > 255 {
200                 return false
201         }
202         if s[len(s)-1] != '.' { // simplify checking loop: make name end in dot
203                 s += "."
204         }
205
206         last := byte('.')
207         ok := false // ok once we've seen a letter
208         partlen := 0
209         for i := 0; i < len(s); i++ {
210                 c := s[i]
211                 switch {
212                 default:
213                         return false
214                 case 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || c == '_':
215                         ok = true
216                         partlen++
217                 case '0' <= c && c <= '9':
218                         // fine
219                         partlen++
220                 case c == '-':
221                         // byte before dash cannot be dot
222                         if last == '.' {
223                                 return false
224                         }
225                         partlen++
226                 case c == '.':
227                         // byte before dot cannot be dot, dash
228                         if last == '.' || last == '-' {
229                                 return false
230                         }
231                         if partlen > 63 || partlen == 0 {
232                                 return false
233                         }
234                         partlen = 0
235                 }
236                 last = c
237         }
238
239         return ok
240 }
241
242 var onceLoadConfig sync.Once
243
244 func lookup(name string, qtype uint16) (cname string, addrs []dnsRR, err os.Error) {
245         if !isDomainName(name) {
246                 return name, nil, &DNSError{Error: "invalid domain name", Name: name}
247         }
248         onceLoadConfig.Do(loadConfig)
249         if dnserr != nil || cfg == nil {
250                 err = dnserr
251                 return
252         }
253         // If name is rooted (trailing dot) or has enough dots,
254         // try it by itself first.
255         rooted := len(name) > 0 && name[len(name)-1] == '.'
256         if rooted || count(name, '.') >= cfg.ndots {
257                 rname := name
258                 if !rooted {
259                         rname += "."
260                 }
261                 // Can try as ordinary name.
262                 addrs, err = tryOneName(cfg, rname, qtype)
263                 if err == nil {
264                         cname = rname
265                         return
266                 }
267         }
268         if rooted {
269                 return
270         }
271
272         // Otherwise, try suffixes.
273         for i := 0; i < len(cfg.search); i++ {
274                 rname := name + "." + cfg.search[i]
275                 if rname[len(rname)-1] != '.' {
276                         rname += "."
277                 }
278                 addrs, err = tryOneName(cfg, rname, qtype)
279                 if err == nil {
280                         cname = rname
281                         return
282                 }
283         }
284
285         // Last ditch effort: try unsuffixed.
286         rname := name
287         if !rooted {
288                 rname += "."
289         }
290         addrs, err = tryOneName(cfg, rname, qtype)
291         if err == nil {
292                 cname = rname
293                 return
294         }
295         return
296 }
297
298 // LookupHost looks for name using the local hosts file and DNS resolver.
299 // It returns the canonical name for the host and an array of that
300 // host's addresses.
301 func LookupHost(name string) (cname string, addrs []string, err os.Error) {
302         onceLoadConfig.Do(loadConfig)
303         if dnserr != nil || cfg == nil {
304                 err = dnserr
305                 return
306         }
307         // Use entries from /etc/hosts if they match.
308         addrs = lookupStaticHost(name)
309         if len(addrs) > 0 {
310                 cname = name
311                 return
312         }
313         var records []dnsRR
314         cname, records, err = lookup(name, dnsTypeA)
315         if err != nil {
316                 return
317         }
318         addrs = convertRR_A(records)
319         return
320 }
321
322 type SRV struct {
323         Target   string
324         Port     uint16
325         Priority uint16
326         Weight   uint16
327 }
328
329 // LookupSRV tries to resolve an SRV query of the given service,
330 // protocol, and domain name, as specified in RFC 2782. In most cases
331 // the proto argument can be the same as the corresponding
332 // Addr.Network().
333 func LookupSRV(service, proto, name string) (cname string, addrs []*SRV, err os.Error) {
334         target := "_" + service + "._" + proto + "." + name
335         var records []dnsRR
336         cname, records, err = lookup(target, dnsTypeSRV)
337         if err != nil {
338                 return
339         }
340         addrs = make([]*SRV, len(records))
341         for i := 0; i < len(records); i++ {
342                 r := records[i].(*dnsRR_SRV)
343                 addrs[i] = &SRV{r.Target, r.Port, r.Priority, r.Weight}
344         }
345         return
346 }
347
348 type MX struct {
349         Host string
350         Pref uint16
351 }
352
353 func LookupMX(name string) (entries []*MX, err os.Error) {
354         var records []dnsRR
355         _, records, err = lookup(name, dnsTypeMX)
356         if err != nil {
357                 return
358         }
359         entries = make([]*MX, len(records))
360         for i := 0; i < len(records); i++ {
361                 r := records[i].(*dnsRR_MX)
362                 entries[i] = &MX{r.Mx, r.Pref}
363         }
364         return
365 }