1package configs
2
3import "fmt"
4
5// HostUID gets the translated uid for the process on host which could be
6// different when user namespaces are enabled.
7func (c Config) HostUID(containerId int) (int, error) {
8	if c.Namespaces.Contains(NEWUSER) {
9		if c.UidMappings == nil {
10			return -1, fmt.Errorf("User namespaces enabled, but no uid mappings found.")
11		}
12		id, found := c.hostIDFromMapping(containerId, c.UidMappings)
13		if !found {
14			return -1, fmt.Errorf("User namespaces enabled, but no user mapping found.")
15		}
16		return id, nil
17	}
18	// Return unchanged id.
19	return containerId, nil
20}
21
22// HostRootUID gets the root uid for the process on host which could be non-zero
23// when user namespaces are enabled.
24func (c Config) HostRootUID() (int, error) {
25	return c.HostUID(0)
26}
27
28// HostGID gets the translated gid for the process on host which could be
29// different when user namespaces are enabled.
30func (c Config) HostGID(containerId int) (int, error) {
31	if c.Namespaces.Contains(NEWUSER) {
32		if c.GidMappings == nil {
33			return -1, fmt.Errorf("User namespaces enabled, but no gid mappings found.")
34		}
35		id, found := c.hostIDFromMapping(containerId, c.GidMappings)
36		if !found {
37			return -1, fmt.Errorf("User namespaces enabled, but no group mapping found.")
38		}
39		return id, nil
40	}
41	// Return unchanged id.
42	return containerId, nil
43}
44
45// HostRootGID gets the root gid for the process on host which could be non-zero
46// when user namespaces are enabled.
47func (c Config) HostRootGID() (int, error) {
48	return c.HostGID(0)
49}
50
51// Utility function that gets a host ID for a container ID from user namespace map
52// if that ID is present in the map.
53func (c Config) hostIDFromMapping(containerID int, uMap []IDMap) (int, bool) {
54	for _, m := range uMap {
55		if (containerID >= m.ContainerID) && (containerID <= (m.ContainerID + m.Size - 1)) {
56			hostID := m.HostID + (containerID - m.ContainerID)
57			return hostID, true
58		}
59	}
60	return -1, false
61}
62