From 09f4cc6fc3d431c67b8f035b3ba25de9d3ec5496 Mon Sep 17 00:00:00 2001 From: Giuseppe Scrivano Date: Wed, 23 Dec 2020 10:23:35 +0100 Subject: rootless: add function to retrieve uid mappings Signed-off-by: Giuseppe Scrivano --- pkg/rootless/rootless.go | 43 ++++++++++++++++++++++++++++++++++++++----- 1 file changed, 38 insertions(+), 5 deletions(-) (limited to 'pkg/rootless') diff --git a/pkg/rootless/rootless.go b/pkg/rootless/rootless.go index 2ba0f8e81..2894c043f 100644 --- a/pkg/rootless/rootless.go +++ b/pkg/rootless/rootless.go @@ -50,11 +50,29 @@ func TryJoinPauseProcess(pausePidPath string) (bool, int, error) { } var ( + uidMap []user.IDMap + uidMapError error + uidMapOnce sync.Once + gidMap []user.IDMap gidMapError error gidMapOnce sync.Once ) +// GetAvailableUidMap returns the UID mappings in the +// current user namespace. +func GetAvailableUidMap() ([]user.IDMap, error) { + uidMapOnce.Do(func() { + var err error + uidMap, err = user.ParseIDMapFile("/proc/self/uid_map") + if err != nil { + uidMapError = err + return + } + }) + return uidMap, uidMapError +} + // GetAvailableGidMap returns the GID mappings in the // current user namespace. func GetAvailableGidMap() ([]user.IDMap, error) { @@ -69,6 +87,25 @@ func GetAvailableGidMap() ([]user.IDMap, error) { return gidMap, gidMapError } +func countAvailableIDs(mappings []user.IDMap) int64 { + availableUids := int64(0) + for _, r := range mappings { + availableUids += r.Count + } + return availableUids +} + +// GetAvailableUids returns how many UIDs are available in the +// current user namespace. +func GetAvailableUids() (int64, error) { + uids, err := GetAvailableUidMap() + if err != nil { + return -1, err + } + + return countAvailableIDs(uids), nil +} + // GetAvailableGids returns how many GIDs are available in the // current user namespace. func GetAvailableGids() (int64, error) { @@ -77,9 +114,5 @@ func GetAvailableGids() (int64, error) { return -1, err } - availableGids := int64(0) - for _, r := range gids { - availableGids += r.Count - } - return availableGids, nil + return countAvailableIDs(gids), nil } -- cgit v1.2.3-54-g00ecf