basicfs_windows.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. //go:build windows
  7. // +build windows
  8. package fs
  9. import (
  10. "bytes"
  11. "errors"
  12. "os"
  13. "path/filepath"
  14. "strings"
  15. "syscall"
  16. "unsafe"
  17. )
  18. var errNotSupported = errors.New("symlinks not supported")
  19. func (BasicFilesystem) SymlinksSupported() bool {
  20. return false
  21. }
  22. func (BasicFilesystem) ReadSymlink(path string) (string, error) {
  23. return "", errNotSupported
  24. }
  25. func (BasicFilesystem) CreateSymlink(target, name string) error {
  26. return errNotSupported
  27. }
  28. // Required due to https://github.com/golang/go/issues/10900
  29. func (f *BasicFilesystem) mkdirAll(path string, perm os.FileMode) error {
  30. // Fast path: if we can tell whether path is a directory or file, stop with success or error.
  31. dir, err := os.Stat(path)
  32. if err == nil {
  33. if dir.IsDir() {
  34. return nil
  35. }
  36. return &os.PathError{
  37. Op: "mkdir",
  38. Path: path,
  39. Err: syscall.ENOTDIR,
  40. }
  41. }
  42. // Slow path: make sure parent exists and then call Mkdir for path.
  43. i := len(path)
  44. for i > 0 && IsPathSeparator(path[i-1]) { // Skip trailing path separator.
  45. i--
  46. }
  47. j := i
  48. for j > 0 && !IsPathSeparator(path[j-1]) { // Scan backward over element.
  49. j--
  50. }
  51. if j > 1 {
  52. // Create parent
  53. parent := path[0 : j-1]
  54. if parent != filepath.VolumeName(parent) {
  55. err = f.mkdirAll(parent, perm)
  56. if err != nil {
  57. return err
  58. }
  59. }
  60. }
  61. // Parent now exists; invoke Mkdir and use its result.
  62. err = os.Mkdir(path, perm)
  63. if err != nil {
  64. // Handle arguments like "foo/." by
  65. // double-checking that directory doesn't exist.
  66. dir, err1 := os.Lstat(path)
  67. if err1 == nil && dir.IsDir() {
  68. return nil
  69. }
  70. return err
  71. }
  72. return nil
  73. }
  74. func (f *BasicFilesystem) Unhide(name string) error {
  75. name, err := f.rooted(name)
  76. if err != nil {
  77. return err
  78. }
  79. p, err := syscall.UTF16PtrFromString(name)
  80. if err != nil {
  81. return err
  82. }
  83. attrs, err := syscall.GetFileAttributes(p)
  84. if err != nil {
  85. return err
  86. }
  87. attrs &^= syscall.FILE_ATTRIBUTE_HIDDEN
  88. return syscall.SetFileAttributes(p, attrs)
  89. }
  90. func (f *BasicFilesystem) Hide(name string) error {
  91. name, err := f.rooted(name)
  92. if err != nil {
  93. return err
  94. }
  95. p, err := syscall.UTF16PtrFromString(name)
  96. if err != nil {
  97. return err
  98. }
  99. attrs, err := syscall.GetFileAttributes(p)
  100. if err != nil {
  101. return err
  102. }
  103. attrs |= syscall.FILE_ATTRIBUTE_HIDDEN
  104. return syscall.SetFileAttributes(p, attrs)
  105. }
  106. func (f *BasicFilesystem) Roots() ([]string, error) {
  107. kernel32, err := syscall.LoadDLL("kernel32.dll")
  108. if err != nil {
  109. return nil, err
  110. }
  111. getLogicalDriveStringsHandle, err := kernel32.FindProc("GetLogicalDriveStringsA")
  112. if err != nil {
  113. return nil, err
  114. }
  115. buffer := [1024]byte{}
  116. bufferSize := uint32(len(buffer))
  117. hr, _, _ := getLogicalDriveStringsHandle.Call(uintptr(unsafe.Pointer(&bufferSize)), uintptr(unsafe.Pointer(&buffer)))
  118. if hr == 0 {
  119. return nil, errors.New("syscall failed")
  120. }
  121. var drives []string
  122. parts := bytes.Split(buffer[:], []byte{0})
  123. for _, part := range parts {
  124. if len(part) == 0 {
  125. break
  126. }
  127. drives = append(drives, string(part))
  128. }
  129. return drives, nil
  130. }
  131. // unrootedChecked returns the path relative to the folder root (same as
  132. // unrooted) or an error if the given path is not a subpath and handles the
  133. // special case when the given path is the folder root without a trailing
  134. // pathseparator.
  135. func (f *BasicFilesystem) unrootedChecked(absPath string, roots []string) (string, error) {
  136. absPath = f.resolveWin83(absPath)
  137. lowerAbsPath := UnicodeLowercaseNormalized(absPath)
  138. for _, root := range roots {
  139. lowerRoot := UnicodeLowercaseNormalized(root)
  140. if lowerAbsPath+string(PathSeparator) == lowerRoot {
  141. return ".", nil
  142. }
  143. if strings.HasPrefix(lowerAbsPath, lowerRoot) {
  144. return rel(absPath, root), nil
  145. }
  146. }
  147. return "", f.newErrWatchEventOutsideRoot(lowerAbsPath, roots)
  148. }
  149. func rel(path, prefix string) string {
  150. lowerRel := strings.TrimPrefix(strings.TrimPrefix(UnicodeLowercaseNormalized(path), UnicodeLowercaseNormalized(prefix)), string(PathSeparator))
  151. return path[len(path)-len(lowerRel):]
  152. }
  153. func (f *BasicFilesystem) resolveWin83(absPath string) string {
  154. if !isMaybeWin83(absPath) {
  155. return absPath
  156. }
  157. if in, err := syscall.UTF16FromString(absPath); err == nil {
  158. out := make([]uint16, 4*len(absPath)) // *2 for UTF16 and *2 to double path length
  159. if n, err := syscall.GetLongPathName(&in[0], &out[0], uint32(len(out))); err == nil {
  160. if n <= uint32(len(out)) {
  161. return syscall.UTF16ToString(out[:n])
  162. }
  163. out = make([]uint16, n)
  164. if _, err = syscall.GetLongPathName(&in[0], &out[0], n); err == nil {
  165. return syscall.UTF16ToString(out)
  166. }
  167. }
  168. }
  169. // Failed getting the long path. Return the part of the path which is
  170. // already a long path.
  171. lowerRoot := UnicodeLowercaseNormalized(f.root)
  172. for absPath = filepath.Dir(absPath); strings.HasPrefix(UnicodeLowercaseNormalized(absPath), lowerRoot); absPath = filepath.Dir(absPath) {
  173. if !isMaybeWin83(absPath) {
  174. return absPath
  175. }
  176. }
  177. return f.root
  178. }
  179. func isMaybeWin83(absPath string) bool {
  180. if !strings.Contains(absPath, "~") {
  181. return false
  182. }
  183. if strings.Contains(filepath.Dir(absPath), "~") {
  184. return true
  185. }
  186. return strings.Contains(strings.TrimPrefix(filepath.Base(absPath), WindowsTempPrefix), "~")
  187. }
  188. func getFinalPathName(in string) (string, error) {
  189. // Return the normalized path
  190. // Wrap the call to GetFinalPathNameByHandleW
  191. // The string returned by this function uses the \?\ syntax
  192. // Implies GetFullPathName + GetLongPathName
  193. kernel32, err := syscall.LoadDLL("kernel32.dll")
  194. if err != nil {
  195. return "", err
  196. }
  197. GetFinalPathNameByHandleW, err := kernel32.FindProc("GetFinalPathNameByHandleW")
  198. // https://github.com/golang/go/blob/ff048033e4304898245d843e79ed1a0897006c6d/src/internal/syscall/windows/syscall_windows.go#L303
  199. if err != nil {
  200. return "", err
  201. }
  202. inPath, err := syscall.UTF16PtrFromString(in)
  203. if err != nil {
  204. return "", err
  205. }
  206. // Get a file handler
  207. h, err := syscall.CreateFile(inPath,
  208. syscall.GENERIC_READ,
  209. syscall.FILE_SHARE_READ,
  210. nil,
  211. syscall.OPEN_EXISTING,
  212. uint32(syscall.FILE_FLAG_BACKUP_SEMANTICS),
  213. 0)
  214. if err != nil {
  215. return "", err
  216. }
  217. defer syscall.CloseHandle(h)
  218. // Call GetFinalPathNameByHandleW
  219. var VOLUME_NAME_DOS uint32 = 0x0 // not yet defined in syscall
  220. var bufSize uint32 = syscall.MAX_PATH // 260
  221. for i := 0; i < 2; i++ {
  222. buf := make([]uint16, bufSize)
  223. var ret uintptr
  224. ret, _, err = GetFinalPathNameByHandleW.Call(
  225. uintptr(h), // HANDLE hFile
  226. uintptr(unsafe.Pointer(&buf[0])), // LPWSTR lpszFilePath
  227. uintptr(bufSize), // DWORD cchFilePath
  228. uintptr(VOLUME_NAME_DOS), // DWORD dwFlags
  229. )
  230. // The returned value is the actual length of the norm path
  231. // After Win 10 build 1607, MAX_PATH limitations have been removed
  232. // so it is necessary to check newBufSize
  233. newBufSize := uint32(ret) + 1
  234. if ret == 0 || newBufSize > bufSize*100 {
  235. break
  236. }
  237. if newBufSize <= bufSize {
  238. return syscall.UTF16ToString(buf), nil
  239. }
  240. bufSize = newBufSize
  241. }
  242. return "", err
  243. }
  244. func evalSymlinks(in string) (string, error) {
  245. out, err := filepath.EvalSymlinks(in)
  246. if err != nil && strings.HasPrefix(in, `\\?\`) {
  247. // Try again without the `\\?\` prefix
  248. out, err = filepath.EvalSymlinks(in[4:])
  249. }
  250. if err != nil {
  251. // Try to get a normalized path from Win-API
  252. var err1 error
  253. out, err1 = getFinalPathName(in)
  254. if err1 != nil {
  255. return "", err // return the prior error
  256. }
  257. // Trim UNC prefix, equivalent to
  258. // https://github.com/golang/go/blob/2396101e0590cb7d77556924249c26af0ccd9eff/src/os/file_windows.go#L470
  259. if strings.HasPrefix(out, `\\?\UNC\`) {
  260. out = `\` + out[7:] // path like \\server\share\...
  261. } else {
  262. out = strings.TrimPrefix(out, `\\?\`)
  263. }
  264. }
  265. return longFilenameSupport(out), nil
  266. }
  267. // watchPaths adjust the folder root for use with the notify backend and the
  268. // corresponding absolute path to be passed to notify to watch name.
  269. func (f *BasicFilesystem) watchPaths(name string) (string, []string, error) {
  270. root, err := evalSymlinks(f.root)
  271. if err != nil {
  272. return "", nil, err
  273. }
  274. // Remove `\\?\` prefix if the path is just a drive letter as a dirty
  275. // fix for https://github.com/syncthing/syncthing/issues/5578
  276. if filepath.Clean(name) == "." && len(root) <= 7 && len(root) > 4 && root[:4] == `\\?\` {
  277. root = root[4:]
  278. }
  279. absName, err := rooted(name, root)
  280. if err != nil {
  281. return "", nil, err
  282. }
  283. roots := []string{f.resolveWin83(root)}
  284. absName = f.resolveWin83(absName)
  285. // Events returned from fs watching are all over the place, so allow
  286. // both the user's input and the result of "canonicalizing" the path.
  287. if roots[0] != f.root {
  288. roots = append(roots, f.root)
  289. }
  290. return filepath.Join(absName, "..."), roots, nil
  291. }