basicfs.go 9.7 KB

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