-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfetch.go
114 lines (94 loc) · 2.34 KB
/
fetch.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
package main
import (
"context"
"fmt"
"io/ioutil"
"net"
"net/http"
"os"
"strings"
"syscall"
"unsafe"
)
type fetcher interface {
FetchIP(context.Context) (net.IP, error)
Source() string
}
func newFetcher(conf configSection) (fetcher, error) {
switch conf.Type {
case "ipbouncer":
if conf.BouncerURL == "" {
return nil, fmt.Errorf("%s: missing bouncer_url", conf.Name)
}
return newIPBouncerFetcher(conf.BouncerURL), nil
case "device":
if conf.Device == "" {
return nil, fmt.Errorf("%s: missing device", conf.Name)
}
return newDeviceFetcher(conf.Device), nil
default:
return nil, fmt.Errorf("unknown type %s", conf.Type)
}
}
type ipBouncerFetcher struct {
url string
}
func newIPBouncerFetcher(url string) fetcher {
return &ipBouncerFetcher{
url: url,
}
}
func (f *ipBouncerFetcher) Source() string {
return f.url
}
func (f *ipBouncerFetcher) FetchIP(ctx context.Context) (net.IP, error) {
req, err := http.NewRequestWithContext(ctx, "GET", f.url, nil)
if err != nil {
return nil, err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%s returned HTTP %d", f.url, resp.StatusCode)
}
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
ipStr := strings.Split(string(data), "\n")[0]
ip := net.ParseIP(ipStr)
if ip == nil {
return nil, fmt.Errorf("parsing IP %s failed", ipStr)
}
return ip, nil
}
type deviceFetcher struct {
device string
}
func newDeviceFetcher(device string) fetcher {
return &deviceFetcher{
device: device,
}
}
func (f *deviceFetcher) Source() string {
return f.device
}
func (f *deviceFetcher) FetchIP(context.Context) (net.IP, error) {
var ifreqbuf [40]byte
for i := 0; i < len(f.device); i++ {
ifreqbuf[i] = f.device[i]
}
socketfd, _, errno := syscall.Syscall(syscall.SYS_SOCKET, syscall.AF_INET, syscall.SOCK_DGRAM, 0)
if err := os.NewSyscallError("SYS_SOCKET", errno); err != nil {
return nil, err
}
defer syscall.Close(int(socketfd))
_, _, errno = syscall.Syscall(syscall.SYS_IOCTL, uintptr(socketfd), uintptr(syscall.SIOCGIFADDR), uintptr(unsafe.Pointer(&ifreqbuf)))
if err := os.NewSyscallError("SYS_IOCTL", errno); err != nil {
return nil, err
}
return net.IPv4(ifreqbuf[20], ifreqbuf[21], ifreqbuf[22], ifreqbuf[23]), nil
}