~humaid/cloudflare-ddns-client

cloudflare-ddns-client/main.go -rw-r--r-- 4.1 KiB
39d89d83 — Humaid AlQassimi Fix capitalisation in log message. 4 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net"
	"net/http"
	"os"
	"strings"
	"time"
)

var (
	APIKey     string = os.Getenv("APIKey")
	Zone       string = os.Getenv("Zone")
	RecordName string = os.Getenv("RecordName")

	tr = &http.Transport{
		MaxIdleConns:       10,
		IdleConnTimeout:    5 * time.Second,
		DisableCompression: true,
	}

	previousIP string

	recType string
)

func main() {
	log.Printf("Getting initial IP address\n")
	ip, err := getIP()
	if err != nil {
		log.Printf("Failed to get IP: %v\n", err)
		os.Exit(-1)
	}
	log.Printf("Determining IP type\n")
	parsedIP := net.ParseIP(ip)
	if parsedIP.To4() != nil {
		recType = "A"
	} else {
		recType = "AAAA"
	}
	log.Printf("Getting the ID of the record (%s)\n", Zone)
	recID, err := getRecordID()
	if err != nil {
		log.Printf("Failed to get the ID of the record %v (%s)\n", err, recType)
		os.Exit(-1)
	}
	log.Printf("Got record ID: %s\n", recID)
	for {
		ip, err := getIP()
		if err == nil {
			if previousIP == ip {
				log.Println("No change to public IP")
			} else {
				log.Printf("Current public IP: %s\n", ip)
				err = setIP(ip, recID)
				if err != nil {
					log.Printf("Error setting IP: %v\n", err)
				} else {
					log.Println("Updated!")
					previousIP = ip
				}
			}
		}
		time.Sleep(1 * time.Minute)
	}
}

// DNSRecords holds the result of Cloudflare's DNS record listing.
type DNSRecords struct {
	Success  bool          `json:"success"`
	Errors   []interface{} `json:"errors"`
	Messages []interface{} `json:"messages"`
	Result   []struct {
		ID         string    `json:"id"`
		Type       string    `json:"type"`
		Name       string    `json:"name"`
		Content    string    `json:"content"`
		Proxiable  bool      `json:"proxiable"`
		Proxied    bool      `json:"proxied"`
		TTL        int       `json:"ttl"`
		Locked     bool      `json:"locked"`
		ZoneID     string    `json:"zone_id"`
		ZoneName   string    `json:"zone_name"`
		CreatedOn  time.Time `json:"created_on"`
		ModifiedOn time.Time `json:"modified_on"`
		Data       struct {
		} `json:"data"`
		Meta struct {
			AutoAdded bool   `json:"auto_added"`
			Source    string `json:"source"`
		} `json:"meta"`
	} `json:"result"`
}

func setHeaders(req *http.Request) {
	req.Header.Set("Authorization", "Bearer "+APIKey)
	req.Header.Set("Content-Type", "application/json")
}

func newClient() *http.Client {
	return &http.Client{
		Transport: tr,
		Timeout:   time.Second * 10,
	}
}

// getRecordID gets the record ID of a DNS record based on the record name
func getRecordID() (string, error) {
	client := newClient()
	url := "https://api.cloudflare.com/client/v4/zones/" + Zone + "/dns_records?type=" + recType + "&name=" + RecordName
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return "", fmt.Errorf("cannot create request: %v", err)
	}
	setHeaders(req)
	resp, err := client.Do(req)
	s, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	if resp.StatusCode != http.StatusOK {
		return "", fmt.Errorf("cloudflare returned non-OK status: %s", resp.Status)
	}
	var recs DNSRecords
	err = json.Unmarshal(s, &recs)
	if len(recs.Result) == 0 {
		return "", fmt.Errorf("cannot find record: %s", RecordName)
	}

	return recs.Result[0].ID, nil
}

// setIP sets the IP address based on record ID.
func setIP(ip string, recID string) error {
	client := newClient()
	body := `{"type":"` + recType + `","name":"` + RecordName + `","content":"` + ip + `","ttl":120,"proxied":false}`
	url := "https://api.cloudflare.com/client/v4/zones/" + Zone + "/dns_records/" + recID
	req, err := http.NewRequest("PUT", url, strings.NewReader(body))
	if err != nil {
		return fmt.Errorf("cannot create request: %v", err)
	}
	setHeaders(req)
	resp, err := client.Do(req)
	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("cloudflare returned non-OK status: %s", resp.Status)
	}
	return nil
}

// getIP returns the public IP address.
func getIP() (string, error) {
	client := newClient()
	req, err := http.NewRequest("GET", "https://icanhazip.com", nil)
	resp, err := client.Do(req)
	if err != nil {
		return "", err
	}
	s, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	return strings.TrimSpace(string(s)), nil
}