osfs.go 12 KB

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