dns/config.go

102 lines
2.3 KiB
Go
Raw Normal View History

2011-03-08 07:27:36 +00:00
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Read system DNS config from /etc/resolv.conf
2011-03-28 15:19:26 +00:00
// Extend this further, but need to thinks about Conn
2011-03-08 07:27:36 +00:00
package dns
import (
"os"
"bufio"
"strconv"
"strings"
"net"
)
// See resolv.conf(5) on a Linux machine.
2011-03-28 15:19:26 +00:00
// Parse a /etc/resolv.conf like file. For only
// only return the nameservers with :53 added as a slice.
func FromFile(conf string) ([]string, os.Error) {
2011-03-08 07:27:36 +00:00
file, err := os.Open(conf, os.O_RDONLY, 0)
defer file.Close()
if err != nil {
2011-03-28 15:19:26 +00:00
return nil, err
2011-03-08 07:27:36 +00:00
}
b := bufio.NewReader(file)
2011-03-28 15:19:26 +00:00
servers := make([]string, 3)[0:0] // small, but the standard limit
search := make([]string, 0)
ndots := 1; var _ = ndots
timeout := 5; var _ = timeout
attempts := 2; var _ = attempts
2011-03-08 07:27:36 +00:00
for line, ok := b.ReadString('\n'); ok == nil; line, ok = b.ReadString('\n') {
f := strings.Fields(line)
if len(f) < 1 {
continue
}
switch f[0] {
case "nameserver": // add one name server
2011-03-28 15:19:26 +00:00
a := servers
2011-03-08 07:27:36 +00:00
n := len(a)
if len(f) > 1 && n < cap(a) {
// One more check: make sure server name is
// just an IP address. Otherwise we need DNS
// to look it up.
name := f[1]
switch len(net.ParseIP(name)) {
case 16:
name = "[" + name + "]"
fallthrough
case 4:
a = a[0 : n+1]
2011-03-28 15:19:26 +00:00
a[n] = name + ":53"
servers = a
2011-03-08 07:27:36 +00:00
}
}
case "domain": // set search path to just this domain
if len(f) > 1 {
2011-03-28 15:19:26 +00:00
search = make([]string, 1)
search[0] = f[1]
2011-03-08 07:27:36 +00:00
} else {
2011-03-28 15:19:26 +00:00
search = make([]string, 0)
2011-03-08 07:27:36 +00:00
}
case "search": // set search path to given servers
2011-03-28 15:19:26 +00:00
search = make([]string, len(f)-1)
for i := 0; i < len(search); i++ {
search[i] = f[i+1]
2011-03-08 07:27:36 +00:00
}
case "options": // magic options
for i := 1; i < len(f); i++ {
s := f[i]
switch {
case len(s) >= 6 && s[:6] == "ndots:":
n, _ := strconv.Atoi(s[6:])
if n < 1 {
n = 1
}
2011-03-28 15:19:26 +00:00
ndots = n
2011-03-08 07:27:36 +00:00
case len(s) >= 8 && s[:8] == "timeout:":
n, _ := strconv.Atoi(s[8:])
if n < 1 {
n = 1
}
2011-03-28 15:19:26 +00:00
timeout = n
2011-03-08 07:27:36 +00:00
case len(s) >= 8 && s[:9] == "attempts:":
n, _ := strconv.Atoi(s[9:])
if n < 1 {
n = 1
}
2011-03-28 15:19:26 +00:00
attempts = n
2011-03-08 07:27:36 +00:00
case s == "rotate":
2011-03-24 08:24:24 +00:00
/* not imp */
2011-03-08 07:27:36 +00:00
}
}
}
}
2011-03-28 15:19:26 +00:00
return servers, nil
2011-03-08 07:27:36 +00:00
}