forked from navilg/namecheap-ddns-docker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
updaterecord.go
184 lines (139 loc) · 4.14 KB
/
updaterecord.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
package main
import (
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"io"
"net/http"
"os"
"os/signal"
"strings"
"time"
)
func updateRecord(domain, host, password string) {
DDNSLogger(InformationLog, "", "", "Started daemon process")
ticker := time.NewTicker(daemon_poll_time)
done := make(chan bool)
go func() {
for {
select {
case <-done:
return
case <-ticker.C:
pubIp, err := getPubIP()
if err != nil {
DDNSLogger(ErrorLog, host, domain, err.Error())
}
currentIp := os.Getenv("NC_PUB_IP")
if currentIp == pubIp {
DDNSLogger(InformationLog, host, domain, "DNS record is same as current IP. "+pubIp)
} else {
err = setDNSRecord(host, domain, password, pubIp)
if err != nil {
DDNSLogger(ErrorLog, host, domain, err.Error())
} else {
DDNSLogger(InformationLog, host, domain, "Record updated (ip: "+currentIp+"->"+pubIp+")")
}
}
}
}
}()
// Handle signal interrupt
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func() {
for range c {
DDNSLogger(InformationLog, "", "", "Interrupt signal received. Exiting")
ticker.Stop()
done <- true
os.Exit(0)
}
}()
time.Sleep(8760 * time.Hour) // Sleep for 365 days
ticker.Stop()
done <- true
}
func getPubIP() (string, error) {
type GetIPBody struct {
IP string `json:"ip"`
}
var ipbody GetIPBody
apiclient := &http.Client{Timeout: httpTimeout}
response, err := apiclient.Get("https://api.ipify.org?format=json")
if err != nil {
response, err = apiclient.Get("https://ipinfo.io/json")
if err != nil {
return "", nil
}
}
defer response.Body.Close()
bodyBytes, err := io.ReadAll(response.Body)
if err != nil {
// fmt.Println(err.Error())
return "", &CustomError{ErrorCode: response.StatusCode, Err: errors.New("IP could not be fetched." + err.Error())}
}
err = json.Unmarshal(bodyBytes, &ipbody)
if err != nil {
// fmt.Println(err.Error())
return "", &CustomError{ErrorCode: response.StatusCode, Err: errors.New("IP could not be fetched." + err.Error())}
}
if ipbody.IP == "" {
return "", &CustomError{ErrorCode: response.StatusCode, Err: errors.New("IP could not be fetched. Empty IP value detected")}
}
return ipbody.IP, nil
}
func setDNSRecord(host, domain, password, pubIp string) error {
type InterfaceError struct {
Err1 string `xml:"Err1"`
}
type InterfaceResponse struct {
ErrorCount int `xml:"ErrCount"`
Errors InterfaceError `xml:"errors"`
}
var interfaceResponse InterfaceResponse
// Link from Namecheap knowledge article.
// https://www.namecheap.com/support/knowledgebase/article.aspx/29/11/how-to-dynamically-update-the-hosts-ip-with-an-http-request/
ncURL := "https://dynamicdns.park-your-domain.com/update?host=" + host + "&domain=" + domain + "&password=" + password + "&ip=" + pubIp
apiclient := &http.Client{Timeout: httpTimeout}
req, err := http.NewRequest("GET", ncURL, nil)
if err != nil {
// fmt.Println(1, err.Error())
return err
}
// req.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*")
// req.Header.Add("Accept-Encoding", "gzip, deflate, br")
// req.Header.Add("Connection", "keep-alive")
response, err := apiclient.Do(req)
if err != nil {
// fmt.Println(2, err.Error())
return err
}
defer response.Body.Close()
bodyBytes, err := io.ReadAll(response.Body)
if err != nil {
return err
}
// Below function removes first line (below line) from response body because golang xml encoder does not support utf-16
// <?xml version="1.0" encoding="utf-16"?>
modifyBodyBytes := func(bodyBytes []byte) []byte {
bodyString := string(bodyBytes)
read_lines := strings.Split(bodyString, "\n")
var updatedString string
for i, line := range read_lines {
if i != 0 {
updatedString = fmt.Sprintf("%s%s\n", updatedString, line)
}
}
return []byte(updatedString)
}
err = xml.Unmarshal(modifyBodyBytes(bodyBytes), &interfaceResponse)
if err != nil {
return err
}
if interfaceResponse.ErrorCount != 0 {
return &CustomError{ErrorCode: -1, Err: errors.New(interfaceResponse.Errors.Err1)}
}
os.Setenv("NC_PUB_IP", pubIp)
return nil
}