basicfs_windows.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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. // +build windows
  7. package fs
  8. import (
  9. "bytes"
  10. "errors"
  11. "fmt"
  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, fmt.Errorf("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, root string) (string, error) {
  136. absPath = f.resolveWin83(absPath)
  137. lowerAbsPath := UnicodeLowercase(absPath)
  138. lowerRoot := UnicodeLowercase(root)
  139. if lowerAbsPath+string(PathSeparator) == lowerRoot {
  140. return ".", nil
  141. }
  142. if !strings.HasPrefix(lowerAbsPath, lowerRoot) {
  143. return "", f.newErrWatchEventOutsideRoot(lowerAbsPath, lowerRoot)
  144. }
  145. return rel(absPath, root), nil
  146. }
  147. func rel(path, prefix string) string {
  148. lowerRel := strings.TrimPrefix(strings.TrimPrefix(UnicodeLowercase(path), UnicodeLowercase(prefix)), string(PathSeparator))
  149. return path[len(path)-len(lowerRel):]
  150. }
  151. func (f *BasicFilesystem) resolveWin83(absPath string) string {
  152. if !isMaybeWin83(absPath) {
  153. return absPath
  154. }
  155. if in, err := syscall.UTF16FromString(absPath); err == nil {
  156. out := make([]uint16, 4*len(absPath)) // *2 for UTF16 and *2 to double path length
  157. if n, err := syscall.GetLongPathName(&in[0], &out[0], uint32(len(out))); err == nil {
  158. if n <= uint32(len(out)) {
  159. return syscall.UTF16ToString(out[:n])
  160. }
  161. out = make([]uint16, n)
  162. if _, err = syscall.GetLongPathName(&in[0], &out[0], n); err == nil {
  163. return syscall.UTF16ToString(out)
  164. }
  165. }
  166. }
  167. // Failed getting the long path. Return the part of the path which is
  168. // already a long path.
  169. lowerRoot := UnicodeLowercase(f.root)
  170. for absPath = filepath.Dir(absPath); strings.HasPrefix(UnicodeLowercase(absPath), lowerRoot); absPath = filepath.Dir(absPath) {
  171. if !isMaybeWin83(absPath) {
  172. return absPath
  173. }
  174. }
  175. return f.root
  176. }
  177. func isMaybeWin83(absPath string) bool {
  178. if !strings.Contains(absPath, "~") {
  179. return false
  180. }
  181. if strings.Contains(filepath.Dir(absPath), "~") {
  182. return true
  183. }
  184. return strings.Contains(strings.TrimPrefix(filepath.Base(absPath), WindowsTempPrefix), "~")
  185. }
  186. func getFinalPathName(in string) (string, error) {
  187. // Return the normalized path
  188. // Wrap the call to GetFinalPathNameByHandleW
  189. // The string returned by this function uses the \?\ syntax
  190. // Implies GetFullPathName + GetLongPathName
  191. kernel32, err := syscall.LoadDLL("kernel32.dll")
  192. if err != nil {
  193. return "", err
  194. }
  195. GetFinalPathNameByHandleW, err := kernel32.FindProc("GetFinalPathNameByHandleW")
  196. // https://github.com/golang/go/blob/ff048033e4304898245d843e79ed1a0897006c6d/src/internal/syscall/windows/syscall_windows.go#L303
  197. if err != nil {
  198. return "", err
  199. }
  200. inPath, err := syscall.UTF16PtrFromString(in)
  201. if err != nil {
  202. return "", err
  203. }
  204. // Get a file handler
  205. h, err := syscall.CreateFile(inPath,
  206. syscall.GENERIC_READ,
  207. syscall.FILE_SHARE_READ,
  208. nil,
  209. syscall.OPEN_EXISTING,
  210. uint32(syscall.FILE_FLAG_BACKUP_SEMANTICS),
  211. 0)
  212. if err != nil {
  213. return "", err
  214. }
  215. defer syscall.CloseHandle(h)
  216. // Call GetFinalPathNameByHandleW
  217. var VOLUME_NAME_DOS uint32 = 0x0 // not yet defined in syscall
  218. var bufSize uint32 = syscall.MAX_PATH // 260
  219. for i := 0; i < 2; i++ {
  220. buf := make([]uint16, bufSize)
  221. var ret uintptr
  222. ret, _, err = GetFinalPathNameByHandleW.Call(
  223. uintptr(h), // HANDLE hFile
  224. uintptr(unsafe.Pointer(&buf[0])), // LPWSTR lpszFilePath
  225. uintptr(bufSize), // DWORD cchFilePath
  226. uintptr(VOLUME_NAME_DOS), // DWORD dwFlags
  227. )
  228. // The returned value is the actual length of the norm path
  229. // After Win 10 build 1607, MAX_PATH limitations have been removed
  230. // so it is necessary to check newBufSize
  231. newBufSize := uint32(ret) + 1
  232. if ret == 0 || newBufSize > bufSize*100 {
  233. break
  234. }
  235. if newBufSize <= bufSize {
  236. return syscall.UTF16ToString(buf), nil
  237. }
  238. bufSize = newBufSize
  239. }
  240. return "", err
  241. }
  242. func evalSymlinks(in string) (string, error) {
  243. out, err := filepath.EvalSymlinks(in)
  244. if err != nil && strings.HasPrefix(in, `\\?\`) {
  245. // Try again without the `\\?\` prefix
  246. out, err = filepath.EvalSymlinks(in[4:])
  247. }
  248. if err != nil {
  249. // Try to get a normalized path from Win-API
  250. var err1 error
  251. out, err1 = getFinalPathName(in)
  252. if err1 != nil {
  253. return "", err // return the prior error
  254. }
  255. // Trim UNC prefix, equivalent to
  256. // https://github.com/golang/go/blob/2396101e0590cb7d77556924249c26af0ccd9eff/src/os/file_windows.go#L470
  257. if strings.HasPrefix(out, `\\?\UNC\`) {
  258. out = `\` + out[7:] // path like \\server\share\...
  259. } else {
  260. out = strings.TrimPrefix(out, `\\?\`)
  261. }
  262. }
  263. return longFilenameSupport(out), nil
  264. }
  265. // watchPaths adjust the folder root for use with the notify backend and the
  266. // corresponding absolute path to be passed to notify to watch name.
  267. func (f *BasicFilesystem) watchPaths(name string) (string, string, error) {
  268. root, err := evalSymlinks(f.root)
  269. if err != nil {
  270. return "", "", err
  271. }
  272. // Remove `\\?\` prefix if the path is just a drive letter as a dirty
  273. // fix for https://github.com/syncthing/syncthing/issues/5578
  274. if filepath.Clean(name) == "." && len(root) <= 7 && len(root) > 4 && root[:4] == `\\?\` {
  275. root = root[4:]
  276. }
  277. absName, err := rooted(name, root)
  278. if err != nil {
  279. return "", "", err
  280. }
  281. root = f.resolveWin83(root)
  282. absName = f.resolveWin83(absName)
  283. return filepath.Join(absName, "..."), root, nil
  284. }