2022-10-26 20:18:16 +00:00
|
|
|
package dnsmasq
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"os"
|
|
|
|
"text/template"
|
|
|
|
)
|
|
|
|
|
2022-10-29 19:11:40 +00:00
|
|
|
// ConfDataHost describes a host which can be resolved by dnsmasq.
|
|
|
|
type ConfDataHost struct {
|
|
|
|
Name string
|
|
|
|
IP string
|
|
|
|
}
|
|
|
|
|
2022-10-26 20:18:16 +00:00
|
|
|
// ConfData describes all the data needed to populate a dnsmasq.conf file.
|
|
|
|
type ConfData struct {
|
|
|
|
Resolvers []string
|
|
|
|
Domain string
|
|
|
|
IP string
|
2022-10-29 19:11:40 +00:00
|
|
|
Hosts []ConfDataHost
|
2022-10-26 20:18:16 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
var confTpl = template.Must(template.New("").Parse(`
|
|
|
|
port=53
|
|
|
|
|
|
|
|
bind-interfaces
|
|
|
|
listen-address={{ .IP }}
|
|
|
|
|
|
|
|
no-resolv
|
|
|
|
no-hosts
|
|
|
|
|
|
|
|
user=
|
|
|
|
group=
|
|
|
|
|
2022-11-05 15:25:24 +00:00
|
|
|
{{- $domain := .Domain -}}
|
2022-11-05 12:57:21 +00:00
|
|
|
|
|
|
|
{{- range .Hosts }}
|
|
|
|
address=/{{ .Name }}.hosts.{{ $domain }}/{{ .IP }}
|
2022-10-26 20:18:16 +00:00
|
|
|
{{ end -}}
|
|
|
|
|
|
|
|
{{- range .Resolvers }}
|
|
|
|
server={{ . }}
|
|
|
|
{{ end -}}
|
|
|
|
`))
|
|
|
|
|
|
|
|
// WriteConfFile renders a dnsmasq.conf using the given data to a new
|
|
|
|
// file at the given path.
|
|
|
|
func WriteConfFile(path string, data ConfData) error {
|
|
|
|
|
|
|
|
file, err := os.OpenFile(
|
|
|
|
path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0640,
|
|
|
|
)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("creating file: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
defer file.Close()
|
|
|
|
|
|
|
|
if err := confTpl.Execute(file, data); err != nil {
|
|
|
|
return fmt.Errorf("rendering template to file: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|