check / check (push) Successful in 2m32s
A VM with NAT networking makes vmnet install a default route scoped to
its bridge (bridge100) with no gateway. The detector counted it as a
second physical default route and refused to start:
multiple physical default-route interfaces found (bridge100, en0)
Scoped routes cannot simply be dropped: while a VPN holds the default
route, the physical interface keeps only a default route scoped to
itself. That route still names its gateway (flag G). The on-link one
does not, so a physical default route now requires a next-hop gateway.
parseNetstat records a gateway only when the G flag is set; a link#N
gateway column is the interface itself, not a next hop.
409 lines
11 KiB
Go
409 lines
11 KiB
Go
// Package netdetect chooses which network interfaces rtnetmon should monitor.
|
|
//
|
|
// The host-specific queries (enumerating interfaces, reading the routing
|
|
// table) live behind small data types so the selection logic and the route
|
|
// parsers are pure functions that can be unit-tested on any OS with fake
|
|
// data. Only the real routing-table query is build-tagged per platform.
|
|
package netdetect
|
|
|
|
import (
|
|
"encoding/hex"
|
|
"errors"
|
|
"fmt"
|
|
"net"
|
|
"sort"
|
|
"strings"
|
|
)
|
|
|
|
// Selection failures. Those needing the offending interface names are
|
|
// wrapped with %w at the call site.
|
|
var (
|
|
errUnsupportedOS = errors.New("unsupported operating system")
|
|
errOneOfPair = errors.New(
|
|
"found only one of the configured interfaces; " +
|
|
"rtnetmon needs both, or neither (default route only)")
|
|
errNoDefaultRoute = errors.New(
|
|
"no default route found; rtnetmon needs one internet interface")
|
|
errManyDefaultRoutes = errors.New(
|
|
"multiple default-route interfaces found; rtnetmon supports only one")
|
|
errNoPhysRoute = errors.New(
|
|
"no physical default-route interface found; " +
|
|
"rtnetmon needs one internet interface")
|
|
errManyPhysRoutes = errors.New(
|
|
"multiple physical default-route interfaces found; " +
|
|
"rtnetmon supports only one")
|
|
)
|
|
|
|
// Interface is a network interface reduced to what detection needs.
|
|
type Interface struct {
|
|
Name string
|
|
Up bool
|
|
IPv4 []string
|
|
}
|
|
|
|
// Route is one routing-table entry reduced to what detection needs. Gateway
|
|
// is the next-hop address, empty for an on-link route that has none: a
|
|
// tunnel, or the pseudo-default that vmnet and Internet Sharing install on a
|
|
// bridge so the hosted subnet works. Scoped marks a macOS interface-scoped
|
|
// route (flag I), which only traffic bound to that interface uses.
|
|
type Route struct {
|
|
Iface string
|
|
Gateway string
|
|
Default bool
|
|
Scoped bool
|
|
}
|
|
|
|
// Pane names one interface to display, with its label.
|
|
type Pane struct {
|
|
Name string
|
|
Label string
|
|
}
|
|
|
|
// Flags carries the user's --iface/--label choices and whether each label was
|
|
// set explicitly on the command line.
|
|
type Flags struct {
|
|
IfaceA string
|
|
LabelA string
|
|
IfaceB string
|
|
LabelB string
|
|
LabelASet bool
|
|
LabelBSet bool
|
|
}
|
|
|
|
// Interfaces enumerates the host's interfaces and their IPv4 addresses. This
|
|
// uses the standard library and is the same on every platform.
|
|
func Interfaces() ([]Interface, error) {
|
|
ifs, err := net.Interfaces()
|
|
if err != nil {
|
|
return nil, fmt.Errorf("listing interfaces: %w", err)
|
|
}
|
|
|
|
out := make([]Interface, 0, len(ifs))
|
|
for _, ifi := range ifs {
|
|
var v4 []string
|
|
|
|
addrs, _ := ifi.Addrs()
|
|
for _, a := range addrs {
|
|
if n, ok := a.(*net.IPNet); ok && n.IP.To4() != nil {
|
|
v4 = append(v4, n.IP.String())
|
|
}
|
|
}
|
|
|
|
out = append(out, Interface{
|
|
Name: ifi.Name,
|
|
Up: ifi.Flags&net.FlagUp != 0,
|
|
IPv4: v4,
|
|
})
|
|
}
|
|
|
|
return out, nil
|
|
}
|
|
|
|
// Select decides which one or two interfaces to monitor for the given OS.
|
|
// See the README's supported matrix for the exact rules.
|
|
func Select(goos string, ifaces []Interface, routes []Route, f Flags) ([]Pane, error) {
|
|
switch goos {
|
|
case "linux":
|
|
return selectLinux(ifaces, routes, f)
|
|
case "darwin":
|
|
return selectDarwin(ifaces, routes, f)
|
|
default:
|
|
return nil, fmt.Errorf("%w: %q", errUnsupportedOS, goos)
|
|
}
|
|
}
|
|
|
|
// selectLinux keeps today's behavior: if both configured interfaces exist,
|
|
// monitor them as two panes; if neither exists, monitor the single
|
|
// default-route interface; anything else is an error.
|
|
func selectLinux(ifaces []Interface, routes []Route, f Flags) ([]Pane, error) {
|
|
haveA := hasInterface(ifaces, f.IfaceA)
|
|
haveB := hasInterface(ifaces, f.IfaceB)
|
|
|
|
switch {
|
|
case haveA && haveB:
|
|
return []Pane{
|
|
{Name: f.IfaceA, Label: f.LabelA},
|
|
{Name: f.IfaceB, Label: f.LabelB},
|
|
}, nil
|
|
case !haveA && !haveB:
|
|
name, err := onlyDefaultRoute(routes)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return []Pane{{Name: name, Label: singleLabel(f)}}, nil
|
|
default:
|
|
return nil, fmt.Errorf("%w (%q, %q)", errOneOfPair, f.IfaceA, f.IfaceB)
|
|
}
|
|
}
|
|
|
|
// selectDarwin monitors the physical default-route interface, plus a VPN
|
|
// tunnel as the primary pane while one is connected.
|
|
func selectDarwin(ifaces []Interface, routes []Route, f Flags) ([]Pane, error) {
|
|
vpn := findVPN(ifaces, routes)
|
|
|
|
phys, err := onlyPhysicalDefaultRoute(routes, vpn)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if vpn == "" {
|
|
return []Pane{{Name: phys, Label: singleLabel(f)}}, nil
|
|
}
|
|
|
|
return []Pane{
|
|
{Name: vpn, Label: labelOr(f.LabelA, f.LabelASet, "VPN")},
|
|
{Name: phys, Label: labelOr(f.LabelB, f.LabelBSet, "default route")},
|
|
}, nil
|
|
}
|
|
|
|
// findVPN returns the name of the connected VPN tunnel, or "" if there is
|
|
// none. A tunnel is the VPN only while it carries the default route; one that
|
|
// is merely up, even with a routable address (Tailscale without an exit node,
|
|
// or a tunnel a disconnected client left behind), is not. A default route
|
|
// scoped to the tunnel does not count: only traffic bound there uses it.
|
|
func findVPN(ifaces []Interface, routes []Route) string {
|
|
routeIfaces := map[string]bool{}
|
|
|
|
for _, r := range routes {
|
|
if r.Default && !r.Scoped {
|
|
routeIfaces[r.Iface] = true
|
|
}
|
|
}
|
|
|
|
sorted := append([]Interface(nil), ifaces...)
|
|
sort.Slice(sorted, func(i, j int) bool { return sorted[i].Name < sorted[j].Name })
|
|
|
|
for _, ifi := range sorted {
|
|
if !isTunnel(ifi.Name) {
|
|
continue
|
|
}
|
|
|
|
if routeIfaces[ifi.Name] {
|
|
return ifi.Name
|
|
}
|
|
}
|
|
|
|
return ""
|
|
}
|
|
|
|
// onlyDefaultRoute returns the single default-route interface, or an error if
|
|
// there is not exactly one.
|
|
func onlyDefaultRoute(routes []Route) (string, error) {
|
|
names := defaultRouteIfaces(routes, func(r Route) bool {
|
|
return !isTunnel(r.Iface)
|
|
})
|
|
|
|
switch len(names) {
|
|
case 1:
|
|
return names[0], nil
|
|
case 0:
|
|
return "", errNoDefaultRoute
|
|
default:
|
|
return "", fmt.Errorf("%w (%s)",
|
|
errManyDefaultRoutes, strings.Join(names, ", "))
|
|
}
|
|
}
|
|
|
|
// onlyPhysicalDefaultRoute returns the single non-tunnel default-route
|
|
// interface (ignoring the VPN), or an error if there is not exactly one. Only
|
|
// a default route with a next-hop gateway counts: scoped routes do, since
|
|
// while a VPN holds the default route the physical interface keeps only a
|
|
// default route scoped to itself, but that route still names the gateway. An
|
|
// on-link default without one (vmnet's on bridge100) reaches nothing beyond
|
|
// its own subnet and is not an uplink.
|
|
func onlyPhysicalDefaultRoute(routes []Route, vpn string) (string, error) {
|
|
names := defaultRouteIfaces(routes, func(r Route) bool {
|
|
return r.Iface != vpn && !isTunnel(r.Iface) && r.Gateway != ""
|
|
})
|
|
|
|
switch len(names) {
|
|
case 1:
|
|
return names[0], nil
|
|
case 0:
|
|
return "", errNoPhysRoute
|
|
default:
|
|
return "", fmt.Errorf("%w (%s)",
|
|
errManyPhysRoutes, strings.Join(names, ", "))
|
|
}
|
|
}
|
|
|
|
// defaultRouteIfaces returns the sorted, unique interface names that carry a
|
|
// default route accepted by keep.
|
|
func defaultRouteIfaces(routes []Route, keep func(Route) bool) []string {
|
|
seen := map[string]bool{}
|
|
|
|
var names []string
|
|
|
|
for _, r := range routes {
|
|
if !r.Default || !keep(r) || seen[r.Iface] {
|
|
continue
|
|
}
|
|
|
|
seen[r.Iface] = true
|
|
names = append(names, r.Iface)
|
|
}
|
|
|
|
sort.Strings(names)
|
|
|
|
return names
|
|
}
|
|
|
|
// hasInterface reports whether an interface with the given name exists.
|
|
func hasInterface(ifaces []Interface, name string) bool {
|
|
for _, ifi := range ifaces {
|
|
if ifi.Name == name {
|
|
return true
|
|
}
|
|
}
|
|
|
|
return false
|
|
}
|
|
|
|
// isTunnel reports whether the interface name is a macOS userspace tunnel
|
|
// (utunN), which is what Mullvad and other WireGuard/OpenVPN clients use.
|
|
func isTunnel(name string) bool {
|
|
return strings.HasPrefix(name, "utun")
|
|
}
|
|
|
|
// singleLabel is the label for a lone pane: the explicit --labelA if given,
|
|
// otherwise a plain description.
|
|
func singleLabel(f Flags) string {
|
|
return labelOr(f.LabelA, f.LabelASet, "default route")
|
|
}
|
|
|
|
// labelOr returns value when it was set explicitly, otherwise fallback.
|
|
func labelOr(value string, set bool, fallback string) string {
|
|
if set {
|
|
return value
|
|
}
|
|
|
|
return fallback
|
|
}
|
|
|
|
// parseIPRoute reads `ip -4 route show default` output. Every printed line is
|
|
// a default route.
|
|
func parseIPRoute(out string) []Route {
|
|
var routes []Route
|
|
|
|
for _, line := range strings.Split(out, "\n") {
|
|
fields := strings.Fields(line)
|
|
if len(fields) == 0 || fields[0] != "default" {
|
|
continue
|
|
}
|
|
|
|
r := Route{Default: true}
|
|
|
|
for i := range len(fields) - 1 {
|
|
switch fields[i] {
|
|
case "dev":
|
|
r.Iface = fields[i+1]
|
|
case "via":
|
|
r.Gateway = fields[i+1]
|
|
}
|
|
}
|
|
|
|
if r.Iface != "" {
|
|
routes = append(routes, r)
|
|
}
|
|
}
|
|
|
|
return routes
|
|
}
|
|
|
|
// parseProcNetRoute reads /proc/net/route. A default route has destination
|
|
// 00000000; the gateway is a little-endian hex IPv4 address.
|
|
func parseProcNetRoute(out string) []Route {
|
|
var routes []Route
|
|
|
|
for i, line := range strings.Split(out, "\n") {
|
|
if i == 0 { // column header
|
|
continue
|
|
}
|
|
|
|
fields := strings.Fields(line)
|
|
if len(fields) < 3 || fields[1] != "00000000" {
|
|
continue
|
|
}
|
|
|
|
routes = append(routes, Route{
|
|
Iface: fields[0],
|
|
Gateway: hexToIP(fields[2]),
|
|
Default: true,
|
|
})
|
|
}
|
|
|
|
return routes
|
|
}
|
|
|
|
// netstat route flags (see `man netstat`).
|
|
const (
|
|
netstatFlagGateway = "G" // destination is reached through a next-hop gateway
|
|
netstatFlagScoped = "I" // route is scoped to its interface
|
|
)
|
|
|
|
// parseNetstat reads `netstat -rn -f inet` output (macOS); the Netif column
|
|
// (field 4) names the interface. A row whose destination is "default" is a
|
|
// default route, scoped when its flags include I. Its Gateway column is the
|
|
// next hop only when the flags include G; otherwise it names the link itself
|
|
// (link#N) and the route is on-link, with no gateway. A "0/1" row and a
|
|
// "128.0/1" row on one interface together also make a default route there:
|
|
// VPN clients that leave the physical default in place send all traffic
|
|
// through them.
|
|
func parseNetstat(out string) []Route {
|
|
const columns = 4 // Destination, Gateway, Flags, Netif; Expire is optional
|
|
|
|
var routes []Route
|
|
|
|
var lowHalf []string // interfaces with a 0/1 row
|
|
|
|
highHalf := map[string]bool{} // interfaces with a 128.0/1 row
|
|
|
|
for _, line := range strings.Split(out, "\n") {
|
|
fields := strings.Fields(line)
|
|
if len(fields) < columns {
|
|
continue
|
|
}
|
|
|
|
dest, gateway, flags, iface := fields[0], fields[1], fields[2], fields[3]
|
|
|
|
switch dest {
|
|
case "default":
|
|
if !strings.Contains(flags, netstatFlagGateway) {
|
|
gateway = ""
|
|
}
|
|
|
|
routes = append(routes, Route{
|
|
Iface: iface,
|
|
Gateway: gateway,
|
|
Default: true,
|
|
Scoped: strings.Contains(flags, netstatFlagScoped),
|
|
})
|
|
case "0/1":
|
|
lowHalf = append(lowHalf, iface)
|
|
case "128.0/1":
|
|
highHalf[iface] = true
|
|
}
|
|
}
|
|
|
|
for _, iface := range lowHalf {
|
|
if highHalf[iface] {
|
|
routes = append(routes, Route{Iface: iface, Default: true})
|
|
}
|
|
}
|
|
|
|
return routes
|
|
}
|
|
|
|
// hexToIP converts a little-endian hex IPv4 address (as found in
|
|
// /proc/net/route) to dotted-quad form.
|
|
func hexToIP(h string) string {
|
|
b, err := hex.DecodeString(h)
|
|
if err != nil || len(b) != net.IPv4len {
|
|
return ""
|
|
}
|
|
|
|
// /proc/net/route stores the address little-endian.
|
|
return net.IPv4(b[3], b[2], b[1], b[0]).String()
|
|
}
|