filesys_windows.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. package system // import "github.com/docker/docker/pkg/system"
  2. import (
  3. "os"
  4. "path/filepath"
  5. "regexp"
  6. "strconv"
  7. "strings"
  8. "sync"
  9. "syscall"
  10. "time"
  11. "unsafe"
  12. winio "github.com/Microsoft/go-winio"
  13. "golang.org/x/sys/windows"
  14. )
  15. const (
  16. // SddlAdministratorsLocalSystem is local administrators plus NT AUTHORITY\System
  17. SddlAdministratorsLocalSystem = "D:P(A;OICI;GA;;;BA)(A;OICI;GA;;;SY)"
  18. )
  19. // MkdirAllWithACL is a wrapper for MkdirAll that creates a directory
  20. // with an appropriate SDDL defined ACL.
  21. func MkdirAllWithACL(path string, perm os.FileMode, sddl string) error {
  22. return mkdirall(path, true, sddl)
  23. }
  24. // MkdirAll implementation that is volume path aware for Windows.
  25. func MkdirAll(path string, _ os.FileMode, sddl string) error {
  26. return mkdirall(path, false, sddl)
  27. }
  28. // mkdirall is a custom version of os.MkdirAll modified for use on Windows
  29. // so that it is both volume path aware, and can create a directory with
  30. // a DACL.
  31. func mkdirall(path string, applyACL bool, sddl string) error {
  32. if re := regexp.MustCompile(`^\\\\\?\\Volume{[a-z0-9-]+}$`); re.MatchString(path) {
  33. return nil
  34. }
  35. // The rest of this method is largely copied from os.MkdirAll and should be kept
  36. // as-is to ensure compatibility.
  37. // Fast path: if we can tell whether path is a directory or file, stop with success or error.
  38. dir, err := os.Stat(path)
  39. if err == nil {
  40. if dir.IsDir() {
  41. return nil
  42. }
  43. return &os.PathError{
  44. Op: "mkdir",
  45. Path: path,
  46. Err: syscall.ENOTDIR,
  47. }
  48. }
  49. // Slow path: make sure parent exists and then call Mkdir for path.
  50. i := len(path)
  51. for i > 0 && os.IsPathSeparator(path[i-1]) { // Skip trailing path separator.
  52. i--
  53. }
  54. j := i
  55. for j > 0 && !os.IsPathSeparator(path[j-1]) { // Scan backward over element.
  56. j--
  57. }
  58. if j > 1 {
  59. // Create parent
  60. err = mkdirall(path[0:j-1], false, sddl)
  61. if err != nil {
  62. return err
  63. }
  64. }
  65. // Parent now exists; invoke os.Mkdir or mkdirWithACL and use its result.
  66. if applyACL {
  67. err = mkdirWithACL(path, sddl)
  68. } else {
  69. err = os.Mkdir(path, 0)
  70. }
  71. if err != nil {
  72. // Handle arguments like "foo/." by
  73. // double-checking that directory doesn't exist.
  74. dir, err1 := os.Lstat(path)
  75. if err1 == nil && dir.IsDir() {
  76. return nil
  77. }
  78. return err
  79. }
  80. return nil
  81. }
  82. // mkdirWithACL creates a new directory. If there is an error, it will be of
  83. // type *PathError. .
  84. //
  85. // This is a modified and combined version of os.Mkdir and windows.Mkdir
  86. // in golang to cater for creating a directory am ACL permitting full
  87. // access, with inheritance, to any subfolder/file for Built-in Administrators
  88. // and Local System.
  89. func mkdirWithACL(name string, sddl string) error {
  90. sa := windows.SecurityAttributes{Length: 0}
  91. sd, err := winio.SddlToSecurityDescriptor(sddl)
  92. if err != nil {
  93. return &os.PathError{Op: "mkdir", Path: name, Err: err}
  94. }
  95. sa.Length = uint32(unsafe.Sizeof(sa))
  96. sa.InheritHandle = 1
  97. sa.SecurityDescriptor = uintptr(unsafe.Pointer(&sd[0]))
  98. namep, err := windows.UTF16PtrFromString(name)
  99. if err != nil {
  100. return &os.PathError{Op: "mkdir", Path: name, Err: err}
  101. }
  102. e := windows.CreateDirectory(namep, &sa)
  103. if e != nil {
  104. return &os.PathError{Op: "mkdir", Path: name, Err: e}
  105. }
  106. return nil
  107. }
  108. // IsAbs is a platform-specific wrapper for filepath.IsAbs. On Windows,
  109. // golang filepath.IsAbs does not consider a path \windows\system32 as absolute
  110. // as it doesn't start with a drive-letter/colon combination. However, in
  111. // docker we need to verify things such as WORKDIR /windows/system32 in
  112. // a Dockerfile (which gets translated to \windows\system32 when being processed
  113. // by the daemon. This SHOULD be treated as absolute from a docker processing
  114. // perspective.
  115. func IsAbs(path string) bool {
  116. if !filepath.IsAbs(path) {
  117. if !strings.HasPrefix(path, string(os.PathSeparator)) {
  118. return false
  119. }
  120. }
  121. return true
  122. }
  123. // The origin of the functions below here are the golang OS and windows packages,
  124. // slightly modified to only cope with files, not directories due to the
  125. // specific use case.
  126. //
  127. // The alteration is to allow a file on Windows to be opened with
  128. // FILE_FLAG_SEQUENTIAL_SCAN (particular for docker load), to avoid eating
  129. // the standby list, particularly when accessing large files such as layer.tar.
  130. // CreateSequential creates the named file with mode 0666 (before umask), truncating
  131. // it if it already exists. If successful, methods on the returned
  132. // File can be used for I/O; the associated file descriptor has mode
  133. // O_RDWR.
  134. // If there is an error, it will be of type *PathError.
  135. func CreateSequential(name string) (*os.File, error) {
  136. return OpenFileSequential(name, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0)
  137. }
  138. // OpenSequential opens the named file for reading. If successful, methods on
  139. // the returned file can be used for reading; the associated file
  140. // descriptor has mode O_RDONLY.
  141. // If there is an error, it will be of type *PathError.
  142. func OpenSequential(name string) (*os.File, error) {
  143. return OpenFileSequential(name, os.O_RDONLY, 0)
  144. }
  145. // OpenFileSequential is the generalized open call; most users will use Open
  146. // or Create instead.
  147. // If there is an error, it will be of type *PathError.
  148. func OpenFileSequential(name string, flag int, _ os.FileMode) (*os.File, error) {
  149. if name == "" {
  150. return nil, &os.PathError{Op: "open", Path: name, Err: syscall.ENOENT}
  151. }
  152. r, errf := windowsOpenFileSequential(name, flag, 0)
  153. if errf == nil {
  154. return r, nil
  155. }
  156. return nil, &os.PathError{Op: "open", Path: name, Err: errf}
  157. }
  158. func windowsOpenFileSequential(name string, flag int, _ os.FileMode) (file *os.File, err error) {
  159. r, e := windowsOpenSequential(name, flag|windows.O_CLOEXEC, 0)
  160. if e != nil {
  161. return nil, e
  162. }
  163. return os.NewFile(uintptr(r), name), nil
  164. }
  165. func makeInheritSa() *windows.SecurityAttributes {
  166. var sa windows.SecurityAttributes
  167. sa.Length = uint32(unsafe.Sizeof(sa))
  168. sa.InheritHandle = 1
  169. return &sa
  170. }
  171. func windowsOpenSequential(path string, mode int, _ uint32) (fd windows.Handle, err error) {
  172. if len(path) == 0 {
  173. return windows.InvalidHandle, windows.ERROR_FILE_NOT_FOUND
  174. }
  175. pathp, err := windows.UTF16PtrFromString(path)
  176. if err != nil {
  177. return windows.InvalidHandle, err
  178. }
  179. var access uint32
  180. switch mode & (windows.O_RDONLY | windows.O_WRONLY | windows.O_RDWR) {
  181. case windows.O_RDONLY:
  182. access = windows.GENERIC_READ
  183. case windows.O_WRONLY:
  184. access = windows.GENERIC_WRITE
  185. case windows.O_RDWR:
  186. access = windows.GENERIC_READ | windows.GENERIC_WRITE
  187. }
  188. if mode&windows.O_CREAT != 0 {
  189. access |= windows.GENERIC_WRITE
  190. }
  191. if mode&windows.O_APPEND != 0 {
  192. access &^= windows.GENERIC_WRITE
  193. access |= windows.FILE_APPEND_DATA
  194. }
  195. sharemode := uint32(windows.FILE_SHARE_READ | windows.FILE_SHARE_WRITE)
  196. var sa *windows.SecurityAttributes
  197. if mode&windows.O_CLOEXEC == 0 {
  198. sa = makeInheritSa()
  199. }
  200. var createmode uint32
  201. switch {
  202. case mode&(windows.O_CREAT|windows.O_EXCL) == (windows.O_CREAT | windows.O_EXCL):
  203. createmode = windows.CREATE_NEW
  204. case mode&(windows.O_CREAT|windows.O_TRUNC) == (windows.O_CREAT | windows.O_TRUNC):
  205. createmode = windows.CREATE_ALWAYS
  206. case mode&windows.O_CREAT == windows.O_CREAT:
  207. createmode = windows.OPEN_ALWAYS
  208. case mode&windows.O_TRUNC == windows.O_TRUNC:
  209. createmode = windows.TRUNCATE_EXISTING
  210. default:
  211. createmode = windows.OPEN_EXISTING
  212. }
  213. // Use FILE_FLAG_SEQUENTIAL_SCAN rather than FILE_ATTRIBUTE_NORMAL as implemented in golang.
  214. //https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx
  215. const fileFlagSequentialScan = 0x08000000 // FILE_FLAG_SEQUENTIAL_SCAN
  216. h, e := windows.CreateFile(pathp, access, sharemode, sa, createmode, fileFlagSequentialScan, 0)
  217. return h, e
  218. }
  219. // Helpers for TempFileSequential
  220. var rand uint32
  221. var randmu sync.Mutex
  222. func reseed() uint32 {
  223. return uint32(time.Now().UnixNano() + int64(os.Getpid()))
  224. }
  225. func nextSuffix() string {
  226. randmu.Lock()
  227. r := rand
  228. if r == 0 {
  229. r = reseed()
  230. }
  231. r = r*1664525 + 1013904223 // constants from Numerical Recipes
  232. rand = r
  233. randmu.Unlock()
  234. return strconv.Itoa(int(1e9 + r%1e9))[1:]
  235. }
  236. // TempFileSequential is a copy of ioutil.TempFile, modified to use sequential
  237. // file access. Below is the original comment from golang:
  238. // TempFile creates a new temporary file in the directory dir
  239. // with a name beginning with prefix, opens the file for reading
  240. // and writing, and returns the resulting *os.File.
  241. // If dir is the empty string, TempFile uses the default directory
  242. // for temporary files (see os.TempDir).
  243. // Multiple programs calling TempFile simultaneously
  244. // will not choose the same file. The caller can use f.Name()
  245. // to find the pathname of the file. It is the caller's responsibility
  246. // to remove the file when no longer needed.
  247. func TempFileSequential(dir, prefix string) (f *os.File, err error) {
  248. if dir == "" {
  249. dir = os.TempDir()
  250. }
  251. nconflict := 0
  252. for i := 0; i < 10000; i++ {
  253. name := filepath.Join(dir, prefix+nextSuffix())
  254. f, err = OpenFileSequential(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600)
  255. if os.IsExist(err) {
  256. if nconflict++; nconflict > 10 {
  257. randmu.Lock()
  258. rand = reseed()
  259. randmu.Unlock()
  260. }
  261. continue
  262. }
  263. break
  264. }
  265. return
  266. }