osfs.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. package vfs
  2. import (
  3. "fmt"
  4. "os"
  5. "path"
  6. "path/filepath"
  7. "strings"
  8. "time"
  9. "github.com/drakkan/sftpgo/logger"
  10. "github.com/drakkan/sftpgo/utils"
  11. "github.com/eikenb/pipeat"
  12. "github.com/rs/xid"
  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, *pipeat.PipeWriterAt, 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.ExcludeFromQuota {
  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. // GetFsPaths returns the base path and filesystem path for the given sftpPath.
  224. // base path is the root dir or matching the virtual folder dir for the sftpPath.
  225. // file path is the filesystem path matching the sftpPath
  226. func (fs *OsFs) GetFsPaths(sftpPath string) (string, string) {
  227. basePath := fs.rootDir
  228. virtualPath, mappedPath := fs.getMappedFolderForPath(sftpPath)
  229. if len(mappedPath) > 0 {
  230. basePath = mappedPath
  231. sftpPath = strings.TrimPrefix(utils.CleanSFTPPath(sftpPath), virtualPath)
  232. }
  233. r := filepath.Clean(filepath.Join(basePath, sftpPath))
  234. return basePath, r
  235. }
  236. // returns the path for the mapped folders or an empty string
  237. func (fs *OsFs) getMappedFolderForPath(p string) (virtualPath, mappedPath string) {
  238. if len(fs.virtualFolders) == 0 {
  239. return
  240. }
  241. dirsForPath := utils.GetDirsForSFTPPath(p)
  242. // dirsForPath contains all the dirs for a given path in reverse order
  243. // for example if the path is: /1/2/3/4 it contains:
  244. // [ "/1/2/3/4", "/1/2/3", "/1/2", "/1", "/" ]
  245. // so the first match is the one we are interested to
  246. for _, val := range dirsForPath {
  247. for _, v := range fs.virtualFolders {
  248. if val == v.VirtualPath {
  249. return v.VirtualPath, v.MappedPath
  250. }
  251. }
  252. }
  253. return
  254. }
  255. func (fs *OsFs) findNonexistentDirs(path, rootPath string) ([]string, error) {
  256. results := []string{}
  257. cleanPath := filepath.Clean(path)
  258. parent := filepath.Dir(cleanPath)
  259. _, err := os.Stat(parent)
  260. for os.IsNotExist(err) {
  261. results = append(results, parent)
  262. parent = filepath.Dir(parent)
  263. _, err = os.Stat(parent)
  264. }
  265. if err != nil {
  266. return results, err
  267. }
  268. p, err := filepath.EvalSymlinks(parent)
  269. if err != nil {
  270. return results, err
  271. }
  272. err = fs.isSubDir(p, rootPath)
  273. if err != nil {
  274. fsLog(fs, logger.LevelWarn, "error finding non existing dir: %v", err)
  275. }
  276. return results, err
  277. }
  278. func (fs *OsFs) findFirstExistingDir(path, rootPath string) (string, error) {
  279. results, err := fs.findNonexistentDirs(path, rootPath)
  280. if err != nil {
  281. fsLog(fs, logger.LevelWarn, "unable to find non existent dirs: %v", err)
  282. return "", err
  283. }
  284. var parent string
  285. if len(results) > 0 {
  286. lastMissingDir := results[len(results)-1]
  287. parent = filepath.Dir(lastMissingDir)
  288. } else {
  289. parent = rootPath
  290. }
  291. p, err := filepath.EvalSymlinks(parent)
  292. if err != nil {
  293. return "", err
  294. }
  295. fileInfo, err := os.Stat(p)
  296. if err != nil {
  297. return "", err
  298. }
  299. if !fileInfo.IsDir() {
  300. return "", fmt.Errorf("resolved path is not a dir: %#v", p)
  301. }
  302. err = fs.isSubDir(p, rootPath)
  303. return p, err
  304. }
  305. func (fs *OsFs) isSubDir(sub, rootPath string) error {
  306. // rootPath must exist and it is already a validated absolute path
  307. parent, err := filepath.EvalSymlinks(rootPath)
  308. if err != nil {
  309. fsLog(fs, logger.LevelWarn, "invalid root path %#v: %v", rootPath, err)
  310. return err
  311. }
  312. if !strings.HasPrefix(sub, parent) {
  313. err = fmt.Errorf("path %#v is not inside: %#v", sub, parent)
  314. fsLog(fs, logger.LevelWarn, "error: %v ", err)
  315. return err
  316. }
  317. return nil
  318. }
  319. func (fs *OsFs) createMissingDirs(filePath string, uid, gid int) error {
  320. dirsToCreate, err := fs.findNonexistentDirs(filePath, fs.rootDir)
  321. if err != nil {
  322. return err
  323. }
  324. last := len(dirsToCreate) - 1
  325. for i := range dirsToCreate {
  326. d := dirsToCreate[last-i]
  327. if err := os.Mkdir(d, 0777); err != nil {
  328. fsLog(fs, logger.LevelError, "error creating missing dir: %#v", d)
  329. return err
  330. }
  331. SetPathPermissions(fs, d, uid, gid)
  332. }
  333. return nil
  334. }
  335. func (fs *OsFs) getDirSize(dirname string) (int, int64, error) {
  336. numFiles := 0
  337. size := int64(0)
  338. isDir, err := IsDirectory(fs, dirname)
  339. if err == nil && isDir {
  340. err = filepath.Walk(dirname, func(path string, info os.FileInfo, err error) error {
  341. if err != nil {
  342. return err
  343. }
  344. if info != nil && info.Mode().IsRegular() {
  345. size += info.Size()
  346. numFiles++
  347. }
  348. return err
  349. })
  350. }
  351. return numFiles, size, err
  352. }