Skip to content
Permalink
Browse files

Fix: Restore /etc/resolv.conf after unclean program exit

  • Loading branch information...
janeczku
janeczku committed Oct 2, 2016
1 parent 6c45375 commit 0808cf7eda60eb14822001dec0576c53a91635c3
Showing with 14 additions and 9 deletions.
  1. +4 −3 hostsfile/hostsfile.go
  2. +6 −1 main.go
  3. +4 −5 resolvconf/resolvconf.go
@@ -55,9 +55,10 @@ func NewHostsfile(path string, config *Config) (*Hostsfile, error) {

log.Debugf("Found host:ip pairs in %s:", h.file.path)
for _, hostname := range *h.hosts {
log.Debugf("%s : %s",
log.Debugf("%s -> %s *=%t",
hostname.domain,
hostname.ip.String())
hostname.ip.String(),
hostname.wildcard)
}

return &h, nil
@@ -67,7 +68,7 @@ func (h *Hostsfile) FindHosts(name string) (addrs []net.IP, err error) {
name = strings.TrimSuffix(name, ".")
h.hostMutex.RLock()
defer h.hostMutex.RUnlock()
addrs = h.hosts.FindHosts(name);
addrs = h.hosts.FindHosts(name)
return
}

@@ -252,6 +252,7 @@ func main() {
Verbose: c.Bool("verbose"),
}

resolvconf.Clean()
if err := server.ResolvConf(config, c); err != nil {
if !os.IsNotExist(err) {
log.Warnf("Error parsing resolv.conf: %s", err.Error())
@@ -322,7 +323,11 @@ func main() {
if err != nil {
log.Warnf("Failed to register as default nameserver: %s", err)
}
defer resolvconf.Clean()

defer func() {
log.Info("Restoring /etc/resolv.conf")
resolvconf.Clean()
}()
}

go func() {
@@ -24,13 +24,12 @@ const RESOLVCONF_PATH = "/etc/resolv.conf"
var resolvConfPattern = regexp.MustCompile("(?m:^.*" + regexp.QuoteMeta(RESOLVCONF_COMMENT_ADD) + ")(?:$|\n)")

func StoreAddress(address string) error {
log.Info("Setting host nameserver to %s", address)
log.Infof("Setting host nameserver to %s", address)
resolveConfEntry := fmt.Sprintf("nameserver %s %s\n", address, RESOLVCONF_COMMENT_ADD)
return updateResolvConf(resolveConfEntry, RESOLVCONF_PATH)
}

func Clean() {
log.Info("Restoring /etc/resolv.conf")
updateResolvConf("", RESOLVCONF_PATH)
}

@@ -60,17 +59,17 @@ func updateResolvConf(insert, path string) error {
for _, line := range lines {
switch insert {
case "":
// Uncomment lines we commented
// uncomment lines we commented
if strings.Contains(line, RESOLVCONF_COMMENT_OUT) {
line = strings.Replace(line, RESOLVCONF_COMMENT_OUT, "", -1)
line = strings.TrimLeft(line, " ")
}
default:
// Comment out active nameservers only
// comment out active nameservers only
if strings.HasPrefix(strings.ToLower(strings.TrimSpace(line)), "nameserver") {
line = fmt.Sprintf("%s %s", RESOLVCONF_COMMENT_OUT, line)
}
}
}

if _, err = f.WriteString(line); err != nil {
return err

0 comments on commit 0808cf7

Please sign in to comment.
You can’t perform that action at this time.