osfs.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. package vfs
  2. import (
  3. "fmt"
  4. "os"
  5. "path"
  6. "path/filepath"
  7. "strings"
  8. "time"
  9. "github.com/eikenb/pipeat"
  10. "github.com/rs/xid"
  11. "github.com/drakkan/sftpgo/logger"
  12. "github.com/drakkan/sftpgo/utils"
  13. )
  14. const (
  15. // osFsName is the name for the local Fs implementation
  16. osFsName = "osfs"
  17. )
  18. // OsFs is a Fs implementation that uses functions provided by the os package.
  19. type OsFs struct {
  20. name string
  21. connectionID string
  22. rootDir string
  23. virtualFolders []VirtualFolder
  24. }
  25. // NewOsFs returns an OsFs object that allows to interact with local Os filesystem
  26. func NewOsFs(connectionID, rootDir string, virtualFolders []VirtualFolder) Fs {
  27. return OsFs{
  28. name: osFsName,
  29. connectionID: connectionID,
  30. rootDir: rootDir,
  31. virtualFolders: virtualFolders,
  32. }
  33. }
  34. // Name returns the name for the Fs implementation
  35. func (fs OsFs) Name() string {
  36. return fs.name
  37. }
  38. // ConnectionID returns the SSH connection ID associated to this Fs implementation
  39. func (fs OsFs) ConnectionID() string {
  40. return fs.connectionID
  41. }
  42. // Stat returns a FileInfo describing the named file
  43. func (OsFs) Stat(name string) (os.FileInfo, error) {
  44. return os.Stat(name)
  45. }
  46. // Lstat returns a FileInfo describing the named file
  47. func (OsFs) Lstat(name string) (os.FileInfo, error) {
  48. return os.Lstat(name)
  49. }
  50. // Open opens the named file for reading
  51. func (OsFs) Open(name string) (*os.File, *pipeat.PipeReaderAt, func(), error) {
  52. f, err := os.Open(name)
  53. return f, nil, nil, err
  54. }
  55. // Create creates or opens the named file for writing
  56. func (OsFs) Create(name string, flag int) (*os.File, *PipeWriter, func(), error) {
  57. var err error
  58. var f *os.File
  59. if flag == 0 {
  60. f, err = os.Create(name)
  61. } else {
  62. f, err = os.OpenFile(name, flag, 0666)
  63. }
  64. return f, nil, nil, err
  65. }
  66. // Rename renames (moves) source to target
  67. func (OsFs) Rename(source, target string) error {
  68. return os.Rename(source, target)
  69. }
  70. // Remove removes the named file or (empty) directory.
  71. func (OsFs) Remove(name string, isDir bool) error {
  72. return os.Remove(name)
  73. }
  74. // Mkdir creates a new directory with the specified name and default permissions
  75. func (OsFs) Mkdir(name string) error {
  76. return os.Mkdir(name, 0777)
  77. }
  78. // Symlink creates source as a symbolic link to target.
  79. func (OsFs) Symlink(source, target string) error {
  80. return os.Symlink(source, target)
  81. }
  82. // Chown changes the numeric uid and gid of the named file.
  83. func (OsFs) Chown(name string, uid int, gid int) error {
  84. return os.Chown(name, uid, gid)
  85. }
  86. // Chmod changes the mode of the named file to mode
  87. func (OsFs) Chmod(name string, mode os.FileMode) error {
  88. return os.Chmod(name, mode)
  89. }
  90. // Chtimes changes the access and modification times of the named file
  91. func (OsFs) Chtimes(name string, atime, mtime time.Time) error {
  92. return os.Chtimes(name, atime, mtime)
  93. }
  94. // ReadDir reads the directory named by dirname and returns
  95. // a list of directory entries.
  96. func (OsFs) ReadDir(dirname string) ([]os.FileInfo, error) {
  97. f, err := os.Open(dirname)
  98. if err != nil {
  99. return nil, err
  100. }
  101. list, err := f.Readdir(-1)
  102. f.Close()
  103. if err != nil {
  104. return nil, err
  105. }
  106. return list, nil
  107. }
  108. // IsUploadResumeSupported returns true if upload resume is supported
  109. func (OsFs) IsUploadResumeSupported() bool {
  110. return true
  111. }
  112. // IsAtomicUploadSupported returns true if atomic upload is supported
  113. func (OsFs) IsAtomicUploadSupported() bool {
  114. return true
  115. }
  116. // IsNotExist returns a boolean indicating whether the error is known to
  117. // report that a file or directory does not exist
  118. func (OsFs) IsNotExist(err error) bool {
  119. return os.IsNotExist(err)
  120. }
  121. // IsPermission returns a boolean indicating whether the error is known to
  122. // report that permission is denied.
  123. func (OsFs) IsPermission(err error) bool {
  124. return os.IsPermission(err)
  125. }
  126. // CheckRootPath creates the root directory if it does not exists
  127. func (fs OsFs) CheckRootPath(username string, uid int, gid int) bool {
  128. var err error
  129. if _, err = fs.Stat(fs.rootDir); fs.IsNotExist(err) {
  130. err = os.MkdirAll(fs.rootDir, 0777)
  131. fsLog(fs, logger.LevelDebug, "root directory %#v for user %#v does not exist, try to create, mkdir error: %v",
  132. fs.rootDir, username, err)
  133. if err == nil {
  134. SetPathPermissions(fs, fs.rootDir, uid, gid)
  135. }
  136. }
  137. // create any missing dirs to the defined virtual dirs
  138. for _, v := range fs.virtualFolders {
  139. p := filepath.Clean(filepath.Join(fs.rootDir, v.VirtualPath))
  140. err = fs.createMissingDirs(p, uid, gid)
  141. if err != nil {
  142. return false
  143. }
  144. }
  145. return (err == nil)
  146. }
  147. // ScanRootDirContents returns the number of files contained in a directory and
  148. // their size
  149. func (fs OsFs) ScanRootDirContents() (int, int64, error) {
  150. numFiles, size, err := fs.GetDirSize(fs.rootDir)
  151. for _, v := range fs.virtualFolders {
  152. if !v.IsIncludedInUserQuota() {
  153. continue
  154. }
  155. num, s, err := fs.GetDirSize(v.MappedPath)
  156. if err != nil {
  157. if fs.IsNotExist(err) {
  158. fsLog(fs, logger.LevelWarn, "unable to scan contents for non-existent mapped path: %#v", v.MappedPath)
  159. continue
  160. }
  161. return numFiles, size, err
  162. }
  163. numFiles += num
  164. size += s
  165. }
  166. return numFiles, size, err
  167. }
  168. // GetAtomicUploadPath returns the path to use for an atomic upload
  169. func (OsFs) GetAtomicUploadPath(name string) string {
  170. dir := filepath.Dir(name)
  171. guid := xid.New().String()
  172. return filepath.Join(dir, ".sftpgo-upload."+guid+"."+filepath.Base(name))
  173. }
  174. // GetRelativePath returns the path for a file relative to the user's home dir.
  175. // This is the path as seen by SFTP users
  176. func (fs OsFs) GetRelativePath(name string) string {
  177. basePath := fs.rootDir
  178. virtualPath := "/"
  179. for _, v := range fs.virtualFolders {
  180. if strings.HasPrefix(name, v.MappedPath+string(os.PathSeparator)) ||
  181. filepath.Clean(name) == v.MappedPath {
  182. basePath = v.MappedPath
  183. virtualPath = v.VirtualPath
  184. }
  185. }
  186. rel, err := filepath.Rel(basePath, filepath.Clean(name))
  187. if err != nil {
  188. return ""
  189. }
  190. if rel == "." || strings.HasPrefix(rel, "..") {
  191. rel = ""
  192. }
  193. return path.Join(virtualPath, filepath.ToSlash(rel))
  194. }
  195. // Join joins any number of path elements into a single path
  196. func (OsFs) Join(elem ...string) string {
  197. return filepath.Join(elem...)
  198. }
  199. // ResolvePath returns the matching filesystem path for the specified sftp path
  200. func (fs OsFs) ResolvePath(sftpPath string) (string, error) {
  201. if !filepath.IsAbs(fs.rootDir) {
  202. return "", fmt.Errorf("Invalid root path: %v", fs.rootDir)
  203. }
  204. basePath, r := fs.GetFsPaths(sftpPath)
  205. p, err := filepath.EvalSymlinks(r)
  206. if err != nil && !os.IsNotExist(err) {
  207. return "", err
  208. } else if os.IsNotExist(err) {
  209. // The requested path doesn't exist, so at this point we need to iterate up the
  210. // path chain until we hit a directory that _does_ exist and can be validated.
  211. _, err = fs.findFirstExistingDir(r, basePath)
  212. if err != nil {
  213. fsLog(fs, logger.LevelWarn, "error resolving non-existent path: %#v", err)
  214. }
  215. return r, err
  216. }
  217. err = fs.isSubDir(p, basePath)
  218. if err != nil {
  219. fsLog(fs, logger.LevelWarn, "Invalid path resolution, dir: %#v outside user home: %#v err: %v", p, fs.rootDir, err)
  220. }
  221. return r, err
  222. }
  223. // GetDirSize returns the number of files and the size for a folder
  224. // including any subfolders
  225. func (fs OsFs) GetDirSize(dirname string) (int, int64, error) {
  226. numFiles := 0
  227. size := int64(0)
  228. isDir, err := IsDirectory(fs, dirname)
  229. if err == nil && isDir {
  230. err = filepath.Walk(dirname, func(path string, info os.FileInfo, err error) error {
  231. if err != nil {
  232. return err
  233. }
  234. if info != nil && info.Mode().IsRegular() {
  235. size += info.Size()
  236. numFiles++
  237. }
  238. return err
  239. })
  240. }
  241. return numFiles, size, err
  242. }
  243. // GetFsPaths returns the base path and filesystem path for the given sftpPath.
  244. // base path is the root dir or matching the virtual folder dir for the sftpPath.
  245. // file path is the filesystem path matching the sftpPath
  246. func (fs *OsFs) GetFsPaths(sftpPath string) (string, string) {
  247. basePath := fs.rootDir
  248. virtualPath, mappedPath := fs.getMappedFolderForPath(sftpPath)
  249. if len(mappedPath) > 0 {
  250. basePath = mappedPath
  251. sftpPath = strings.TrimPrefix(utils.CleanSFTPPath(sftpPath), virtualPath)
  252. }
  253. r := filepath.Clean(filepath.Join(basePath, sftpPath))
  254. return basePath, r
  255. }
  256. // returns the path for the mapped folders or an empty string
  257. func (fs *OsFs) getMappedFolderForPath(p string) (virtualPath, mappedPath string) {
  258. if len(fs.virtualFolders) == 0 {
  259. return
  260. }
  261. dirsForPath := utils.GetDirsForSFTPPath(p)
  262. // dirsForPath contains all the dirs for a given path in reverse order
  263. // for example if the path is: /1/2/3/4 it contains:
  264. // [ "/1/2/3/4", "/1/2/3", "/1/2", "/1", "/" ]
  265. // so the first match is the one we are interested to
  266. for _, val := range dirsForPath {
  267. for _, v := range fs.virtualFolders {
  268. if val == v.VirtualPath {
  269. return v.VirtualPath, v.MappedPath
  270. }
  271. }
  272. }
  273. return
  274. }
  275. func (fs *OsFs) findNonexistentDirs(path, rootPath string) ([]string, error) {
  276. results := []string{}
  277. cleanPath := filepath.Clean(path)
  278. parent := filepath.Dir(cleanPath)
  279. _, err := os.Stat(parent)
  280. for os.IsNotExist(err) {
  281. results = append(results, parent)
  282. parent = filepath.Dir(parent)
  283. _, err = os.Stat(parent)
  284. }
  285. if err != nil {
  286. return results, err
  287. }
  288. p, err := filepath.EvalSymlinks(parent)
  289. if err != nil {
  290. return results, err
  291. }
  292. err = fs.isSubDir(p, rootPath)
  293. if err != nil {
  294. fsLog(fs, logger.LevelWarn, "error finding non existing dir: %v", err)
  295. }
  296. return results, err
  297. }
  298. func (fs *OsFs) findFirstExistingDir(path, rootPath string) (string, error) {
  299. results, err := fs.findNonexistentDirs(path, rootPath)
  300. if err != nil {
  301. fsLog(fs, logger.LevelWarn, "unable to find non existent dirs: %v", err)
  302. return "", err
  303. }
  304. var parent string
  305. if len(results) > 0 {
  306. lastMissingDir := results[len(results)-1]
  307. parent = filepath.Dir(lastMissingDir)
  308. } else {
  309. parent = rootPath
  310. }
  311. p, err := filepath.EvalSymlinks(parent)
  312. if err != nil {
  313. return "", err
  314. }
  315. fileInfo, err := os.Stat(p)
  316. if err != nil {
  317. return "", err
  318. }
  319. if !fileInfo.IsDir() {
  320. return "", fmt.Errorf("resolved path is not a dir: %#v", p)
  321. }
  322. err = fs.isSubDir(p, rootPath)
  323. return p, err
  324. }
  325. func (fs *OsFs) isSubDir(sub, rootPath string) error {
  326. // rootPath must exist and it is already a validated absolute path
  327. parent, err := filepath.EvalSymlinks(rootPath)
  328. if err != nil {
  329. fsLog(fs, logger.LevelWarn, "invalid root path %#v: %v", rootPath, err)
  330. return err
  331. }
  332. if !strings.HasPrefix(sub, parent) {
  333. err = fmt.Errorf("path %#v is not inside: %#v", sub, parent)
  334. fsLog(fs, logger.LevelWarn, "error: %v ", err)
  335. return err
  336. }
  337. return nil
  338. }
  339. func (fs *OsFs) createMissingDirs(filePath string, uid, gid int) error {
  340. dirsToCreate, err := fs.findNonexistentDirs(filePath, fs.rootDir)
  341. if err != nil {
  342. return err
  343. }
  344. last := len(dirsToCreate) - 1
  345. for i := range dirsToCreate {
  346. d := dirsToCreate[last-i]
  347. if err := os.Mkdir(d, 0777); err != nil {
  348. fsLog(fs, logger.LevelError, "error creating missing dir: %#v", d)
  349. return err
  350. }
  351. SetPathPermissions(fs, d, uid, gid)
  352. }
  353. return nil
  354. }