Revert r215321.
[official-gcc.git] / libgo / go / net / dnsconfig_unix.go
blobdb45716f124a155aa0519cd70ff6ad25c6e763f3
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 // +build darwin dragonfly freebsd linux nacl netbsd openbsd solaris
7 // Read system DNS config from /etc/resolv.conf
9 package net
11 type dnsConfig struct {
12 servers []string // servers to use
13 search []string // suffixes to append to local name
14 ndots int // number of dots in name to trigger absolute lookup
15 timeout int // seconds before giving up on packet
16 attempts int // lost packets before giving up on server
17 rotate bool // round robin among servers
20 // See resolv.conf(5) on a Linux machine.
21 // TODO(rsc): Supposed to call uname() and chop the beginning
22 // of the host name to get the default search domain.
23 func dnsReadConfig(filename string) (*dnsConfig, error) {
24 file, err := open(filename)
25 if err != nil {
26 return nil, &DNSConfigError{err}
28 conf := new(dnsConfig)
29 conf.servers = make([]string, 0, 3) // small, but the standard limit
30 conf.search = make([]string, 0)
31 conf.ndots = 1
32 conf.timeout = 5
33 conf.attempts = 2
34 conf.rotate = false
35 for line, ok := file.readLine(); ok; line, ok = file.readLine() {
36 f := getFields(line)
37 if len(f) < 1 {
38 continue
40 switch f[0] {
41 case "nameserver": // add one name server
42 a := conf.servers
43 n := len(a)
44 if len(f) > 1 && n < cap(a) {
45 // One more check: make sure server name is
46 // just an IP address. Otherwise we need DNS
47 // to look it up.
48 name := f[1]
49 switch len(ParseIP(name)) {
50 case 16:
51 name = "[" + name + "]"
52 fallthrough
53 case 4:
54 a = a[0 : n+1]
55 a[n] = name
56 conf.servers = a
60 case "domain": // set search path to just this domain
61 if len(f) > 1 {
62 conf.search = make([]string, 1)
63 conf.search[0] = f[1]
64 } else {
65 conf.search = make([]string, 0)
68 case "search": // set search path to given servers
69 conf.search = make([]string, len(f)-1)
70 for i := 0; i < len(conf.search); i++ {
71 conf.search[i] = f[i+1]
74 case "options": // magic options
75 for i := 1; i < len(f); i++ {
76 s := f[i]
77 switch {
78 case hasPrefix(s, "ndots:"):
79 n, _, _ := dtoi(s, 6)
80 if n < 1 {
81 n = 1
83 conf.ndots = n
84 case hasPrefix(s, "timeout:"):
85 n, _, _ := dtoi(s, 8)
86 if n < 1 {
87 n = 1
89 conf.timeout = n
90 case hasPrefix(s, "attempts:"):
91 n, _, _ := dtoi(s, 9)
92 if n < 1 {
93 n = 1
95 conf.attempts = n
96 case s == "rotate":
97 conf.rotate = true
102 file.close()
104 return conf, nil
107 func hasPrefix(s, prefix string) bool {
108 return len(s) >= len(prefix) && s[:len(prefix)] == prefix