diff --git a/cfdns.example.yaml b/cfdns.example.yaml new file mode 100644 index 0000000..79ca8e2 --- /dev/null +++ b/cfdns.example.yaml @@ -0,0 +1,11 @@ +zone_id: a0e0184261924d449b673e1ae0a3df04 +token: zFTsCDbMk69Ncegah6dxhyxeyyOJxazRh6SKEE2Y +frequency: 4h +verbose: true +domains: + - hostname: a.example.com + proxied: true + - hostname: b.example.com + proxied: true + - hostname: c.example.com + proxied: false \ No newline at end of file diff --git a/cmd/cf.go b/cmd/cf.go new file mode 100644 index 0000000..d27a375 --- /dev/null +++ b/cmd/cf.go @@ -0,0 +1,130 @@ +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, + }) + 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 { + 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 new file mode 100644 index 0000000..736ffce --- /dev/null +++ b/cmd/flags.go @@ -0,0 +1,22 @@ +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 new file mode 100644 index 0000000..5a5c59b --- /dev/null +++ b/cmd/getip.go @@ -0,0 +1,57 @@ +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 new file mode 100644 index 0000000..ad277d7 --- /dev/null +++ b/cmd/loop.go @@ -0,0 +1,68 @@ +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 { + ipv4, err := GetPublicIPv4() + if err != nil { + log.Panic().Err(err).Msg("failed to get public ipv4") + } + + 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 { + ipv6, err := GetPublicIPv6() + if err != nil { + log.Panic().Err(err).Msg("failed to get public ipv6") + } + + 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 new file mode 100644 index 0000000..c0fa256 --- /dev/null +++ b/cmd/main.go @@ -0,0 +1,62 @@ +package main + +import ( + "context" + "os" + "time" + + "github.com/cloudflare/cloudflare-go" + "github.com/goodieshq/cfdns/config" + "github.com/rs/zerolog" + "github.com/rs/zerolog/log" +) + +const VERSION = "0.1" + +func main() { + log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}) + + log.Info().Str("version", VERSION).Msg("starting cfdns...") + + info := cli() + + // load the configuration file from JSON or YAML + cfg, err := config.LoadConfig(info.ConfigFile) + if err != nil { + log.Fatal().Err(err).Msg("failed to load config file") + } + + var cfopts []cloudflare.Option + + // 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...) + if err != nil { + log.Fatal().Err(err).Msg("failed to create the cloudflare api client") + } + + // 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) + if !valid { + evt := log.Fatal() + if err != nil { + evt = evt.Err(err) + } + evt.Msg("failed to validate the zone") + } + + for { + loop(ctx, api, cfg) + time.Sleep(cfg.Frequency) + } +} diff --git a/config/config.go b/config/config.go new file mode 100644 index 0000000..cdf07c8 --- /dev/null +++ b/config/config.go @@ -0,0 +1,77 @@ +package config + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "strings" + "time" + + "gopkg.in/yaml.v2" +) + +const DEFAULT_FREQUENCY = time.Hour * 1 + +type Domain struct { + Hostname string `json:"hostname" yaml:"hostname"` + Proxied *bool `json:"proxied" yaml:"proxied"` +} + +type Config struct { + ZoneID string `json:"zone_id" yaml:"zone_id"` // CloudFlare Zone ID + Token string `json:"token" yaml:"token"` // CloudFlare zone-scoped token (read/write) + Frequency time.Duration `json:"frequency" yaml:"frequency"` // Frequency at which to update the domains + Verbose bool `json:"verbose" yaml:"verbose"` // Verbose logging output + IPv4 bool `json:"ipv4" yaml:"ipv4"` // use IPv4 A records + IPv6 bool `json:"ipv6" yaml:"ipv6"` // use IPv6 AAAA records + Domains []Domain `json:"domains" yaml:"domains"` // List of domains to update +} + +func LoadConfig(filename string) (*Config, error) { + // Read the file content + data, err := os.ReadFile(filename) + if err != nil { + return nil, fmt.Errorf("could not read file: %w", err) + } + + // Initialize the Config struct + var config Config + + // Check the file extension + ext := strings.ToLower(filepath.Ext(filename)) + switch ext { + case ".json": + // Parse JSON + if err := json.Unmarshal(data, &config); err != nil { + return nil, fmt.Errorf("could not parse JSON config file: %w", err) + } + case ".yaml", ".yml": + // Parse YAML + if err := yaml.Unmarshal(data, &config); err != nil { + return nil, fmt.Errorf("could not parse YAML config file: %w", err) + } + default: + return nil, fmt.Errorf("unsupported file extension: %s", ext) + } + + if config.ZoneID == "" { + return nil, fmt.Errorf("zone id cannot be empty") + } + + if len(config.Domains) == 0 { + return nil, fmt.Errorf("domains list cannot be empty") + } + + if config.Frequency == 0 { + config.Frequency = DEFAULT_FREQUENCY + } + + // if neither IPv6 nor IPv6 are explicitly specified, use both + if !config.IPv4 && !config.IPv6 { + config.IPv4 = true + config.IPv6 = true + } + + return &config, nil +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..7f5be52 --- /dev/null +++ b/go.mod @@ -0,0 +1,17 @@ +module github.com/goodieshq/cfdns + +go 1.23.2 + +require ( + github.com/cloudflare/cloudflare-go v0.108.0 // indirect + github.com/goccy/go-json v0.10.3 // indirect + github.com/google/go-querystring v1.1.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 +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..416b0a1 --- /dev/null +++ b/go.sum @@ -0,0 +1,33 @@ +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/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/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= +github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +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/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= +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/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/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=