1
0

osfs.go 16 KB

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