-
Notifications
You must be signed in to change notification settings - Fork 2
/
namecheap.go
469 lines (379 loc) · 11.9 KB
/
namecheap.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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
package namecheap
import (
"context"
"encoding/xml"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
)
// Provides some basic structs to interact with the Namecheap api with.
// From the docs: https://www.namecheap.com/support/api/methods/domains-dns/set-hosts/
func mustParse(endpoint string) *url.URL {
u, err := url.Parse(endpoint)
if err != nil {
panic(err)
}
return u
}
const (
defaultEndpoint = "https://api.namecheap.com/xml.response"
defaultDiscoveryAddress = "https://icanhazip.com"
)
var (
defaultEndpointURL = mustParse(defaultEndpoint)
)
// RecordType is the type of DNS Record.
type RecordType string
const (
A RecordType = "A"
AAAA RecordType = "AAAA"
ALIAS RecordType = "ALIAS"
CAA RecordType = "CAA"
CNAME RecordType = "CNAME"
MX RecordType = "MX"
MXE RecordType = "MXE"
NS RecordType = "NS"
TXT RecordType = "TXT"
URL RecordType = "URL"
URL301 RecordType = "URL301"
FRAME RecordType = "FRAME"
)
type HostRecord struct {
// The domain or subdomain for which host record is set.
Name string
// RecordType the type of DNS record e.g. A, AAAA
RecordType RecordType
// Possible values are URL or IP address. The value for this parameter is based on RecordType.
Address string
// MX preference for host. Applicable for MX records only.
MXPref string
// 60 to 60000
// Default Value: 1800
TTL uint16
// HostID is the unique ID of the host record.
// Readonly field.
HostID string
}
// This gets unmarshalled from the server's XML response.
type getHostsResponseRecord struct {
// HostID is the unique ID of the host record.
HostID string `xml:"HostId,attr"`
// The domain or subdomain for which host record is set
Name string `xml:"Name,attr"`
// RecordType the type of DNS record e.g. A, AAAA
Type string `xml:"Type,attr"`
// Possible values are URL or IP address. The value for this parameter is based on RecordType.
Address string `xml:"Address,attr"`
// MX preference for host. Applicable for MX records only.
MXPref string `xml:"MXPref,attr"`
// 60 to 60000
// Default Value: 1800
TTL uint16 `xml:"TTL,attr"`
}
// Converts the XML response into the public HostRecord struct.
func (r getHostsResponseRecord) ToHostRecord() HostRecord {
return HostRecord{
HostID: r.HostID,
Name: r.Name,
RecordType: RecordType(r.Type),
Address: r.Address,
MXPref: r.MXPref,
TTL: r.TTL,
}
}
// addToValues adds the HostRecord fields to values. Ignores read only fields.
func addToValues(host HostRecord, hostNumber int, values *url.Values) {
setValueIfPresent := func(key, value string) {
if value != "" && value != "0" {
keyWithNumber := fmt.Sprintf("%s%d", key, hostNumber)
values.Set(keyWithNumber, value)
}
}
setValueIfPresent("HostName", host.Name)
setValueIfPresent("RecordType", string(host.RecordType))
setValueIfPresent("Address", string(host.Address))
setValueIfPresent("MXPref", host.MXPref)
setValueIfPresent("TTL", strconv.Itoa(int(host.TTL)))
}
// getPublicIP tries to determine the public ip of the machine by
// making a request to an external service that returns the public
// IP of the caller.
func getPublicIP(discoveryAddress string) (string, error) {
resp, err := http.Get(discoveryAddress)
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
return strings.TrimSpace(string(body)), nil
}
type Client struct {
// apiKey is the namecheap api key.
// See: https://www.namecheap.com/support/api/intro/ for more info.
apiKey string
// Username required to access the API
apiUser string
// The Username on which a command is executed. Generally, the values of ApiUser and UserName parameters are the same.
username string
// The API endpoint to talk to. Don't modify this. Instead create a new URL from this one.
endpointURL *url.URL
// An IP address of the server from which our system receives API calls (only IPv4 can be used).
clientIP string
// Used to determine external IP of client.
discoveryAddress string
// Will determine the PublicIP of the client by calling a service.
autoDiscoverPublicIP bool
}
type ClientOption func(*Client) error
func WithEndpoint(endpoint string) ClientOption {
return func(c *Client) error {
u, err := url.Parse(endpoint)
if err != nil {
return err
}
c.endpointURL = u
return nil
}
}
func WithClientIP(ip string) ClientOption {
return func(c *Client) error {
c.clientIP = ip
return nil
}
}
func WithDiscoveryAddress(address string) ClientOption {
return func(c *Client) error {
c.discoveryAddress = address
return nil
}
}
func AutoDiscoverPublicIP() ClientOption {
return func(c *Client) error {
c.autoDiscoverPublicIP = true
return nil
}
}
func NewClient(apiKey, apiUser string, opts ...ClientOption) (*Client, error) {
client := &Client{
apiKey: apiKey,
apiUser: apiUser,
endpointURL: defaultEndpointURL,
username: apiUser,
discoveryAddress: defaultDiscoveryAddress,
}
for _, opt := range opts {
if err := opt(client); err != nil {
return nil, fmt.Errorf("error while applying option. Err: %s", err)
}
}
if client.autoDiscoverPublicIP {
ip, err := getPublicIP(client.discoveryAddress)
if err != nil {
return nil, fmt.Errorf("unable to determine public IP automatically. Err: %s", err)
}
client.clientIP = ip
}
if client.clientIP == "" {
return nil, fmt.Errorf("clientIP is not set. Either provide one through the 'WithClientIP' option or have it set automatically with the 'AutoDiscoverPublicIP' option")
}
return client, nil
}
// GetHosts returns the host records for the given domain.
func (c *Client) GetHosts(ctx context.Context, domain string) ([]HostRecord, error) {
u, err := c.buildURL("namecheap.domains.dns.getHosts", domain)
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
if err != nil {
return nil, err
}
apiResp, err := doRequest(req)
if err != nil {
return nil, err
}
var records []HostRecord
for _, host := range apiResp.CommandResponse.DomainDNSGetHostsResult.Hosts {
records = append(records, host.ToHostRecord())
}
return records, nil
}
// AddHosts adds the host records for the given domain.
func (c *Client) AddHosts(ctx context.Context, domain string, hosts []HostRecord) ([]HostRecord, error) {
// Need to first get the existing hosts before adding new ones since we can only "set hosts" in namecheap api.
existingHosts, err := c.GetHosts(ctx, domain)
if err != nil {
return nil, err
}
// Add the hosts to the existing hosts to try and preserve the original order.
existingHosts = append(existingHosts, hosts...)
_, err = c.setHosts(ctx, domain, existingHosts)
if err != nil {
return nil, err
}
return hosts, err
}
// DeleteHosts removes the host records for the given domain.
// Deletes the hosts by HostID. Deleting a host that does not exist
// has no effect.
func (c *Client) DeleteHosts(ctx context.Context, domain string, hosts []HostRecord) ([]HostRecord, error) {
existingHosts, err := c.GetHosts(ctx, domain)
if err != nil {
return nil, err
}
var hostsToRemoveByID = make(map[string]HostRecord)
for _, host := range hosts {
hostsToRemoveByID[host.HostID] = host
}
// Build the array from only existing hosts that aren't being removed.
var updatedHosts []HostRecord
for _, host := range existingHosts {
if _, found := hostsToRemoveByID[host.HostID]; !found {
updatedHosts = append(updatedHosts, host)
}
}
return c.setHosts(ctx, domain, updatedHosts)
}
func (c *Client) setHosts(ctx context.Context, domain string, hosts []HostRecord) ([]HostRecord, error) {
u, err := c.buildURL("namecheap.domains.dns.setHosts", domain, hosts...)
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, u.String(), nil)
if err != nil {
return nil, err
}
_, err = doRequest(req)
return hosts, err
}
// SetHosts creates or updates existing hosts. Existing hosts must have a host ID
// otherwise the record is treated as a new host. Does not delete any existing hosts.
func (c *Client) SetHosts(ctx context.Context, domain string, hosts []HostRecord) ([]HostRecord, error) {
existingHosts, err := c.GetHosts(ctx, domain)
if err != nil {
return nil, nil
}
var existingHostsByID = make(map[string]*HostRecord)
for i := range existingHosts {
existingHostsByID[existingHosts[i].HostID] = &existingHosts[i]
}
var newHosts []HostRecord
for _, host := range hosts {
if existingHost, found := existingHostsByID[host.HostID]; found {
// This will update the value in existingHosts
*existingHost = host
} else {
newHosts = append(newHosts, host)
}
}
existingHosts = append(existingHosts, newHosts...)
return c.setHosts(ctx, domain, existingHosts)
}
// buildURL builds a URL needed to talk to the namecheap API based on the query params.
func (c *Client) buildURL(command, domain string, hosts ...HostRecord) (*url.URL, error) {
// example.com. should be SLD: example TLD: com
// example.co.uk should be SLD: example TLD: co.uk
if strings.HasSuffix(domain, ".") {
domain = domain[:len(domain)-1]
}
split_domain := strings.Split(domain, ".")
if len(split_domain) < 2 {
return nil, fmt.Errorf("domain: %s is not a valid domain. Expected at least 1 TLD and 1 SLD", domain)
}
sld := split_domain[0]
// Assuming everything else is TLD. This may be a bad assumption.
tld := strings.Join(split_domain[1:], ".")
u := *c.endpointURL
q := u.Query()
q.Set("ApiUser", c.apiUser)
q.Set("ApiKey", c.apiKey)
q.Set("UserName", c.username)
q.Set("ClientIp", c.clientIP)
q.Set("Command", command)
q.Set("TLD", tld)
q.Set("SLD", sld)
for i, host := range hosts {
addToValues(host, i+1, &q)
}
u.RawQuery = q.Encode()
return &u, nil
}
type apiErrors []apiError
func (e apiErrors) String() string {
var errMsg string
for i, apiError := range e {
errMsg += fmt.Sprintf("Error%d: %s\t", i, apiError.Err)
}
return errMsg
}
// Go XML doesn't support unmarshaling self closing tags e.g. <Errors /> so need to
// define our own unmarshaling.
func (a *apiErrors) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
errors := make(apiErrors, 0)
e := &apiError{}
for {
err := d.Decode(e)
if err == io.EOF {
break
}
if err != nil {
return err
}
errors = append(errors, *e)
}
*a = errors
return nil
}
type apiError struct {
Number string `xml:"Number,attr"`
Err string `xml:",innerxml"`
}
type apiResponse struct {
XMLName xml.Name `xml:"ApiResponse"`
Status string `xml:"Status,attr"`
Errors apiErrors `xml:"Errors,omitempty"`
RequestedCommand string `xml:"RequestedCommand"`
CommandResponse commandResponse `xml:"CommandResponse"`
Server string `xml:"Server"`
// Let's just ignore the other fields because we probably don't need them..
}
type commandResponse struct {
Type string `xml:"Type,attr"`
DomainDNSSetHostsResult *domainDNSSetHostsResult `xml:"DomainDNSSetHostsResult,omitempty"`
DomainDNSGetHostsResult *domainDNSGetHostsResult `xml:"DomainDNSGetHostsResult,omitempty"`
}
type domainDNSSetHostsResult struct {
Domain string `xml:"Domain,attr"`
IsSuccess bool `xml:"IsSuccess,attr"`
}
type domainDNSGetHostsResult struct {
Domain string `xml:"Domain,attr"`
IsUsingOurDNS bool `xml:"IsUsingOurDNS,attr"`
Hosts []getHostsResponseRecord `xml:",any"`
}
func doRequest(req *http.Request) (*apiResponse, error) {
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var apiResp apiResponse
err = xml.Unmarshal(body, &apiResp)
if err != nil {
return nil, err
}
if len(apiResp.Errors) > 0 {
return nil, fmt.Errorf("namecheap api returned error in response. Err: %s", apiResp.Errors)
}
return &apiResp, nil
}