filesys_windows.go 9.1 KB

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