safeopen.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. package hcsshim
  2. import (
  3. "errors"
  4. "io"
  5. "os"
  6. "path/filepath"
  7. "strings"
  8. "syscall"
  9. "unicode/utf16"
  10. "unsafe"
  11. winio "github.com/Microsoft/go-winio"
  12. )
  13. //sys ntCreateFile(handle *uintptr, accessMask uint32, oa *objectAttributes, iosb *ioStatusBlock, allocationSize *uint64, fileAttributes uint32, shareAccess uint32, createDisposition uint32, createOptions uint32, eaBuffer *byte, eaLength uint32) (status uint32) = ntdll.NtCreateFile
  14. //sys ntSetInformationFile(handle uintptr, iosb *ioStatusBlock, information uintptr, length uint32, class uint32) (status uint32) = ntdll.NtSetInformationFile
  15. //sys rtlNtStatusToDosError(status uint32) (winerr error) = ntdll.RtlNtStatusToDosErrorNoTeb
  16. //sys localAlloc(flags uint32, size int) (ptr uintptr) = kernel32.LocalAlloc
  17. //sys localFree(ptr uintptr) = kernel32.LocalFree
  18. type ioStatusBlock struct {
  19. Status, Information uintptr
  20. }
  21. type objectAttributes struct {
  22. Length uintptr
  23. RootDirectory uintptr
  24. ObjectName uintptr
  25. Attributes uintptr
  26. SecurityDescriptor uintptr
  27. SecurityQoS uintptr
  28. }
  29. type unicodeString struct {
  30. Length uint16
  31. MaximumLength uint16
  32. Buffer uintptr
  33. }
  34. type fileLinkInformation struct {
  35. ReplaceIfExists bool
  36. RootDirectory uintptr
  37. FileNameLength uint32
  38. FileName [1]uint16
  39. }
  40. type fileDispositionInformationEx struct {
  41. Flags uintptr
  42. }
  43. const (
  44. _FileLinkInformation = 11
  45. _FileDispositionInformationEx = 64
  46. _FILE_READ_ATTRIBUTES = 0x0080
  47. _FILE_WRITE_ATTRIBUTES = 0x0100
  48. _DELETE = 0x10000
  49. _FILE_OPEN = 1
  50. _FILE_CREATE = 2
  51. _FILE_DIRECTORY_FILE = 0x00000001
  52. _FILE_SYNCHRONOUS_IO_NONALERT = 0x00000020
  53. _FILE_DELETE_ON_CLOSE = 0x00001000
  54. _FILE_OPEN_FOR_BACKUP_INTENT = 0x00004000
  55. _FILE_OPEN_REPARSE_POINT = 0x00200000
  56. _FILE_DISPOSITION_DELETE = 0x00000001
  57. _OBJ_DONT_REPARSE = 0x1000
  58. _STATUS_REPARSE_POINT_ENCOUNTERED = 0xC000050B
  59. )
  60. func openRoot(path string) (*os.File, error) {
  61. longpath, err := makeLongAbsPath(path)
  62. if err != nil {
  63. return nil, err
  64. }
  65. return winio.OpenForBackup(longpath, syscall.GENERIC_READ, syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE|syscall.FILE_SHARE_DELETE, syscall.OPEN_EXISTING)
  66. }
  67. func ntRelativePath(path string) ([]uint16, error) {
  68. path = filepath.Clean(path)
  69. if strings.Contains(":", path) {
  70. // Since alternate data streams must follow the file they
  71. // are attached to, finding one here (out of order) is invalid.
  72. return nil, errors.New("path contains invalid character `:`")
  73. }
  74. fspath := filepath.FromSlash(path)
  75. if len(fspath) > 0 && fspath[0] == '\\' {
  76. return nil, errors.New("expected relative path")
  77. }
  78. path16 := utf16.Encode(([]rune)(fspath))
  79. if len(path16) > 32767 {
  80. return nil, syscall.ENAMETOOLONG
  81. }
  82. return path16, nil
  83. }
  84. // openRelativeInternal opens a relative path from the given root, failing if
  85. // any of the intermediate path components are reparse points.
  86. func openRelativeInternal(path string, root *os.File, accessMask uint32, shareFlags uint32, createDisposition uint32, flags uint32) (*os.File, error) {
  87. var (
  88. h uintptr
  89. iosb ioStatusBlock
  90. oa objectAttributes
  91. )
  92. path16, err := ntRelativePath(path)
  93. if err != nil {
  94. return nil, err
  95. }
  96. if root == nil || root.Fd() == 0 {
  97. return nil, errors.New("missing root directory")
  98. }
  99. upathBuffer := localAlloc(0, int(unsafe.Sizeof(unicodeString{}))+len(path16)*2)
  100. defer localFree(upathBuffer)
  101. upath := (*unicodeString)(unsafe.Pointer(upathBuffer))
  102. upath.Length = uint16(len(path16) * 2)
  103. upath.MaximumLength = upath.Length
  104. upath.Buffer = upathBuffer + unsafe.Sizeof(*upath)
  105. copy((*[32768]uint16)(unsafe.Pointer(upath.Buffer))[:], path16)
  106. oa.Length = unsafe.Sizeof(oa)
  107. oa.ObjectName = upathBuffer
  108. oa.RootDirectory = uintptr(root.Fd())
  109. oa.Attributes = _OBJ_DONT_REPARSE
  110. status := ntCreateFile(
  111. &h,
  112. accessMask|syscall.SYNCHRONIZE,
  113. &oa,
  114. &iosb,
  115. nil,
  116. 0,
  117. shareFlags,
  118. createDisposition,
  119. _FILE_OPEN_FOR_BACKUP_INTENT|_FILE_SYNCHRONOUS_IO_NONALERT|flags,
  120. nil,
  121. 0,
  122. )
  123. if status != 0 {
  124. return nil, rtlNtStatusToDosError(status)
  125. }
  126. fullPath, err := makeLongAbsPath(filepath.Join(root.Name(), path))
  127. if err != nil {
  128. syscall.Close(syscall.Handle(h))
  129. return nil, err
  130. }
  131. return os.NewFile(h, fullPath), nil
  132. }
  133. // openRelative opens a relative path from the given root, failing if
  134. // any of the intermediate path components are reparse points.
  135. func openRelative(path string, root *os.File, accessMask uint32, shareFlags uint32, createDisposition uint32, flags uint32) (*os.File, error) {
  136. f, err := openRelativeInternal(path, root, accessMask, shareFlags, createDisposition, flags)
  137. if err != nil {
  138. err = &os.PathError{Op: "open", Path: filepath.Join(root.Name(), path), Err: err}
  139. }
  140. return f, err
  141. }
  142. // linkRelative creates a hard link from oldname to newname (relative to oldroot
  143. // and newroot), failing if any of the intermediate path components are reparse
  144. // points.
  145. func linkRelative(oldname string, oldroot *os.File, newname string, newroot *os.File) error {
  146. // Open the old file.
  147. oldf, err := openRelativeInternal(
  148. oldname,
  149. oldroot,
  150. syscall.FILE_WRITE_ATTRIBUTES,
  151. syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE|syscall.FILE_SHARE_DELETE,
  152. _FILE_OPEN,
  153. 0,
  154. )
  155. if err != nil {
  156. return &os.LinkError{Op: "link", Old: filepath.Join(oldroot.Name(), oldname), New: filepath.Join(newroot.Name(), newname), Err: err}
  157. }
  158. defer oldf.Close()
  159. // Open the parent of the new file.
  160. var parent *os.File
  161. parentPath := filepath.Dir(newname)
  162. if parentPath != "." {
  163. parent, err = openRelativeInternal(
  164. parentPath,
  165. newroot,
  166. syscall.GENERIC_READ,
  167. syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE|syscall.FILE_SHARE_DELETE,
  168. _FILE_OPEN,
  169. _FILE_DIRECTORY_FILE)
  170. if err != nil {
  171. return &os.LinkError{Op: "link", Old: oldf.Name(), New: filepath.Join(newroot.Name(), newname), Err: err}
  172. }
  173. defer parent.Close()
  174. fi, err := winio.GetFileBasicInfo(parent)
  175. if err != nil {
  176. return err
  177. }
  178. if (fi.FileAttributes & syscall.FILE_ATTRIBUTE_REPARSE_POINT) != 0 {
  179. return &os.LinkError{Op: "link", Old: oldf.Name(), New: filepath.Join(newroot.Name(), newname), Err: rtlNtStatusToDosError(_STATUS_REPARSE_POINT_ENCOUNTERED)}
  180. }
  181. } else {
  182. parent = newroot
  183. }
  184. // Issue an NT call to create the link. This will be safe because NT will
  185. // not open any more directories to create the link, so it cannot walk any
  186. // more reparse points.
  187. newbase := filepath.Base(newname)
  188. newbase16, err := ntRelativePath(newbase)
  189. if err != nil {
  190. return err
  191. }
  192. size := int(unsafe.Offsetof(fileLinkInformation{}.FileName)) + len(newbase16)*2
  193. linkinfoBuffer := localAlloc(0, size)
  194. defer localFree(linkinfoBuffer)
  195. linkinfo := (*fileLinkInformation)(unsafe.Pointer(linkinfoBuffer))
  196. linkinfo.RootDirectory = parent.Fd()
  197. linkinfo.FileNameLength = uint32(len(newbase16) * 2)
  198. copy((*[32768]uint16)(unsafe.Pointer(&linkinfo.FileName[0]))[:], newbase16)
  199. var iosb ioStatusBlock
  200. status := ntSetInformationFile(
  201. oldf.Fd(),
  202. &iosb,
  203. linkinfoBuffer,
  204. uint32(size),
  205. _FileLinkInformation,
  206. )
  207. if status != 0 {
  208. return &os.LinkError{Op: "link", Old: oldf.Name(), New: filepath.Join(parent.Name(), newbase), Err: rtlNtStatusToDosError(status)}
  209. }
  210. return nil
  211. }
  212. // deleteOnClose marks a file to be deleted when the handle is closed.
  213. func deleteOnClose(f *os.File) error {
  214. disposition := fileDispositionInformationEx{Flags: _FILE_DISPOSITION_DELETE}
  215. var iosb ioStatusBlock
  216. status := ntSetInformationFile(
  217. f.Fd(),
  218. &iosb,
  219. uintptr(unsafe.Pointer(&disposition)),
  220. uint32(unsafe.Sizeof(disposition)),
  221. _FileDispositionInformationEx,
  222. )
  223. if status != 0 {
  224. return rtlNtStatusToDosError(status)
  225. }
  226. return nil
  227. }
  228. // clearReadOnly clears the readonly attribute on a file.
  229. func clearReadOnly(f *os.File) error {
  230. bi, err := winio.GetFileBasicInfo(f)
  231. if err != nil {
  232. return err
  233. }
  234. if bi.FileAttributes&syscall.FILE_ATTRIBUTE_READONLY == 0 {
  235. return nil
  236. }
  237. sbi := winio.FileBasicInfo{
  238. FileAttributes: bi.FileAttributes &^ syscall.FILE_ATTRIBUTE_READONLY,
  239. }
  240. if sbi.FileAttributes == 0 {
  241. sbi.FileAttributes = syscall.FILE_ATTRIBUTE_NORMAL
  242. }
  243. return winio.SetFileBasicInfo(f, &sbi)
  244. }
  245. // removeRelative removes a file or directory relative to a root, failing if any
  246. // intermediate path components are reparse points.
  247. func removeRelative(path string, root *os.File) error {
  248. f, err := openRelativeInternal(
  249. path,
  250. root,
  251. _FILE_READ_ATTRIBUTES|_FILE_WRITE_ATTRIBUTES|_DELETE,
  252. syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE|syscall.FILE_SHARE_DELETE,
  253. _FILE_OPEN,
  254. _FILE_OPEN_REPARSE_POINT)
  255. if err == nil {
  256. defer f.Close()
  257. err = deleteOnClose(f)
  258. if err == syscall.ERROR_ACCESS_DENIED {
  259. // Maybe the file is marked readonly. Clear the bit and retry.
  260. clearReadOnly(f)
  261. err = deleteOnClose(f)
  262. }
  263. }
  264. if err != nil {
  265. return &os.PathError{Op: "remove", Path: filepath.Join(root.Name(), path), Err: err}
  266. }
  267. return nil
  268. }
  269. // removeAllRelative removes a directory tree relative to a root, failing if any
  270. // intermediate path components are reparse points.
  271. func removeAllRelative(path string, root *os.File) error {
  272. fi, err := lstatRelative(path, root)
  273. if err != nil {
  274. if os.IsNotExist(err) {
  275. return nil
  276. }
  277. return err
  278. }
  279. fileAttributes := fi.Sys().(*syscall.Win32FileAttributeData).FileAttributes
  280. if fileAttributes&syscall.FILE_ATTRIBUTE_DIRECTORY == 0 || fileAttributes&syscall.FILE_ATTRIBUTE_REPARSE_POINT != 0 {
  281. // If this is a reparse point, it can't have children. Simple remove will do.
  282. err := removeRelative(path, root)
  283. if err == nil || os.IsNotExist(err) {
  284. return nil
  285. }
  286. return err
  287. }
  288. // It is necessary to use os.Open as Readdirnames does not work with
  289. // openRelative. This is safe because the above lstatrelative fails
  290. // if the target is outside the root, and we know this is not a
  291. // symlink from the above FILE_ATTRIBUTE_REPARSE_POINT check.
  292. fd, err := os.Open(filepath.Join(root.Name(), path))
  293. if err != nil {
  294. if os.IsNotExist(err) {
  295. // Race. It was deleted between the Lstat and Open.
  296. // Return nil per RemoveAll's docs.
  297. return nil
  298. }
  299. return err
  300. }
  301. // Remove contents & return first error.
  302. for {
  303. names, err1 := fd.Readdirnames(100)
  304. for _, name := range names {
  305. err1 := removeAllRelative(path+string(os.PathSeparator)+name, root)
  306. if err == nil {
  307. err = err1
  308. }
  309. }
  310. if err1 == io.EOF {
  311. break
  312. }
  313. // If Readdirnames returned an error, use it.
  314. if err == nil {
  315. err = err1
  316. }
  317. if len(names) == 0 {
  318. break
  319. }
  320. }
  321. fd.Close()
  322. // Remove directory.
  323. err1 := removeRelative(path, root)
  324. if err1 == nil || os.IsNotExist(err1) {
  325. return nil
  326. }
  327. if err == nil {
  328. err = err1
  329. }
  330. return err
  331. }
  332. // mkdirRelative creates a directory relative to a root, failing if any
  333. // intermediate path components are reparse points.
  334. func mkdirRelative(path string, root *os.File) error {
  335. f, err := openRelativeInternal(
  336. path,
  337. root,
  338. 0,
  339. syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE|syscall.FILE_SHARE_DELETE,
  340. _FILE_CREATE,
  341. _FILE_DIRECTORY_FILE)
  342. if err == nil {
  343. f.Close()
  344. } else {
  345. err = &os.PathError{Op: "mkdir", Path: filepath.Join(root.Name(), path), Err: err}
  346. }
  347. return err
  348. }
  349. // lstatRelative performs a stat operation on a file relative to a root, failing
  350. // if any intermediate path components are reparse points.
  351. func lstatRelative(path string, root *os.File) (os.FileInfo, error) {
  352. f, err := openRelativeInternal(
  353. path,
  354. root,
  355. _FILE_READ_ATTRIBUTES,
  356. syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE|syscall.FILE_SHARE_DELETE,
  357. _FILE_OPEN,
  358. _FILE_OPEN_REPARSE_POINT)
  359. if err != nil {
  360. return nil, &os.PathError{Op: "stat", Path: filepath.Join(root.Name(), path), Err: err}
  361. }
  362. defer f.Close()
  363. return f.Stat()
  364. }
  365. // ensureNotReparsePointRelative validates that a given file (relative to a
  366. // root) and all intermediate path components are not a reparse points.
  367. func ensureNotReparsePointRelative(path string, root *os.File) error {
  368. // Perform an open with OBJ_DONT_REPARSE but without specifying FILE_OPEN_REPARSE_POINT.
  369. f, err := openRelative(
  370. path,
  371. root,
  372. 0,
  373. syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE|syscall.FILE_SHARE_DELETE,
  374. _FILE_OPEN,
  375. 0)
  376. if err != nil {
  377. return err
  378. }
  379. f.Close()
  380. return nil
  381. }