util.go 9.6 KB

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