diff --git a/client/internal/networkmonitor/check_change_linux.go b/client/internal/networkmonitor/check_change_linux.go index efd8b5884..4fbff4448 100644 --- a/client/internal/networkmonitor/check_change_linux.go +++ b/client/internal/networkmonitor/check_change_linux.go @@ -6,6 +6,7 @@ import ( "context" "errors" "fmt" + "net" "syscall" log "github.com/sirupsen/logrus" @@ -35,7 +36,7 @@ func checkChange(ctx context.Context, nexthopv4, nexthopv6 systemops.Nexthop) er // handle route changes case route := <-routeChan: // default route and main table - if route.Dst != nil || route.Table != syscall.RT_TABLE_MAIN { + if !isDefaultRoute(route.Dst) || route.Table != syscall.RT_TABLE_MAIN { continue } switch route.Type { @@ -52,3 +53,13 @@ func checkChange(ctx context.Context, nexthopv4, nexthopv6 systemops.Nexthop) er } } } + +// isDefaultRoute reports whether dst is a default route. netlink v1.3 reports +// the default as 0.0.0.0/0 or ::/0, older versions as a nil Dst. +func isDefaultRoute(dst *net.IPNet) bool { + if dst == nil { + return true + } + ones, _ := dst.Mask.Size() + return ones == 0 +} diff --git a/client/internal/networkmonitor/check_change_linux_test.go b/client/internal/networkmonitor/check_change_linux_test.go new file mode 100644 index 000000000..13e1c9e6d --- /dev/null +++ b/client/internal/networkmonitor/check_change_linux_test.go @@ -0,0 +1,43 @@ +//go:build !android + +package networkmonitor + +import ( + "net" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestIsDefaultRoute(t *testing.T) { + mustCIDR := func(s string) *net.IPNet { + t.Helper() + _, n, err := net.ParseCIDR(s) + if err != nil { + t.Fatalf("parse %s: %v", s, err) + } + return n + } + + tests := []struct { + name string + dst *net.IPNet + want bool + }{ + // netlink before v1.3 left Dst nil for the default route. + {name: "nil dst", dst: nil, want: true}, + // netlink v1.3 reports the default route with an explicit zero-length prefix. + {name: "v4 default", dst: mustCIDR("0.0.0.0/0"), want: true}, + {name: "v6 default", dst: mustCIDR("::/0"), want: true}, + // The exit node split routes and ordinary prefixes are not defaults. + {name: "v4 split half", dst: mustCIDR("0.0.0.0/1"), want: false}, + {name: "v4 subnet", dst: mustCIDR("10.0.0.0/8"), want: false}, + {name: "v4 host", dst: mustCIDR("1.1.1.1/32"), want: false}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.want, isDefaultRoute(tt.dst), "default route detection") + }) + } +}