osfs.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  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 %q", 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, path %q original path %q resolved %q err: %v",
  292. p, virtualPath, r, err)
  293. }
  294. return r, err
  295. }
  296. // RealPath implements the FsRealPather interface
  297. func (fs *OsFs) RealPath(p string) (string, error) {
  298. linksWalked := 0
  299. for {
  300. info, err := os.Lstat(p)
  301. if err != nil {
  302. if errors.Is(err, os.ErrNotExist) {
  303. return fs.GetRelativePath(p), nil
  304. }
  305. return "", err
  306. }
  307. if info.Mode()&os.ModeSymlink == 0 {
  308. return fs.GetRelativePath(p), nil
  309. }
  310. resolvedLink, err := os.Readlink(p)
  311. if err != nil {
  312. return "", err
  313. }
  314. resolvedLink = filepath.Clean(resolvedLink)
  315. if filepath.IsAbs(resolvedLink) {
  316. p = resolvedLink
  317. } else {
  318. p = filepath.Join(filepath.Dir(p), resolvedLink)
  319. }
  320. linksWalked++
  321. if linksWalked > 10 {
  322. fsLog(fs, logger.LevelError, "unable to get real path, too many links: %d", linksWalked)
  323. return "", &pathResolutionError{err: "too many links"}
  324. }
  325. }
  326. }
  327. // GetDirSize returns the number of files and the size for a folder
  328. // including any subfolders
  329. func (fs *OsFs) GetDirSize(dirname string) (int, int64, error) {
  330. numFiles := 0
  331. size := int64(0)
  332. isDir, err := IsDirectory(fs, dirname)
  333. if err == nil && isDir {
  334. err = filepath.Walk(dirname, func(_ string, info os.FileInfo, err error) error {
  335. if err != nil {
  336. return err
  337. }
  338. if info != nil && info.Mode().IsRegular() {
  339. size += info.Size()
  340. numFiles++
  341. }
  342. return err
  343. })
  344. }
  345. return numFiles, size, err
  346. }
  347. // HasVirtualFolders returns true if folders are emulated
  348. func (*OsFs) HasVirtualFolders() bool {
  349. return false
  350. }
  351. func (fs *OsFs) findNonexistentDirs(filePath string) ([]string, error) {
  352. results := []string{}
  353. cleanPath := filepath.Clean(filePath)
  354. parent := filepath.Dir(cleanPath)
  355. _, err := os.Stat(parent)
  356. for fs.IsNotExist(err) {
  357. results = append(results, parent)
  358. parent = filepath.Dir(parent)
  359. _, err = os.Stat(parent)
  360. }
  361. if err != nil {
  362. return results, err
  363. }
  364. p, err := filepath.EvalSymlinks(parent)
  365. if err != nil {
  366. return results, err
  367. }
  368. err = fs.isSubDir(p)
  369. if err != nil {
  370. fsLog(fs, logger.LevelError, "error finding non existing dir: %v", err)
  371. }
  372. return results, err
  373. }
  374. func (fs *OsFs) findFirstExistingDir(path string) (string, error) {
  375. results, err := fs.findNonexistentDirs(path)
  376. if err != nil {
  377. fsLog(fs, logger.LevelError, "unable to find non existent dirs: %v", err)
  378. return "", err
  379. }
  380. var parent string
  381. if len(results) > 0 {
  382. lastMissingDir := results[len(results)-1]
  383. parent = filepath.Dir(lastMissingDir)
  384. } else {
  385. parent = fs.rootDir
  386. }
  387. p, err := filepath.EvalSymlinks(parent)
  388. if err != nil {
  389. return "", err
  390. }
  391. fileInfo, err := os.Stat(p)
  392. if err != nil {
  393. return "", err
  394. }
  395. if !fileInfo.IsDir() {
  396. return "", fmt.Errorf("resolved path is not a dir: %#v", p)
  397. }
  398. err = fs.isSubDir(p)
  399. return p, err
  400. }
  401. func (fs *OsFs) isSubDir(sub string) error {
  402. // fs.rootDir must exist and it is already a validated absolute path
  403. parent, err := filepath.EvalSymlinks(fs.rootDir)
  404. if err != nil {
  405. fsLog(fs, logger.LevelError, "invalid root path %q: %v", fs.rootDir, err)
  406. return err
  407. }
  408. if parent == sub {
  409. return nil
  410. }
  411. if len(sub) < len(parent) {
  412. err = fmt.Errorf("path %q is not inside %q", sub, parent)
  413. return &pathResolutionError{err: err.Error()}
  414. }
  415. separator := string(os.PathSeparator)
  416. if parent == filepath.Dir(parent) {
  417. // parent is the root dir, on Windows we can have C:\, D:\ and so on here
  418. // so we still need the prefix check
  419. separator = ""
  420. }
  421. if !strings.HasPrefix(sub, parent+separator) {
  422. err = fmt.Errorf("path %q is not inside %q", sub, parent)
  423. return &pathResolutionError{err: err.Error()}
  424. }
  425. return nil
  426. }
  427. // GetMimeType returns the content type
  428. func (fs *OsFs) GetMimeType(name string) (string, error) {
  429. f, err := os.OpenFile(name, os.O_RDONLY, 0)
  430. if err != nil {
  431. return "", err
  432. }
  433. defer f.Close()
  434. var buf [512]byte
  435. n, err := io.ReadFull(f, buf[:])
  436. if err != nil && err != io.EOF && err != io.ErrUnexpectedEOF {
  437. return "", err
  438. }
  439. ctype := http.DetectContentType(buf[:n])
  440. // Rewind file.
  441. _, err = f.Seek(0, io.SeekStart)
  442. return ctype, err
  443. }
  444. // Close closes the fs
  445. func (*OsFs) Close() error {
  446. return nil
  447. }
  448. // GetAvailableDiskSize returns the available size for the specified path
  449. func (*OsFs) GetAvailableDiskSize(dirName string) (*sftp.StatVFS, error) {
  450. return getStatFS(dirName)
  451. }