diff --git a/cmd/cf.go b/cmd/cf.go deleted file mode 100644 index 46053ba..0000000 --- a/cmd/cf.go +++ /dev/null @@ -1,131 +0,0 @@ -package main - -import ( - "context" - "time" - - "github.com/cloudflare/cloudflare-go" - "github.com/goodieshq/cfdns/config" - "github.com/rs/zerolog/log" -) - -const ( - RECORD_TYPE_IPV4 = "A" - RECORD_TYPE_IPV6 = "AAAA" -) - -func getRecords(ctx context.Context, api *cloudflare.API, zoneID, hostname, recordType string) ([]cloudflare.DNSRecord, error) { - records, _, err := api.ListDNSRecords(ctx, cloudflare.ZoneIdentifier(zoneID), cloudflare.ListDNSRecordsParams{ - Name: hostname, - Type: recordType, - }) - if err != nil { - return nil, err - } - return records, nil -} - -func checkAndUpdate( - ctx context.Context, - api *cloudflare.API, - cfg *config.Config, - domain *config.Domain, - recordType, - address string, -) error { - const timeout = time.Second * 5 - var ctxTimeout context.Context - var cancel context.CancelFunc - - ctxTimeout, cancel = context.WithTimeout(ctx, timeout) - defer cancel() - - records, err := getRecords(ctxTimeout, api, cfg.ZoneID, domain.Hostname, recordType) - if err != nil { - return err - } - - // no records found for this hostname, create a new one - if len(records) == 0 { - ctxTimeout, cancel = context.WithTimeout(ctx, timeout) - defer cancel() - recordNew, err := api.CreateDNSRecord(ctxTimeout, cloudflare.ZoneIdentifier(cfg.ZoneID), cloudflare.CreateDNSRecordParams{ - Name: domain.Hostname, - Content: address, - Type: recordType, - Proxied: domain.Proxied, - }) - if err != nil { - return err - } - log.Info(). - Str("id", recordNew.ID). - Str("hostname", recordNew.Name). - Str("type", recordNew.Type). - Str("address", recordNew.Content). - Msgf("created DNS record") - return nil - } - - for _, record := range records { - ctxTimeout, cancel = context.WithTimeout(ctx, timeout) - defer cancel() - - if record.Content == address && (record.Proxied == nil || domain.Proxied == nil || (*record.Proxied == *domain.Proxied)) { - log.Info(). - Str("id", record.ID). - Str("hostname", record.Name). - Str("type", record.Type). - Str("address", record.Content). - Msgf("skipping DNS record") - continue - } - - recordNew, err := api.UpdateDNSRecord(ctxTimeout, cloudflare.ZoneIdentifier(cfg.ZoneID), cloudflare.UpdateDNSRecordParams{ - ID: record.ID, - Content: address, - Proxied: domain.Proxied, - }) - if err != nil { - log.Error().Err(err). - Str("id", record.ID). - Str("hostname", record.Name). - Str("type", record.Type). - Str("address", record.Content). - Msg("failed to update DNS record") - return err - } - - log.Info(). - Str("id", recordNew.ID). - Str("hostname", recordNew.Name). - Str("type", recordNew.Type). - Str("address", recordNew.Content). - Msgf("updated DNS record") - } - return nil -} - -func CheckAndUpdateIPv4(ctx context.Context, api *cloudflare.API, cfg *config.Config, domain *config.Domain) error { - return checkAndUpdate(ctx, api, cfg, domain, RECORD_TYPE_IPV4, currentIPv4) -} - -func CheckAndUpdateIPv6(ctx context.Context, api *cloudflare.API, cfg *config.Config, domain *config.Domain) error { - return checkAndUpdate(ctx, api, cfg, domain, RECORD_TYPE_IPV6, currentIPv6) -} - -func zoneIsValid(ctx context.Context, api *cloudflare.API, zoneID string) (bool, error) { - zones, err := api.ListZones(ctx) - - if err != nil { - return false, err - } - - for _, zone := range zones { - if zone.ID == zoneID { - return true, nil - } - } - - return false, nil -} diff --git a/cmd/flags.go b/cmd/flags.go deleted file mode 100644 index 736ffce..0000000 --- a/cmd/flags.go +++ /dev/null @@ -1,22 +0,0 @@ -package main - -import "flag" - -const DEFAULT_CONFIG_FILE = "cfdns.yaml" - -type CLIFlags struct { - ConfigFile string -} - -func cli() *CLIFlags { - var cliFlags CLIFlags - flag.StringVar(&cliFlags.ConfigFile, "config", "", "Configuration File") - flag.StringVar(&cliFlags.ConfigFile, "c", "", "Configuration File (alias)") - flag.Parse() - - if cliFlags.ConfigFile == "" { - cliFlags.ConfigFile = DEFAULT_CONFIG_FILE - } - - return &cliFlags -} diff --git a/cmd/getip.go b/cmd/getip.go deleted file mode 100644 index 5a5c59b..0000000 --- a/cmd/getip.go +++ /dev/null @@ -1,57 +0,0 @@ -package main - -import ( - "fmt" - "io" - "net/http" - "strings" - "time" -) - -var ( - ipv4Services = []string{ // URLs to acquire IPv4 address - "https://api.ipify.org", - "https://ipv4.icanhazip.com", - "https://v4.ident.me", - } - ipv6Services = []string{ // URLs to acquire IPv6 address - "https://api6.ipify.org", - "https://ipv6.icanhazip.com", - "https://v6.ident.me", - } -) - -const TIMEOUT_DEFAULT = time.Second * 5 - -func getPublicIP(services []string) (string, error) { - client := &http.Client{ - Timeout: TIMEOUT_DEFAULT, - } - - for _, service := range services { - resp, err := client.Get(service) - if err != nil { - continue - } - defer resp.Body.Close() - - ip, err := io.ReadAll(resp.Body) - if err != nil { - continue - } - - if resp.StatusCode == http.StatusOK { - return strings.TrimSpace(string(ip)), nil - } - } - - return "", fmt.Errorf("could not retrieve IP address") -} - -func GetPublicIPv4() (string, error) { - return getPublicIP(ipv4Services) -} - -func GetPublicIPv6() (string, error) { - return getPublicIP(ipv6Services) -} diff --git a/cmd/loop.go b/cmd/loop.go deleted file mode 100644 index 802dde9..0000000 --- a/cmd/loop.go +++ /dev/null @@ -1,62 +0,0 @@ -package main - -import ( - "context" - "sync" - - "github.com/cloudflare/cloudflare-go" - "github.com/goodieshq/cfdns/config" - "github.com/rs/zerolog/log" -) - -var ( - currentIPv4 = "" - currentIPv6 = "" -) - -func loop(ctx context.Context, api *cloudflare.API, cfg *config.Config) { - defer func() { - value := recover() - if value != nil { - log.Error().Any("recovered", value).Send() - } - }() - - if cfg.IPv4 { - if ipv4, err := GetPublicIPv4(); err != nil { - log.Panic().Err(err).Msg("failed to get public ipv4") - } else if ipv4 != currentIPv4 { - currentIPv4 = ipv4 - log.Info().Msgf("updated ipv4 address: %s", ipv4) - } - - var wg sync.WaitGroup - for _, domain := range cfg.Domains { - wg.Add(1) - go func() { - CheckAndUpdateIPv4(ctx, api, cfg, &domain) - wg.Done() - }() - } - wg.Wait() - } - - if cfg.IPv6 { - if ipv6, err := GetPublicIPv6(); err != nil { - log.Panic().Err(err).Msg("failed to get public ipv6") - } else if ipv6 != currentIPv6 { - currentIPv6 = ipv6 - log.Info().Msgf("updated ipv6 address: %s", ipv6) - } - - var wg sync.WaitGroup - for _, domain := range cfg.Domains { - wg.Add(1) - go func() { - CheckAndUpdateIPv6(ctx, api, cfg, &domain) - wg.Done() - }() - } - wg.Wait() - } -} diff --git a/cmd/main.go b/cmd/main.go index c0fa256..cae03e4 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -2,24 +2,36 @@ package main import ( "context" + "flag" "os" + "os/signal" "time" "github.com/cloudflare/cloudflare-go" - "github.com/goodieshq/cfdns/config" + "github.com/goodieshq/cfdns/pkg/cf" + "github.com/goodieshq/cfdns/pkg/config" "github.com/rs/zerolog" "github.com/rs/zerolog/log" ) const VERSION = "0.1" +const DEFAULT_CONFIG_FILE = "cfdns.yaml" + +type CLIFlags struct { + ConfigFile string +} + +func init() { + log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}) +} func main() { - log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}) - log.Info().Str("version", VERSION).Msg("starting cfdns...") - info := cli() + ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt) + defer cancel() + // load the configuration file from JSON or YAML cfg, err := config.LoadConfig(info.ConfigFile) if err != nil { @@ -31,22 +43,17 @@ func main() { // set the log output verbosity level if cfg.Verbose { zerolog.SetGlobalLevel(zerolog.InfoLevel) - cfopts = append(cfopts, cloudflare.UsingLogger(&log.Logger)) } else { zerolog.SetGlobalLevel(zerolog.ErrorLevel) } - // create a new cloudflare API client from the scoped token - api, err := cloudflare.NewWithAPIToken(cfg.Token, cfopts...) + cfdns, err := cf.NewCFDNS(*cfg, cfopts...) if err != nil { - log.Fatal().Err(err).Msg("failed to create the cloudflare api client") + log.Fatal().Err(err).Msg("failed to create cfdns instance") } - // create a background context - ctx := context.Background() - // check if the provided zone ID is valid for the scoped token - valid, err := zoneIsValid(ctx, api, cfg.ZoneID) + valid, err := cfdns.ZoneIsValid(ctx) if !valid { evt := log.Fatal() if err != nil { @@ -55,8 +62,94 @@ func main() { evt.Msg("failed to validate the zone") } + watcher := watchFile(ctx, info.ConfigFile) + for { - loop(ctx, api, cfg) - time.Sleep(cfg.Frequency) + log.Info().Msg("starting cfdns processing cycle...") + cfdns.Process(ctx) + cfdns.Wait() + select { + case <-ctx.Done(): + log.Info().Msg("shutting down cfdns...") + cfdns.Close() + log.Info().Msg("cfdns stopped") + return + case <-time.After(cfg.Frequency): + case _, _ = <-watcher: + // check file modification time and reload if changed + log.Info().Msg("configuration file changed, reloading...") + cfg, err = config.LoadConfig(info.ConfigFile) + if err != nil { + log.Error().Err(err).Msg("failed to reload config file, keeping existing configuration") + continue + } + if cfg.Verbose { + zerolog.SetGlobalLevel(zerolog.InfoLevel) + } else { + zerolog.SetGlobalLevel(zerolog.ErrorLevel) + } + cfdns.SetConfig(cfg) + } } } + +func cli() *CLIFlags { + var cliFlags CLIFlags + flag.StringVar(&cliFlags.ConfigFile, "config", "", "Configuration File") + flag.StringVar(&cliFlags.ConfigFile, "c", "", "Configuration File (alias)") + flag.Parse() + + if cliFlags.ConfigFile == "" { + cliFlags.ConfigFile = DEFAULT_CONFIG_FILE + } + + return &cliFlags +} + +func getLastModTime(filename string) time.Time { + info, err := os.Stat(filename) + if err != nil { + return time.Time{} + } + return info.ModTime() +} + +func watchFile(ctx context.Context, filename string) <-chan struct{} { + ch := make(chan struct{}, 1) + interval := 1 * time.Second + + go func() { + modTime := getLastModTime(filename) + for { + select { + case <-ctx.Done(): + return + case <-time.After(interval): + // get the last modification time of the file + newModTime := getLastModTime(filename) + + // if we couldn't get the mod time, skip this iteration + if newModTime.IsZero() { + continue + } + + // if this is the first time checking, just set the modTime + if modTime.IsZero() { + modTime = newModTime + continue + } + + // if the modification time has changed, notify via channel + if newModTime.After(modTime) { + modTime = newModTime + <-time.After(50 * time.Millisecond) + select { + case ch <- struct{}{}: + default: + } + } + } + } + }() + return ch +} diff --git a/go.mod b/go.mod index 7f5be52..1128fa8 100644 --- a/go.mod +++ b/go.mod @@ -1,17 +1,22 @@ module github.com/goodieshq/cfdns -go 1.23.2 +go 1.25 require ( - github.com/cloudflare/cloudflare-go v0.108.0 // indirect - github.com/goccy/go-json v0.10.3 // indirect + github.com/cloudflare/cloudflare-go v0.116.0 + github.com/rs/zerolog v1.34.0 + gopkg.in/yaml.v2 v2.4.0 +) + +require ( + github.com/goccy/go-json v0.10.5 // indirect + github.com/goodieshq/goropo v0.1.2 // indirect github.com/google/go-querystring v1.1.0 // indirect + github.com/kr/text v0.2.0 // indirect github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-isatty v0.0.19 // indirect - github.com/rs/zerolog v1.33.0 // indirect - golang.org/x/net v0.30.0 // indirect - golang.org/x/sys v0.26.0 // indirect - golang.org/x/text v0.19.0 // indirect - golang.org/x/time v0.7.0 // indirect - gopkg.in/yaml.v2 v2.4.0 // indirect + golang.org/x/net v0.34.0 // indirect + golang.org/x/sys v0.29.0 // indirect + golang.org/x/text v0.21.0 // indirect + golang.org/x/time v0.9.0 // indirect ) diff --git a/go.sum b/go.sum index 416b0a1..eb92ab8 100644 --- a/go.sum +++ b/go.sum @@ -1,33 +1,54 @@ -github.com/cloudflare/cloudflare-go v0.108.0 h1:C4Skfjd8I8X3uEOGmQUT4/iGyZcWdkIU7HwvMoLkEE0= -github.com/cloudflare/cloudflare-go v0.108.0/go.mod h1:m492eNahT/9MsN7Ppnoge8AaI7QhVFtEgVm3I9HJFeU= +github.com/cloudflare/cloudflare-go v0.116.0 h1:iRPMnTtnswRpELO65NTwMX4+RTdxZl+Xf/zi+HPE95s= +github.com/cloudflare/cloudflare-go v0.116.0/go.mod h1:Ds6urDwn/TF2uIU24mu7H91xkKP8gSAHxQ44DSZgVmU= github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= -github.com/goccy/go-json v0.10.3 h1:KZ5WoDbxAIgm2HNbYckL0se1fHD6rz5j4ywS6ebzDqA= -github.com/goccy/go-json v0.10.3/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M= +github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4= +github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M= github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= +github.com/goodieshq/goropo v0.1.2 h1:aP+wnqNO43DGoYr7SFlNeuUo4r8hSoGk1DuRXa9reFQ= +github.com/goodieshq/goropo v0.1.2/go.mod h1:2eXKgB9hrJSN747/2u6hesMont5R5srk2bv7tUe5WiE= github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.8 h1:e6P7q2lk1O+qJJb4BtCQXlK8vWEO8V1ZeuEdJNOqZyg= +github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8= github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU= +github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= +github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA= github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= -github.com/rs/zerolog v1.33.0 h1:1cU2KZkvPxNyfgEmhHAz/1A9Bz+llsdYzklWFzgp0r8= -github.com/rs/zerolog v1.33.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss= -golang.org/x/net v0.30.0 h1:AcW1SDZMkb8IpzCdQUaIq2sP4sZ4zw+55h6ynffypl4= -golang.org/x/net v0.30.0/go.mod h1:2wGyMJ5iFasEhkwi13ChkO/t1ECNC4X4eBKkVFyYFlU= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.8.1 h1:geMPLpDpQOgVyCg5z5GoRwLHepNdb71NXb67XFkP+Eg= +github.com/rogpeppe/go-internal v1.8.1/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4nPKWu0nJ5d+o= +github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0= +github.com/rs/zerolog v1.34.0 h1:k43nTLIwcTVQAncfCw4KZ2VY6ukYoZaBPNOE8txlOeY= +github.com/rs/zerolog v1.34.0/go.mod h1:bJsvje4Z08ROH4Nhs5iH600c3IkWhwp44iRc54W6wYQ= +github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +golang.org/x/net v0.34.0 h1:Mb7Mrk043xzHgnRM88suvJFwzVrRfHEHJEl5/71CKw0= +golang.org/x/net v0.34.0/go.mod h1:di0qlW3YNM5oh6GqDGQr92MyTozJPmybPK4Ev/Gm31k= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.26.0 h1:KHjCJyddX0LoSTb3J+vWpupP9p0oznkqVk/IfjymZbo= -golang.org/x/sys v0.26.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/text v0.19.0 h1:kTxAhCbGbxhK0IwgSKiMO5awPoDQ0RpfiVYBfK860YM= -golang.org/x/text v0.19.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= -golang.org/x/time v0.7.0 h1:ntUhktv3OPE6TgYxXWv9vKvUSJyIFJlyohwbkEwPrKQ= -golang.org/x/time v0.7.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= +golang.org/x/sys v0.29.0 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU= +golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo= +golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ= +golang.org/x/time v0.9.0 h1:EsRrnYcQiGH+5FfbgvV4AP7qEZstoyrHB0DzarOQ4ZY= +golang.org/x/time v0.9.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/pkg/cf/cf.go b/pkg/cf/cf.go new file mode 100644 index 0000000..3bda8a9 --- /dev/null +++ b/pkg/cf/cf.go @@ -0,0 +1,293 @@ +package cf + +import ( + "context" + "fmt" + "net/http" + "sync" + "time" + + "github.com/cloudflare/cloudflare-go" + "github.com/goodieshq/cfdns/pkg/config" + "github.com/goodieshq/cfdns/pkg/ipget" + "github.com/goodieshq/goropo" + "github.com/rs/zerolog/log" +) + +const ( + RECORD_TYPE_IPV4 = "A" + RECORD_TYPE_IPV6 = "AAAA" +) + +type CFDNS struct { + mu sync.Mutex + cfg config.Config + api *cloudflare.API + httpClient http.Client + myIPv4 string + myIPv6 string + pool *goropo.Pool +} + +func NewCFDNS(cfg config.Config, options ...cloudflare.Option) (*CFDNS, error) { + // create a new cloudflare API client from the scoped token + api, err := cloudflare.NewWithAPIToken(cfg.Token, options...) + if err != nil { + return nil, err + } + + return &CFDNS{ + api: api, + cfg: cfg, + httpClient: http.Client{ + Timeout: 5 * time.Second, + }, + pool: goropo.NewPool(10, 50), + }, nil +} + +func (cfdns *CFDNS) Close() { + // abort all tasks in the pool and close it + cfdns.pool.Abort() + cfdns.pool.Close() +} + +func (cfdns *CFDNS) Wait() { + // wait for all tasks in the pool to complete + cfdns.pool.WaitIdle() +} + +func (cfdns *CFDNS) SetConfig(cfg *config.Config) { + if cfg != nil { + cfdns.mu.Lock() + cfdns.cfg = *cfg + cfdns.mu.Unlock() + } +} + +func (cfdns *CFDNS) getRecords(ctx context.Context, hostname, recordType string) ([]cloudflare.DNSRecord, error) { + records, _, err := cfdns.api.ListDNSRecords( + ctx, + cloudflare.ZoneIdentifier(cfdns.cfg.ZoneID), + cloudflare.ListDNSRecordsParams{ + Name: hostname, + Type: recordType, + }, + ) + if err != nil { + return nil, err + } + return records, nil +} + +func (cfdns *CFDNS) ZoneIsValid(ctx context.Context) (bool, error) { + zones, err := goropo.Submit( + cfdns.pool, + ctx, + func(ctx context.Context) ([]cloudflare.Zone, error) { + return cfdns.api.ListZones(ctx) + }, + ).Await(ctx) + + if err != nil { + return false, err + } + + for _, zone := range zones { + if zone.ID == cfdns.cfg.ZoneID { + return true, nil + } + } + + return false, nil +} + +func (cfdns *CFDNS) CheckAndUpdateIPv4(ctx context.Context, domain *config.Domain) error { + if cfdns.myIPv4 == "" { + return fmt.Errorf("no ipv4 address to update") + } + return cfdns.checkAndUpdate(ctx, domain, RECORD_TYPE_IPV4, cfdns.myIPv4) +} + +func (cfdns *CFDNS) CheckAndUpdateIPv6(ctx context.Context, domain *config.Domain) error { + if cfdns.myIPv6 == "" { + return fmt.Errorf("no ipv6 address to update") + } + return cfdns.checkAndUpdate(ctx, domain, RECORD_TYPE_IPV6, cfdns.myIPv6) +} + +func (cfdns *CFDNS) checkAndUpdate( + ctx context.Context, + domain *config.Domain, + recordType, + address string, +) error { + const timeout = time.Second * 5 + + ctxTimeout, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + + records, err := cfdns.getRecords(ctxTimeout, domain.Hostname, recordType) + if err != nil { + return err + } + + // no records found for this hostname, create a new one + if len(records) == 0 { + ctxTimeout, cancel = context.WithTimeout(ctx, timeout) + defer cancel() + + recordNew, err := cfdns.api.CreateDNSRecord( + ctxTimeout, + cloudflare.ZoneIdentifier(cfdns.cfg.ZoneID), + cloudflare.CreateDNSRecordParams{ + Name: domain.Hostname, + Content: address, + Type: recordType, + Proxied: domain.Proxied, + }, + ) + if err != nil { + return err + } + log.Info(). + Str("id", recordNew.ID). + Str("hostname", recordNew.Name). + Str("type", recordNew.Type). + Str("address", recordNew.Content). + Msgf("created DNS record") + return nil + } + + for _, record := range records { + ctxTimeout, cancel = context.WithTimeout(ctx, timeout) + defer cancel() + + if record.Content == address && (record.Proxied == nil || + domain.Proxied == nil || + (*record.Proxied == *domain.Proxied)) { + + log.Info(). + Str("id", record.ID). + Str("hostname", record.Name). + Str("type", record.Type). + Str("address", record.Content). + Msgf("skipping DNS record") + return nil + } + + recordNew, err := cfdns.api.UpdateDNSRecord( + ctxTimeout, + cloudflare.ZoneIdentifier(cfdns.cfg.ZoneID), + cloudflare.UpdateDNSRecordParams{ + ID: record.ID, + Content: address, + Proxied: domain.Proxied, + }, + ) + if err != nil { + log.Error().Err(err). + Str("id", record.ID). + Str("hostname", record.Name). + Str("type", record.Type). + Str("address", record.Content). + Msg("failed to update DNS record") + return err + } + + log.Info(). + Str("id", recordNew.ID). + Str("hostname", recordNew.Name). + Str("type", recordNew.Type). + Str("address", recordNew.Content). + Msgf("updated DNS record") + } + return nil +} + +func (cfdns *CFDNS) setPublicIPs(ctx context.Context) { + var fut4, fut6 *goropo.Future[string] + + if cfdns.cfg.IPv4 { + fut4 = goropo.Submit(cfdns.pool, ctx, ipget.GetPublicIPv4) + } else { + cfdns.myIPv4 = "" + } + + if cfdns.cfg.IPv6 { + fut6 = goropo.Submit(cfdns.pool, ctx, ipget.GetPublicIPv6) + } else { + cfdns.myIPv6 = "" + } + + if fut4 != nil { + ipv4, err4 := fut4.Await(ctx) + if err4 != nil { + cfdns.myIPv4 = "" + log.Error().Err(err4).Msg("failed to get public ipv4") + } else if ipv4 != cfdns.myIPv4 { + cfdns.myIPv4 = ipv4 + log.Info().Str("new_ipv4", ipv4).Msg("updated ipv4 address") + } + } + + if fut6 != nil { + ipv6, err6 := fut6.Await(ctx) + if err6 != nil { + cfdns.myIPv6 = "" + log.Error().Err(err6).Msg("failed to get public ipv6") + } else if ipv6 != cfdns.myIPv6 { + cfdns.myIPv6 = ipv6 + log.Info().Str("new_ipv6", ipv6).Msg("updated ipv6 address") + } + } +} + +func (cfdns *CFDNS) Process(ctx context.Context) { + // lock the config + cfdns.mu.Lock() + defer cfdns.mu.Unlock() + + // acquire and set the current public IP addresses for this instance + cfdns.setPublicIPs(ctx) + futs := make([]*goropo.FutureAny, 0, len(cfdns.cfg.Domains)*2) + + // iterate over all configured domains and update their DNS records as needed + for _, domain := range cfdns.cfg.Domains { + domain := domain // capture range variable + + if cfdns.cfg.IPv4 { + fut := goropo.Submit( + cfdns.pool, + ctx, + func(ctx context.Context) (any, error) { + if err := cfdns.CheckAndUpdateIPv4(ctx, &domain); err != nil { + log.Error().Err(err).Str("domain", domain.Hostname).Msg("failed to update ipv4 record") + return nil, err + } + return nil, nil + }, + ) + futs = append(futs, fut) + } + + if cfdns.cfg.IPv6 { + fut := goropo.Submit( + cfdns.pool, + ctx, + func(ctx context.Context) (any, error) { + if err := cfdns.CheckAndUpdateIPv6(ctx, &domain); err != nil { + log.Error().Err(err).Str("domain", domain.Hostname).Msg("failed to update ipv4 record") + return nil, err + } + return nil, nil + }, + ) + futs = append(futs, fut) + } + } + + for _, fut := range futs { + _, _ = fut.Await(ctx) + } +} diff --git a/config/config.go b/pkg/config/config.go similarity index 100% rename from config/config.go rename to pkg/config/config.go diff --git a/pkg/ipget/ipget.go b/pkg/ipget/ipget.go new file mode 100644 index 0000000..2e092e6 --- /dev/null +++ b/pkg/ipget/ipget.go @@ -0,0 +1,131 @@ +package ipget + +import ( + "context" + "errors" + "fmt" + "io" + "math/rand" + "net" + "net/http" + "strings" + "time" + + "github.com/rs/zerolog/log" +) + +var ( + // URLs to acquire IPv4 address as a string + ipv4Services = []string{ + "https://api.ipify.org", + "https://ipv4.icanhazip.com", + "https://v4.ident.me", + } + // URLs to acquire IPv6 address as a string + ipv6Services = []string{ + "https://api6.ipify.org", + "https://ipv6.icanhazip.com", + "https://v6.ident.me", + } +) + +const TIMEOUT_DEFAULT = time.Second * 5 + +// drain reads and discards all remaining data from an io.ReadCloser +func drain(body io.ReadCloser) { + _, _ = io.Copy(io.Discard, body) +} + +// strToIP converts a string to a net.IP, returning nil if invalid +func strToIP(ipStr string) net.IP { + ip := net.ParseIP(ipStr) + if ip == nil { + return nil + } + if ip4 := ip.To4(); ip4 != nil { + return ip4 + } + return ip.To16() +} + +// shared HTTP client with timeout +var client = &http.Client{ + Timeout: TIMEOUT_DEFAULT, +} + +// shuffle returns a new slice with the elements of the input slice shuffled +func shuffle[T any](items []T) []T { + shuffled := make([]T, len(items)) + copy(shuffled, items) + + rand.Shuffle(len(shuffled), func(i, j int) { + shuffled[i], shuffled[j] = shuffled[j], shuffled[i] + }) + + return shuffled +} + +// getSmallText is a helper function to get text content from a URL efficiently +func getSmallText(ctx context.Context, url string) (string, error) { + // create a new request tied to the context + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + if err != nil { + return "", err + } + + // perform the request + resp, err := client.Do(req) + if err != nil { + return "", err + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + drain(resp.Body) + return "", fmt.Errorf("unexpected status code: %d", resp.StatusCode) + } + + body, err := io.ReadAll(io.LimitReader(resp.Body, 128)) + if err != nil { + return "", err + } + + drain(resp.Body) + + return strings.TrimSpace(string(body)), nil +} + +// getPublicIP tries to get the public IP address from a list of services +func getPublicIP(ctx context.Context, services []string) (string, error) { + services = shuffle(services) + for _, service := range services { + logger := log.With().Str("service", service).Logger() + ipStr, err := getSmallText(ctx, service) + if err != nil { + // context-related errors should be returned immediately + if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) { + logger.Error().Err(err).Msg("request context error") + return "", err + } + + // all other errors are logged and we continue to the next service + logger.Warn().Err(err).Msg("failed to acquire IP address from service") + continue + } + + // validate the returned IP address + if ip := strToIP(ipStr); ip != nil { + return ip.String(), nil + } + } + + return "", fmt.Errorf("could not retrieve public IP address") +} + +func GetPublicIPv4(ctx context.Context) (string, error) { + return getPublicIP(ctx, ipv4Services) +} + +func GetPublicIPv6(ctx context.Context) (string, error) { + return getPublicIP(ctx, ipv6Services) +}