Repository navigation
Expand file tree
/
Copy pathprovider.go
More file actions
318 lines (271 loc) · 8.73 KB
/
Copy pathprovider.go
File metadata and controls
318 lines (271 loc) · 8.73 KB
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
// Package hostinger implements a DNS record management client compatible
// with the libdns interfaces for Hostinger.
package hostinger
import (
"context"
"encoding/json"
"fmt"
"net/http"
"strings"
"sync"
"time"
"github.com/libdns/libdns"
)
// unquoteTXT strips surrounding double quotes from TXT record content.
// The Hostinger API returns TXT values wrapped in quotes, but libdns
// expects unquoted values.
func unquoteTXT(recordType, content string) string {
if recordType == "TXT" {
content = strings.TrimPrefix(content, "\"")
content = strings.TrimSuffix(content, "\"")
}
return content
}
// Provider facilitates DNS record manipulation with Hostinger.
type Provider struct {
// APIToken is the Hostinger API token used for authentication.
// Tokens can be managed at https://hpanel.hostinger.com/profile/api.
// If empty, defaults to the HOSTINGER_API_TOKEN environment variable.
APIToken string `json:"api_token,omitempty"`
httpClient *http.Client
once sync.Once
mu sync.Mutex
}
// GetRecords lists all the records in the zone.
func (p *Provider) GetRecords(ctx context.Context, zone string) ([]libdns.Record, error) {
p.mu.Lock()
defer p.mu.Unlock()
domain := unFQDN(zone)
respBody, err := p.doRequest(ctx, http.MethodGet, "/api/dns/v1/zones/"+domain, nil)
if err != nil {
return nil, fmt.Errorf("getting records for zone %s: %w", zone, err)
}
var zoneRecords []dnsZoneRecord
if err := json.Unmarshal(respBody, &zoneRecords); err != nil {
return nil, fmt.Errorf("decoding response: %w", err)
}
var records []libdns.Record
for _, zr := range zoneRecords {
ttl := time.Duration(zr.TTL) * time.Second
for _, rc := range zr.Records {
rr := libdns.RR{
Name: zr.Name,
Type: zr.Type,
TTL: ttl,
Data: unquoteTXT(zr.Type, rc.Content),
}
parsed, _ := rr.Parse()
records = append(records, parsed)
}
}
return records, nil
}
// AppendRecords creates the inputted records in the given zone and returns
// the populated records that were created. It never changes existing records.
func (p *Provider) AppendRecords(ctx context.Context, zone string, records []libdns.Record) ([]libdns.Record, error) {
p.mu.Lock()
defer p.mu.Unlock()
domain := unFQDN(zone)
zoneEntries := groupRecords(records)
req := updateRequest{
Zone: zoneEntries,
Overwrite: false,
}
_, err := p.doRequest(ctx, http.MethodPut, "/api/dns/v1/zones/"+domain, req)
if err != nil {
return nil, fmt.Errorf("appending records to zone %s: %w", zone, err)
}
return toConcrete(records), nil
}
// SetRecords sets the records in the zone, either by updating existing records
// or creating new ones. For each (name, type) pair in the input, all existing
// records with that pair are replaced with the provided records. It returns the
// records that were set.
func (p *Provider) SetRecords(ctx context.Context, zone string, records []libdns.Record) ([]libdns.Record, error) {
p.mu.Lock()
defer p.mu.Unlock()
domain := unFQDN(zone)
zoneEntries := groupRecords(records)
req := updateRequest{
Zone: zoneEntries,
Overwrite: true,
}
_, err := p.doRequest(ctx, http.MethodPut, "/api/dns/v1/zones/"+domain, req)
if err != nil {
return nil, fmt.Errorf("setting records in zone %s: %w", zone, err)
}
return toConcrete(records), nil
}
// DeleteRecords deletes the specified records from the zone. It returns the
// records that were deleted. Records that do not exist in the zone are silently
// ignored.
//
// Because the Hostinger API only supports deleting all records matching a
// (name, type) pair, this method performs a read-modify-write: it reads the
// current zone, determines which records to keep, and either deletes the entire
// record set or overwrites it with the remaining records.
func (p *Provider) DeleteRecords(ctx context.Context, zone string, records []libdns.Record) ([]libdns.Record, error) {
p.mu.Lock()
defer p.mu.Unlock()
domain := unFQDN(zone)
// Fetch current records to match against and handle selective deletion.
respBody, err := p.doRequest(ctx, http.MethodGet, "/api/dns/v1/zones/"+domain, nil)
if err != nil {
return nil, fmt.Errorf("getting current records for zone %s: %w", zone, err)
}
var currentZone []dnsZoneRecord
if err := json.Unmarshal(respBody, ¤tZone); err != nil {
return nil, fmt.Errorf("decoding response: %w", err)
}
// Build lookup of current records by (name, type).
type rrsetKey struct{ Name, Type string }
currentByKey := make(map[rrsetKey]dnsZoneRecord)
for _, zr := range currentZone {
for i, rc := range zr.Records {
zr.Records[i].Content = unquoteTXT(zr.Type, rc.Content)
}
key := rrsetKey{zr.Name, zr.Type}
currentByKey[key] = zr
}
// For each affected (name, type), track content values to keep vs delete.
type rrsetAction struct {
toKeep []recordContent
deleted []libdns.Record
ttl int
}
actions := make(map[rrsetKey]*rrsetAction)
for _, rec := range records {
rr := rec.RR()
if rr.Name == "" {
continue
}
for key, current := range currentByKey {
// Name must match.
if key.Name != rr.Name {
continue
}
// Type: if input type is empty, match any; otherwise must match.
if rr.Type != "" && key.Type != rr.Type {
continue
}
if actions[key] == nil {
actions[key] = &rrsetAction{
toKeep: append([]recordContent{}, current.Records...),
ttl: current.TTL,
}
}
act := actions[key]
ttlDur := time.Duration(current.TTL) * time.Second
var remaining []recordContent
for _, rc := range act.toKeep {
dataMatch := rr.Data == "" || rc.Content == rr.Data
ttlMatch := rr.TTL == 0 || ttlDur == rr.TTL
if dataMatch && ttlMatch {
delRR := libdns.RR{
Name: key.Name,
Type: key.Type,
TTL: ttlDur,
Data: rc.Content,
}
parsed, _ := delRR.Parse()
act.deleted = append(act.deleted, parsed)
} else {
remaining = append(remaining, rc)
}
}
act.toKeep = remaining
}
}
// Build API requests for the two possible actions:
// 1. DELETE filter for (name, type) pairs being fully removed.
// 2. PUT overwrite=true for (name, type) pairs being partially updated.
var deleteFilters []deleteFilter
var updateEntries []dnsZoneRecord
var allDeleted []libdns.Record
for key, act := range actions {
if len(act.deleted) == 0 {
continue
}
allDeleted = append(allDeleted, act.deleted...)
if len(act.toKeep) == 0 {
deleteFilters = append(deleteFilters, deleteFilter{
Name: key.Name,
Type: key.Type,
})
} else {
updateEntries = append(updateEntries, dnsZoneRecord{
Name: key.Name,
Type: key.Type,
TTL: act.ttl,
Records: act.toKeep,
})
}
}
if len(deleteFilters) > 0 {
_, err := p.doRequest(ctx, http.MethodDelete, "/api/dns/v1/zones/"+domain, deleteRequest{Filters: deleteFilters})
if err != nil {
return nil, fmt.Errorf("deleting records from zone %s: %w", zone, err)
}
}
if len(updateEntries) > 0 {
_, err := p.doRequest(ctx, http.MethodPut, "/api/dns/v1/zones/"+domain, updateRequest{Zone: updateEntries, Overwrite: true})
if err != nil {
return nil, fmt.Errorf("updating remaining records in zone %s: %w", zone, err)
}
}
return allDeleted, nil
}
// toConcrete ensures all records are concrete types (Address, TXT, etc.)
// rather than opaque RR structs.
func toConcrete(records []libdns.Record) []libdns.Record {
result := make([]libdns.Record, len(records))
for i, rec := range records {
parsed, _ := rec.RR().Parse()
result[i] = parsed
}
return result
}
// groupRecords groups libdns records by (name, type) into the Hostinger
// zone record format. When multiple records share the same (name, type),
// the minimum TTL is used for the group.
func groupRecords(records []libdns.Record) []dnsZoneRecord {
type rrsetKey struct{ Name, Type string }
groups := make(map[rrsetKey]*dnsZoneRecord)
var order []rrsetKey
for _, rec := range records {
rr := rec.RR()
name := rr.Name
if name == "" {
name = "@"
}
key := rrsetKey{name, rr.Type}
if groups[key] == nil {
groups[key] = &dnsZoneRecord{
Name: name,
Type: rr.Type,
TTL: int(rr.TTL / time.Second),
}
order = append(order, key)
}
groups[key].Records = append(groups[key].Records, recordContent{Content: rr.Data})
if ttl := int(rr.TTL / time.Second); ttl < groups[key].TTL {
groups[key].TTL = ttl
}
}
entries := make([]dnsZoneRecord, 0, len(order))
for _, key := range order {
entries = append(entries, *groups[key])
}
return entries
}
// unFQDN removes the trailing dot from a fully-qualified domain name.
func unFQDN(zone string) string {
return strings.TrimSuffix(zone, ".")
}
// Interface guards
var (
_ libdns.RecordGetter = (*Provider)(nil)
_ libdns.RecordAppender = (*Provider)(nil)
_ libdns.RecordSetter = (*Provider)(nil)
_ libdns.RecordDeleter = (*Provider)(nil)
)