From 35c56d3f98e4394d37151fd62630b797434aa3ad Mon Sep 17 00:00:00 2001 From: brent saner Date: Tue, 7 Oct 2025 17:11:37 -0400 Subject: [PATCH] v1.14.3 ADDED: * Convenience function to return a namespace FD and its type from a namespace ID (Linux only) --- errs/errs_linux.go | 9 +++++++++ funcs_linux.go | 35 +++++++++++++++++++++++++++++++---- 2 files changed, 40 insertions(+), 4 deletions(-) create mode 100644 errs/errs_linux.go diff --git a/errs/errs_linux.go b/errs/errs_linux.go new file mode 100644 index 0000000..4c13a46 --- /dev/null +++ b/errs/errs_linux.go @@ -0,0 +1,9 @@ +package errs + +import ( + "errors" +) + +var ( + ErrInvalidNs error = errors.New("invalid namespace identifier") +) diff --git a/funcs_linux.go b/funcs_linux.go index 8de6194..934c450 100644 --- a/funcs_linux.go +++ b/funcs_linux.go @@ -1,11 +1,14 @@ package sysutils import ( - `fmt` - `os` + "fmt" + "os" + "strconv" + "strings" - `golang.org/x/sys/unix` - `r00t2.io/sysutils/envs` + "golang.org/x/sys/unix" + "r00t2.io/sysutils/envs" + "r00t2.io/sysutils/errs" ) // GetIDState returns current ID/elevation information. An IDState should *not* be explicitly created/defined. @@ -48,3 +51,27 @@ func GetIDState() (ids IDState) { return } + +// NsToFD splits a namespace identifier (e.g. `net:[12345]`) to its type (e.g. `net`) and FD (e.g. `12345`). +func NsToFD(ns string) (typ string, fd uint64, err error) { + + var fields []string + + fields = strings.SplitN(ns, ":", 2) + + if len(fields) != 2 { + err = errs.ErrInvalidNs + return + } + + fields[1] = strings.TrimPrefix(fields[1], "[") + fields[1] = strings.TrimSuffix(fields[1], "]") + + if fd, err = strconv.ParseUint(fields[1], 10, 64); err != nil { + return + } + + typ = fields[0] + + return +}