| 1 | package routing |
| 2 | |
| 3 | import ( |
| 4 | "regexp" |
| 5 | "strings" |
| 6 | |
| 7 | "github.com/bettercap/bettercap/core" |
| 8 | "github.com/evilsocket/islazy/str" |
| 9 | ) |
| 10 | |
| 11 | var ( |
| 12 | routeHeadings []string |
| 13 | whitespaceParser = regexp.MustCompile(`\s+`) |
| 14 | ) |
| 15 | |
| 16 | func update() ([]Route, error) { |
| 17 | table = make([]Route, 0) |
| 18 | |
| 19 | output, err := core.Exec("netstat", []string{"-r", "-n", "-4", "-6"}) |
| 20 | if err != nil { |
| 21 | return nil, err |
| 22 | } |
| 23 | // because entries are separated by whitespace |
| 24 | output = strings.ReplaceAll(output, "Next Hop", "Gateway") |
| 25 | |
| 26 | for _, line := range strings.Split(output, "\n") { |
| 27 | if line = str.Trim(line); len(line) != 0 { |
| 28 | parts := whitespaceParser.Split(line, -1) |
| 29 | if parts[0] == "Kernel" { |
| 30 | continue |
| 31 | } |
| 32 | |
| 33 | if parts[0] == "Destination" { |
| 34 | routeHeadings = parts |
| 35 | continue |
| 36 | } |
| 37 | |
| 38 | // skip line if no route headings found yet |
| 39 | if routeHeadings == nil { |
| 40 | continue |
| 41 | } |
| 42 | |
| 43 | route := Route{} |
| 44 | for i, s := range parts { |
| 45 | switch routeHeadings[i] { |
| 46 | case "Destination": |
| 47 | route.Destination = s |
| 48 | break |
| 49 | case "Flag": |
| 50 | route.Flags = s |
| 51 | break |
| 52 | case "Flags": |
| 53 | route.Flags = s |
| 54 | break |
| 55 | case "Gateway": |
| 56 | route.Gateway = s |
| 57 | break |
| 58 | case "If": |
| 59 | route.Device = s |
| 60 | break |
| 61 | case "Iface": |
| 62 | route.Device = s |
| 63 | break |
| 64 | case "Netif": |
| 65 | route.Device = s |
| 66 | break |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | route.Default = strings.Contains(route.Flags, "G") |
| 71 | |
| 72 | if strings.ContainsRune(route.Destination, '.') || strings.ContainsRune(route.Gateway, '.') { |
| 73 | route.Type = IPv4 |
| 74 | } else { |
| 75 | route.Type = IPv6 |
| 76 | } |
| 77 | |
| 78 | table = append(table, route) |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | return table, nil |
| 83 | } |