1
0

basicfs.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. // Copyright (C) 2016 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. package fs
  7. import (
  8. "errors"
  9. "fmt"
  10. "os"
  11. "path/filepath"
  12. "runtime"
  13. "strings"
  14. "time"
  15. "github.com/shirou/gopsutil/disk"
  16. )
  17. var (
  18. errInvalidFilenameEmpty = errors.New("name is invalid, must not be empty")
  19. errInvalidFilenameWindowsSpacePeriod = errors.New("name is invalid, must not end in space or period on Windows")
  20. errInvalidFilenameWindowsReservedName = errors.New("name is invalid, contains Windows reserved name (NUL, COM1, etc.)")
  21. errInvalidFilenameWindowsReservedChar = errors.New("name is invalid, contains Windows reserved character (?, *, etc.)")
  22. errNotRelative = errors.New("not a relative path")
  23. )
  24. func WithJunctionsAsDirs() Option {
  25. return func(fs Filesystem) {
  26. if basic, ok := fs.(*BasicFilesystem); !ok {
  27. l.Warnln("WithJunctionsAsDirs must only be used with FilesystemTypeBasic")
  28. } else {
  29. basic.junctionsAsDirs = true
  30. }
  31. }
  32. }
  33. // The BasicFilesystem implements all aspects by delegating to package os.
  34. // All paths are relative to the root and cannot (should not) escape the root directory.
  35. type BasicFilesystem struct {
  36. root string
  37. junctionsAsDirs bool
  38. }
  39. func newBasicFilesystem(root string, opts ...Option) *BasicFilesystem {
  40. if root == "" {
  41. root = "." // Otherwise "" becomes "/" below
  42. }
  43. // The reason it's done like this:
  44. // C: -> C:\ -> C:\ (issue that this is trying to fix)
  45. // C:\somedir -> C:\somedir\ -> C:\somedir
  46. // C:\somedir\ -> C:\somedir\\ -> C:\somedir
  47. // This way in the tests, we get away without OS specific separators
  48. // in the test configs.
  49. sep := string(filepath.Separator)
  50. root = filepath.Dir(root + sep)
  51. // Attempt tilde expansion; leave unchanged in case of error
  52. if path, err := ExpandTilde(root); err == nil {
  53. root = path
  54. }
  55. // Attempt absolutification; leave unchanged in case of error
  56. if !filepath.IsAbs(root) {
  57. // Abs() looks like a fairly expensive syscall on Windows, while
  58. // IsAbs() is a whole bunch of string mangling. I think IsAbs() may be
  59. // somewhat faster in the general case, hence the outer if...
  60. if path, err := filepath.Abs(root); err == nil {
  61. root = path
  62. }
  63. }
  64. // Attempt to enable long filename support on Windows. We may still not
  65. // have an absolute path here if the previous steps failed.
  66. if runtime.GOOS == "windows" {
  67. root = longFilenameSupport(root)
  68. }
  69. fs := &BasicFilesystem{
  70. root: root,
  71. }
  72. for _, opt := range opts {
  73. opt(fs)
  74. }
  75. return fs
  76. }
  77. // rooted expands the relative path to the full path that is then used with os
  78. // package. If the relative path somehow causes the final path to escape the root
  79. // directory, this returns an error, to prevent accessing files that are not in the
  80. // shared directory.
  81. func (f *BasicFilesystem) rooted(rel string) (string, error) {
  82. return rooted(rel, f.root)
  83. }
  84. func rooted(rel, root string) (string, error) {
  85. // The root must not be empty.
  86. if root == "" {
  87. return "", errInvalidFilenameEmpty
  88. }
  89. var err error
  90. // Takes care that rel does not try to escape
  91. rel, err = Canonicalize(rel)
  92. if err != nil {
  93. return "", err
  94. }
  95. return filepath.Join(root, rel), nil
  96. }
  97. func (f *BasicFilesystem) unrooted(path string) string {
  98. return rel(path, f.root)
  99. }
  100. func (f *BasicFilesystem) Chmod(name string, mode FileMode) error {
  101. name, err := f.rooted(name)
  102. if err != nil {
  103. return err
  104. }
  105. return os.Chmod(name, os.FileMode(mode))
  106. }
  107. func (f *BasicFilesystem) Lchown(name string, uid, gid int) error {
  108. name, err := f.rooted(name)
  109. if err != nil {
  110. return err
  111. }
  112. return os.Lchown(name, uid, gid)
  113. }
  114. func (f *BasicFilesystem) Chtimes(name string, atime time.Time, mtime time.Time) error {
  115. name, err := f.rooted(name)
  116. if err != nil {
  117. return err
  118. }
  119. return os.Chtimes(name, atime, mtime)
  120. }
  121. func (f *BasicFilesystem) Mkdir(name string, perm FileMode) error {
  122. name, err := f.rooted(name)
  123. if err != nil {
  124. return err
  125. }
  126. return os.Mkdir(name, os.FileMode(perm))
  127. }
  128. // MkdirAll creates a directory named path, along with any necessary parents,
  129. // and returns nil, or else returns an error.
  130. // The permission bits perm are used for all directories that MkdirAll creates.
  131. // If path is already a directory, MkdirAll does nothing and returns nil.
  132. func (f *BasicFilesystem) MkdirAll(path string, perm FileMode) error {
  133. path, err := f.rooted(path)
  134. if err != nil {
  135. return err
  136. }
  137. return f.mkdirAll(path, os.FileMode(perm))
  138. }
  139. func (f *BasicFilesystem) Lstat(name string) (FileInfo, error) {
  140. name, err := f.rooted(name)
  141. if err != nil {
  142. return nil, err
  143. }
  144. fi, err := f.underlyingLstat(name)
  145. if err != nil {
  146. return nil, err
  147. }
  148. return basicFileInfo{fi}, err
  149. }
  150. func (f *BasicFilesystem) Remove(name string) error {
  151. name, err := f.rooted(name)
  152. if err != nil {
  153. return err
  154. }
  155. return os.Remove(name)
  156. }
  157. func (f *BasicFilesystem) RemoveAll(name string) error {
  158. name, err := f.rooted(name)
  159. if err != nil {
  160. return err
  161. }
  162. return os.RemoveAll(name)
  163. }
  164. func (f *BasicFilesystem) Rename(oldpath, newpath string) error {
  165. oldpath, err := f.rooted(oldpath)
  166. if err != nil {
  167. return err
  168. }
  169. newpath, err = f.rooted(newpath)
  170. if err != nil {
  171. return err
  172. }
  173. return os.Rename(oldpath, newpath)
  174. }
  175. func (f *BasicFilesystem) Stat(name string) (FileInfo, error) {
  176. name, err := f.rooted(name)
  177. if err != nil {
  178. return nil, err
  179. }
  180. fi, err := os.Stat(name)
  181. if err != nil {
  182. return nil, err
  183. }
  184. return basicFileInfo{fi}, err
  185. }
  186. func (f *BasicFilesystem) DirNames(name string) ([]string, error) {
  187. name, err := f.rooted(name)
  188. if err != nil {
  189. return nil, err
  190. }
  191. fd, err := os.OpenFile(name, OptReadOnly, 0777)
  192. if err != nil {
  193. return nil, err
  194. }
  195. defer fd.Close()
  196. names, err := fd.Readdirnames(-1)
  197. if err != nil {
  198. return nil, err
  199. }
  200. return names, nil
  201. }
  202. func (f *BasicFilesystem) Open(name string) (File, error) {
  203. rootedName, err := f.rooted(name)
  204. if err != nil {
  205. return nil, err
  206. }
  207. fd, err := os.Open(rootedName)
  208. if err != nil {
  209. return nil, err
  210. }
  211. return basicFile{fd, name}, err
  212. }
  213. func (f *BasicFilesystem) OpenFile(name string, flags int, mode FileMode) (File, error) {
  214. rootedName, err := f.rooted(name)
  215. if err != nil {
  216. return nil, err
  217. }
  218. fd, err := os.OpenFile(rootedName, flags, os.FileMode(mode))
  219. if err != nil {
  220. return nil, err
  221. }
  222. return basicFile{fd, name}, err
  223. }
  224. func (f *BasicFilesystem) Create(name string) (File, error) {
  225. rootedName, err := f.rooted(name)
  226. if err != nil {
  227. return nil, err
  228. }
  229. fd, err := os.Create(rootedName)
  230. if err != nil {
  231. return nil, err
  232. }
  233. return basicFile{fd, name}, err
  234. }
  235. func (f *BasicFilesystem) Walk(root string, walkFn WalkFunc) error {
  236. // implemented in WalkFilesystem
  237. return errors.New("not implemented")
  238. }
  239. func (f *BasicFilesystem) Glob(pattern string) ([]string, error) {
  240. pattern, err := f.rooted(pattern)
  241. if err != nil {
  242. return nil, err
  243. }
  244. files, err := filepath.Glob(pattern)
  245. unrooted := make([]string, len(files))
  246. for i := range files {
  247. unrooted[i] = f.unrooted(files[i])
  248. }
  249. return unrooted, err
  250. }
  251. func (f *BasicFilesystem) Usage(name string) (Usage, error) {
  252. name, err := f.rooted(name)
  253. if err != nil {
  254. return Usage{}, err
  255. }
  256. u, err := disk.Usage(name)
  257. if err != nil {
  258. return Usage{}, err
  259. }
  260. return Usage{
  261. Free: u.Free,
  262. Total: u.Total,
  263. }, nil
  264. }
  265. func (f *BasicFilesystem) Type() FilesystemType {
  266. return FilesystemTypeBasic
  267. }
  268. func (f *BasicFilesystem) URI() string {
  269. return strings.TrimPrefix(f.root, `\\?\`)
  270. }
  271. func (f *BasicFilesystem) SameFile(fi1, fi2 FileInfo) bool {
  272. // Like os.SameFile, we always return false unless fi1 and fi2 were created
  273. // by this package's Stat/Lstat method.
  274. f1, ok1 := fi1.(basicFileInfo)
  275. f2, ok2 := fi2.(basicFileInfo)
  276. if !ok1 || !ok2 {
  277. return false
  278. }
  279. return os.SameFile(f1.osFileInfo(), f2.osFileInfo())
  280. }
  281. // basicFile implements the fs.File interface on top of an os.File
  282. type basicFile struct {
  283. *os.File
  284. name string
  285. }
  286. func (f basicFile) Name() string {
  287. return f.name
  288. }
  289. func (f basicFile) Stat() (FileInfo, error) {
  290. info, err := f.File.Stat()
  291. if err != nil {
  292. return nil, err
  293. }
  294. return basicFileInfo{info}, nil
  295. }
  296. // basicFileInfo implements the fs.FileInfo interface on top of an os.FileInfo.
  297. type basicFileInfo struct {
  298. os.FileInfo
  299. }
  300. func (e basicFileInfo) IsSymlink() bool {
  301. // Must use basicFileInfo.Mode() because it may apply magic.
  302. return e.Mode()&ModeSymlink != 0
  303. }
  304. func (e basicFileInfo) IsRegular() bool {
  305. // Must use basicFileInfo.Mode() because it may apply magic.
  306. return e.Mode()&ModeType == 0
  307. }
  308. // longFilenameSupport adds the necessary prefix to the path to enable long
  309. // filename support on windows if necessary.
  310. // This does NOT check the current system, i.e. will also take effect on unix paths.
  311. func longFilenameSupport(path string) string {
  312. if filepath.IsAbs(path) && !strings.HasPrefix(path, `\\`) {
  313. return `\\?\` + path
  314. }
  315. return path
  316. }
  317. type ErrWatchEventOutsideRoot struct{ msg string }
  318. func (e *ErrWatchEventOutsideRoot) Error() string {
  319. return e.msg
  320. }
  321. func (f *BasicFilesystem) newErrWatchEventOutsideRoot(absPath string, roots []string) *ErrWatchEventOutsideRoot {
  322. return &ErrWatchEventOutsideRoot{fmt.Sprintf("Watching for changes encountered an event outside of the filesystem root: f.root==%v, roots==%v, path==%v. This should never happen, please report this message to forum.syncthing.net.", f.root, roots, absPath)}
  323. }