config_linux.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package configs
  2. import "errors"
  3. var (
  4. errNoUIDMap = errors.New("User namespaces enabled, but no uid mappings found.")
  5. errNoUserMap = errors.New("User namespaces enabled, but no user mapping found.")
  6. errNoGIDMap = errors.New("User namespaces enabled, but no gid mappings found.")
  7. errNoGroupMap = errors.New("User namespaces enabled, but no group mapping found.")
  8. )
  9. // HostUID gets the translated uid for the process on host which could be
  10. // different when user namespaces are enabled.
  11. func (c Config) HostUID(containerId int) (int, error) {
  12. if c.Namespaces.Contains(NEWUSER) {
  13. if c.UidMappings == nil {
  14. return -1, errNoUIDMap
  15. }
  16. id, found := c.hostIDFromMapping(containerId, c.UidMappings)
  17. if !found {
  18. return -1, errNoUserMap
  19. }
  20. return id, nil
  21. }
  22. // Return unchanged id.
  23. return containerId, nil
  24. }
  25. // HostRootUID gets the root uid for the process on host which could be non-zero
  26. // when user namespaces are enabled.
  27. func (c Config) HostRootUID() (int, error) {
  28. return c.HostUID(0)
  29. }
  30. // HostGID gets the translated gid for the process on host which could be
  31. // different when user namespaces are enabled.
  32. func (c Config) HostGID(containerId int) (int, error) {
  33. if c.Namespaces.Contains(NEWUSER) {
  34. if c.GidMappings == nil {
  35. return -1, errNoGIDMap
  36. }
  37. id, found := c.hostIDFromMapping(containerId, c.GidMappings)
  38. if !found {
  39. return -1, errNoGroupMap
  40. }
  41. return id, nil
  42. }
  43. // Return unchanged id.
  44. return containerId, nil
  45. }
  46. // HostRootGID gets the root gid for the process on host which could be non-zero
  47. // when user namespaces are enabled.
  48. func (c Config) HostRootGID() (int, error) {
  49. return c.HostGID(0)
  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.
  53. func (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. }