github.com/zhuohuang-hust/src-cbuild@v0.0.0-20230105071821-c7aab3e7c840/mergeCode/runc/libcontainer/configs/config_unix.go (about)

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