Merge from mainline (167278:168000).
[official-gcc/graphite-test-results.git] / libgo / go / net / dnsclient.go
blobf1cd47bb19c9cb5baa99c9b5f5b70cac670f2c6f
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.
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.
15 package net
17 import (
18 "os"
19 "rand"
20 "sync"
21 "time"
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
32 func (e *DNSError) String() string {
33 if e == nil {
34 return "<nil>"
36 s := "lookup " + e.Name
37 if e.Server != "" {
38 s += " on " + e.Server
40 s += ": " + e.Error
41 return s
44 func (e *DNSError) Timeout() bool { return e.IsTimeout }
45 func (e *DNSError) Temporary() bool { return e.IsTimeout }
47 const noSuchHost = "no such host"
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}
55 out := new(dnsMsg)
56 out.id = uint16(rand.Int()) ^ uint16(time.Nanoseconds())
57 out.question = []dnsQuestion{
58 {name, qtype, dnsClassINET},
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}
66 for attempt := 0; attempt < cfg.attempts; attempt++ {
67 n, err := c.Write(msg)
68 if err != nil {
69 return nil, err
72 c.SetReadTimeout(int64(cfg.timeout) * 1e9) // nanoseconds
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
80 return nil, err
82 buf = buf[0:n]
83 in := new(dnsMsg)
84 if !in.Unpack(buf) || in.id != out.id {
85 continue
87 return in, nil
89 var server string
90 if a := c.RemoteAddr(); a != nil {
91 server = a.String()
93 return nil, &DNSError{Error: "no answer from server", Name: name, Server: server, IsTimeout: true}
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))
102 if dns.rcode == dnsRcodeNameError && dns.recursion_available {
103 return nil, &DNSError{Error: noSuchHost, Name: name}
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}
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
137 if len(addrs) == 0 {
138 return nil, &DNSError{Error: noSuchHost, Name: name, Server: server}
140 return addrs, nil
143 return nil, &DNSError{Error: "too many redirects", Name: name, Server: server}
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}
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
165 msg, merr := exchange(cfg, c, name, qtype)
166 c.Close()
167 if merr != nil {
168 err = merr
169 continue
171 addrs, err = answer(name, server, msg, qtype)
172 if err == nil || err.(*DNSError).Error == noSuchHost {
173 break
176 return
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()
186 return addrs
189 var cfg *dnsConfig
190 var dnserr os.Error
192 func loadConfig() { cfg, dnserr = dnsReadConfig() }
194 func isDomainName(s string) bool {
195 // See RFC 1035, RFC 3696.
196 if len(s) == 0 {
197 return false
199 if len(s) > 255 {
200 return false
202 if s[len(s)-1] != '.' { // simplify checking loop: make name end in dot
203 s += "."
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
225 partlen++
226 case c == '.':
227 // byte before dot cannot be dot, dash
228 if last == '.' || last == '-' {
229 return false
231 if partlen > 63 || partlen == 0 {
232 return false
234 partlen = 0
236 last = c
239 return ok
242 var onceLoadConfig sync.Once
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}
248 onceLoadConfig.Do(loadConfig)
249 if dnserr != nil || cfg == nil {
250 err = dnserr
251 return
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 += "."
261 // Can try as ordinary name.
262 addrs, err = tryOneName(cfg, rname, qtype)
263 if err == nil {
264 cname = rname
265 return
268 if rooted {
269 return
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 += "."
278 addrs, err = tryOneName(cfg, rname, qtype)
279 if err == nil {
280 cname = rname
281 return
285 // Last ditch effort: try unsuffixed.
286 rname := name
287 if !rooted {
288 rname += "."
290 addrs, err = tryOneName(cfg, rname, qtype)
291 if err == nil {
292 cname = rname
293 return
295 return
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
307 // Use entries from /etc/hosts if they match.
308 addrs = lookupStaticHost(name)
309 if len(addrs) > 0 {
310 cname = name
311 return
313 var records []dnsRR
314 cname, records, err = lookup(name, dnsTypeA)
315 if err != nil {
316 return
318 addrs = convertRR_A(records)
319 return
322 type SRV struct {
323 Target string
324 Port uint16
325 Priority uint16
326 Weight uint16
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
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}
345 return
348 type MX struct {
349 Host string
350 Pref uint16
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
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}
364 return