osfs.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. // Copyright (C) 2019-2022 Nicola Murino
  2. //
  3. // This program is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU Affero General Public License as published
  5. // by the Free Software Foundation, version 3.
  6. //
  7. // This program is distributed in the hope that it will be useful,
  8. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. // GNU Affero General Public License for more details.
  11. //
  12. // You should have received a copy of the GNU Affero General Public License
  13. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. package vfs
  15. import (
  16. "errors"
  17. "fmt"
  18. "io"
  19. "io/fs"
  20. "net/http"
  21. "os"
  22. "path"
  23. "path/filepath"
  24. "strings"
  25. "time"
  26. "github.com/eikenb/pipeat"
  27. fscopy "github.com/otiai10/copy"
  28. "github.com/pkg/sftp"
  29. "github.com/rs/xid"
  30. "github.com/drakkan/sftpgo/v2/logger"
  31. )
  32. const (
  33. // osFsName is the name for the local Fs implementation
  34. osFsName = "osfs"
  35. )
  36. type pathResolutionError struct {
  37. err string
  38. }
  39. func (e *pathResolutionError) Error() string {
  40. return fmt.Sprintf("Path resolution error: %s", e.err)
  41. }
  42. // OsFs is a Fs implementation that uses functions provided by the os package.
  43. type OsFs struct {
  44. name string
  45. connectionID string
  46. rootDir string
  47. // if not empty this fs is mouted as virtual folder in the specified path
  48. mountPath string
  49. }
  50. // NewOsFs returns an OsFs object that allows to interact with local Os filesystem
  51. func NewOsFs(connectionID, rootDir, mountPath string) Fs {
  52. return &OsFs{
  53. name: osFsName,
  54. connectionID: connectionID,
  55. rootDir: rootDir,
  56. mountPath: getMountPath(mountPath),
  57. }
  58. }
  59. // Name returns the name for the Fs implementation
  60. func (fs *OsFs) Name() string {
  61. return fs.name
  62. }
  63. // ConnectionID returns the SSH connection ID associated to this Fs implementation
  64. func (fs *OsFs) ConnectionID() string {
  65. return fs.connectionID
  66. }
  67. // Stat returns a FileInfo describing the named file
  68. func (fs *OsFs) Stat(name string) (os.FileInfo, error) {
  69. return os.Stat(name)
  70. }
  71. // Lstat returns a FileInfo describing the named file
  72. func (fs *OsFs) Lstat(name string) (os.FileInfo, error) {
  73. return os.Lstat(name)
  74. }
  75. // Open opens the named file for reading
  76. func (*OsFs) Open(name string, offset int64) (File, *pipeat.PipeReaderAt, func(), error) {
  77. f, err := os.Open(name)
  78. if err != nil {
  79. return nil, nil, nil, err
  80. }
  81. if offset > 0 {
  82. _, err = f.Seek(offset, io.SeekStart)
  83. if err != nil {
  84. f.Close()
  85. return nil, nil, nil, err
  86. }
  87. }
  88. return f, nil, nil, err
  89. }
  90. // Create creates or opens the named file for writing
  91. func (*OsFs) Create(name string, flag int) (File, *PipeWriter, func(), error) {
  92. var err error
  93. var f *os.File
  94. if flag == 0 {
  95. f, err = os.Create(name)
  96. } else {
  97. f, err = os.OpenFile(name, flag, 0666)
  98. }
  99. return f, nil, nil, err
  100. }
  101. // Rename renames (moves) source to target
  102. func (fs *OsFs) Rename(source, target string) error {
  103. err := os.Rename(source, target)
  104. if err != nil && isCrossDeviceError(err) {
  105. fsLog(fs, logger.LevelError, "cross device error detected while renaming %#v -> %#v. Trying a copy and remove, this could take a long time",
  106. source, target)
  107. err = fscopy.Copy(source, target, fscopy.Options{
  108. OnSymlink: func(src string) fscopy.SymlinkAction {
  109. return fscopy.Skip
  110. },
  111. })
  112. if err != nil {
  113. fsLog(fs, logger.LevelError, "cross device copy error: %v", err)
  114. return err
  115. }
  116. return os.RemoveAll(source)
  117. }
  118. return err
  119. }
  120. // Remove removes the named file or (empty) directory.
  121. func (*OsFs) Remove(name string, isDir bool) error {
  122. return os.Remove(name)
  123. }
  124. // Mkdir creates a new directory with the specified name and default permissions
  125. func (*OsFs) Mkdir(name string) error {
  126. return os.Mkdir(name, os.ModePerm)
  127. }
  128. // Symlink creates source as a symbolic link to target.
  129. func (*OsFs) Symlink(source, target string) error {
  130. return os.Symlink(source, target)
  131. }
  132. // Readlink returns the destination of the named symbolic link
  133. // as absolute virtual path
  134. func (fs *OsFs) Readlink(name string) (string, error) {
  135. // we don't have to follow multiple links:
  136. // https://github.com/openssh/openssh-portable/blob/7bf2eb958fbb551e7d61e75c176bb3200383285d/sftp-server.c#L1329
  137. resolved, err := os.Readlink(name)
  138. if err != nil {
  139. return "", err
  140. }
  141. resolved = filepath.Clean(resolved)
  142. if !filepath.IsAbs(resolved) {
  143. resolved = filepath.Join(filepath.Dir(name), resolved)
  144. }
  145. return fs.GetRelativePath(resolved), nil
  146. }
  147. // Chown changes the numeric uid and gid of the named file.
  148. func (*OsFs) Chown(name string, uid int, gid int) error {
  149. return os.Chown(name, uid, gid)
  150. }
  151. // Chmod changes the mode of the named file to mode
  152. func (*OsFs) Chmod(name string, mode os.FileMode) error {
  153. return os.Chmod(name, mode)
  154. }
  155. // Chtimes changes the access and modification times of the named file
  156. func (*OsFs) Chtimes(name string, atime, mtime time.Time, isUploading bool) error {
  157. return os.Chtimes(name, atime, mtime)
  158. }
  159. // Truncate changes the size of the named file
  160. func (*OsFs) Truncate(name string, size int64) error {
  161. return os.Truncate(name, size)
  162. }
  163. // ReadDir reads the directory named by dirname and returns
  164. // a list of directory entries.
  165. func (*OsFs) ReadDir(dirname string) ([]os.FileInfo, error) {
  166. f, err := os.Open(dirname)
  167. if err != nil {
  168. if isInvalidNameError(err) {
  169. err = os.ErrNotExist
  170. }
  171. return nil, err
  172. }
  173. list, err := f.Readdir(-1)
  174. f.Close()
  175. if err != nil {
  176. return nil, err
  177. }
  178. return list, nil
  179. }
  180. // IsUploadResumeSupported returns true if resuming uploads is supported
  181. func (*OsFs) IsUploadResumeSupported() bool {
  182. return true
  183. }
  184. // IsAtomicUploadSupported returns true if atomic upload is supported
  185. func (*OsFs) IsAtomicUploadSupported() bool {
  186. return true
  187. }
  188. // IsNotExist returns a boolean indicating whether the error is known to
  189. // report that a file or directory does not exist
  190. func (*OsFs) IsNotExist(err error) bool {
  191. return errors.Is(err, fs.ErrNotExist)
  192. }
  193. // IsPermission returns a boolean indicating whether the error is known to
  194. // report that permission is denied.
  195. func (*OsFs) IsPermission(err error) bool {
  196. if _, ok := err.(*pathResolutionError); ok {
  197. return true
  198. }
  199. return errors.Is(err, fs.ErrPermission)
  200. }
  201. // IsNotSupported returns true if the error indicate an unsupported operation
  202. func (*OsFs) IsNotSupported(err error) bool {
  203. if err == nil {
  204. return false
  205. }
  206. return err == ErrVfsUnsupported
  207. }
  208. // CheckRootPath creates the root directory if it does not exists
  209. func (fs *OsFs) CheckRootPath(username string, uid int, gid int) bool {
  210. var err error
  211. if _, err = fs.Stat(fs.rootDir); fs.IsNotExist(err) {
  212. err = os.MkdirAll(fs.rootDir, os.ModePerm)
  213. if err == nil {
  214. SetPathPermissions(fs, fs.rootDir, uid, gid)
  215. } else {
  216. fsLog(fs, logger.LevelError, "error creating root directory %q for user %q: %v", fs.rootDir, username, err)
  217. }
  218. }
  219. return err == nil
  220. }
  221. // ScanRootDirContents returns the number of files contained in the root
  222. // directory and their size
  223. func (fs *OsFs) ScanRootDirContents() (int, int64, error) {
  224. return fs.GetDirSize(fs.rootDir)
  225. }
  226. // CheckMetadata checks the metadata consistency
  227. func (*OsFs) CheckMetadata() error {
  228. return nil
  229. }
  230. // GetAtomicUploadPath returns the path to use for an atomic upload
  231. func (*OsFs) GetAtomicUploadPath(name string) string {
  232. dir := filepath.Dir(name)
  233. if tempPath != "" {
  234. dir = tempPath
  235. }
  236. guid := xid.New().String()
  237. return filepath.Join(dir, ".sftpgo-upload."+guid+"."+filepath.Base(name))
  238. }
  239. // GetRelativePath returns the path for a file relative to the user's home dir.
  240. // This is the path as seen by SFTPGo users
  241. func (fs *OsFs) GetRelativePath(name string) string {
  242. virtualPath := "/"
  243. if fs.mountPath != "" {
  244. virtualPath = fs.mountPath
  245. }
  246. rel, err := filepath.Rel(fs.rootDir, filepath.Clean(name))
  247. if err != nil {
  248. return ""
  249. }
  250. if rel == "." || strings.HasPrefix(rel, "..") {
  251. rel = ""
  252. }
  253. return path.Join(virtualPath, filepath.ToSlash(rel))
  254. }
  255. // Walk walks the file tree rooted at root, calling walkFn for each file or
  256. // directory in the tree, including root
  257. func (*OsFs) Walk(root string, walkFn filepath.WalkFunc) error {
  258. return filepath.Walk(root, walkFn)
  259. }
  260. // Join joins any number of path elements into a single path
  261. func (*OsFs) Join(elem ...string) string {
  262. return filepath.Join(elem...)
  263. }
  264. // ResolvePath returns the matching filesystem path for the specified sftp path
  265. func (fs *OsFs) ResolvePath(virtualPath string) (string, error) {
  266. if !filepath.IsAbs(fs.rootDir) {
  267. return "", fmt.Errorf("invalid root path: %v", fs.rootDir)
  268. }
  269. if fs.mountPath != "" {
  270. virtualPath = strings.TrimPrefix(virtualPath, fs.mountPath)
  271. }
  272. r := filepath.Clean(filepath.Join(fs.rootDir, virtualPath))
  273. p, err := filepath.EvalSymlinks(r)
  274. if isInvalidNameError(err) {
  275. err = os.ErrNotExist
  276. }
  277. isNotExist := fs.IsNotExist(err)
  278. if err != nil && !isNotExist {
  279. return "", err
  280. } else if isNotExist {
  281. // The requested path doesn't exist, so at this point we need to iterate up the
  282. // path chain until we hit a directory that _does_ exist and can be validated.
  283. _, err = fs.findFirstExistingDir(r)
  284. if err != nil {
  285. fsLog(fs, logger.LevelError, "error resolving non-existent path %#v", err)
  286. }
  287. return r, err
  288. }
  289. err = fs.isSubDir(p)
  290. if err != nil {
  291. fsLog(fs, logger.LevelError, "Invalid path resolution, dir %#v original path %#v resolved %#v err: %v",
  292. p, virtualPath, r, err)
  293. }
  294. return r, err
  295. }
  296. // GetDirSize returns the number of files and the size for a folder
  297. // including any subfolders
  298. func (fs *OsFs) GetDirSize(dirname string) (int, int64, error) {
  299. numFiles := 0
  300. size := int64(0)
  301. isDir, err := IsDirectory(fs, dirname)
  302. if err == nil && isDir {
  303. err = filepath.Walk(dirname, func(path string, info os.FileInfo, err error) error {
  304. if err != nil {
  305. return err
  306. }
  307. if info != nil && info.Mode().IsRegular() {
  308. size += info.Size()
  309. numFiles++
  310. }
  311. return err
  312. })
  313. }
  314. return numFiles, size, err
  315. }
  316. // HasVirtualFolders returns true if folders are emulated
  317. func (*OsFs) HasVirtualFolders() bool {
  318. return false
  319. }
  320. func (fs *OsFs) findNonexistentDirs(filePath string) ([]string, error) {
  321. results := []string{}
  322. cleanPath := filepath.Clean(filePath)
  323. parent := filepath.Dir(cleanPath)
  324. _, err := os.Stat(parent)
  325. for fs.IsNotExist(err) {
  326. results = append(results, parent)
  327. parent = filepath.Dir(parent)
  328. _, err = os.Stat(parent)
  329. }
  330. if err != nil {
  331. return results, err
  332. }
  333. p, err := filepath.EvalSymlinks(parent)
  334. if err != nil {
  335. return results, err
  336. }
  337. err = fs.isSubDir(p)
  338. if err != nil {
  339. fsLog(fs, logger.LevelError, "error finding non existing dir: %v", err)
  340. }
  341. return results, err
  342. }
  343. func (fs *OsFs) findFirstExistingDir(path string) (string, error) {
  344. results, err := fs.findNonexistentDirs(path)
  345. if err != nil {
  346. fsLog(fs, logger.LevelError, "unable to find non existent dirs: %v", err)
  347. return "", err
  348. }
  349. var parent string
  350. if len(results) > 0 {
  351. lastMissingDir := results[len(results)-1]
  352. parent = filepath.Dir(lastMissingDir)
  353. } else {
  354. parent = fs.rootDir
  355. }
  356. p, err := filepath.EvalSymlinks(parent)
  357. if err != nil {
  358. return "", err
  359. }
  360. fileInfo, err := os.Stat(p)
  361. if err != nil {
  362. return "", err
  363. }
  364. if !fileInfo.IsDir() {
  365. return "", fmt.Errorf("resolved path is not a dir: %#v", p)
  366. }
  367. err = fs.isSubDir(p)
  368. return p, err
  369. }
  370. func (fs *OsFs) isSubDir(sub string) error {
  371. // fs.rootDir must exist and it is already a validated absolute path
  372. parent, err := filepath.EvalSymlinks(fs.rootDir)
  373. if err != nil {
  374. fsLog(fs, logger.LevelError, "invalid root path %#v: %v", fs.rootDir, err)
  375. return err
  376. }
  377. if parent == sub {
  378. return nil
  379. }
  380. if len(sub) < len(parent) {
  381. err = fmt.Errorf("path %#v is not inside %#v", sub, parent)
  382. return &pathResolutionError{err: err.Error()}
  383. }
  384. separator := string(os.PathSeparator)
  385. if parent == filepath.Dir(parent) {
  386. // parent is the root dir, on Windows we can have C:\, D:\ and so on here
  387. // so we still need the prefix check
  388. separator = ""
  389. }
  390. if !strings.HasPrefix(sub, parent+separator) {
  391. err = fmt.Errorf("path %#v is not inside %#v", sub, parent)
  392. return &pathResolutionError{err: err.Error()}
  393. }
  394. return nil
  395. }
  396. // GetMimeType returns the content type
  397. func (fs *OsFs) GetMimeType(name string) (string, error) {
  398. f, err := os.OpenFile(name, os.O_RDONLY, 0)
  399. if err != nil {
  400. return "", err
  401. }
  402. defer f.Close()
  403. var buf [512]byte
  404. n, err := io.ReadFull(f, buf[:])
  405. if err != nil && err != io.EOF && err != io.ErrUnexpectedEOF {
  406. return "", err
  407. }
  408. ctype := http.DetectContentType(buf[:n])
  409. // Rewind file.
  410. _, err = f.Seek(0, io.SeekStart)
  411. return ctype, err
  412. }
  413. // Close closes the fs
  414. func (*OsFs) Close() error {
  415. return nil
  416. }
  417. // GetAvailableDiskSize returns the available size for the specified path
  418. func (*OsFs) GetAvailableDiskSize(dirName string) (*sftp.StatVFS, error) {
  419. return getStatFS(dirName)
  420. }