util.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package versioner
  7. import (
  8. "context"
  9. "errors"
  10. "fmt"
  11. "os"
  12. "path/filepath"
  13. "regexp"
  14. "slices"
  15. "strings"
  16. "time"
  17. "github.com/syncthing/syncthing/lib/config"
  18. "github.com/syncthing/syncthing/lib/fs"
  19. "github.com/syncthing/syncthing/lib/osutil"
  20. "github.com/syncthing/syncthing/lib/stringutil"
  21. )
  22. var (
  23. ErrDirectory = errors.New("cannot restore on top of a directory")
  24. errNotFound = errors.New("version not found")
  25. errFileAlreadyExists = errors.New("file already exists")
  26. )
  27. const (
  28. DefaultPath = ".stversions"
  29. )
  30. // TagFilename inserts ~tag just before the extension of the filename.
  31. func TagFilename(name, tag string) string {
  32. dir, file := filepath.Dir(name), filepath.Base(name)
  33. ext := filepath.Ext(file)
  34. withoutExt := file[:len(file)-len(ext)]
  35. return filepath.Join(dir, withoutExt+"~"+tag+ext)
  36. }
  37. var tagExp = regexp.MustCompile(`.*~([^~.]+)(?:\.[^.]+)?$`)
  38. // extractTag returns the tag from a filename, whether at the end or middle.
  39. func extractTag(path string) string {
  40. match := tagExp.FindStringSubmatch(path)
  41. // match is []string{"whole match", "submatch"} when successful
  42. if len(match) != 2 {
  43. return ""
  44. }
  45. return match[1]
  46. }
  47. // UntagFilename returns the filename without tag, and the extracted tag
  48. func UntagFilename(path string) (string, string) {
  49. ext := filepath.Ext(path)
  50. versionTag := extractTag(path)
  51. // Files tagged with old style tags cannot be untagged.
  52. if versionTag == "" {
  53. return "", ""
  54. }
  55. // Old style tag
  56. if strings.HasSuffix(ext, versionTag) {
  57. return strings.TrimSuffix(path, "~"+versionTag), versionTag
  58. }
  59. withoutExt := path[:len(path)-len(ext)-len(versionTag)-1]
  60. name := withoutExt + ext
  61. return name, versionTag
  62. }
  63. func retrieveVersions(fileSystem fs.Filesystem) (map[string][]FileVersion, error) {
  64. files := make(map[string][]FileVersion)
  65. err := fileSystem.Walk(".", func(path string, f fs.FileInfo, err error) error {
  66. // Skip root (which is ok to be a symlink)
  67. if path == "." {
  68. return nil
  69. }
  70. // Skip walking if we cannot walk...
  71. if err != nil {
  72. return err
  73. }
  74. // Ignore symlinks
  75. if f.IsSymlink() {
  76. return fs.SkipDir
  77. }
  78. // No records for directories
  79. if f.IsDir() {
  80. return nil
  81. }
  82. modTime := f.ModTime().Truncate(time.Second)
  83. path = osutil.NormalizedFilename(path)
  84. name, tag := UntagFilename(path)
  85. // Something invalid, assume it's an untagged file (trashcan versioner stuff)
  86. if name == "" || tag == "" {
  87. files[path] = append(files[path], FileVersion{
  88. VersionTime: modTime,
  89. ModTime: modTime,
  90. Size: f.Size(),
  91. })
  92. return nil
  93. }
  94. versionTime, err := time.ParseInLocation(TimeFormat, tag, time.Local)
  95. if err != nil {
  96. // Can't parse it, welp, continue
  97. return nil
  98. }
  99. files[name] = append(files[name], FileVersion{
  100. VersionTime: versionTime,
  101. ModTime: modTime,
  102. Size: f.Size(),
  103. })
  104. return nil
  105. })
  106. if err != nil {
  107. return nil, err
  108. }
  109. return files, nil
  110. }
  111. type fileTagger func(string, string) string
  112. func archiveFile(method fs.CopyRangeMethod, srcFs, dstFs fs.Filesystem, filePath string, tagger fileTagger) error {
  113. filePath = osutil.NativeFilename(filePath)
  114. info, err := srcFs.Lstat(filePath)
  115. if fs.IsNotExist(err) {
  116. l.Debugln("not archiving nonexistent file", filePath)
  117. return nil
  118. } else if err != nil {
  119. return err
  120. }
  121. if info.IsSymlink() {
  122. panic("bug: attempting to version a symlink")
  123. }
  124. _, err = dstFs.Stat(".")
  125. if err != nil {
  126. if fs.IsNotExist(err) {
  127. l.Debugln("creating versions dir")
  128. err := dstFs.MkdirAll(".", 0o755)
  129. if err != nil {
  130. return err
  131. }
  132. _ = dstFs.Hide(".")
  133. } else {
  134. return err
  135. }
  136. }
  137. file := filepath.Base(filePath)
  138. inFolderPath := filepath.Dir(filePath)
  139. err = dupDirTree(srcFs, dstFs, inFolderPath)
  140. if err != nil {
  141. l.Debugln("archiving", filePath, err)
  142. return err
  143. }
  144. now := time.Now()
  145. ver := tagger(file, now.Format(TimeFormat))
  146. dst := filepath.Join(inFolderPath, ver)
  147. l.Debugln("archiving", filePath, "moving to", dst)
  148. err = osutil.RenameOrCopy(method, srcFs, dstFs, filePath, dst)
  149. mtime := info.ModTime()
  150. // If it's a trashcan versioner type thing, then it does not have version time in the name
  151. // so use mtime for that.
  152. if ver == file {
  153. mtime = now
  154. }
  155. _ = dstFs.Chtimes(dst, mtime, mtime)
  156. return err
  157. }
  158. func dupDirTree(srcFs, dstFs fs.Filesystem, folderPath string) error {
  159. // Return early if the folder already exists.
  160. _, err := dstFs.Stat(folderPath)
  161. if err == nil || !fs.IsNotExist(err) {
  162. return err
  163. }
  164. hadParent := true
  165. for i := range folderPath {
  166. if os.IsPathSeparator(folderPath[i]) {
  167. // If the parent folder didn't exist, then this folder doesn't exist
  168. // so we can skip the check
  169. if hadParent {
  170. _, err := dstFs.Stat(folderPath[:i])
  171. if err == nil {
  172. continue
  173. }
  174. if !fs.IsNotExist(err) {
  175. return err
  176. }
  177. }
  178. hadParent = false
  179. err := dupDirWithPerms(srcFs, dstFs, folderPath[:i])
  180. if err != nil {
  181. return err
  182. }
  183. }
  184. }
  185. return dupDirWithPerms(srcFs, dstFs, folderPath)
  186. }
  187. func dupDirWithPerms(srcFs, dstFs fs.Filesystem, folderPath string) error {
  188. srcStat, err := srcFs.Stat(folderPath)
  189. if err != nil {
  190. return err
  191. }
  192. // If we call Mkdir with srcStat.Mode(), we won't get the expected perms because of umask
  193. // So, we create the folder with 0700, and then change the perms to the srcStat.Mode()
  194. err = dstFs.Mkdir(folderPath, 0o700)
  195. if err != nil {
  196. return err
  197. }
  198. return dstFs.Chmod(folderPath, srcStat.Mode())
  199. }
  200. func restoreFile(method fs.CopyRangeMethod, src, dst fs.Filesystem, filePath string, versionTime time.Time, tagger fileTagger) error {
  201. tag := versionTime.In(time.Local).Truncate(time.Second).Format(TimeFormat)
  202. taggedFilePath := tagger(filePath, tag)
  203. // If the something already exists where we are restoring to, archive existing file for versioning
  204. // remove if it's a symlink, or fail if it's a directory
  205. if info, err := dst.Lstat(filePath); err == nil {
  206. switch {
  207. case info.IsDir():
  208. return ErrDirectory
  209. case info.IsSymlink():
  210. // Remove existing symlinks (as we don't want to archive them)
  211. if err := dst.Remove(filePath); err != nil {
  212. return fmt.Errorf("removing existing symlink: %w", err)
  213. }
  214. case info.IsRegular():
  215. if err := archiveFile(method, dst, src, filePath, tagger); err != nil {
  216. return fmt.Errorf("archiving existing file: %w", err)
  217. }
  218. default:
  219. panic("bug: unknown item type")
  220. }
  221. } else if !fs.IsNotExist(err) {
  222. return err
  223. }
  224. filePath = osutil.NativeFilename(filePath)
  225. // Try and find a file that has the correct mtime
  226. sourceFile := ""
  227. sourceMtime := time.Time{}
  228. if info, err := src.Lstat(taggedFilePath); err == nil && info.IsRegular() {
  229. sourceFile = taggedFilePath
  230. sourceMtime = info.ModTime()
  231. } else if err == nil {
  232. l.Debugln("restore:", taggedFilePath, "not regular")
  233. } else {
  234. l.Debugln("restore:", taggedFilePath, err.Error())
  235. }
  236. // Check for untagged file
  237. if sourceFile == "" {
  238. info, err := src.Lstat(filePath)
  239. if err == nil && info.IsRegular() && info.ModTime().Truncate(time.Second).Equal(versionTime) {
  240. sourceFile = filePath
  241. sourceMtime = info.ModTime()
  242. }
  243. }
  244. if sourceFile == "" {
  245. return errNotFound
  246. }
  247. // Check that the target location of where we are supposed to restore does not exist.
  248. // This should have been taken care of by the first few lines of this function.
  249. if _, err := dst.Lstat(filePath); err == nil {
  250. return errFileAlreadyExists
  251. } else if !fs.IsNotExist(err) {
  252. return err
  253. }
  254. _ = dst.MkdirAll(filepath.Dir(filePath), 0o755)
  255. err := osutil.RenameOrCopy(method, src, dst, sourceFile, filePath)
  256. _ = dst.Chtimes(filePath, sourceMtime, sourceMtime)
  257. return err
  258. }
  259. func versionerFsFromFolderCfg(cfg config.FolderConfiguration) (versionsFs fs.Filesystem) {
  260. folderFs := cfg.Filesystem(nil)
  261. if cfg.Versioning.FSPath == "" {
  262. versionsFs = fs.NewFilesystem(folderFs.Type(), filepath.Join(folderFs.URI(), DefaultPath))
  263. } else if cfg.Versioning.FSType == config.FilesystemTypeBasic {
  264. // Expand any leading tildes for basic filesystems,
  265. // before checking for absolute paths.
  266. path, err := fs.ExpandTilde(cfg.Versioning.FSPath)
  267. if err != nil {
  268. path = cfg.Versioning.FSPath
  269. }
  270. // We only know how to deal with relative folders for
  271. // basic filesystems, as that's the only one we know
  272. // how to check if it's absolute or relative.
  273. if !filepath.IsAbs(path) {
  274. path = filepath.Join(folderFs.URI(), path)
  275. }
  276. versionsFs = fs.NewFilesystem(cfg.Versioning.FSType.ToFS(), path)
  277. } else {
  278. versionsFs = fs.NewFilesystem(cfg.Versioning.FSType.ToFS(), cfg.Versioning.FSPath)
  279. }
  280. l.Debugf("%s (%s) folder using %s (%s) versioner dir", folderFs.URI(), folderFs.Type(), versionsFs.URI(), versionsFs.Type())
  281. return
  282. }
  283. func findAllVersions(fs fs.Filesystem, filePath string) []string {
  284. inFolderPath := filepath.Dir(filePath)
  285. file := filepath.Base(filePath)
  286. // Glob according to the new file~timestamp.ext pattern.
  287. pattern := filepath.Join(inFolderPath, TagFilename(file, timeGlob))
  288. versions, err := fs.Glob(pattern)
  289. if err != nil {
  290. l.Warnln("globbing:", err, "for", pattern)
  291. return nil
  292. }
  293. versions = stringutil.UniqueTrimmedStrings(versions)
  294. slices.Sort(versions)
  295. return versions
  296. }
  297. func clean(ctx context.Context, versionsFs fs.Filesystem, toRemove func([]string, time.Time) []string) error {
  298. l.Debugln("Versioner clean: Cleaning", versionsFs)
  299. if _, err := versionsFs.Stat("."); fs.IsNotExist(err) {
  300. // There is no need to clean a nonexistent dir.
  301. return nil
  302. }
  303. versionsPerFile := make(map[string][]string)
  304. dirTracker := make(emptyDirTracker)
  305. walkFn := func(path string, f fs.FileInfo, err error) error {
  306. if err != nil {
  307. return err
  308. }
  309. select {
  310. case <-ctx.Done():
  311. return ctx.Err()
  312. default:
  313. }
  314. if f.IsDir() && !f.IsSymlink() {
  315. dirTracker.addDir(path)
  316. return nil
  317. }
  318. // Regular file, or possibly a symlink.
  319. dirTracker.addFile(path)
  320. name, _ := UntagFilename(path)
  321. if name == "" {
  322. return nil
  323. }
  324. versionsPerFile[name] = append(versionsPerFile[name], path)
  325. return nil
  326. }
  327. if err := versionsFs.Walk(".", walkFn); err != nil {
  328. if !errors.Is(err, context.Canceled) {
  329. l.Warnln("Versioner: scanning versions dir:", err)
  330. }
  331. return err
  332. }
  333. for _, versionList := range versionsPerFile {
  334. select {
  335. case <-ctx.Done():
  336. return ctx.Err()
  337. default:
  338. }
  339. cleanVersions(versionsFs, versionList, toRemove)
  340. }
  341. dirTracker.deleteEmptyDirs(versionsFs)
  342. l.Debugln("Cleaner: Finished cleaning", versionsFs)
  343. return nil
  344. }
  345. func cleanVersions(versionsFs fs.Filesystem, versions []string, toRemove func([]string, time.Time) []string) {
  346. l.Debugln("Versioner: Expiring versions", versions)
  347. for _, file := range toRemove(versions, time.Now()) {
  348. if err := versionsFs.Remove(file); err != nil {
  349. l.Warnf("Versioner: can't remove %q: %v", file, err)
  350. }
  351. }
  352. }