util.go 11 KB

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