package main import ( "crypto/tls" "fmt" "io" "net" "net/http" "strings" "time" ) // parseDyfiResponse interprets dy.fi update response codes func parseDyfiResponse(response string) (string, string) { errorCodes := map[string]string{ "abuse": "The service feels YOU are ABUSING it!", "badauth": "Authentication failed", "nohost": "No hostname given for update, or hostname not yours", "notfqdn": "The given hostname is not a valid FQDN", "badip": "The client IP address is not valid or permitted", "dnserr": "Update failed due to a problem at dy.fi", "good": "The update was processed successfully", "nochg": "The successful update did not cause a DNS data change", } // Response format: "code" or "code ipaddress" parts := strings.Fields(response) if len(parts) == 0 { return "", "Empty response from dy.fi" } code := parts[0] description, exists := errorCodes[code] if !exists { description = response } return code, description } // getCurrentDNSIP looks up the current IP address the hostname points to func getCurrentDNSIP(hostname string) (string, error) { ips, err := net.LookupIP(hostname) if err != nil { return "", err } // Return first IPv4 address for _, ip := range ips { if ipv4 := ip.To4(); ipv4 != nil { return ipv4.String(), nil } } return "", fmt.Errorf("no IPv4 address found for %s", hostname) } // getOurPublicIP attempts to determine our own public IP address func getOurPublicIP() (string, error) { // Try to get our public IP from a reliable source services := []string{ "https://api.ipify.org", "https://checkip.amazonaws.com", "https://icanhazip.com", } client := &http.Client{Timeout: 5 * time.Second} for _, service := range services { resp, err := client.Get(service) if err != nil { continue } defer resp.Body.Close() body, err := io.ReadAll(resp.Body) if err != nil { continue } ip := strings.TrimSpace(string(body)) // Validate it's an IP if net.ParseIP(ip) != nil { return ip, nil } } return "", fmt.Errorf("failed to determine public IP") } // checkManagerHealthAt checks if a manager instance is responding at the given IP func checkManagerHealthAt(ip string, port string) bool { // Try HTTPS first, then HTTP schemes := []string{"https", "http"} for _, scheme := range schemes { url := fmt.Sprintf("%s://%s:%s/health", scheme, ip, port) // Create client with relaxed TLS verification (self-signed certs) transport := &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, } client := &http.Client{ Timeout: 5 * time.Second, Transport: transport, } resp, err := client.Get(url) if err != nil { continue } resp.Body.Close() // Consider 200 OK as healthy if resp.StatusCode == 200 { return true } } return false } func startDyfiUpdater(hostname, username, password, managerPort string) { if hostname == "" || username == "" || password == "" { return } logger.Info("Starting dy.fi updater for %s", hostname) logger.Info("Update interval: 20 hours (dy.fi requires update at least every 7 days)") logger.Info("Multi-instance mode: will only update if current pointer is down (failover)") // Default to 443 if not specified if managerPort == "" { managerPort = "443" } update := func() { // Step 1: Check where DNS currently points currentIP, err := getCurrentDNSIP(hostname) if err != nil { logger.Warn("dy.fi: failed to lookup current DNS for %s: %v", hostname, err) logger.Info("dy.fi: assuming initial state, proceeding with update") // Continue to update since we can't verify } else { logger.Info("dy.fi: %s currently points to %s", hostname, currentIP) // Step 2: Get our own public IP ourIP, err := getOurPublicIP() if err != nil { logger.Warn("dy.fi: failed to determine our public IP: %v", err) logger.Info("dy.fi: proceeding with cautious update") } else { logger.Info("dy.fi: our public IP is %s", ourIP) // Step 3: Decide what to do based on current state if currentIP == ourIP { // We are the active instance - normal refresh logger.Info("dy.fi: we are the ACTIVE instance, performing normal refresh") } else { // DNS points to a different IP - check if that instance is healthy logger.Info("dy.fi: DNS points to different IP, checking health of instance at %s", currentIP) if checkManagerHealthAt(currentIP, managerPort) { // Another instance is healthy and serving - we are standby logger.Info("dy.fi: manager instance at %s is HEALTHY - we are STANDBY", currentIP) logger.Info("dy.fi: skipping update to avoid DNS pointer conflict") return // Don't update, stay in standby mode } else { // The instance at current IP is not responding - failover! logger.Warn("dy.fi: manager instance at %s is NOT responding", currentIP) logger.Info("dy.fi: initiating FAILOVER - taking over DNS pointer") } } } } // If we reach here, we should perform the update url := fmt.Sprintf("https://www.dy.fi/nic/update?hostname=%s", hostname) req, err := http.NewRequest("GET", url, nil) if err != nil { logger.Error("dy.fi: failed to create request: %v", err) return } req.SetBasicAuth(username, password) req.Header.Set("User-Agent", "PingServiceManager/1.0") client := &http.Client{Timeout: 30 * time.Second} resp, err := client.Do(req) if err != nil { logger.Error("dy.fi: update request failed: %v", err) return } defer resp.Body.Close() // Read response body body, err := io.ReadAll(resp.Body) if err != nil { logger.Error("dy.fi: failed to read response: %v", err) return } responseText := strings.TrimSpace(string(body)) // Check HTTP status if resp.StatusCode != 200 { logger.Error("dy.fi: HTTP error %d: %s", resp.StatusCode, responseText) return } // Check Content-Type contentType := resp.Header.Get("Content-Type") if !strings.HasPrefix(strings.ToLower(contentType), "text/plain") { logger.Warn("dy.fi: unexpected content-type: %s", contentType) } // Parse dy.fi response code, description := parseDyfiResponse(responseText) switch code { case "good": // Extract IP if present parts := strings.Fields(responseText) if len(parts) > 1 { logger.Info("dy.fi: ✅ SUCCESSFUL UPDATE for %s - DNS now points to %s", hostname, parts[1]) logger.Info("dy.fi: we are now the ACTIVE instance") } else { logger.Info("dy.fi: ✅ SUCCESSFUL UPDATE for %s", hostname) logger.Info("dy.fi: we are now the ACTIVE instance") } case "nochg": logger.Info("dy.fi: ✅ SUCCESSFUL REFRESH for %s (no DNS change, we remain ACTIVE)", hostname) case "abuse": logger.Error("dy.fi: ABUSE DETECTED! The service is denying our requests for %s", hostname) logger.Error("dy.fi: This usually means the update script is running too frequently") logger.Error("dy.fi: Stopping dy.fi updater to prevent further abuse flags") return // Stop updating if abuse is detected case "badauth": logger.Error("dy.fi: authentication failed for %s - check username/password", hostname) case "nohost": logger.Error("dy.fi: hostname %s not found or not owned by this account", hostname) case "notfqdn": logger.Error("dy.fi: %s is not a valid FQDN", hostname) case "badip": logger.Error("dy.fi: client IP address is not valid or permitted", hostname) case "dnserr": logger.Error("dy.fi: DNS update failed due to a problem at dy.fi for %s", hostname) default: logger.Warn("dy.fi: unknown response for %s: %s (%s)", hostname, responseText, description) } } // Update immediately on start update() // Update every 20 hours (dy.fi deletes inactive domains after 7 days) go func() { ticker := time.NewTicker(20 * time.Hour) defer ticker.Stop() for range ticker.C { update() } }() }