basicfs.go 9.5 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. "path/filepath"
  12. "runtime"
  13. "strings"
  14. "time"
  15. "github.com/shirou/gopsutil/v3/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. )
  23. type OptionJunctionsAsDirs struct{}
  24. func (*OptionJunctionsAsDirs) apply(fs Filesystem) Filesystem {
  25. if basic, ok := fs.(*BasicFilesystem); !ok {
  26. l.Warnln("WithJunctionsAsDirs must only be used with FilesystemTypeBasic")
  27. } else {
  28. basic.junctionsAsDirs = true
  29. }
  30. return fs
  31. }
  32. func (*OptionJunctionsAsDirs) String() string {
  33. return "junctionsAsDirs"
  34. }
  35. // The BasicFilesystem implements all aspects by delegating to package os.
  36. // All paths are relative to the root and cannot (should not) escape the root directory.
  37. type BasicFilesystem struct {
  38. root string
  39. junctionsAsDirs bool
  40. options []Option
  41. }
  42. func newBasicFilesystem(root string, opts ...Option) *BasicFilesystem {
  43. if root == "" {
  44. root = "." // Otherwise "" becomes "/" below
  45. }
  46. // The reason it's done like this:
  47. // C: -> C:\ -> C:\ (issue that this is trying to fix)
  48. // C:\somedir -> C:\somedir\ -> C:\somedir
  49. // C:\somedir\ -> C:\somedir\\ -> C:\somedir
  50. // This way in the tests, we get away without OS specific separators
  51. // in the test configs.
  52. sep := string(filepath.Separator)
  53. root = filepath.Dir(root + sep)
  54. // Attempt tilde expansion; leave unchanged in case of error
  55. if path, err := ExpandTilde(root); err == nil {
  56. root = path
  57. }
  58. // Attempt absolutification; leave unchanged in case of error
  59. if !filepath.IsAbs(root) {
  60. // Abs() looks like a fairly expensive syscall on Windows, while
  61. // IsAbs() is a whole bunch of string mangling. I think IsAbs() may be
  62. // somewhat faster in the general case, hence the outer if...
  63. if path, err := filepath.Abs(root); err == nil {
  64. root = path
  65. }
  66. }
  67. // Attempt to enable long filename support on Windows. We may still not
  68. // have an absolute path here if the previous steps failed.
  69. if runtime.GOOS == "windows" {
  70. root = longFilenameSupport(root)
  71. }
  72. fs := &BasicFilesystem{
  73. root: root,
  74. options: opts,
  75. }
  76. for _, opt := range opts {
  77. opt.apply(fs)
  78. }
  79. return fs
  80. }
  81. // rooted expands the relative path to the full path that is then used with os
  82. // package. If the relative path somehow causes the final path to escape the root
  83. // directory, this returns an error, to prevent accessing files that are not in the
  84. // shared directory.
  85. func (f *BasicFilesystem) rooted(rel string) (string, error) {
  86. return rooted(rel, f.root)
  87. }
  88. func rooted(rel, root string) (string, error) {
  89. // The root must not be empty.
  90. if root == "" {
  91. return "", errInvalidFilenameEmpty
  92. }
  93. var err error
  94. // Takes care that rel does not try to escape
  95. rel, err = Canonicalize(rel)
  96. if err != nil {
  97. return "", err
  98. }
  99. return filepath.Join(root, rel), nil
  100. }
  101. func (f *BasicFilesystem) unrooted(path string) string {
  102. return rel(path, f.root)
  103. }
  104. func (f *BasicFilesystem) Chmod(name string, mode FileMode) error {
  105. name, err := f.rooted(name)
  106. if err != nil {
  107. return err
  108. }
  109. return os.Chmod(name, os.FileMode(mode))
  110. }
  111. func (f *BasicFilesystem) Chtimes(name string, atime time.Time, mtime time.Time) error {
  112. name, err := f.rooted(name)
  113. if err != nil {
  114. return err
  115. }
  116. return os.Chtimes(name, atime, mtime)
  117. }
  118. func (f *BasicFilesystem) Mkdir(name string, perm FileMode) error {
  119. name, err := f.rooted(name)
  120. if err != nil {
  121. return err
  122. }
  123. return os.Mkdir(name, os.FileMode(perm))
  124. }
  125. // MkdirAll creates a directory named path, along with any necessary parents,
  126. // and returns nil, or else returns an error.
  127. // The permission bits perm are used for all directories that MkdirAll creates.
  128. // If path is already a directory, MkdirAll does nothing and returns nil.
  129. func (f *BasicFilesystem) MkdirAll(path string, perm FileMode) error {
  130. path, err := f.rooted(path)
  131. if err != nil {
  132. return err
  133. }
  134. return f.mkdirAll(path, os.FileMode(perm))
  135. }
  136. func (f *BasicFilesystem) Lstat(name string) (FileInfo, error) {
  137. name, err := f.rooted(name)
  138. if err != nil {
  139. return nil, err
  140. }
  141. fi, err := f.underlyingLstat(name)
  142. if err != nil {
  143. return nil, err
  144. }
  145. return basicFileInfo{fi}, err
  146. }
  147. func (f *BasicFilesystem) Remove(name string) error {
  148. name, err := f.rooted(name)
  149. if err != nil {
  150. return err
  151. }
  152. return os.Remove(name)
  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. }