You've already forked dyndns-client
Initial Commit
This commit is contained in:
147
pkg/config/config.go
Normal file
147
pkg/config/config.go
Normal file
@ -0,0 +1,147 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
_ "embed"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"git.cryptic.systems/volker.raschek/dyndns-client/pkg/types"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
//go:embed config.json
|
||||
var defaultConfig string
|
||||
|
||||
// GetDefaultConfiguration returns a default configuration
|
||||
func GetDefaultConfiguration() (*types.Config, error) {
|
||||
cnf := new(types.Config)
|
||||
jsonDecoder := json.NewDecoder(strings.NewReader(defaultConfig))
|
||||
|
||||
err := jsonDecoder.Decode(cnf)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode default config: %w", err)
|
||||
}
|
||||
|
||||
defaultInterface, err := getDefaultInterfaceByIP()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cnf.Ifaces = []string{defaultInterface.Name}
|
||||
|
||||
return cnf, nil
|
||||
}
|
||||
|
||||
// Read config from a file
|
||||
func Read(cnfFile string) (*types.Config, error) {
|
||||
|
||||
// Load burned in configuration if config not available
|
||||
if _, err := os.Stat(cnfFile); os.IsNotExist(err) {
|
||||
if err := os.MkdirAll(filepath.Dir(cnfFile), 0755); err != nil {
|
||||
return nil, fmt.Errorf("failed to create directory: %w", err)
|
||||
}
|
||||
cnf, err := GetDefaultConfiguration()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = cnf.Validate()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
log.Infof("use embedded configuration")
|
||||
|
||||
return cnf, nil
|
||||
}
|
||||
|
||||
f, err := os.Open(cnfFile)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to open file: %w", err)
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
cnf := new(types.Config)
|
||||
jsonDecoder := json.NewDecoder(f)
|
||||
err = jsonDecoder.Decode(cnf)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode json: %w", err)
|
||||
}
|
||||
|
||||
for _, iface := range cnf.Ifaces {
|
||||
if _, err := net.InterfaceByName(iface); err != nil {
|
||||
return nil, fmt.Errorf("unknown interface: %v", iface)
|
||||
}
|
||||
}
|
||||
|
||||
err = cnf.Validate()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
log.Infof("use configuration from file %v", cnfFile)
|
||||
|
||||
return cnf, nil
|
||||
}
|
||||
|
||||
// Write config into a file
|
||||
func Write(cnf *types.Config, cnfFile string) error {
|
||||
if _, err := os.Stat(filepath.Dir(cnfFile)); os.IsNotExist(err) {
|
||||
err := os.MkdirAll(filepath.Dir(cnfFile), 0755)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
f, err := os.Create(cnfFile)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create file %v: %v", cnfFile, err)
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
jsonEncoder := json.NewEncoder(f)
|
||||
jsonEncoder.SetIndent("", " ")
|
||||
err = jsonEncoder.Encode(cnf)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to encode json: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func getDefaultInterfaceByIP() (*net.Interface, error) {
|
||||
ifaces, err := net.Interfaces()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to fet network interfaces from kernel: %w", err)
|
||||
}
|
||||
|
||||
defaultIP := getOutboundIP()
|
||||
|
||||
for _, iface := range ifaces {
|
||||
addrs, err := iface.Addrs()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to list ip addresses for interface %v: %w", iface.Name, err)
|
||||
}
|
||||
|
||||
for _, addr := range addrs {
|
||||
addrIP := strings.Split(addr.String(), "/")[0]
|
||||
if addrIP == defaultIP.String() {
|
||||
return &iface, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("no interface found fo ip address %v", defaultIP)
|
||||
}
|
||||
|
||||
func getOutboundIP() net.IP {
|
||||
conn, err := net.Dial("udp", "8.8.8.8:80")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer conn.Close()
|
||||
localAddr := conn.LocalAddr().(*net.UDPAddr)
|
||||
return localAddr.IP
|
||||
}
|
1
pkg/config/config.json
Normal file
1
pkg/config/config.json
Normal file
@ -0,0 +1 @@
|
||||
{}
|
335
pkg/daemon/daemon.go
Normal file
335
pkg/daemon/daemon.go
Normal file
@ -0,0 +1,335 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"os/signal"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"git.cryptic.systems/volker.raschek/dyndns-client/pkg/types"
|
||||
"git.cryptic.systems/volker.raschek/dyndns-client/pkg/updater"
|
||||
"github.com/asaskevich/govalidator"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/vishvananda/netlink"
|
||||
)
|
||||
|
||||
func Start(cnf *types.Config) {
|
||||
addrUpdates := make(chan netlink.AddrUpdate, 1)
|
||||
done := make(chan struct{}, 1)
|
||||
err := netlink.AddrSubscribeWithOptions(addrUpdates, done, netlink.AddrSubscribeOptions{
|
||||
ListExisting: true,
|
||||
})
|
||||
if err != nil {
|
||||
log.Fatalf("failed to subscribe netlink notifications from kernel: %v", err.Error())
|
||||
}
|
||||
|
||||
interuptChannel := make(chan os.Signal, 1)
|
||||
signal.Notify(interuptChannel, syscall.SIGINT, syscall.SIGTERM)
|
||||
|
||||
ctx := context.Background()
|
||||
daemonCtx, cancle := context.WithCancel(ctx)
|
||||
defer cancle()
|
||||
|
||||
updaters, err := getUpdaterForEachZone(cnf)
|
||||
if err != nil {
|
||||
log.Fatalf("%v", err.Error())
|
||||
}
|
||||
|
||||
if err := pruneRecords(daemonCtx, updaters, cnf.Zones); err != nil {
|
||||
log.Fatalf("%v", err.Error())
|
||||
}
|
||||
|
||||
for {
|
||||
interfaces, err := netlink.LinkList()
|
||||
if err != nil {
|
||||
log.Fatal("%v", err.Error())
|
||||
}
|
||||
|
||||
select {
|
||||
case update := <-addrUpdates:
|
||||
|
||||
interfaceLogger := log.WithFields(log.Fields{
|
||||
"ip": update.LinkAddress.IP.String(),
|
||||
})
|
||||
|
||||
// search interface by index
|
||||
iface, err := searchInterfaceByIndex(update.LinkIndex, interfaces)
|
||||
if err != nil {
|
||||
log.Errorf("%v", err.Error())
|
||||
continue
|
||||
}
|
||||
interfaceLogger = interfaceLogger.WithField("device", iface.Attrs().Name)
|
||||
|
||||
var recordType string
|
||||
switch {
|
||||
case govalidator.IsIPv4(strings.TrimRight(update.LinkAddress.IP.String(), "/")):
|
||||
recordType = "A"
|
||||
case govalidator.IsIPv6(strings.TrimRight(update.LinkAddress.IP.String(), "/")):
|
||||
recordType = "AAAA"
|
||||
default:
|
||||
interfaceLogger.Error("failed to detect record type")
|
||||
continue
|
||||
}
|
||||
interfaceLogger = interfaceLogger.WithField("rr", recordType)
|
||||
|
||||
interfaceLogger.Debug("receive kernel notification for interface")
|
||||
|
||||
// filter out not configured interfaces
|
||||
if !matchInterfaces(iface.Attrs().Name, cnf.Ifaces) {
|
||||
interfaceLogger.Warn("interface is not part of the allowed interface list")
|
||||
continue
|
||||
}
|
||||
|
||||
// filter out notification for a bad interface ip address, for example link-local-addresses
|
||||
if update.LinkAddress.IP.IsLoopback() || strings.HasPrefix(update.LinkAddress.IP.String(), "fe80") {
|
||||
interfaceLogger.Warn("interface is a loopback device or part of a loopback network")
|
||||
continue
|
||||
}
|
||||
|
||||
// decide if trigger a add or delete event
|
||||
if update.NewAddr {
|
||||
err = addIPRecords(daemonCtx, interfaceLogger, updaters, cnf.Zones, recordType, update.LinkAddress.IP)
|
||||
if err != nil {
|
||||
interfaceLogger.Error(err.Error())
|
||||
}
|
||||
} else {
|
||||
err = removeIPRecords(daemonCtx, interfaceLogger, updaters, cnf.Zones, recordType, update.LinkAddress.IP)
|
||||
if err != nil {
|
||||
interfaceLogger.Error(err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
case killSignal := <-interuptChannel:
|
||||
log.Debugf("got signal: %v", killSignal)
|
||||
log.Debugf("daemon was killed by: %v", killSignal)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func getUpdaterForEachZone(config *types.Config) (map[string]updater.Updater, error) {
|
||||
updaterCollection := make(map[string]updater.Updater)
|
||||
|
||||
for zoneName, zone := range config.Zones {
|
||||
nsUpdater, err := updater.NewNSUpdate(zone.DNSServer, config.TSIGKeys[zone.TSIGKeyName])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
updaterCollection[zoneName] = nsUpdater
|
||||
}
|
||||
|
||||
return updaterCollection, nil
|
||||
}
|
||||
|
||||
func matchInterfaces(iface string, ifaces []string) bool {
|
||||
for _, i := range ifaces {
|
||||
if i == iface {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func searchInterfaceByIndex(index int, interfaces []netlink.Link) (netlink.Link, error) {
|
||||
for _, iface := range interfaces {
|
||||
if iface.Attrs().Index == index {
|
||||
return iface, nil
|
||||
}
|
||||
}
|
||||
return nil, fmt.Errorf("can not find interface by index %v", index)
|
||||
}
|
||||
|
||||
func addIPRecords(ctx context.Context, logEntry *log.Entry, updaters map[string]updater.Updater, zones map[string]*types.Zone, recordType string, ip net.IP) error {
|
||||
|
||||
var (
|
||||
errorChannel = make(chan error, len(zones))
|
||||
wg = new(sync.WaitGroup)
|
||||
)
|
||||
|
||||
hostname, err := os.Hostname()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get host name from kernel: %w", err)
|
||||
}
|
||||
hostname = strings.ToLower(hostname)
|
||||
|
||||
if !verifyHostname(hostname) {
|
||||
return fmt.Errorf("host name not valid: %w", err)
|
||||
}
|
||||
|
||||
for zoneName := range zones {
|
||||
wg.Add(1)
|
||||
|
||||
go func(ctx context.Context, zoneName string, hostname string, recordType string, ip net.IP, wg *sync.WaitGroup) {
|
||||
|
||||
zoneLogger := logEntry.WithFields(log.Fields{
|
||||
"zone": zoneName,
|
||||
"hostname": hostname,
|
||||
})
|
||||
|
||||
defer wg.Done()
|
||||
|
||||
pruneRecordCtx, cancle := context.WithTimeout(ctx, time.Second*15)
|
||||
defer cancle()
|
||||
|
||||
fqdn := fmt.Sprintf("%v.%v", hostname, zoneName)
|
||||
|
||||
err := updaters[zoneName].AddRecord(pruneRecordCtx, fqdn, 60, recordType, ip.String())
|
||||
if err != nil {
|
||||
errorChannel <- fmt.Errorf("failed to remove record type %v for %v: %v", recordType, fqdn, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
zoneLogger.Info("dns-record successfully updated")
|
||||
|
||||
}(ctx, zoneName, hostname, recordType, ip, wg)
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
close(errorChannel)
|
||||
|
||||
for err := range errorChannel {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func pruneRecords(ctx context.Context, updaters map[string]updater.Updater, zones map[string]*types.Zone) error {
|
||||
|
||||
var (
|
||||
errorChannel = make(chan error, len(zones))
|
||||
wg = new(sync.WaitGroup)
|
||||
)
|
||||
|
||||
hostname, err := os.Hostname()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get host name from kernel: %w", err)
|
||||
}
|
||||
hostname = strings.ToLower(hostname)
|
||||
|
||||
if !verifyHostname(hostname) {
|
||||
return fmt.Errorf("host name not valid: %w", err)
|
||||
}
|
||||
|
||||
for zoneName := range zones {
|
||||
wg.Add(1)
|
||||
|
||||
go func(zoneName string, hostname string, errorChannel chan<- error, wg *sync.WaitGroup) {
|
||||
defer wg.Done()
|
||||
|
||||
pruneRecordCtx, cancle := context.WithTimeout(ctx, time.Second*15)
|
||||
defer cancle()
|
||||
|
||||
fqdn := fmt.Sprintf("%v.%v", hostname, zoneName)
|
||||
|
||||
err := updaters[zoneName].PruneRecords(pruneRecordCtx, fqdn)
|
||||
if err != nil {
|
||||
errorChannel <- fmt.Errorf("failed to prune %v: %v", fqdn, err)
|
||||
return
|
||||
}
|
||||
}(zoneName, hostname, errorChannel, wg)
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
close(errorChannel)
|
||||
|
||||
for err := range errorChannel {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func removeIPRecords(ctx context.Context, logEntry *log.Entry, updaters map[string]updater.Updater, zones map[string]*types.Zone, recordType string, ip net.IP) error {
|
||||
|
||||
var (
|
||||
errorChannel = make(chan error, len(zones))
|
||||
wg = new(sync.WaitGroup)
|
||||
)
|
||||
|
||||
hostname, err := os.Hostname()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get host name from kernel: %w", err)
|
||||
}
|
||||
hostname = strings.ToLower(hostname)
|
||||
|
||||
if !verifyHostname(hostname) {
|
||||
return fmt.Errorf("host name not valid: %w", err)
|
||||
}
|
||||
|
||||
for zoneName := range zones {
|
||||
wg.Add(1)
|
||||
|
||||
go func(ctx context.Context, zoneName string, hostname string, recordType string, wg *sync.WaitGroup) {
|
||||
defer wg.Done()
|
||||
|
||||
zoneLogger := logEntry.WithFields(log.Fields{
|
||||
"zone": zoneName,
|
||||
"hostname": hostname,
|
||||
})
|
||||
|
||||
pruneRecordCtx, cancle := context.WithTimeout(ctx, time.Second*15)
|
||||
defer cancle()
|
||||
|
||||
fqdn := fmt.Sprintf("%v.%v", hostname, zoneName)
|
||||
|
||||
err := updaters[zoneName].DeleteRecord(pruneRecordCtx, fqdn, recordType)
|
||||
if err != nil {
|
||||
errorChannel <- fmt.Errorf("failed to remove record type %v for %v: %v", recordType, fqdn, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
zoneLogger.Info("dns-record successfully removed")
|
||||
|
||||
}(ctx, zoneName, hostname, recordType, wg)
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
close(errorChannel)
|
||||
|
||||
for err := range errorChannel {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// verifyHostname returns a boolean if the hostname id valid. The hostname does
|
||||
// not contains any dot or local, localhost, localdomain.
|
||||
func verifyHostname(hostname string) bool {
|
||||
|
||||
if !validHostname.MatchString(hostname) {
|
||||
return false
|
||||
}
|
||||
|
||||
hostnames := []string{
|
||||
"local",
|
||||
"localhost",
|
||||
"localdomain",
|
||||
"orbisos",
|
||||
}
|
||||
|
||||
for i := range hostnames {
|
||||
if hostnames[i] == hostname {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
var (
|
||||
validHostname = regexp.MustCompile(`^[a-zA-Z0-9]+([\-][a-zA-Z0-9]+)*$`)
|
||||
)
|
42
pkg/types/config.go
Normal file
42
pkg/types/config.go
Normal file
@ -0,0 +1,42 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/asaskevich/govalidator"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Ifaces []string `json:"interfaces"`
|
||||
Zones map[string]*Zone `json:"zones"`
|
||||
TSIGKeys map[string]*TSIGKey `json:"tsig-keys"`
|
||||
}
|
||||
|
||||
func (c *Config) Validate() error {
|
||||
if len(c.Zones) <= 0 {
|
||||
return fmt.Errorf("no dns zones configured")
|
||||
}
|
||||
|
||||
if len(c.Ifaces) <= 0 {
|
||||
return fmt.Errorf("no interfaces configured")
|
||||
}
|
||||
|
||||
ZONE_LOOP:
|
||||
for _, zone := range c.Zones {
|
||||
if !govalidator.IsIP(zone.DNSServer) && !govalidator.IsDNSName(zone.DNSServer) {
|
||||
return fmt.Errorf("invalid dns server %v", zone.DNSServer)
|
||||
}
|
||||
|
||||
if !govalidator.IsDNSName(zone.Name) {
|
||||
return fmt.Errorf("invalid dns zone name %v", zone.Name)
|
||||
}
|
||||
|
||||
for _, tsigkey := range c.TSIGKeys {
|
||||
if tsigkey.Name == zone.TSIGKeyName {
|
||||
continue ZONE_LOOP
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("no matching tsigkey found for zone %v", zone.Name)
|
||||
}
|
||||
return nil
|
||||
}
|
7
pkg/types/tsigkey.go
Normal file
7
pkg/types/tsigkey.go
Normal file
@ -0,0 +1,7 @@
|
||||
package types
|
||||
|
||||
type TSIGKey struct {
|
||||
Algorithm string `json:"algorithm"`
|
||||
Name string `json:"name"`
|
||||
Secret string `json:"secret"`
|
||||
}
|
7
pkg/types/zone.go
Normal file
7
pkg/types/zone.go
Normal file
@ -0,0 +1,7 @@
|
||||
package types
|
||||
|
||||
type Zone struct {
|
||||
DNSServer string `json:"dns-server"`
|
||||
Name string `json:"name"`
|
||||
TSIGKeyName string `json:"tsig-key"`
|
||||
}
|
72
pkg/updater/updater.go
Normal file
72
pkg/updater/updater.go
Normal file
@ -0,0 +1,72 @@
|
||||
package updater
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"os/exec"
|
||||
"strings"
|
||||
|
||||
"git.cryptic.systems/volker.raschek/dyndns-client/pkg/types"
|
||||
)
|
||||
|
||||
type Updater interface {
|
||||
AddRecord(ctx context.Context, name string, ttl uint, recordType string, data string) error
|
||||
DeleteRecord(ctx context.Context, name string, recordType string) error
|
||||
PruneRecords(ctx context.Context, name string) error
|
||||
}
|
||||
|
||||
type NSUpdate struct {
|
||||
server string
|
||||
tsigKey *types.TSIGKey
|
||||
}
|
||||
|
||||
func (u *NSUpdate) AddRecord(ctx context.Context, name string, ttl uint, recordType string, data string) error {
|
||||
nsUpdateCmd := ""
|
||||
switch recordType {
|
||||
case "A", "AAAA":
|
||||
nsUpdateCmd = fmt.Sprintf("update add %v %v IN %v %v", name, ttl, recordType, data)
|
||||
case "TXT":
|
||||
nsUpdateCmd = fmt.Sprintf("update add %v %v IN %v \"%v\"", name, ttl, recordType, data)
|
||||
default:
|
||||
return fmt.Errorf("RecordType %v not supported", recordType)
|
||||
}
|
||||
|
||||
return u.execute(ctx, nsUpdateCmd)
|
||||
}
|
||||
|
||||
func (u *NSUpdate) DeleteRecord(ctx context.Context, name string, recordType string) error {
|
||||
nsUpdateCmd := fmt.Sprintf("update delete %v IN %v", name, recordType)
|
||||
return u.execute(ctx, nsUpdateCmd)
|
||||
}
|
||||
|
||||
func (u *NSUpdate) execute(ctx context.Context, nsUpdateCmd string) error {
|
||||
body := fmt.Sprintf("server %v\n%v\nsend\nquit", u.server, nsUpdateCmd)
|
||||
|
||||
errBuffer := new(bytes.Buffer)
|
||||
|
||||
cmd := exec.CommandContext(ctx, "nsupdate", "-y", fmt.Sprintf("%v:%v:%v", u.tsigKey.Algorithm, u.tsigKey.Name, u.tsigKey.Secret))
|
||||
// cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = bufio.NewWriter(errBuffer)
|
||||
cmd.Stdin = strings.NewReader(body)
|
||||
|
||||
err := cmd.Run()
|
||||
if err != nil {
|
||||
return fmt.Errorf("nsupdate error %w: %v", err, errBuffer.String())
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (u *NSUpdate) PruneRecords(ctx context.Context, name string) error {
|
||||
nsUpdateCmd := fmt.Sprintf("update delete %v", name)
|
||||
return u.execute(ctx, nsUpdateCmd)
|
||||
}
|
||||
|
||||
func NewNSUpdate(server string, tsigKey *types.TSIGKey) (Updater, error) {
|
||||
return &NSUpdate{
|
||||
server: server,
|
||||
tsigKey: tsigKey,
|
||||
}, nil
|
||||
}
|
Reference in New Issue
Block a user