idtools_unix.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. // +build !windows
  2. package idtools
  3. import (
  4. "bytes"
  5. "fmt"
  6. "io"
  7. "os"
  8. "path/filepath"
  9. "strings"
  10. "sync"
  11. "syscall"
  12. "github.com/docker/docker/pkg/system"
  13. "github.com/opencontainers/runc/libcontainer/user"
  14. )
  15. var (
  16. entOnce sync.Once
  17. getentCmd string
  18. )
  19. func mkdirAs(path string, mode os.FileMode, ownerUID, ownerGID int, mkAll, chownExisting bool) error {
  20. // make an array containing the original path asked for, plus (for mkAll == true)
  21. // all path components leading up to the complete path that don't exist before we MkdirAll
  22. // so that we can chown all of them properly at the end. If chownExisting is false, we won't
  23. // chown the full directory path if it exists
  24. var paths []string
  25. stat, err := system.Stat(path)
  26. if err == nil {
  27. if !stat.IsDir() {
  28. return &os.PathError{Op: "mkdir", Path: path, Err: syscall.ENOTDIR}
  29. }
  30. if !chownExisting {
  31. return nil
  32. }
  33. // short-circuit--we were called with an existing directory and chown was requested
  34. return lazyChown(path, ownerUID, ownerGID, stat)
  35. }
  36. if os.IsNotExist(err) {
  37. paths = []string{path}
  38. }
  39. if mkAll {
  40. // walk back to "/" looking for directories which do not exist
  41. // and add them to the paths array for chown after creation
  42. dirPath := path
  43. for {
  44. dirPath = filepath.Dir(dirPath)
  45. if dirPath == "/" {
  46. break
  47. }
  48. if _, err := os.Stat(dirPath); err != nil && os.IsNotExist(err) {
  49. paths = append(paths, dirPath)
  50. }
  51. }
  52. if err := system.MkdirAll(path, mode, ""); err != nil {
  53. return err
  54. }
  55. } else {
  56. if err := os.Mkdir(path, mode); err != nil && !os.IsExist(err) {
  57. return err
  58. }
  59. }
  60. // even if it existed, we will chown the requested path + any subpaths that
  61. // didn't exist when we called MkdirAll
  62. for _, pathComponent := range paths {
  63. if err := lazyChown(pathComponent, ownerUID, ownerGID, nil); err != nil {
  64. return err
  65. }
  66. }
  67. return nil
  68. }
  69. // CanAccess takes a valid (existing) directory and a uid, gid pair and determines
  70. // if that uid, gid pair has access (execute bit) to the directory
  71. func CanAccess(path string, pair IDPair) bool {
  72. statInfo, err := system.Stat(path)
  73. if err != nil {
  74. return false
  75. }
  76. fileMode := os.FileMode(statInfo.Mode())
  77. permBits := fileMode.Perm()
  78. return accessible(statInfo.UID() == uint32(pair.UID),
  79. statInfo.GID() == uint32(pair.GID), permBits)
  80. }
  81. func accessible(isOwner, isGroup bool, perms os.FileMode) bool {
  82. if isOwner && (perms&0100 == 0100) {
  83. return true
  84. }
  85. if isGroup && (perms&0010 == 0010) {
  86. return true
  87. }
  88. if perms&0001 == 0001 {
  89. return true
  90. }
  91. return false
  92. }
  93. // LookupUser uses traditional local system files lookup (from libcontainer/user) on a username,
  94. // followed by a call to `getent` for supporting host configured non-files passwd and group dbs
  95. func LookupUser(username string) (user.User, error) {
  96. // first try a local system files lookup using existing capabilities
  97. usr, err := user.LookupUser(username)
  98. if err == nil {
  99. return usr, nil
  100. }
  101. // local files lookup failed; attempt to call `getent` to query configured passwd dbs
  102. usr, err = getentUser(fmt.Sprintf("%s %s", "passwd", username))
  103. if err != nil {
  104. return user.User{}, err
  105. }
  106. return usr, nil
  107. }
  108. // LookupUID uses traditional local system files lookup (from libcontainer/user) on a uid,
  109. // followed by a call to `getent` for supporting host configured non-files passwd and group dbs
  110. func LookupUID(uid int) (user.User, error) {
  111. // first try a local system files lookup using existing capabilities
  112. usr, err := user.LookupUid(uid)
  113. if err == nil {
  114. return usr, nil
  115. }
  116. // local files lookup failed; attempt to call `getent` to query configured passwd dbs
  117. return getentUser(fmt.Sprintf("%s %d", "passwd", uid))
  118. }
  119. func getentUser(args string) (user.User, error) {
  120. reader, err := callGetent(args)
  121. if err != nil {
  122. return user.User{}, err
  123. }
  124. users, err := user.ParsePasswd(reader)
  125. if err != nil {
  126. return user.User{}, err
  127. }
  128. if len(users) == 0 {
  129. return user.User{}, fmt.Errorf("getent failed to find passwd entry for %q", strings.Split(args, " ")[1])
  130. }
  131. return users[0], nil
  132. }
  133. // LookupGroup uses traditional local system files lookup (from libcontainer/user) on a group name,
  134. // followed by a call to `getent` for supporting host configured non-files passwd and group dbs
  135. func LookupGroup(groupname string) (user.Group, error) {
  136. // first try a local system files lookup using existing capabilities
  137. group, err := user.LookupGroup(groupname)
  138. if err == nil {
  139. return group, nil
  140. }
  141. // local files lookup failed; attempt to call `getent` to query configured group dbs
  142. return getentGroup(fmt.Sprintf("%s %s", "group", groupname))
  143. }
  144. // LookupGID uses traditional local system files lookup (from libcontainer/user) on a group ID,
  145. // followed by a call to `getent` for supporting host configured non-files passwd and group dbs
  146. func LookupGID(gid int) (user.Group, error) {
  147. // first try a local system files lookup using existing capabilities
  148. group, err := user.LookupGid(gid)
  149. if err == nil {
  150. return group, nil
  151. }
  152. // local files lookup failed; attempt to call `getent` to query configured group dbs
  153. return getentGroup(fmt.Sprintf("%s %d", "group", gid))
  154. }
  155. func getentGroup(args string) (user.Group, error) {
  156. reader, err := callGetent(args)
  157. if err != nil {
  158. return user.Group{}, err
  159. }
  160. groups, err := user.ParseGroup(reader)
  161. if err != nil {
  162. return user.Group{}, err
  163. }
  164. if len(groups) == 0 {
  165. return user.Group{}, fmt.Errorf("getent failed to find groups entry for %q", strings.Split(args, " ")[1])
  166. }
  167. return groups[0], nil
  168. }
  169. func callGetent(args string) (io.Reader, error) {
  170. entOnce.Do(func() { getentCmd, _ = resolveBinary("getent") })
  171. // if no `getent` command on host, can't do anything else
  172. if getentCmd == "" {
  173. return nil, fmt.Errorf("")
  174. }
  175. out, err := execCmd(getentCmd, args)
  176. if err != nil {
  177. exitCode, errC := system.GetExitCode(err)
  178. if errC != nil {
  179. return nil, err
  180. }
  181. switch exitCode {
  182. case 1:
  183. return nil, fmt.Errorf("getent reported invalid parameters/database unknown")
  184. case 2:
  185. terms := strings.Split(args, " ")
  186. return nil, fmt.Errorf("getent unable to find entry %q in %s database", terms[1], terms[0])
  187. case 3:
  188. return nil, fmt.Errorf("getent database doesn't support enumeration")
  189. default:
  190. return nil, err
  191. }
  192. }
  193. return bytes.NewReader(out), nil
  194. }
  195. // lazyChown performs a chown only if the uid/gid don't match what's requested
  196. // Normally a Chown is a no-op if uid/gid match, but in some cases this can still cause an error, e.g. if the
  197. // dir is on an NFS share, so don't call chown unless we absolutely must.
  198. func lazyChown(p string, uid, gid int, stat *system.StatT) error {
  199. if stat == nil {
  200. var err error
  201. stat, err = system.Stat(p)
  202. if err != nil {
  203. return err
  204. }
  205. }
  206. if stat.UID() == uint32(uid) && stat.GID() == uint32(gid) {
  207. return nil
  208. }
  209. return os.Chown(p, uid, gid)
  210. }