osfs.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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. num, s, err := fs.getDirSize(v.MappedPath)
  153. if err != nil {
  154. if fs.IsNotExist(err) {
  155. fsLog(fs, logger.LevelWarn, "unable to scan contents for not existent mapped path: %#v", v.MappedPath)
  156. continue
  157. }
  158. return numFiles, size, err
  159. }
  160. numFiles += num
  161. size += s
  162. }
  163. return numFiles, size, err
  164. }
  165. // GetAtomicUploadPath returns the path to use for an atomic upload
  166. func (OsFs) GetAtomicUploadPath(name string) string {
  167. dir := filepath.Dir(name)
  168. guid := xid.New().String()
  169. return filepath.Join(dir, ".sftpgo-upload."+guid+"."+filepath.Base(name))
  170. }
  171. // GetRelativePath returns the path for a file relative to the user's home dir.
  172. // This is the path as seen by SFTP users
  173. func (fs OsFs) GetRelativePath(name string) string {
  174. basePath := fs.rootDir
  175. virtualPath := "/"
  176. for _, v := range fs.virtualFolders {
  177. if strings.HasPrefix(name, v.MappedPath+string(os.PathSeparator)) ||
  178. filepath.Clean(name) == v.MappedPath {
  179. basePath = v.MappedPath
  180. virtualPath = v.VirtualPath
  181. }
  182. }
  183. rel, err := filepath.Rel(basePath, filepath.Clean(name))
  184. if err != nil {
  185. return ""
  186. }
  187. if rel == "." || strings.HasPrefix(rel, "..") {
  188. rel = ""
  189. }
  190. return path.Join(virtualPath, filepath.ToSlash(rel))
  191. }
  192. // Join joins any number of path elements into a single path
  193. func (OsFs) Join(elem ...string) string {
  194. return filepath.Join(elem...)
  195. }
  196. // ResolvePath returns the matching filesystem path for the specified sftp path
  197. func (fs OsFs) ResolvePath(sftpPath string) (string, error) {
  198. if !filepath.IsAbs(fs.rootDir) {
  199. return "", fmt.Errorf("Invalid root path: %v", fs.rootDir)
  200. }
  201. basePath, r := fs.GetFsPaths(sftpPath)
  202. p, err := filepath.EvalSymlinks(r)
  203. if err != nil && !os.IsNotExist(err) {
  204. return "", err
  205. } else if os.IsNotExist(err) {
  206. // The requested path doesn't exist, so at this point we need to iterate up the
  207. // path chain until we hit a directory that _does_ exist and can be validated.
  208. _, err = fs.findFirstExistingDir(r, basePath)
  209. if err != nil {
  210. fsLog(fs, logger.LevelWarn, "error resolving not existent path: %#v", err)
  211. }
  212. return r, err
  213. }
  214. err = fs.isSubDir(p, basePath)
  215. if err != nil {
  216. fsLog(fs, logger.LevelWarn, "Invalid path resolution, dir: %#v outside user home: %#v err: %v", p, fs.rootDir, err)
  217. }
  218. return r, err
  219. }
  220. // GetFsPaths returns the base path and filesystem path for the given sftpPath.
  221. // base path is the root dir or matching the virtual folder dir for the sftpPath.
  222. // file path is the filesystem path matching the sftpPath
  223. func (fs *OsFs) GetFsPaths(sftpPath string) (string, string) {
  224. basePath := fs.rootDir
  225. virtualPath, mappedPath := fs.getMappedFolderForPath(sftpPath)
  226. if len(mappedPath) > 0 {
  227. basePath = mappedPath
  228. sftpPath = strings.TrimPrefix(utils.CleanSFTPPath(sftpPath), virtualPath)
  229. }
  230. r := filepath.Clean(filepath.Join(basePath, sftpPath))
  231. return basePath, r
  232. }
  233. // returns the path for the mapped folders or an empty string
  234. func (fs *OsFs) getMappedFolderForPath(p string) (virtualPath, mappedPath string) {
  235. if len(fs.virtualFolders) == 0 {
  236. return
  237. }
  238. dirsForPath := utils.GetDirsForSFTPPath(p)
  239. // dirsForPath contains all the dirs for a given path in reverse order
  240. // for example if the path is: /1/2/3/4 it contains:
  241. // [ "/1/2/3/4", "/1/2/3", "/1/2", "/1", "/" ]
  242. // so the first match is the one we are interested to
  243. for _, val := range dirsForPath {
  244. for _, v := range fs.virtualFolders {
  245. if val == v.VirtualPath {
  246. return v.VirtualPath, v.MappedPath
  247. }
  248. }
  249. }
  250. return
  251. }
  252. func (fs *OsFs) findNonexistentDirs(path, rootPath string) ([]string, error) {
  253. results := []string{}
  254. cleanPath := filepath.Clean(path)
  255. parent := filepath.Dir(cleanPath)
  256. _, err := os.Stat(parent)
  257. for os.IsNotExist(err) {
  258. results = append(results, parent)
  259. parent = filepath.Dir(parent)
  260. _, err = os.Stat(parent)
  261. }
  262. if err != nil {
  263. return results, err
  264. }
  265. p, err := filepath.EvalSymlinks(parent)
  266. if err != nil {
  267. return results, err
  268. }
  269. err = fs.isSubDir(p, rootPath)
  270. if err != nil {
  271. fsLog(fs, logger.LevelWarn, "error finding non existing dir: %v", err)
  272. }
  273. return results, err
  274. }
  275. func (fs *OsFs) findFirstExistingDir(path, rootPath string) (string, error) {
  276. results, err := fs.findNonexistentDirs(path, rootPath)
  277. if err != nil {
  278. fsLog(fs, logger.LevelWarn, "unable to find non existent dirs: %v", err)
  279. return "", err
  280. }
  281. var parent string
  282. if len(results) > 0 {
  283. lastMissingDir := results[len(results)-1]
  284. parent = filepath.Dir(lastMissingDir)
  285. } else {
  286. parent = rootPath
  287. }
  288. p, err := filepath.EvalSymlinks(parent)
  289. if err != nil {
  290. return "", err
  291. }
  292. fileInfo, err := os.Stat(p)
  293. if err != nil {
  294. return "", err
  295. }
  296. if !fileInfo.IsDir() {
  297. return "", fmt.Errorf("resolved path is not a dir: %#v", p)
  298. }
  299. err = fs.isSubDir(p, rootPath)
  300. return p, err
  301. }
  302. func (fs *OsFs) isSubDir(sub, rootPath string) error {
  303. // rootPath must exist and it is already a validated absolute path
  304. parent, err := filepath.EvalSymlinks(rootPath)
  305. if err != nil {
  306. fsLog(fs, logger.LevelWarn, "invalid root path %#v: %v", rootPath, err)
  307. return err
  308. }
  309. if !strings.HasPrefix(sub, parent) {
  310. err = fmt.Errorf("path %#v is not inside: %#v", sub, parent)
  311. fsLog(fs, logger.LevelWarn, "error: %v ", err)
  312. return err
  313. }
  314. return nil
  315. }
  316. func (fs *OsFs) createMissingDirs(filePath string, uid, gid int) error {
  317. dirsToCreate, err := fs.findNonexistentDirs(filePath, fs.rootDir)
  318. if err != nil {
  319. return err
  320. }
  321. last := len(dirsToCreate) - 1
  322. for i := range dirsToCreate {
  323. d := dirsToCreate[last-i]
  324. if err := os.Mkdir(d, 0777); err != nil {
  325. fsLog(fs, logger.LevelError, "error creating missing dir: %#v", d)
  326. return err
  327. }
  328. SetPathPermissions(fs, d, uid, gid)
  329. }
  330. return nil
  331. }
  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(path 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. }