commit 444b8b2f2fff2945d01f9f0097afb60e6c6b50c0 Author: Alex Denes Date: Fri Jun 14 21:26:46 2024 +0000 Initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e96e8d7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +net-predictable +go.sum diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..0291a45 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,7 @@ +Copyright (c) 2024 Alex Denes + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..b7be6ea --- /dev/null +++ b/go.mod @@ -0,0 +1,10 @@ +module git.redxen.eu/caskd/net-predictable + +go 1.22.3 + +require github.com/vishvananda/netlink v1.1.0 + +require ( + github.com/vishvananda/netns v0.0.0-20191106174202-0a2b9b5464df // indirect + golang.org/x/sys v0.0.0-20190606203320-7fc4e5ec1444 // indirect +) diff --git a/main.go b/main.go new file mode 100644 index 0000000..405f24c --- /dev/null +++ b/main.go @@ -0,0 +1,74 @@ +package main + +import ( + "flag" + "log" + "os" + + "github.com/vishvananda/netlink" +) + +func main() { + var ( + err error + mainlog = log.New(os.Stderr, "net-predictable: ", log.Lmsgprefix|log.Ltime) + ifnparam string + ) + flag.StringVar(&ifnparam, "ifname", "", "Interface name to rename") + flag.Parse() + + mainlog.Printf("%#v", os.Environ()) + // Probe different methods to get interface name + var ifname = "" + for _, v := range []string{ + ifnparam, + os.Getenv("INTERFACE"), + os.Getenv("MDEV"), + os.Getenv("IFNAME"), + } { + if v != "" { + ifname = v + break + } + } + + if ifname == "" { + mainlog.Println("No interface name provided") + return + } + + var cif iface + if cif, err = New(ifname); err != nil { + mainlog.Println("Failed creating interface data:", err) + return + } + + var should bool + if should, err = cif.shouldRun(); err != nil { + mainlog.Println(err) + } + if !should { + mainlog.Println("Interface is already renamed, exiting") + return + } + + var nln string + if nln, err = cif.Process(); err != nil { + mainlog.Println("Failed to process interface:", err) + return + } + + if ifname == nln { + mainlog.Println("Interface already named correctly") + return + } + mainlog.Printf("Renaming %s to %s\n", ifname, nln) + + var l netlink.Link + if l, err = netlink.LinkByName(ifname); err != nil { + mainlog.Fatalln("Interface", ifname, "disappeared before it could be renamed") + } + if err = netlink.LinkSetName(l, nln); err != nil { + mainlog.Fatalf("Could not rename interface %s: %s\n", ifname, err) + } +} diff --git a/misc.go b/misc.go new file mode 100644 index 0000000..d418cdd --- /dev/null +++ b/misc.go @@ -0,0 +1,164 @@ +package main + +import ( + "errors" + "fmt" + "io" + "os" + "path/filepath" + "strconv" + "strings" +) + +const ( + PathProcPCI = iota + PathProcUSB +) + +var ( + ErrInvalidPCIFormat = errors.New("Invalid PCI address format") + ErrInvalidUSBFormat = errors.New("Invalid USB address format") +) + +var SYSFS = "/sys" + +// Sourced from include/uapi/linux/netdevice.h +// as of v6.8 +const ( + NET_NAME_UNKNOWN = 0 /* unknown origin (not exposed to userspace) */ + NET_NAME_ENUM = 1 /* enumerated by kernel */ + NET_NAME_PREDICTABLE = 2 /* predictably named by the kernel */ + NET_NAME_USER = 3 /* provided by user-space */ + NET_NAME_RENAMED = 4 /* renamed by user-space */ +) + +const ( + ClassEthernet = iota + ClassWireless +) + +type iface struct { + class int + orig string + path []string + pci, usb string +} + +func (i iface) String() string { + var pfx string + switch i.class { + case ClassEthernet: + pfx = "en" + case ClassWireless: + pfx = "wl" + } + return fmt.Sprintf("%s%s%s", pfx, i.pci, i.usb) +} + +func New(ifname string) (i iface, err error) { + i.orig = ifname + + spath := strings.Join([]string{SYSFS, "class/net", i.orig, "device"}, "/") + + var real string + if real, err = filepath.EvalSymlinks(spath); err != nil { + if errors.Is(err, os.ErrNotExist) { + err = fmt.Errorf("Interface %s isn't a device", i.orig) + return + } + err = fmt.Errorf("Failed to resolve symlink to device: %w", err) + return + } + + var devpath string + var ok bool + + sysdev := strings.Join([]string{SYSFS, "devices/"}, "/") + if devpath, ok = strings.CutPrefix(real, sysdev); !ok { + err = fmt.Errorf("Symlink doesn't point to %s\n", sysdev) + return + } + + i.path = strings.Split(devpath, "/") + + switch ifname[0] { + case 'e': + i.class = ClassEthernet + case 'w': + i.class = ClassWireless + } + return +} + +func (i iface) shouldRun() (should bool, err error) { + ifname_assign_type := strings.Join([]string{SYSFS, "class/net", i.orig, "name_assign_type"}, "/") + should = true + + var ( + file *os.File + contents []byte + ) + + if file, err = os.Open(ifname_assign_type); err != nil { + err = fmt.Errorf("Failed to open interface rename property: %w", err) + } else { + if contents, err = io.ReadAll(file); err != nil { + err = fmt.Errorf("Failed to read interface rename property: %w", err) + } else { + file.Close() + num, _ := strings.CutSuffix(string(contents), "\n") + + var res int + if res, err = strconv.Atoi(num); err != nil { + err = fmt.Errorf("Failed to interpret interface rename property as number: %w", err) + } else { + if res != NET_NAME_ENUM { + should = false + return + } + } + } + } + return +} + +func (i iface) Process() (nif string, err error) { + var ( + procmode int + ) + + for _, v := range i.path { + if strings.HasPrefix(v, "pci") { + procmode = PathProcPCI + continue + } else if strings.HasPrefix(v, "usb") { + procmode = PathProcUSB + continue + } + + switch procmode { + case PathProcPCI: + { + var hold string + if hold, err = ProcPCI(v); err != nil { + continue + } + i.pci = hold + } + case PathProcUSB: + { + var hold string + if hold, err = ProcUSB(v); err != nil { + continue + } + i.usb = hold + } + } + } + nif = i.String() + // It can error but as long as we get a identifier along the path it's okay + if i.pci != "" { + err = nil + } + return +} diff --git a/pci.go b/pci.go new file mode 100644 index 0000000..9f3aa59 --- /dev/null +++ b/pci.go @@ -0,0 +1,17 @@ +package main + +import ( + "fmt" +) + +func ProcPCI(devpath string) (segment string, err error) { + var ( + domain, bus, device, function int + ) + if _, err = fmt.Sscanf(devpath, "%x:%x:%x.%x", &domain, &bus, &device, &function); err != nil { + err = ErrInvalidPCIFormat + return + } + segment = fmt.Sprintf("p%ds%df%d", bus, device, function) + return +} diff --git a/usb.go b/usb.go new file mode 100644 index 0000000..3ae6c67 --- /dev/null +++ b/usb.go @@ -0,0 +1,49 @@ +package main + +import ( + "fmt" + "strings" +) + +func ProcUSB(devpath string) (segment string, err error) { + var ( + bus, conf, iface int + port_path []int + work string + ) + + res := strings.Split(devpath, ":") + if len(res) != 2 { + err = ErrInvalidUSBFormat + return + } + + // Bus and ports + if _, err = fmt.Sscanf(res[0], "%d-%s", &bus, &work); err != nil { + err = ErrInvalidUSBFormat + return + } + + for _, v := range strings.Split(work, ".") { + var cp int + if _, err = fmt.Sscanf(v, "%d", &cp); err != nil { + err = ErrInvalidUSBFormat + return + } + port_path = append(port_path, cp) + } + + // Configuration and interface + if _, err = fmt.Sscanf(res[1], "%d.%d", &conf, &iface); err != nil { + err = ErrInvalidUSBFormat + return + } + + var b strings.Builder + for _, v := range port_path { + b.WriteString(fmt.Sprintf("u%d", v)) + } + b.WriteString(fmt.Sprintf("i%d", iface)) + segment = b.String() + return +}