refactor: improve network interface validation

Add context parameter to validInterfacesMap for better error handling and
logging. Move Windows-specific network adapter validation logic to the
ctrld package. Key changes include:

- Add context parameter to validInterfacesMap across all platforms
- Move Windows validInterfaces to ctrld.ValidInterfaces
- Improve error handling for virtual interface detection on Linux
- Update all callers to pass appropriate context

This change improves error reporting and makes the interface validation
code more maintainable across different platforms.
This commit is contained in:
Cuong Manh Le
2025-06-19 16:38:03 +07:00
committed by Cuong Manh Le
parent d5cb327620
commit 59ece456b1
8 changed files with 38 additions and 89 deletions
+14 -6
View File
@@ -1,12 +1,15 @@
package cli
import (
"context"
"net"
"net/netip"
"os"
"strings"
"tailscale.com/net/netmon"
"github.com/Control-D-Inc/ctrld"
)
func patchNetIfaceName(iface *net.Interface) (bool, error) { return true, nil }
@@ -19,16 +22,16 @@ func validInterface(iface *net.Interface, validIfacesMap map[string]struct{}) bo
}
// validInterfacesMap returns a set containing non virtual interfaces.
func validInterfacesMap() map[string]struct{} {
func validInterfacesMap(ctx context.Context) map[string]struct{} {
m := make(map[string]struct{})
vis := virtualInterfaces()
vis := virtualInterfaces(ctx)
netmon.ForeachInterface(func(i netmon.Interface, prefixes []netip.Prefix) {
if _, existed := vis[i.Name]; existed {
return
}
m[i.Name] = struct{}{}
})
// Fallback to default route interface if found nothing.
// Fallback to the default route interface if found nothing.
if len(m) == 0 {
defaultRoute, err := netmon.DefaultRoute()
if err != nil {
@@ -39,10 +42,15 @@ func validInterfacesMap() map[string]struct{} {
return m
}
// virtualInterfaces returns a map of virtual interfaces on current machine.
func virtualInterfaces() map[string]struct{} {
// virtualInterfaces returns a map of virtual interfaces on the current machine.
func virtualInterfaces(ctx context.Context) map[string]struct{} {
logger := ctrld.LoggerFromCtx(ctx)
s := make(map[string]struct{})
entries, _ := os.ReadDir("/sys/devices/virtual/net")
entries, err := os.ReadDir("/sys/devices/virtual/net")
if err != nil {
logger.Error().Err(err).Msg("failed to read /sys/devices/virtual/net")
return nil
}
for _, entry := range entries {
if entry.IsDir() {
s[strings.TrimSpace(entry.Name())] = struct{}{}