/
web.go
259 lines (222 loc) · 5.26 KB
/
web.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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
"path"
"strconv"
"strings"
"time"
)
type testStatus struct {
Success bool `json:"success"`
Latency int64 `json:"latency"`
Error string `json:"error"`
}
type toxStatus struct {
LastScan int64 `json:"last_scan"`
LastRefresh int64 `json:"last_refresh"`
Nodes []*toxNode `json:"nodes"`
}
type toxNode struct {
Ipv4Address string `json:"ipv4"`
Ipv6Address string `json:"ipv6"`
Port int `json:"port"`
TCPPorts []int `json:"tcp_ports"`
PublicKey string `json:"public_key"`
Maintainer string `json:"maintainer"`
Location string `json:"location"`
UDPStatus bool `json:"status_udp"`
TCPStatus bool `json:"status_tcp"`
Version string `json:"version"`
MOTD string `json:"motd"`
LastPing int64 `json:"last_ping"`
index int
ip4 net.IP
ip6 net.IP
}
const (
httpListenPort = 8081
wikiURI = "https://wiki.tox.chat/users/nodes?do=export_raw"
)
var (
countries map[string]string
)
func init() {
bytes := mustGetAssetBytes("assets/countries.json")
if err := json.Unmarshal(bytes, &countries); err != nil {
panic(fmt.Errorf("unable to parse countries: %w", err))
}
}
func handleHTTPRequest(w http.ResponseWriter, r *http.Request) {
urlPath := r.URL.Path[1:]
if r.URL.Path == "/" {
urlPath = "index"
}
if r.Method == "POST" && r.URL.Path == "/test" {
handleTestRequest(w, r)
return
}
var content interface{}
var filename string
switch r.URL.Path {
case "/":
content = getState()
fallthrough
case "/test", "/about":
filename = urlPath + ".html"
default:
data, err := getAssetBytes(path.Join("assets", urlPath))
if err != nil {
http.Error(w, http.StatusText(404), 404)
} else {
w.Header().Set("Content-Type", mimeTypeByExtension(urlPath))
w.Write(data)
}
return
}
err := renderTemplate(w, filename, content)
if err != nil {
fmt.Printf("tmpl exec error: %s\n", err.Error())
}
}
func handleTestRequest(w http.ResponseWriter, r *http.Request) {
fmt.Printf("test request from: %s\n", r.RemoteAddr)
err := r.ParseForm()
if err != nil {
http.Error(w, "unable to parse the form", 500)
return
}
ipPort := r.Form.Get("ipPort")
key := r.Form.Get("key")
proto := r.Form.Get("net")
host, portString, err := net.SplitHostPort(ipPort)
if err != nil {
http.Error(w, "invalid ip:port submission", 500)
return
}
port, err := strconv.Atoi(portString)
if err != nil {
http.Error(w, "specified port is not an int", 500)
return
}
ip4, ip6 := resolveIPAddr(host, host)
node := toxNode{
PublicKey: key,
Port: port,
}
if ip4 != nil {
node.ip4 = ip4.IP
}
if ip6 != nil {
node.ip6 = ip6.IP
}
err = nil
start := time.Now()
content := testStatus{Success: true}
switch proto {
case "UDP":
err = probeNode(&node)
case "TCP":
err = probeNodeTCP(&node)
default:
http.Error(w, "invalid net type", 500)
return
}
if err != nil {
content.Success = false
content.Error = err.Error()
} else {
content.Latency = time.Now().Sub(start).Nanoseconds() / int64(time.Millisecond)
}
writeJSONResponse(w, content)
}
func handleJSONRequest(w http.ResponseWriter, r *http.Request) {
content := getState()
writeJSONResponse(w, content)
}
func writeJSONResponse(w http.ResponseWriter, content interface{}) {
bytes, err := json.Marshal(content)
if err != nil {
http.Error(w, http.StatusText(500), 500)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(bytes)
}
func parseNodes() ([]*toxNode, error) {
client := http.Client{}
client.Timeout = 5 * time.Second
res, err := client.Get(wikiURI)
if err != nil {
return nil, err
}
defer res.Body.Close()
nodesList := []*toxNode{}
content, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
lines := strings.Split(string(content), "\n")
for i, line := range lines {
node := parseNode(line)
if node == nil {
continue
}
node.index = i
nodesList = append(nodesList, node)
}
return nodesList, nil
}
func parseNode(nodeString string) *toxNode {
nodeString = stripSpaces(nodeString)
if !strings.HasPrefix(nodeString, "|") {
return nil
}
lineParts := strings.Split(nodeString, "|")
var node *toxNode
if port, err := strconv.Atoi(lineParts[3]); err == nil && len(lineParts) == 8 {
ip4, ip6 := resolveIPAddr(lineParts[1], lineParts[2])
node = &toxNode{
Ipv4Address: lineParts[1],
Ipv6Address: lineParts[2],
Port: port,
TCPPorts: []int{},
PublicKey: lineParts[4],
Maintainer: lineParts[5],
Location: lineParts[6],
UDPStatus: false,
TCPStatus: false,
Version: "",
MOTD: "",
LastPing: 0,
ip4: nil,
ip6: nil,
}
if ip4 != nil {
node.ip4 = ip4.IP
}
if ip6 != nil {
node.ip6 = ip6.IP
}
if node.Ipv6Address == "NONE" {
node.Ipv6Address = "-"
}
}
return node
}
func resolveIPAddr(ip4String string, ip6String string) (*net.IPAddr, *net.IPAddr) {
resolve := func(network string, ipString string) *net.IPAddr {
if ipString != "NONE" {
ip, err := net.ResolveIPAddr(network, ipString)
if err != nil {
fmt.Printf("couldn't resolve %s: %s\n", ip4String, err.Error())
}
return ip
}
return nil
}
return resolve("ip4", ip4String), resolve("ip6", ip6String)
}