util.go 8.8 KB

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