forked from mholt/caddy-dynamicdns
/
ipsource.go
323 lines (280 loc) · 8.19 KB
/
ipsource.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
// Copyright 2020 Matthew Holt
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package dynamicdns
import (
"context"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"strings"
"time"
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
upnp "gitlab.com/NebulousLabs/go-upnp"
"go.uber.org/zap"
)
func init() {
caddy.RegisterModule(SimpleHTTP{})
caddy.RegisterModule(UPnP{})
caddy.RegisterModule(NetInterface{})
}
// IPSource is a type that can get IP addresses.
type IPSource interface {
GetIPs(context.Context, IPVersions) ([]net.IP, error)
}
// SimpleHTTP is an IP source that looks up the public IP addresses by
// making HTTP(S) requests to the specified endpoints; it will try each
// endpoint with IPv4 and IPv6 until at least one returns a valid value.
// It is OK if an endpoint doesn't support both IP versions; returning
// a single valid IP address is sufficient.
//
// The endpoints must return HTTP status 200 and the response body must
// contain only the IP address in plain text.
type SimpleHTTP struct {
// The list of endpoints to query. If empty, a default list will
// be used:
//
// - https://api64.ipify.org
// - https://myip.addr.space
// - https://ifconfig.me
// - https://icanhazip.com
// - https://ident.me
// - https://ipecho.net/plain
Endpoints []string `json:"endpoints,omitempty"`
logger *zap.Logger
}
// CaddyModule returns the Caddy module information.
func (SimpleHTTP) CaddyModule() caddy.ModuleInfo {
return caddy.ModuleInfo{
ID: "dynamic_dns.ip_sources.simple_http",
New: func() caddy.Module { return new(SimpleHTTP) },
}
}
func (sh *SimpleHTTP) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
var (
unused string
endpoint string
)
if !d.AllArgs(&unused, &endpoint) {
return d.ArgErr()
}
sh.Endpoints = append(sh.Endpoints, endpoint)
return nil
}
// Provision sets up the module.
func (sh *SimpleHTTP) Provision(ctx caddy.Context) error {
sh.logger = ctx.Logger(sh)
if len(sh.Endpoints) == 0 {
sh.Endpoints = defaultHTTPIPServices
}
return nil
}
// GetIPs gets the public addresses of this machine.
func (sh SimpleHTTP) GetIPs(ctx context.Context, versions IPVersions) ([]net.IP, error) {
out := []net.IP{}
getForVersion := func(network string, name string) net.IP {
client := sh.makeClient(network)
for _, endpoint := range sh.Endpoints {
ip, err := sh.lookupIP(ctx, client, endpoint)
if err != nil {
sh.logger.Debug("lookup failed",
zap.String("type", name),
zap.String("endpoint", endpoint),
zap.Error(err))
continue
}
sh.logger.Debug("lookup",
zap.String("type", name),
zap.String("endpoint", endpoint),
zap.String("ip", ip.String()))
return ip
}
sh.logger.Warn("no IP found; consider disabling this IP version",
zap.String("type", name))
return nil
}
if versions.V4Enabled() {
ip := getForVersion("tcp4", "IPv4")
if ip != nil {
out = append(out, ip)
}
}
if versions.V6Enabled() {
ip := getForVersion("tcp6", "IPv6")
if ip != nil {
out = append(out, ip)
}
}
return out, nil
}
// makeClient makes an HTTP client that forces use of the specified network type (e.g. "tcp6").
func (SimpleHTTP) makeClient(network string) *http.Client {
dialer := &net.Dialer{Timeout: 10 * time.Second}
return &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: func(ctx context.Context, _, address string) (net.Conn, error) {
return dialer.DialContext(ctx, network, address)
},
IdleConnTimeout: 30 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
},
}
}
func (SimpleHTTP) lookupIP(ctx context.Context, client *http.Client, endpoint string) (net.IP, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
if err != nil {
return nil, err
}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return nil, fmt.Errorf("%s: server response was: %d %s", endpoint, resp.StatusCode, resp.Status)
}
ipASCII, err := ioutil.ReadAll(io.LimitReader(resp.Body, 256))
if err != nil {
return nil, err
}
ipStr := strings.TrimSpace(string(ipASCII))
ip := net.ParseIP(ipStr)
if ip == nil {
return nil, fmt.Errorf("%s: invalid IP address: %s", endpoint, ipStr)
}
return ip, nil
}
var defaultHTTPIPServices = []string{
"https://api64.ipify.org",
"https://myip.addr.space",
"https://ifconfig.me",
"https://icanhazip.com",
"https://ident.me",
"https://ipecho.net/plain",
}
// UPnP gets the IP address from UPnP device.
type UPnP struct {
logger *zap.Logger
}
// CaddyModule returns the Caddy module information.
func (UPnP) CaddyModule() caddy.ModuleInfo {
return caddy.ModuleInfo{
ID: "dynamic_dns.ip_sources.upnp",
New: func() caddy.Module { return new(UPnP) },
}
}
func (u *UPnP) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
return nil
}
// Provision sets up the module.
func (u *UPnP) Provision(ctx caddy.Context) error {
u.logger = ctx.Logger(u)
return nil
}
// GetIPs gets the public address(es) of this machine.
// This implementation ignores the configured IP versions, since
// we can't really choose whether we're looking for IPv4 or IPv6
// with UPnP, we just get what we get.
func (u UPnP) GetIPs(ctx context.Context, _ IPVersions) ([]net.IP, error) {
d, err := upnp.DiscoverCtx(ctx)
if err != nil {
return nil, err
}
ipStr, err := d.ExternalIP()
if err != nil {
return nil, err
}
ip := net.ParseIP(ipStr)
if ip == nil {
return nil, fmt.Errorf("invalid IP: %s", ipStr)
}
u.logger.Debug("lookup",
zap.String("ip", ip.String()))
return []net.IP{ip}, nil
}
// NetInterface gets the IP address from a network interface by name.
type NetInterface struct {
// The name of the network interface.
Name string `json:"name,omitempty"`
logger *zap.Logger
}
// CaddyModule returns the Caddy module information.
func (NetInterface) CaddyModule() caddy.ModuleInfo {
return caddy.ModuleInfo{
ID: "dynamic_dns.ip_sources.interface",
New: func() caddy.Module { return new(NetInterface) },
}
}
func (u *NetInterface) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
d.Next() // skip directive name
if !d.NextArg() {
return d.ArgErr()
}
u.Name = d.Val()
return nil
}
// Provision sets up the module.
func (u *NetInterface) Provision(ctx caddy.Context) error {
u.logger = ctx.Logger(u)
return nil
}
// GetIPs gets the public address(es) of from the network interface.
func (u NetInterface) GetIPs(ctx context.Context, versions IPVersions) ([]net.IP, error) {
iface, err := net.InterfaceByName(u.Name)
if err != nil {
return nil, fmt.Errorf("couldn't find interface '%s': %v", u.Name, err)
}
addrs, err := iface.Addrs()
if err != nil {
return nil, fmt.Errorf("couldn't load addresses for interface '%s': %v", u.Name, err)
}
ips := []net.IP{}
for _, addr := range addrs {
ipNet, ok := addr.(*net.IPNet)
if !ok || ipNet.IP.IsLoopback() {
continue
}
if versions.V4Enabled() && ipNet.IP.To4() != nil {
ips = append(ips, ipNet.IP)
continue
}
if versions.V6Enabled() && ipNet.IP.To16() != nil {
ips = append(ips, ipNet.IP)
continue
}
}
stringIps := make([]string, len(ips))
for i, ip := range ips {
stringIps[i] = ip.String()
}
u.logger.Debug("lookup",
zap.Strings("ip", stringIps))
return ips, nil
}
// Interface guards
var (
_ IPSource = (*SimpleHTTP)(nil)
_ caddy.Provisioner = (*SimpleHTTP)(nil)
_ caddyfile.Unmarshaler = (*SimpleHTTP)(nil)
_ IPSource = (*UPnP)(nil)
_ caddy.Provisioner = (*UPnP)(nil)
_ caddyfile.Unmarshaler = (*UPnP)(nil)
_ IPSource = (*NetInterface)(nil)
_ caddy.Provisioner = (*NetInterface)(nil)
_ caddyfile.Unmarshaler = (*NetInterface)(nil)
)