basicfs.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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. "os"
  10. "path/filepath"
  11. "runtime"
  12. "strings"
  13. "time"
  14. "github.com/calmh/du"
  15. )
  16. var (
  17. ErrInvalidFilename = errors.New("filename is invalid")
  18. ErrNotRelative = errors.New("not a relative path")
  19. )
  20. // The BasicFilesystem implements all aspects by delegating to package os.
  21. // All paths are relative to the root and cannot (should not) escape the root directory.
  22. type BasicFilesystem struct {
  23. root string
  24. }
  25. func newBasicFilesystem(root string) *BasicFilesystem {
  26. // The reason it's done like this:
  27. // C: -> C:\ -> C:\ (issue that this is trying to fix)
  28. // C:\somedir -> C:\somedir\ -> C:\somedir
  29. // C:\somedir\ -> C:\somedir\\ -> C:\somedir
  30. // This way in the tests, we get away without OS specific separators
  31. // in the test configs.
  32. root = filepath.Dir(root + string(filepath.Separator))
  33. // Attempt tilde expansion; leave unchanged in case of error
  34. if path, err := ExpandTilde(root); err == nil {
  35. root = path
  36. }
  37. // Attempt absolutification; leave unchanged in case of error
  38. if !filepath.IsAbs(root) {
  39. // Abs() looks like a fairly expensive syscall on Windows, while
  40. // IsAbs() is a whole bunch of string mangling. I think IsAbs() may be
  41. // somewhat faster in the general case, hence the outer if...
  42. if path, err := filepath.Abs(root); err == nil {
  43. root = path
  44. }
  45. }
  46. // Attempt to enable long filename support on Windows. We may still not
  47. // have an absolute path here if the previous steps failed.
  48. if runtime.GOOS == "windows" {
  49. if filepath.IsAbs(root) && !strings.HasPrefix(root, `\\`) {
  50. root = `\\?\` + root
  51. }
  52. // If we're not on Windows, we want the path to end with a slash to
  53. // penetrate symlinks. On Windows, paths must not end with a slash.
  54. } else if root[len(root)-1] != filepath.Separator {
  55. root = root + string(filepath.Separator)
  56. }
  57. return &BasicFilesystem{
  58. root: root,
  59. }
  60. }
  61. // rooted expands the relative path to the full path that is then used with os
  62. // package. If the relative path somehow causes the final path to escape the root
  63. // directory, this returns an error, to prevent accessing files that are not in the
  64. // shared directory.
  65. func (f *BasicFilesystem) rooted(rel string) (string, error) {
  66. // The root must not be empty.
  67. if f.root == "" {
  68. return "", ErrInvalidFilename
  69. }
  70. pathSep := string(PathSeparator)
  71. // The expected prefix for the resulting path is the root, with a path
  72. // separator at the end.
  73. expectedPrefix := filepath.FromSlash(f.root)
  74. if !strings.HasSuffix(expectedPrefix, pathSep) {
  75. expectedPrefix += pathSep
  76. }
  77. // The relative path should be clean from internal dotdots and similar
  78. // funkyness.
  79. rel = filepath.FromSlash(rel)
  80. if filepath.Clean(rel) != rel {
  81. return "", ErrInvalidFilename
  82. }
  83. // It is not acceptable to attempt to traverse upwards.
  84. switch rel {
  85. case "..", pathSep:
  86. return "", ErrNotRelative
  87. }
  88. if strings.HasPrefix(rel, ".."+pathSep) {
  89. return "", ErrNotRelative
  90. }
  91. if strings.HasPrefix(rel, pathSep+pathSep) {
  92. // The relative path may pretend to be an absolute path within the
  93. // root, but the double path separator on Windows implies something
  94. // else. It would get cleaned by the Join below, but it's out of
  95. // spec anyway.
  96. return "", ErrNotRelative
  97. }
  98. // The supposedly correct path is the one filepath.Join will return, as
  99. // it does cleaning and so on. Check that one first to make sure no
  100. // obvious escape attempts have been made.
  101. joined := filepath.Join(f.root, rel)
  102. if rel == "." && !strings.HasSuffix(joined, pathSep) {
  103. joined += pathSep
  104. }
  105. if !strings.HasPrefix(joined, expectedPrefix) {
  106. return "", ErrNotRelative
  107. }
  108. return joined, nil
  109. }
  110. func (f *BasicFilesystem) unrooted(path string) string {
  111. return strings.TrimPrefix(strings.TrimPrefix(path, f.root), string(PathSeparator))
  112. }
  113. func (f *BasicFilesystem) Chmod(name string, mode FileMode) error {
  114. name, err := f.rooted(name)
  115. if err != nil {
  116. return err
  117. }
  118. return os.Chmod(name, os.FileMode(mode))
  119. }
  120. func (f *BasicFilesystem) Chtimes(name string, atime time.Time, mtime time.Time) error {
  121. name, err := f.rooted(name)
  122. if err != nil {
  123. return err
  124. }
  125. return os.Chtimes(name, atime, mtime)
  126. }
  127. func (f *BasicFilesystem) Mkdir(name string, perm FileMode) error {
  128. name, err := f.rooted(name)
  129. if err != nil {
  130. return err
  131. }
  132. return os.Mkdir(name, os.FileMode(perm))
  133. }
  134. // MkdirAll creates a directory named path, along with any necessary parents,
  135. // and returns nil, or else returns an error.
  136. // The permission bits perm are used for all directories that MkdirAll creates.
  137. // If path is already a directory, MkdirAll does nothing and returns nil.
  138. func (f *BasicFilesystem) MkdirAll(path string, perm FileMode) error {
  139. path, err := f.rooted(path)
  140. if err != nil {
  141. return err
  142. }
  143. return f.mkdirAll(path, os.FileMode(perm))
  144. }
  145. func (f *BasicFilesystem) Lstat(name string) (FileInfo, error) {
  146. name, err := f.rooted(name)
  147. if err != nil {
  148. return nil, err
  149. }
  150. fi, err := underlyingLstat(name)
  151. if err != nil {
  152. return nil, err
  153. }
  154. return fsFileInfo{fi}, err
  155. }
  156. func (f *BasicFilesystem) Remove(name string) error {
  157. name, err := f.rooted(name)
  158. if err != nil {
  159. return err
  160. }
  161. return os.Remove(name)
  162. }
  163. func (f *BasicFilesystem) RemoveAll(name string) error {
  164. name, err := f.rooted(name)
  165. if err != nil {
  166. return err
  167. }
  168. return os.RemoveAll(name)
  169. }
  170. func (f *BasicFilesystem) Rename(oldpath, newpath string) error {
  171. oldpath, err := f.rooted(oldpath)
  172. if err != nil {
  173. return err
  174. }
  175. newpath, err = f.rooted(newpath)
  176. if err != nil {
  177. return err
  178. }
  179. return os.Rename(oldpath, newpath)
  180. }
  181. func (f *BasicFilesystem) Stat(name string) (FileInfo, error) {
  182. name, err := f.rooted(name)
  183. if err != nil {
  184. return nil, err
  185. }
  186. fi, err := os.Stat(name)
  187. if err != nil {
  188. return nil, err
  189. }
  190. return fsFileInfo{fi}, err
  191. }
  192. func (f *BasicFilesystem) DirNames(name string) ([]string, error) {
  193. name, err := f.rooted(name)
  194. if err != nil {
  195. return nil, err
  196. }
  197. fd, err := os.OpenFile(name, OptReadOnly, 0777)
  198. if err != nil {
  199. return nil, err
  200. }
  201. defer fd.Close()
  202. names, err := fd.Readdirnames(-1)
  203. if err != nil {
  204. return nil, err
  205. }
  206. return names, nil
  207. }
  208. func (f *BasicFilesystem) Open(name string) (File, error) {
  209. rootedName, err := f.rooted(name)
  210. if err != nil {
  211. return nil, err
  212. }
  213. fd, err := os.Open(rootedName)
  214. if err != nil {
  215. return nil, err
  216. }
  217. return fsFile{fd, name}, err
  218. }
  219. func (f *BasicFilesystem) OpenFile(name string, flags int, mode FileMode) (File, error) {
  220. rootedName, err := f.rooted(name)
  221. if err != nil {
  222. return nil, err
  223. }
  224. fd, err := os.OpenFile(rootedName, flags, os.FileMode(mode))
  225. if err != nil {
  226. return nil, err
  227. }
  228. return fsFile{fd, name}, err
  229. }
  230. func (f *BasicFilesystem) Create(name string) (File, error) {
  231. rootedName, err := f.rooted(name)
  232. if err != nil {
  233. return nil, err
  234. }
  235. fd, err := os.Create(rootedName)
  236. if err != nil {
  237. return nil, err
  238. }
  239. return fsFile{fd, name}, err
  240. }
  241. func (f *BasicFilesystem) Walk(root string, walkFn WalkFunc) error {
  242. // implemented in WalkFilesystem
  243. return errors.New("not implemented")
  244. }
  245. func (f *BasicFilesystem) Glob(pattern string) ([]string, error) {
  246. pattern, err := f.rooted(pattern)
  247. if err != nil {
  248. return nil, err
  249. }
  250. files, err := filepath.Glob(pattern)
  251. unrooted := make([]string, len(files))
  252. for i := range files {
  253. unrooted[i] = f.unrooted(files[i])
  254. }
  255. return unrooted, err
  256. }
  257. func (f *BasicFilesystem) Usage(name string) (Usage, error) {
  258. name, err := f.rooted(name)
  259. if err != nil {
  260. return Usage{}, err
  261. }
  262. u, err := du.Get(name)
  263. return Usage{
  264. Free: u.FreeBytes,
  265. Total: u.TotalBytes,
  266. }, err
  267. }
  268. func (f *BasicFilesystem) Type() FilesystemType {
  269. return FilesystemTypeBasic
  270. }
  271. func (f *BasicFilesystem) URI() string {
  272. return strings.TrimPrefix(f.root, `\\?\`)
  273. }
  274. func (f *BasicFilesystem) SameFile(fi1, fi2 FileInfo) bool {
  275. // Like os.SameFile, we always return false unless fi1 and fi2 were created
  276. // by this package's Stat/Lstat method.
  277. f1, ok1 := fi1.(fsFileInfo)
  278. f2, ok2 := fi2.(fsFileInfo)
  279. if !ok1 || !ok2 {
  280. return false
  281. }
  282. return os.SameFile(f1.FileInfo, f2.FileInfo)
  283. }
  284. // fsFile implements the fs.File interface on top of an os.File
  285. type fsFile struct {
  286. *os.File
  287. name string
  288. }
  289. func (f fsFile) Name() string {
  290. return f.name
  291. }
  292. func (f fsFile) Stat() (FileInfo, error) {
  293. info, err := f.File.Stat()
  294. if err != nil {
  295. return nil, err
  296. }
  297. return fsFileInfo{info}, nil
  298. }
  299. // fsFileInfo implements the fs.FileInfo interface on top of an os.FileInfo.
  300. type fsFileInfo struct {
  301. os.FileInfo
  302. }
  303. func (e fsFileInfo) IsSymlink() bool {
  304. // Must use fsFileInfo.Mode() because it may apply magic.
  305. return e.Mode()&ModeSymlink != 0
  306. }
  307. func (e fsFileInfo) IsRegular() bool {
  308. // Must use fsFileInfo.Mode() because it may apply magic.
  309. return e.Mode()&ModeType == 0
  310. }