-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnamecheap-dns.go
333 lines (294 loc) · 8.98 KB
/
namecheap-dns.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
package main
import (
"errors"
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"time"
namecheap "github.com/billputer/go-namecheap"
dns "github.com/miekg/dns"
resource "github.com/protosio/protos/resource"
protos "github.com/protosio/protoslib-go"
logrus "github.com/sirupsen/logrus"
cli "github.com/urfave/cli"
)
var log = logrus.New()
var pclient protos.Protos
var nclient *namecheap.Client
func stringInSlice(a string, list []string) (bool, int) {
for i, b := range list {
if strings.TrimSuffix(b, ".") == strings.TrimSuffix(a, ".") {
return true, i
}
}
return false, 0
}
func waitQuit(pclient protos.Protos) {
sigchan := make(chan os.Signal, 10)
signal.Notify(sigchan, syscall.SIGINT, syscall.SIGTERM)
<-sigchan
log.Info("Deregistering as DNS provider")
err := pclient.DeregisterProvider("dns")
if err != nil {
log.Error("Could not deregister as DNS provider: ", err.Error())
}
log.Info("Stopping Namecheap DNS provider")
os.Exit(0)
}
func compareRecords(protosHosts []namecheap.DomainDNSHost, namecheapHosts []namecheap.DomainDNSHost) bool {
// The following 'if' is required because Namecheap has two default hosts (www and @) for a domain that doesn't have any custom hosts
if len(protosHosts) == 0 && len(namecheapHosts) == 2 && namecheapHosts[0].Name == "www" && namecheapHosts[1].Name == "@" {
return true
}
if len(protosHosts) != len(namecheapHosts) {
return false
}
var matchCount = 0
for _, phost := range protosHosts {
for _, nhost := range namecheapHosts {
if strings.TrimSuffix(phost.Address, ".") == strings.TrimSuffix(nhost.Address, ".") && strings.ToLower(phost.Name) == strings.ToLower(nhost.Name) && phost.TTL-120 < nhost.TTL && phost.TTL+120 > nhost.TTL && strings.ToLower(phost.Type) == strings.ToLower(nhost.Type) {
matchCount++
}
}
}
if len(protosHosts) != matchCount {
return false
}
return true
}
func lookUpDNS(dmn string, rtype string) ([]string, error) {
c := dns.Client{}
m := dns.Msg{}
server := "8.8.8.8"
log.Debugf("Checking DNS record %s of type %s using server %s", dmn, rtype, server)
// Setting the question
switch strings.ToUpper(rtype) {
case "TXT":
m.SetQuestion(dmn, dns.TypeTXT)
case "A":
m.SetQuestion(dmn, dns.TypeA)
case "MX":
m.SetQuestion(dmn, dns.TypeMX)
default:
return []string{""}, errors.New("DNS record type " + rtype + " not supported")
}
// Performing the question
r, _, err := c.Exchange(&m, server+":53")
if err != nil {
return []string{""}, err
}
if len(r.Answer) == 0 {
return []string{""}, errors.New("No DNS result for record " + dmn)
}
result := []string{}
for _, ans := range r.Answer {
parts := strings.Split(ans.String(), "\t")
value := strings.Replace(parts[4], "\"", "", -1)
if strings.ToUpper(rtype) == "MX" {
value = strings.Split(value, " ")[1]
}
result = append(result, value)
}
return result, nil
}
func checkRecords(protosHosts []namecheap.DomainDNSHost, domain string) bool {
for _, record := range protosHosts {
var fqdn string
if record.Name == "@" {
fqdn = domain + "."
} else {
fqdn = record.Name + "." + domain + "."
}
values, err := lookUpDNS(fqdn, record.Type)
if err != nil {
log.Warnf("Record %s does not have a value: %s", record.Name, err.Error())
return false
}
if ok, _ := stringInSlice(record.Address, values); ok == false {
log.Warnf("Record %s does not have value %s", record.Name, record.Address)
return false
}
}
return true
}
func syncRecords(newHosts []namecheap.DomainDNSHost, resources map[string]*resource.Resource, domain string, quit <-chan bool) {
domainParts := strings.Split(domain, ".")
_, err := nclient.DomainDNSSetHosts(domainParts[0], domainParts[1], newHosts)
if err != nil {
log.Error(err)
}
loop:
for {
select {
case <-quit:
return
default:
if checkRecords(newHosts, domain) == false {
log.Debug("Records not active yet. Creating bogus record. HACK")
testHost := namecheap.DomainDNSHost{Name: "temp", Type: "TXT", Address: strconv.FormatInt(time.Now().Unix(), 10)}
extraHosts := append(newHosts, testHost)
_, err := nclient.DomainDNSSetHosts(domainParts[0], domainParts[1], extraHosts)
if err != nil {
log.Error(err)
}
time.Sleep(20 * time.Second)
} else {
break loop
}
}
}
nclient.DomainDNSSetHosts(domainParts[0], domainParts[1], newHosts)
log.Info("All records have been created and are active")
log.Info("Updating the status for all DNS resources")
err = pclient.SetStatusBatch(resources, "created")
if err != nil {
log.Error(err)
}
}
func activityLoop(interval time.Duration, protosURL string, apiuser string, apitoken string, username string) {
appID, err := protos.GetAppID()
if err != nil {
log.Fatal(err)
}
log.Info("Starting with a check interval of ", interval*time.Second)
log.Info("Using ", protosURL, " to connect to Protos.")
// Clients to interact with Protos and Namecheap
pclient = protos.NewClient(protosURL, appID)
nclient = namecheap.NewClient(apiuser, apitoken, username)
go waitQuit(pclient)
// Each service provider needs to register with protos
log.Info("Registering as DNS provider")
time.Sleep(4 * time.Second) // Giving Docker some time to assign us an IP
err = pclient.RegisterProvider("dns")
if err != nil {
if strings.Contains(err.Error(), "already registered") {
log.Error("Failed to register as DNS provider: ", strings.TrimRight(err.Error(), "\n"))
} else {
log.Fatal("Failed to register as DNS provider: ", err)
}
}
log.Debug("Getting domain from Protos")
domain, err := pclient.GetDomain()
if err != nil {
log.Fatal(err)
}
domainParts := strings.Split(domain, ".")
// Checking that the given domain exists in the Namecheap account
log.Info("Checking domain ", domain)
domainInfo, err := nclient.DomainGetInfo(domain)
if err != nil {
log.Fatal("Cant find domain: ", domain, ". ", err)
}
log.Info("Found domain ", domain, " with nameservers ", domainInfo.DNSDetails.Nameservers)
// The following periodically checks the resources and creates new ones in Namecheap
first := true
quit := make(chan bool)
for {
if first == false {
time.Sleep(interval * time.Second)
}
first = false
// Retrieving Protos resources
resources, err := pclient.GetResources()
if err != nil {
log.Error(err)
continue
}
newHosts := []namecheap.DomainDNSHost{}
logResources := map[string]*resource.Resource{}
for id, rsc := range resources {
var record *resource.DNSResource
record = rsc.Value.(*resource.DNSResource)
host := namecheap.DomainDNSHost{Name: record.Host, Type: record.Type, Address: record.Value, TTL: record.TTL}
newHosts = append(newHosts, host)
logResources[id] = resources[id]
}
log.Debugf("Retrieved %v resources from Protos: %v", len(resources), logResources)
// Retrieving all subdomains for given domain
domainHosts, err := nclient.DomainsDNSGetHosts(domainParts[0], domainParts[1])
if err != nil {
log.Error(err)
continue
}
log.Debugf("Retrieved %v hosts from Namecheap: %v", len(domainHosts.Hosts), domainHosts.Hosts)
if compareRecords(newHosts, domainHosts.Hosts) {
log.Debug("Records are the same. Doing nothing")
} else {
close(quit) // interrupts the already running syncRecords routing in case there is one
quit = make(chan bool)
log.Info("Records are not the same. Synchronizing.")
go syncRecords(newHosts, resources, domain, quit)
}
}
}
func main() {
app := cli.NewApp()
app.Name = "protos-dns-namecheap"
app.Author = "Alex Giurgiu"
app.Email = "[email protected]"
app.Version = "0.0.6"
var apiuser string
var apitoken string
var username string
var protosURL string
var interval int
var loglevel string
app.Flags = []cli.Flag{
cli.StringFlag{
Name: "username",
Usage: "Specify your Namecheap username",
Destination: &username,
},
cli.StringFlag{
Name: "apiuser",
Usage: "Specify your Namecheap API user",
Destination: &apiuser,
},
cli.StringFlag{
Name: "token",
Usage: "Specify your Namecheap API token",
Destination: &apitoken,
},
cli.IntFlag{
Name: "interval",
Value: 30,
Usage: "Specify check interval in seconds",
Destination: &interval,
},
cli.StringFlag{
Name: "loglevel",
Value: "info",
Usage: "Specify log level: debug, info, warn, error",
Destination: &loglevel,
},
cli.StringFlag{
Name: "protosurl",
Value: "http://protos:8080",
Usage: "Specify url used to connect to Protos API",
Destination: &protosURL,
},
}
app.Before = func(c *cli.Context) error {
level, err := logrus.ParseLevel(loglevel)
if err != nil {
return err
}
log.SetLevel(level)
return nil
}
app.Commands = []cli.Command{
{
Name: "start",
Usage: "start the Namecheap DNS service",
Action: func(c *cli.Context) {
if username == "" || apiuser == "" || apitoken == "" {
log.Fatal("username, apiuser and token are required.")
}
activityLoop(time.Duration(interval), protosURL, apiuser, apitoken, username)
},
},
}
app.Run(os.Args)
}