osfs.go 14 KB

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