osfs.go 13 KB

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