2014-05-05 18:05:14 -04:00
|
|
|
package etchosts
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"fmt"
|
2014-11-05 15:24:15 -05:00
|
|
|
"io"
|
2014-05-05 18:05:14 -04:00
|
|
|
"io/ioutil"
|
2014-07-14 19:19:37 -04:00
|
|
|
"regexp"
|
2014-05-05 18:05:14 -04:00
|
|
|
)
|
|
|
|
|
2014-11-05 15:24:15 -05:00
|
|
|
type Record struct {
|
|
|
|
Hosts string
|
|
|
|
IP string
|
2014-05-05 18:05:14 -04:00
|
|
|
}
|
|
|
|
|
2014-11-05 15:24:15 -05:00
|
|
|
func (r Record) WriteTo(w io.Writer) (int64, error) {
|
|
|
|
n, err := fmt.Fprintf(w, "%s\t%s\n", r.IP, r.Hosts)
|
|
|
|
return int64(n), err
|
|
|
|
}
|
|
|
|
|
|
|
|
var defaultContent = []Record{
|
|
|
|
{Hosts: "localhost", IP: "127.0.0.1"},
|
|
|
|
{Hosts: "localhost ip6-localhost ip6-loopback", IP: "::1"},
|
|
|
|
{Hosts: "ip6-localnet", IP: "fe00::0"},
|
|
|
|
{Hosts: "ip6-mcastprefix", IP: "ff00::0"},
|
|
|
|
{Hosts: "ip6-allnodes", IP: "ff02::1"},
|
|
|
|
{Hosts: "ip6-allrouters", IP: "ff02::2"},
|
|
|
|
}
|
|
|
|
|
|
|
|
func Build(path, IP, hostname, domainname string, extraContent []Record) error {
|
2014-05-05 18:05:14 -04:00
|
|
|
content := bytes.NewBuffer(nil)
|
|
|
|
if IP != "" {
|
2014-11-05 15:24:15 -05:00
|
|
|
var mainRec Record
|
|
|
|
mainRec.IP = IP
|
2014-05-05 18:05:14 -04:00
|
|
|
if domainname != "" {
|
2014-11-05 15:24:15 -05:00
|
|
|
mainRec.Hosts = fmt.Sprintf("%s.%s %s", hostname, domainname, hostname)
|
2014-05-05 18:05:14 -04:00
|
|
|
} else {
|
2014-11-05 15:24:15 -05:00
|
|
|
mainRec.Hosts = hostname
|
|
|
|
}
|
|
|
|
if _, err := mainRec.WriteTo(content); err != nil {
|
|
|
|
return err
|
2014-05-05 18:05:14 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-11-05 15:24:15 -05:00
|
|
|
for _, r := range defaultContent {
|
|
|
|
if _, err := r.WriteTo(content); err != nil {
|
2014-05-05 18:05:14 -04:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
2014-04-07 14:34:07 -04:00
|
|
|
|
2014-11-05 15:24:15 -05:00
|
|
|
for _, r := range extraContent {
|
|
|
|
if _, err := r.WriteTo(content); err != nil {
|
|
|
|
return err
|
2014-04-07 14:34:07 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-05-05 18:05:14 -04:00
|
|
|
return ioutil.WriteFile(path, content.Bytes(), 0644)
|
|
|
|
}
|
2014-07-14 19:19:37 -04:00
|
|
|
|
|
|
|
func Update(path, IP, hostname string) error {
|
|
|
|
old, err := ioutil.ReadFile(path)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
var re = regexp.MustCompile(fmt.Sprintf("(\\S*)(\\t%s)", regexp.QuoteMeta(hostname)))
|
|
|
|
return ioutil.WriteFile(path, re.ReplaceAll(old, []byte(IP+"$2")), 0644)
|
|
|
|
}
|