/
provider_dnspod.go
481 lines (415 loc) · 11.6 KB
/
provider_dnspod.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
470
471
472
473
474
475
476
477
478
479
480
481
package dnsclients
import (
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"github.com/TeaOSLab/EdgeAPI/internal/dnsclients/dnspod"
"github.com/TeaOSLab/EdgeAPI/internal/dnsclients/dnstypes"
"github.com/TeaOSLab/EdgeAPI/internal/utils/numberutils"
"github.com/iwind/TeaGo/maps"
"github.com/iwind/TeaGo/types"
"io"
"net/http"
"net/url"
"strings"
"time"
)
const (
DNSPodMaxTTL int32 = 604800
DNSPodInternational = "international"
)
var dnsPodHTTPClient = &http.Client{
Timeout: 10 * time.Second,
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
},
}
// DNSPodProvider DNSPod服务商
type DNSPodProvider struct {
BaseProvider
ProviderId int64
region string
apiId string
apiToken string
tencentDNSProvider *TencentDNSProvider
}
// Auth 认证
func (this *DNSPodProvider) Auth(params maps.Map) error {
// 兼容腾讯云API
var apiType = params.GetString("apiType")
switch apiType {
case "tencentDNS":
this.tencentDNSProvider = NewTencentDNSProvider()
return this.tencentDNSProvider.Auth(params)
default:
this.apiId = params.GetString("id")
this.apiToken = params.GetString("token")
this.region = params.GetString("region")
if len(this.apiId) == 0 {
return errors.New("'id' should be not empty")
}
if len(this.apiToken) == 0 {
return errors.New("'token' should not be empty")
}
}
return nil
}
// MaskParams 对参数进行掩码
func (this *DNSPodProvider) MaskParams(params maps.Map) {
if params == nil {
return
}
if params.GetString("apiType") == "tencentDNS" {
params["accessKeySecret"] = MaskString(params.GetString("accessKeySecret"))
} else {
params["token"] = MaskString(params.GetString("token"))
}
}
// GetDomains 获取所有域名列表
func (this *DNSPodProvider) GetDomains() (domains []string, err error) {
if this.tencentDNSProvider != nil {
return this.tencentDNSProvider.GetDomains()
}
var offset = 0
var size = 3000
for {
var resp = new(dnspod.DomainListResponse)
err := this.doAPI("/Domain.List", map[string]string{
"offset": numberutils.FormatInt(offset),
"length": numberutils.FormatInt(size),
}, resp)
if err != nil {
return nil, err
}
offset += size
for _, domain := range resp.Domains {
domains = append(domains, domain.Name)
}
// 检查是否到头
var recordTotal = resp.Info.AllTotal
if offset >= recordTotal {
break
}
}
return
}
// GetRecords 获取域名列表
func (this *DNSPodProvider) GetRecords(domain string) (records []*dnstypes.Record, err error) {
if this.tencentDNSProvider != nil {
return this.tencentDNSProvider.GetRecords(domain)
}
var offset = 0
var size = 3000
for {
var resp = new(dnspod.RecordListResponse)
err := this.doAPI("/Record.List", map[string]string{
"domain": domain,
"offset": numberutils.FormatInt(offset),
"length": numberutils.FormatInt(size),
}, resp)
if err != nil {
return nil, err
}
offset += size
// 记录
for _, record := range resp.Records {
records = append(records, &dnstypes.Record{
Id: types.String(record.Id),
Name: record.Name,
Type: record.Type,
Value: record.Value,
Route: record.Line,
TTL: types.Int32(record.TTL),
})
}
// 检查是否到头
var recordTotal = types.Int(resp.Info.RecordTotal)
if offset >= recordTotal {
break
}
}
// 写入缓存
if this.ProviderId > 0 {
sharedDomainRecordsCache.WriteDomainRecords(this.ProviderId, domain, records)
}
return
}
// GetRoutes 读取线路数据
func (this *DNSPodProvider) GetRoutes(domain string) (routes []*dnstypes.Route, err error) {
if this.tencentDNSProvider != nil {
return this.tencentDNSProvider.GetRoutes(domain)
}
var domainInfoResp = new(dnspod.DomainInfoResponse)
err = this.doAPI("/Domain.Info", map[string]string{
"domain": domain,
}, domainInfoResp)
if err != nil {
return nil, err
}
var grade = domainInfoResp.Domain.Grade
var linesResp = new(dnspod.RecordLineResponse)
err = this.doAPI("/Record.Line", map[string]string{
"domain": domain,
"domain_grade": grade,
}, linesResp)
if err != nil {
return nil, err
}
var lines = linesResp.Lines
if len(lines) == 0 {
return nil, nil
}
for _, line := range lines {
lineString := types.String(line)
routes = append(routes, &dnstypes.Route{
Name: lineString,
Code: lineString,
})
}
// 自定义线路分组
var groupsPerPage = 100
var customLineGroupListResponse = new(dnspod.CustomLineGroupListResponse)
err = this.doAPI("/Custom.Line.Group.List", map[string]string{
"domain": domain,
"offset": "0",
"length": types.String(groupsPerPage),
}, customLineGroupListResponse)
if err != nil {
// 忽略自定义分组错误
err = nil
} else {
if len(customLineGroupListResponse.Data.LineGroups) > 0 {
for _, lineGroup := range customLineGroupListResponse.Data.LineGroups {
routes = append(routes, &dnstypes.Route{
Name: "分组:" + lineGroup.Name,
Code: lineGroup.Name,
})
}
}
if customLineGroupListResponse.Data.Info.Total > customLineGroupListResponse.Data.Info.NowTotal {
for page := 1; page <= 100; /** 最多100页 **/ page++ {
err = this.doAPI("/Custom.Line.Group.List", map[string]string{
"domain": domain,
"offset": types.String(page * groupsPerPage),
"length": types.String(groupsPerPage),
}, customLineGroupListResponse)
if err != nil {
// 忽略错误
err = nil
} else {
if len(customLineGroupListResponse.Data.LineGroups) == 0 {
break
}
for _, lineGroup := range customLineGroupListResponse.Data.LineGroups {
routes = append(routes, &dnstypes.Route{
Name: "分组:" + lineGroup.Name,
Code: lineGroup.Name,
})
}
}
}
}
}
return routes, nil
}
// QueryRecord 查询单个记录
func (this *DNSPodProvider) QueryRecord(domain string, name string, recordType dnstypes.RecordType) (*dnstypes.Record, error) {
if this.tencentDNSProvider != nil {
return this.tencentDNSProvider.QueryRecord(domain, name, recordType)
}
// 从缓存中读取
if this.ProviderId > 0 {
record, hasRecords, _ := sharedDomainRecordsCache.QueryDomainRecord(this.ProviderId, domain, name, recordType)
if hasRecords { // 有效的搜索
return record, nil
}
}
records, err := this.GetRecords(domain)
if err != nil {
return nil, err
}
for _, record := range records {
if record.Name == name && record.Type == recordType {
return record, nil
}
}
return nil, nil
}
// QueryRecords 查询多个记录
func (this *DNSPodProvider) QueryRecords(domain string, name string, recordType dnstypes.RecordType) ([]*dnstypes.Record, error) {
if this.tencentDNSProvider != nil {
return this.tencentDNSProvider.QueryRecords(domain, name, recordType)
}
// 从缓存中读取
if this.ProviderId > 0 {
records, hasRecords, _ := sharedDomainRecordsCache.QueryDomainRecords(this.ProviderId, domain, name, recordType)
if hasRecords { // 有效的搜索
return records, nil
}
}
records, err := this.GetRecords(domain)
if err != nil {
return nil, err
}
var result = []*dnstypes.Record{}
for _, record := range records {
if record.Name == name && record.Type == recordType {
result = append(result, record)
}
}
return result, nil
}
// AddRecord 设置记录
func (this *DNSPodProvider) AddRecord(domain string, newRecord *dnstypes.Record) error {
if this.tencentDNSProvider != nil {
return this.tencentDNSProvider.AddRecord(domain, newRecord)
}
if newRecord == nil {
return errors.New("invalid new record")
}
// 在CHANGE记录后面加入点
if newRecord.Type == dnstypes.RecordTypeCNAME && !strings.HasSuffix(newRecord.Value, ".") {
newRecord.Value += "."
}
var args = map[string]string{
"domain": domain,
"sub_domain": newRecord.Name,
"record_type": newRecord.Type,
"value": newRecord.Value,
"record_line": newRecord.Route,
}
if newRecord.TTL > 0 && newRecord.TTL <= DNSPodMaxTTL {
args["ttl"] = types.String(newRecord.TTL)
}
var resp = new(dnspod.RecordCreateResponse)
err := this.doAPI("/Record.Create", args, resp)
if err != nil {
return this.WrapError(err, domain, newRecord)
}
newRecord.Id = types.String(resp.Record.Id)
// 加入缓存
if this.ProviderId > 0 {
sharedDomainRecordsCache.AddDomainRecord(this.ProviderId, domain, newRecord)
}
return nil
}
// UpdateRecord 修改记录
func (this *DNSPodProvider) UpdateRecord(domain string, record *dnstypes.Record, newRecord *dnstypes.Record) error {
if this.tencentDNSProvider != nil {
return this.tencentDNSProvider.UpdateRecord(domain, record, newRecord)
}
if record == nil {
return errors.New("invalid record")
}
if newRecord == nil {
return errors.New("invalid new record")
}
// 在CHANGE记录后面加入点
if newRecord.Type == dnstypes.RecordTypeCNAME && !strings.HasSuffix(newRecord.Value, ".") {
newRecord.Value += "."
}
var args = map[string]string{
"domain": domain,
"record_id": record.Id,
"sub_domain": newRecord.Name,
"record_type": newRecord.Type,
"value": newRecord.Value,
"record_line": newRecord.Route,
}
if newRecord.TTL > 0 && newRecord.TTL <= DNSPodMaxTTL {
args["ttl"] = types.String(newRecord.TTL)
}
var resp = new(dnspod.RecordModifyResponse)
err := this.doAPI("/Record.Modify", args, resp)
if err != nil {
return this.WrapError(err, domain, newRecord)
}
newRecord.Id = record.Id
// 修改缓存
if this.ProviderId > 0 {
sharedDomainRecordsCache.UpdateDomainRecord(this.ProviderId, domain, newRecord)
}
return nil
}
// DeleteRecord 删除记录
func (this *DNSPodProvider) DeleteRecord(domain string, record *dnstypes.Record) error {
if this.tencentDNSProvider != nil {
return this.tencentDNSProvider.DeleteRecord(domain, record)
}
if record == nil {
return errors.New("invalid record to delete")
}
var resp = new(dnspod.RecordRemoveResponse)
err := this.doAPI("/Record.Remove", map[string]string{
"domain": domain,
"record_id": record.Id,
}, resp)
if err != nil {
return this.WrapError(err, domain, record)
}
// 删除缓存
if this.ProviderId > 0 {
sharedDomainRecordsCache.DeleteDomainRecord(this.ProviderId, domain, record.Id)
}
return nil
}
// 发送请求
func (this *DNSPodProvider) doAPI(path string, params map[string]string, respPtr dnspod.ResponseInterface) error {
var apiHost = "https://dnsapi.cn"
var lang = "cn"
if this.isInternational() { // 国际版
apiHost = "https://api.dnspod.com"
lang = "en"
}
var query = url.Values{
"login_token": []string{this.apiId + "," + this.apiToken},
"format": []string{"json"},
"lang": []string{lang},
}
for p, v := range params {
query[p] = []string{v}
}
req, err := http.NewRequest(http.MethodPost, apiHost+path, strings.NewReader(query.Encode()))
if err != nil {
return fmt.Errorf("create request failed: %w", err)
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("User-Agent", "GoEdge-Client/1.0.0 (iwind.liu@gmail.com)")
req.Header.Set("Accept", "*/*")
resp, err := dnsPodHTTPClient.Do(req)
if err != nil {
return err
}
defer func() {
_ = resp.Body.Close()
}()
body, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
err = json.Unmarshal(body, &respPtr)
if err != nil {
return err
}
if !respPtr.IsOk() {
code, message := respPtr.LastError()
return errors.New("API response error: code: " + code + ", message: " + message)
}
return nil
}
// DefaultRoute 默认线路
func (this *DNSPodProvider) DefaultRoute() string {
if this.tencentDNSProvider != nil {
return this.tencentDNSProvider.DefaultRoute()
}
if this.isInternational() {
return "Default"
}
return "默认"
}
func (this *DNSPodProvider) isInternational() bool {
return this.region == DNSPodInternational
}