mirror of
https://github.com/Control-D-Inc/ctrld.git
synced 2026-02-03 22:18:39 +00:00
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.
78 lines
1.8 KiB
Go
78 lines
1.8 KiB
Go
package cli
|
|
|
|
import (
|
|
"bufio"
|
|
"bytes"
|
|
"context"
|
|
"io"
|
|
"net"
|
|
"os/exec"
|
|
"strings"
|
|
)
|
|
|
|
func patchNetIfaceName(iface *net.Interface) (bool, error) {
|
|
b, err := exec.Command("networksetup", "-listnetworkserviceorder").Output()
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
|
|
patched := false
|
|
if name := networkServiceName(iface.Name, bytes.NewReader(b)); name != "" {
|
|
patched = true
|
|
iface.Name = name
|
|
}
|
|
return patched, nil
|
|
}
|
|
|
|
func networkServiceName(ifaceName string, r io.Reader) string {
|
|
scanner := bufio.NewScanner(r)
|
|
prevLine := ""
|
|
for scanner.Scan() {
|
|
line := scanner.Text()
|
|
if strings.Contains(line, "*") {
|
|
// Network services is disabled.
|
|
continue
|
|
}
|
|
if !strings.Contains(line, "Device: "+ifaceName) {
|
|
prevLine = line
|
|
continue
|
|
}
|
|
parts := strings.SplitN(prevLine, " ", 2)
|
|
if len(parts) == 2 {
|
|
return strings.TrimSpace(parts[1])
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// validInterface reports whether the *net.Interface is a valid one.
|
|
func validInterface(iface *net.Interface, validIfacesMap map[string]struct{}) bool {
|
|
_, ok := validIfacesMap[iface.Name]
|
|
return ok
|
|
}
|
|
|
|
// validInterfacesMap returns a set of all valid hardware ports.
|
|
func validInterfacesMap(ctx context.Context) map[string]struct{} {
|
|
b, err := exec.Command("networksetup", "-listallhardwareports").Output()
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
return parseListAllHardwarePorts(bytes.NewReader(b))
|
|
}
|
|
|
|
// parseListAllHardwarePorts parses output of "networksetup -listallhardwareports"
|
|
// and returns map presents all hardware ports.
|
|
func parseListAllHardwarePorts(r io.Reader) map[string]struct{} {
|
|
m := make(map[string]struct{})
|
|
scanner := bufio.NewScanner(r)
|
|
for scanner.Scan() {
|
|
line := scanner.Text()
|
|
after, ok := strings.CutPrefix(line, "Device: ")
|
|
if !ok {
|
|
continue
|
|
}
|
|
m[after] = struct{}{}
|
|
}
|
|
return m
|
|
}
|