config_unix.go 1.9 KB

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