osfs.go 11 KB

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