-
Notifications
You must be signed in to change notification settings - Fork 22
/
digitalocean-dynamic-ip.go
390 lines (357 loc) · 11.2 KB
/
digitalocean-dynamic-ip.go
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
package main
import (
"bytes"
"encoding/hex"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"net"
"net/http"
"net/url"
"os"
"strconv"
homedir "github.com/mitchellh/go-homedir"
)
func checkError(err error) {
if err != nil {
log.SetOutput(os.Stderr)
log.Fatal(err)
}
}
// logError Logs an error message to Stderr and exits the program
func logError(msg string) {
log.SetOutput(os.Stderr)
log.Fatal(msg)
}
// logWarning Logs a warning message to Stderr without exiting the program
func logWarning(msg string) {
old := log.Default().Writer()
log.SetOutput(os.Stderr)
log.Println(msg)
log.SetOutput(old)
}
// logWarning Logs a warning message to Stderr without exiting the program
func logWarningf(format string, v ...interface{}) {
old := log.Default().Writer()
log.SetOutput(os.Stderr)
log.Printf(format, v...)
log.SetOutput(old)
}
var config ClientConfig
// ClientConfig : configuration json
type ClientConfig struct {
APIKey string `json:"apiKey"`
DOPageSize int `json:"doPageSize"`
UseIPv4 *bool `json:"useIPv4"`
UseIPv6 *bool `json:"useIPv6"`
IPv4CheckURL string `json:"ipv4CheckUrl"`
IPv6CheckURL string `json:"ipv6CheckUrl"`
AllowIPv4InIPv6 bool `json:"allowIPv4InIPv6"`
Domains []Domain `json:"domains"`
}
// Domain : domains to be changed
type Domain struct {
Domain string `json:"domain"`
Records []DNSRecord `json:"records"`
}
// DNSRecord : Modifyiable DNS record
type DNSRecord struct {
ID int64 `json:"id"`
Type string `json:"type"`
Name string `json:"name"`
Priority *int `json:"priority"`
Port *int `json:"port"`
Weight *int `json:"weight"`
TTL int `json:"ttl"`
Flags *uint8 `json:"flags"`
Tag *string `json:"tag"`
Data string `json:"data"`
}
// DOResponse : DigitalOcean DNS Records response.
type DOResponse struct {
DomainRecords []DNSRecord `json:"domain_records"`
Meta struct {
Total int `json:"total"`
} `json:"meta"`
Links struct {
Pages struct {
First string `json:"first"`
Previous string `json:"prev"`
Next string `json:"next"`
Last string `json:"last"`
} `json:"pages"`
} `json:"links"`
}
//GetConfig : get configuration file ~/.digitalocean-dynamic-ip.json
func GetConfig() ClientConfig {
cmdHelp := flag.Bool("h", false, "Show the help message")
cmdHelp2 := flag.Bool("help", false, "Show the help message")
cmdDbg := flag.Bool("d", false, "Outputs log messages to the standard console")
cmdDbg2 := flag.Bool("debug", false, "Outputs log messages to the standard console")
flag.Parse()
if *cmdHelp || *cmdHelp2 {
usage()
os.Exit(1)
}
if !((*cmdDbg) || (*cmdDbg2)) {
// if no debug option was selected, discard all debug output
log.SetOutput(ioutil.Discard)
} else {
// default debug output to Stdout instead of Stderr
log.SetOutput(os.Stdout)
}
configFile := ""
if len(flag.Args()) == 0 {
var err error
configFile, err = homedir.Dir()
checkError(err)
configFile += "/.digitalocean-dynamic-ip.json"
} else {
configFile = flag.Args()[0]
}
log.Printf("Using Config file: %s", configFile)
getfile, err := ioutil.ReadFile(configFile)
checkError(err)
var config ClientConfig
err = json.Unmarshal(getfile, &config)
checkError(err)
return config
}
func usage() {
os.Stdout.WriteString(fmt.Sprintf("To use this program you can specify the following command options:\n"+
"-h | -help\n\tShow this help message\n"+
"-d | -debug\n\tPrint debug messages to standard output\n"+
"[config_file]\n\tlocation of the configuration file\n\n"+
"If the [config_file] parameter is not passed, then the default\n"+
"config location of ~/.digitalocean-dynamic-ip.json will be used.\n\n"+
"example usages:\n\t%[1]s -help\n"+
"\t%[1]s\n"+
"\t%[1]s %[2]s\n"+
"\t%[1]s -debug %[2]s\n"+
"",
os.Args[0],
"/path/to/my/config.json",
))
}
//CheckLocalIPs : get current IP of server. checks both IPv4 and Ipv6 to support dual stack environments
func CheckLocalIPs() (ipv4, ipv6 net.IP) {
var ipv4String, ipv6String string
ipv4CheckURL := "https://api.ipify.org/?format=text"
ipv6CheckURL := "https://api64.ipify.org/?format=text"
if len(config.IPv4CheckURL) > 0 {
ipv4CheckURL = config.IPv4CheckURL
}
if len(config.IPv6CheckURL) > 0 {
ipv6CheckURL = config.IPv6CheckURL
}
if config.UseIPv4 == nil || *(config.UseIPv4) {
log.Printf("Checking IPv4 with URL: %s", ipv4CheckURL)
ipv4String, _ = getURLBody(ipv4CheckURL)
if ipv4String == "" {
logWarning("No IPv4 address found. Consider disabling IPv4 checks in the config `\"useIPv4\": false`")
} else {
ipv4 = net.ParseIP(ipv4String)
if ipv4 != nil {
// make sure we got back an actual ipv4 address
ipv4 = ipv4.To4()
log.Printf("Discovered IPv4 address `%s`", ipv4.String())
}
if ipv4 == nil {
logWarningf("Unable to parse `%s` as an IPv4 address", ipv4String)
}
}
}
if config.UseIPv6 == nil || *(config.UseIPv6) {
log.Printf("Checking IPv6 with URL: %s", ipv6CheckURL)
ipv6String, _ = getURLBody(ipv6CheckURL)
if ipv6String == "" {
logWarning("No IPv6 address found. Consider disabling IPv6 checks in the config `\"useIPv6\": false`")
} else {
ipv6 = net.ParseIP(ipv6String)
if ipv6 == nil {
logWarningf("Unable to parse `%s` as an IPv6 address", ipv6String)
} else {
log.Printf("Discovered IPv6 address `%s`", ipv6.String())
}
}
}
return ipv4, ipv6
}
func getURLBody(url string) (string, error) {
request, err := http.Get(url)
checkError(err)
defer request.Body.Close()
body, err := ioutil.ReadAll(request.Body)
checkError(err)
return string(body), nil
}
//GetDomainRecords : Get DNS records of current domain.
func GetDomainRecords(domain string) []DNSRecord {
ret := make([]DNSRecord, 0)
var page DOResponse
pageParam := ""
// 20 is the default page size
if config.DOPageSize > 0 && config.DOPageSize != 20 {
pageSize := config.DOPageSize
// don't let users set more than the max size
if pageSize > 200 {
pageSize = 200
}
pageParam = "?per_page=" + strconv.Itoa(pageSize)
}
for url := "https://api.digitalocean.com/v2/domains/" + url.PathEscape(domain) + "/records" + pageParam; url != ""; url = page.Links.Pages.Next {
page = getPage(url)
ret = append(ret, page.DomainRecords...)
}
return ret
}
func getPage(url string) DOResponse {
log.Println(url)
client := &http.Client{}
request, err := http.NewRequest("GET", url, nil)
checkError(err)
request.Header.Add("Content-type", "Application/json")
request.Header.Add("Authorization", "Bearer "+config.APIKey)
response, err := client.Do(request)
checkError(err)
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
checkError(err)
// log.Println(string(body))
var jsonDOResponse DOResponse
err = json.Unmarshal(body, &jsonDOResponse)
checkError(err)
return jsonDOResponse
}
// UpdateRecords : Update DNS records of domain
func UpdateRecords(domain Domain, ipv4, ipv6 net.IP) {
log.Printf("%s: %d to update", domain.Domain, len(domain.Records))
updated := 0
doRecords := GetDomainRecords(domain.Domain)
// look for the item to update
if len(doRecords) < 1 {
logWarningf("%s: No DNS records found in DigitalOcean", domain.Domain)
return
}
log.Printf("%s: %d DNS records found in DigitalOcean", domain.Domain, len(doRecords))
for _, toUpdateRecord := range domain.Records {
if toUpdateRecord.Type != "A" && toUpdateRecord.Type != "AAAA" {
logWarningf("%s: Unsupported type (Only A and AAAA records supported) for updates %+v", domain.Domain, toUpdateRecord)
continue
}
if ipv4 == nil && toUpdateRecord.Type == "A" {
logWarningf("%s: You are trying to update an IPv4 A record with no IPv4 address: config: %+v", domain.Domain, toUpdateRecord)
continue
}
if toUpdateRecord.ID > 0 {
// update the record directly. skip the extra search
logWarningf("%s: Unable to directly update records yet. Record: %+v", domain.Domain, toUpdateRecord)
continue
}
var currentIP string
if toUpdateRecord.Type == "A" {
currentIP = ipv4.String()
} else if ipv6 == nil || ipv6.To4() != nil {
if ipv6 == nil {
ipv6 = ipv4
}
logWarningf("%s: You are trying to update an IPv6 AAAA record without an IPv6 address: ip: %s config: %+v",
domain.Domain,
ipv6,
toUpdateRecord,
)
if config.AllowIPv4InIPv6 {
currentIP = toIPv6String(ipv6)
log.Printf("%s: Converting IPv4 `%s` to IPv6 `%s`", domain.Domain, ipv6.String(), currentIP)
} else {
continue
}
} else {
currentIP = ipv6.String()
}
log.Printf("%s: trying to update `%s` : `%s`", domain.Domain, toUpdateRecord.Type, toUpdateRecord.Name)
for _, doRecord := range doRecords {
//log.Printf("%s: checking `%s` : `%s`", domain.Domain, doRecord.Type, doRecord.Name)
if doRecord.Name == toUpdateRecord.Name && doRecord.Type == toUpdateRecord.Type {
if doRecord.Data == currentIP && (toUpdateRecord.TTL < 30 || doRecord.TTL == toUpdateRecord.TTL) {
log.Printf("%s: IP/TTL did not change %+v", domain.Domain, doRecord)
continue
}
log.Printf("%s: updating %+v", domain.Domain, doRecord)
// set the IP address
doRecord.Data = currentIP
if toUpdateRecord.TTL >= 30 && doRecord.TTL != toUpdateRecord.TTL {
doRecord.TTL = toUpdateRecord.TTL
}
update, err := json.Marshal(doRecord)
checkError(err)
client := &http.Client{}
request, err := http.NewRequest("PUT",
"https://api.digitalocean.com/v2/domains/"+url.PathEscape(domain.Domain)+"/records/"+strconv.FormatInt(int64(doRecord.ID), 10),
bytes.NewBuffer(update))
checkError(err)
request.Header.Set("Content-Type", "application/json")
request.Header.Add("Authorization", "Bearer "+config.APIKey)
response, err := client.Do(request)
checkError(err)
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
checkError(err)
log.Printf("%s: DO update response for %s: %s", domain.Domain, doRecord.Name, string(body))
updated++
}
}
}
log.Printf("%s: %d of %d records updated", domain.Domain, updated, len(domain.Records))
}
// toIPv6String : net.IP.String will always output an IPv4 address in dot
// notation (127.0.0.1) even if we convert it using net.IP.To16().
// For AAAA records, we can't have that. Instead, force the
// IP to have the IPv6 colon notation.
func toIPv6String(ip net.IP) (currentIP string) {
if ip == nil {
return ""
}
if ipv4 := ip.To4(); ipv4 != nil {
ip = ipv4
}
l := len(ip)
if l < 16 {
// ensure "v4InV6Prefix" for IPv4 addresses
currentIP = "::ffff:"
}
// byte length of an ipv6 segment.
segSize := 2
for i := 0; i < l; i += segSize {
end := i + segSize
bs := ip[i:end]
addColon := (end + 1) < l
currentIP += hex.EncodeToString(bs)
if addColon {
currentIP += ":"
}
}
return currentIP
}
// func areZero(bs []byte) bool {
// for _, b := range bs {
// if b != 0 {
// return false
// }
// }
// return true
// }
func main() {
config = GetConfig()
currentIPv4, currentIPv6 := CheckLocalIPs()
if currentIPv4 == nil && currentIPv6 == nil {
logError("Current IP addresses are not valid, or both are disabled in the config. Check your configuration and internet connection.")
}
for _, domain := range config.Domains {
log.Printf("%s: START", domain.Domain)
UpdateRecords(domain, currentIPv4, currentIPv6)
log.Printf("%s: END", domain.Domain)
}
}