-
Notifications
You must be signed in to change notification settings - Fork 1
/
generate_network.go
123 lines (99 loc) · 2.42 KB
/
generate_network.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
package env
import (
"context"
"log"
"os"
"regexp"
"strings"
"sync"
"github.com/9seconds/chore/internal/network"
)
type ipInfoResponse struct {
IP string `json:"ip"`
Hostname string `json:"hostname"`
City string `json:"city"`
Region string `json:"region"`
Country string `json:"country"`
Loc string `json:"loc"`
Org string `json:"org"`
Postal string `json:"postal"`
Timezone string `json:"timezone"`
}
type ifConfigResponse struct {
IP string `json:"ip"`
}
var ipInfoOrgFormat = regexp.MustCompile(`^AS(\d+)\s+(.*?)$`)
func GenerateNetwork(
ctx context.Context,
results chan<- string,
waiters *sync.WaitGroup,
requireNetwork bool,
) {
if !requireNetwork {
return
}
waiters.Add(1)
go func() {
defer waiters.Done()
if _, ok := os.LookupEnv(NetworkIPv4); ok {
return
}
resp := ipInfoResponse{}
err := network.DoJSONRequestWithClient(
ctx,
network.HTTPClientV4,
"https://ipinfo.io/json",
&resp)
if err != nil {
log.Printf("cannot request network data: %v", err)
return
}
sendValue(ctx, results, NetworkIPv4, resp.IP)
sendValue(ctx, results, NetworkHostname, resp.Hostname)
sendValue(ctx, results, NetworkCity, resp.City)
sendValue(ctx, results, NetworkRegion, resp.Region)
sendValue(ctx, results, NetworkCountry, resp.Country)
sendValue(ctx, results, NetworkPostal, resp.Postal)
sendValue(ctx, results, NetworkTimezone, resp.Timezone)
asnChunks := ipInfoOrgFormat.FindStringSubmatch(resp.Org)
switch {
case asnChunks == nil && resp.Org != "":
sendValue(ctx, results, NetworkOrganization, resp.Org)
case asnChunks != nil:
sendValue(ctx, results, NetworkASN, asnChunks[1])
sendValue(ctx, results, NetworkOrganization, asnChunks[2])
}
if lat, lon, ok := strings.Cut(resp.Loc, ","); ok {
sendValue(ctx, results, NetworkLatitude, lat)
sendValue(ctx, results, NetworkLongitude, lon)
}
}()
}
func GenerateNetworkIPv6(
ctx context.Context,
results chan<- string,
waiters *sync.WaitGroup,
requireNetwork bool,
) {
if !requireNetwork {
return
}
waiters.Add(1)
go func() {
defer waiters.Done()
if _, ok := os.LookupEnv(NetworkIPv6); ok {
return
}
resp := ifConfigResponse{}
err := network.DoJSONRequestWithClient(
ctx,
network.HTTPClientV6,
"https://ifconfig.co",
&resp)
if err != nil {
log.Printf("cannot get IPv6 address: %v", err)
return
}
sendValue(ctx, results, NetworkIPv6, resp.IP)
}()
}