basicfs.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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. func (f *BasicFilesystem) Lstat(name string) (FileInfo, error) {
  135. name, err := f.rooted(name)
  136. if err != nil {
  137. return nil, err
  138. }
  139. fi, err := underlyingLstat(name)
  140. if err != nil {
  141. return nil, err
  142. }
  143. return fsFileInfo{fi}, err
  144. }
  145. func (f *BasicFilesystem) Remove(name string) error {
  146. name, err := f.rooted(name)
  147. if err != nil {
  148. return err
  149. }
  150. return os.Remove(name)
  151. }
  152. func (f *BasicFilesystem) RemoveAll(name string) error {
  153. name, err := f.rooted(name)
  154. if err != nil {
  155. return err
  156. }
  157. return os.RemoveAll(name)
  158. }
  159. func (f *BasicFilesystem) Rename(oldpath, newpath string) error {
  160. oldpath, err := f.rooted(oldpath)
  161. if err != nil {
  162. return err
  163. }
  164. newpath, err = f.rooted(newpath)
  165. if err != nil {
  166. return err
  167. }
  168. return os.Rename(oldpath, newpath)
  169. }
  170. func (f *BasicFilesystem) Stat(name string) (FileInfo, error) {
  171. name, err := f.rooted(name)
  172. if err != nil {
  173. return nil, err
  174. }
  175. fi, err := os.Stat(name)
  176. if err != nil {
  177. return nil, err
  178. }
  179. return fsFileInfo{fi}, err
  180. }
  181. func (f *BasicFilesystem) DirNames(name string) ([]string, error) {
  182. name, err := f.rooted(name)
  183. if err != nil {
  184. return nil, err
  185. }
  186. fd, err := os.OpenFile(name, OptReadOnly, 0777)
  187. if err != nil {
  188. return nil, err
  189. }
  190. defer fd.Close()
  191. names, err := fd.Readdirnames(-1)
  192. if err != nil {
  193. return nil, err
  194. }
  195. return names, nil
  196. }
  197. func (f *BasicFilesystem) Open(name string) (File, error) {
  198. rootedName, err := f.rooted(name)
  199. if err != nil {
  200. return nil, err
  201. }
  202. fd, err := os.Open(rootedName)
  203. if err != nil {
  204. return nil, err
  205. }
  206. return fsFile{fd, name}, err
  207. }
  208. func (f *BasicFilesystem) OpenFile(name string, flags int, mode FileMode) (File, error) {
  209. rootedName, err := f.rooted(name)
  210. if err != nil {
  211. return nil, err
  212. }
  213. fd, err := os.OpenFile(rootedName, flags, os.FileMode(mode))
  214. if err != nil {
  215. return nil, err
  216. }
  217. return fsFile{fd, name}, err
  218. }
  219. func (f *BasicFilesystem) Create(name string) (File, error) {
  220. rootedName, err := f.rooted(name)
  221. if err != nil {
  222. return nil, err
  223. }
  224. fd, err := os.Create(rootedName)
  225. if err != nil {
  226. return nil, err
  227. }
  228. return fsFile{fd, name}, err
  229. }
  230. func (f *BasicFilesystem) Walk(root string, walkFn WalkFunc) error {
  231. // implemented in WalkFilesystem
  232. return errors.New("not implemented")
  233. }
  234. func (f *BasicFilesystem) Glob(pattern string) ([]string, error) {
  235. pattern, err := f.rooted(pattern)
  236. if err != nil {
  237. return nil, err
  238. }
  239. files, err := filepath.Glob(pattern)
  240. unrooted := make([]string, len(files))
  241. for i := range files {
  242. unrooted[i] = f.unrooted(files[i])
  243. }
  244. return unrooted, err
  245. }
  246. func (f *BasicFilesystem) Usage(name string) (Usage, error) {
  247. name, err := f.rooted(name)
  248. if err != nil {
  249. return Usage{}, err
  250. }
  251. u, err := du.Get(name)
  252. return Usage{
  253. Free: u.FreeBytes,
  254. Total: u.TotalBytes,
  255. }, err
  256. }
  257. func (f *BasicFilesystem) Type() FilesystemType {
  258. return FilesystemTypeBasic
  259. }
  260. func (f *BasicFilesystem) URI() string {
  261. return strings.TrimPrefix(f.root, `\\?\`)
  262. }
  263. func (f *BasicFilesystem) SameFile(fi1, fi2 FileInfo) bool {
  264. // Like os.SameFile, we always return false unless fi1 and fi2 were created
  265. // by this package's Stat/Lstat method.
  266. f1, ok1 := fi1.(fsFileInfo)
  267. f2, ok2 := fi2.(fsFileInfo)
  268. if !ok1 || !ok2 {
  269. return false
  270. }
  271. return os.SameFile(f1.FileInfo, f2.FileInfo)
  272. }
  273. // fsFile implements the fs.File interface on top of an os.File
  274. type fsFile struct {
  275. *os.File
  276. name string
  277. }
  278. func (f fsFile) Name() string {
  279. return f.name
  280. }
  281. func (f fsFile) Stat() (FileInfo, error) {
  282. info, err := f.File.Stat()
  283. if err != nil {
  284. return nil, err
  285. }
  286. return fsFileInfo{info}, nil
  287. }
  288. // fsFileInfo implements the fs.FileInfo interface on top of an os.FileInfo.
  289. type fsFileInfo struct {
  290. os.FileInfo
  291. }
  292. func (e fsFileInfo) IsSymlink() bool {
  293. // Must use fsFileInfo.Mode() because it may apply magic.
  294. return e.Mode()&ModeSymlink != 0
  295. }
  296. func (e fsFileInfo) IsRegular() bool {
  297. // Must use fsFileInfo.Mode() because it may apply magic.
  298. return e.Mode()&ModeType == 0
  299. }