-
Notifications
You must be signed in to change notification settings - Fork 68
/
Copy pathgateway_parsers.go
405 lines (340 loc) · 10.1 KB
/
gateway_parsers.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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
package gateway
// References
// * https://superuser.com/questions/622144/what-does-netstat-r-on-osx-tell-you-about-gateways
// * https://man.freebsd.org/cgi/man.cgi?query=netstat&sektion=1
import (
"bufio"
"bytes"
"encoding/binary"
"fmt"
"net"
"regexp"
"slices"
"strconv"
"strings"
)
const (
ns_destination = "Destination"
ns_flags = "Flags"
ns_netif = "Netif"
ns_gateway = "Gateway"
ns_interface = "Interface"
)
type netstatFields map[string]int
type windowsRouteStruct struct {
// Dotted IP address
Gateway string
// Dotted IP address
Interface string
}
type linuxRouteStruct struct {
// Name of interface
Iface string
// big-endian hex string
Gateway string
}
type unixRouteStruct struct {
// Name of interface
Iface string
// Dotted IP address
Gateway string
}
func fieldNum(name string, fields []string) int {
// Return the zero-based index of given field in slice of field names
for num, field := range fields {
if name == field {
return num
}
}
return -1
}
func discoverFields(output []byte) (int, netstatFields) {
// Discover positions of fields of interest in netstat output
nf := make(netstatFields, 4)
outputLines := strings.Split(string(output), "\n")
for lineNo, line := range outputLines {
fields := strings.Fields(line)
if len(fields) > 3 {
d, f, g, netif, iface := fieldNum(ns_destination, fields), fieldNum(ns_flags, fields), fieldNum(ns_gateway, fields), fieldNum(ns_netif, fields), fieldNum(ns_interface, fields)
if d >= 0 && f >= 0 && g >= 0 && (netif >= 0 || iface >= 0) {
nf[ns_destination] = d
nf[ns_flags] = f
nf[ns_gateway] = g
if iface > 0 {
// NetBSD
nf[ns_netif] = iface
} else {
// Other BSD/Solaris/Darwin
nf[ns_netif] = netif
}
return lineNo, nf
}
}
}
// Unable to parse column headers
return -1, nil
}
func flagsContain(flags string, flag ...string) bool {
// Check route table flags field for existence of specific flags
contain := true
for _, f := range flag {
contain = contain && strings.Contains(flags, f)
}
return contain
}
func parseToWindowsRouteStruct(output []byte) (windowsRouteStruct, error) {
// Windows route output format is always like this:
// ===========================================================================
// Interface List
// 8 ...00 12 3f a7 17 ba ...... Intel(R) PRO/100 VE Network Connection
// 1 ........................... Software Loopback Interface 1
// ===========================================================================
// IPv4 Route Table
// ===========================================================================
// Active Routes:
// Network Destination Netmask Gateway Interface Metric
// 0.0.0.0 0.0.0.0 192.168.1.1 192.168.1.100 20
// ===========================================================================
//
// Windows commands are localized, so we can't just look for "Active Routes:" string
// I'm trying to pick the active route,
// then jump 2 lines and get the row
// Not using regex because output is quite standard from Windows XP to 8 (NEEDS TESTING)
//
// If multiple default gateways are present, then the one with the lowest metric is returned.
type gatewayEntry struct {
gateway string
iface string
metric int
}
ipRegex := regexp.MustCompile(`^(((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|$)){4})`)
defaultRoutes := make([]gatewayEntry, 0, 2)
lines := strings.Split(string(output), "\n")
sep := 0
for idx, line := range lines {
if sep == 3 {
// We just entered the 2nd section containing "Active Routes:"
if len(lines) <= idx+2 {
return windowsRouteStruct{}, &ErrNoGateway{}
}
inputLine := lines[idx+2]
if strings.HasPrefix(inputLine, "=======") {
// End of routes
break
}
fields := strings.Fields(inputLine)
if len(fields) < 5 || !ipRegex.MatchString(fields[0]) {
return windowsRouteStruct{}, &ErrCantParse{}
}
if fields[0] != "0.0.0.0" {
// Routes to 0.0.0.0 are listed first
// so we are done
break
}
metric, err := strconv.Atoi(fields[4])
if err != nil {
return windowsRouteStruct{}, err
}
defaultRoutes = append(defaultRoutes, gatewayEntry{
gateway: fields[2],
iface: fields[3],
metric: metric,
})
}
if strings.HasPrefix(line, "=======") {
sep++
continue
}
}
if sep == 0 {
// We saw no separator lines, so input must have been garbage.
return windowsRouteStruct{}, &ErrCantParse{}
}
if len(defaultRoutes) == 0 {
return windowsRouteStruct{}, &ErrNoGateway{}
}
minDefaultRoute := slices.MinFunc(defaultRoutes,
func(a, b gatewayEntry) int {
return a.metric - b.metric
})
return windowsRouteStruct{
Gateway: minDefaultRoute.gateway,
Interface: minDefaultRoute.iface,
}, nil
}
func parseToLinuxRouteStruct(output []byte) (linuxRouteStruct, error) {
// parseLinuxProcNetRoute parses the route file located at /proc/net/route
// and returns the IP address of the default gateway. The default gateway
// is the one with Destination value of 0.0.0.0.
//
// The Linux route file has the following format:
//
// $ cat /proc/net/route
//
// Iface Destination Gateway Flags RefCnt Use Metric Mask
// eno1 00000000 C900A8C0 0003 0 0 100 00000000 0 00
// eno1 0000A8C0 00000000 0001 0 0 100 00FFFFFF 0 00
const (
sep = "\t" // field separator
destinationField = 1 // field containing hex destination address
gatewayField = 2 // field containing hex gateway address
maskField = 7 // field containing hex mask
)
scanner := bufio.NewScanner(bytes.NewReader(output))
// Skip header line
if !scanner.Scan() {
err := scanner.Err()
if err == nil {
return linuxRouteStruct{}, &ErrNoGateway{}
}
return linuxRouteStruct{}, err
}
for scanner.Scan() {
row := scanner.Text()
tokens := strings.Split(row, sep)
if len(tokens) < 11 {
return linuxRouteStruct{}, &ErrInvalidRouteFileFormat{row: row}
}
// The default interface is the one that's 0 for both destination and mask.
if !(tokens[destinationField] == "00000000" && tokens[maskField] == "00000000") {
continue
}
return linuxRouteStruct{
Iface: tokens[0],
Gateway: tokens[2],
}, nil
}
return linuxRouteStruct{}, &ErrNoGateway{}
}
func parseWindowsGatewayIP(output []byte) (net.IP, error) {
parsedOutput, err := parseToWindowsRouteStruct(output)
if err != nil {
return nil, err
}
ip := net.ParseIP(parsedOutput.Gateway)
if ip == nil {
return nil, &ErrCantParse{}
}
return ip, nil
}
func parseWindowsInterfaceIP(output []byte) (net.IP, error) {
parsedOutput, err := parseToWindowsRouteStruct(output)
if err != nil {
return nil, err
}
ip := net.ParseIP(parsedOutput.Interface)
if ip == nil {
return nil, &ErrCantParse{}
}
return ip, nil
}
func parseLinuxGatewayIP(output []byte) (net.IP, error) {
parsedStruct, err := parseToLinuxRouteStruct(output)
if err != nil {
return nil, err
}
// cast hex address to uint32
d, err := strconv.ParseUint(parsedStruct.Gateway, 16, 32)
if err != nil {
return nil, fmt.Errorf(
"parsing default interface address field hex %q: %w",
parsedStruct.Gateway,
err,
)
}
// make net.IP address from uint32
ipd32 := make(net.IP, 4)
binary.LittleEndian.PutUint32(ipd32, uint32(d))
return ipd32, nil
}
func parseLinuxInterfaceIP(output []byte) (net.IP, error) {
// Return the first IPv4 address we encounter.
return parseLinuxInterfaceIPImpl(output, &intefaceGetterImpl{})
}
func parseLinuxInterfaceIPImpl(output []byte, ifaceGetter interfaceGetter) (net.IP, error) {
// Mockable implemenation
parsedStruct, err := parseToLinuxRouteStruct(output)
if err != nil {
return nil, err
}
return getInterfaceIP4(parsedStruct.Iface, ifaceGetter)
}
func parseUnixInterfaceIP(output []byte) (net.IP, error) {
// Return the first IPv4 address we encounter.
return parseUnixInterfaceIPImpl(output, &intefaceGetterImpl{})
}
func parseUnixInterfaceIPImpl(output []byte, ifaceGetter interfaceGetter) (net.IP, error) {
// Mockable implemenation
parsedStruct, err := parseNetstatToRouteStruct(output)
if err != nil {
return nil, err
}
return getInterfaceIP4(parsedStruct.Iface, ifaceGetter)
}
func getInterfaceIP4(name string, ifaceGetter interfaceGetter) (net.IP, error) {
// Given interface name and an interface to "net" package
// lookup ip4 for the given interface
iface, err := ifaceGetter.InterfaceByName(name)
if err != nil {
return nil, err
}
addrs, err := ifaceGetter.Addrs(iface)
if err != nil {
return nil, err
}
for _, addr := range addrs {
ipnet, ok := addr.(*net.IPNet)
if !ok {
continue
}
ip := ipnet.IP.To4()
if ip != nil {
return ip, nil
}
}
return nil, fmt.Errorf("no IPv4 address found for interface %v",
name)
}
func parseUnixGatewayIP(output []byte) (net.IP, error) {
// Extract default gateway IP from netstat route table
parsedStruct, err := parseNetstatToRouteStruct(output)
if err != nil {
return nil, err
}
ip := net.ParseIP(parsedStruct.Gateway)
if ip == nil {
return nil, &ErrCantParse{}
}
return ip, nil
}
// Parse any netstat -rn output
func parseNetstatToRouteStruct(output []byte) (unixRouteStruct, error) {
startLine, nsFields := discoverFields(output)
if startLine == -1 {
// Unable to find required column headers in netstat output
return unixRouteStruct{}, &ErrCantParse{}
}
outputLines := strings.Split(string(output), "\n")
for lineNo, line := range outputLines {
if lineNo <= startLine || strings.Contains(line, "-----") {
// Skip until past column headers and heading underlines (solaris)
continue
}
fields := strings.Fields(line)
if len(fields) < 4 {
// past route entries (got to end or blank line prior to ip6 entries)
break
}
if fields[nsFields[ns_destination]] == "default" && flagsContain(fields[nsFields[ns_flags]], "U", "G") {
iface := ""
if ifaceIdx := nsFields[ns_netif]; ifaceIdx < len(fields) {
iface = fields[nsFields[ns_netif]]
}
return unixRouteStruct{
Iface: iface,
Gateway: fields[nsFields[ns_gateway]],
}, nil
}
}
return unixRouteStruct{}, &ErrNoGateway{}
}