-
Notifications
You must be signed in to change notification settings - Fork 15
/
main.go
137 lines (112 loc) · 2.46 KB
/
main.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
package main
import (
"bytes"
"flag"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"time"
"github.com/hugomd/cloudflare-ddns/lib/providers"
_ "github.com/hugomd/cloudflare-ddns/lib/providers/_all"
)
func checkIP() (string, error) {
rsp, err := http.Get("https://checkip.amazonaws.com")
if err != nil {
return "", err
}
defer rsp.Body.Close()
buf, err := ioutil.ReadAll(rsp.Body)
if err != nil {
return "", err
}
return string(bytes.TrimSpace(buf)), nil
}
func checkIP6() (string, error) {
// has to be a service without A records (for ex api6.ipify.org cant be used)
rsp, err := http.Get("https://v6.ident.me")
if err != nil {
return "", err
}
defer rsp.Body.Close()
buf, err := ioutil.ReadAll(rsp.Body)
if err != nil {
return "", err
}
return string(bytes.TrimSpace(buf)), nil
}
func setEnvVarsFromConfig(filename *string) error {
contents, err := ioutil.ReadFile(*filename)
if err != nil {
return err
}
lines := strings.Split(string(contents), "\n")
for _, line := range lines {
if strings.Contains(line, "=") {
values := strings.SplitN(line, "=", 2)
os.Setenv(values[0], values[1])
}
}
return nil
}
func main() {
var runonce bool
var ticker *time.Ticker
CheckDuration := flag.Duration("duration", 0, "update interval (ex. 15s, 1m, 6h); if not specified or set to 0s, run only once and exit")
ConfigFile := flag.String("config", "", "location of an (optional) config file to load environment variables from")
run4 := flag.Bool("ipv4", true, "update A record")
run6 := flag.Bool("ipv6", false, "update AAAA record")
flag.Parse()
if *CheckDuration == time.Duration(0) {
runonce = true
} else {
ticker = time.NewTicker(*CheckDuration)
}
if *ConfigFile != "" {
err := setEnvVarsFromConfig(ConfigFile)
if err != nil {
panic(err)
}
}
runddns(*run4, *run6)
if runonce {
os.Exit(0)
}
for range ticker.C {
runddns(*run4, *run6)
}
return
}
func runddns(run4, run6 bool) {
PROVIDER := os.Getenv("PROVIDER")
if PROVIDER == "" {
log.Fatal("PROVIDER env. variable is required")
}
provider, err := providers.Providers[PROVIDER]()
if err != nil {
panic(err)
}
if run4 {
ip, err := checkIP()
if err != nil {
panic(err)
}
log.Printf("IP is %s", ip)
err = provider.UpdateRecord(ip)
if err != nil {
panic(err)
}
}
if run6 {
ip, err := checkIP6()
if err != nil {
panic(err)
}
log.Printf("IPv6 is %s", ip)
err = provider.UpdateRecord6(ip)
if err != nil {
panic(err)
}
}
}