walk.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  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 scanner
  7. import (
  8. "context"
  9. "path/filepath"
  10. "runtime"
  11. "strings"
  12. "sync/atomic"
  13. "time"
  14. "unicode/utf8"
  15. "github.com/rcrowley/go-metrics"
  16. "github.com/syncthing/syncthing/lib/events"
  17. "github.com/syncthing/syncthing/lib/fs"
  18. "github.com/syncthing/syncthing/lib/ignore"
  19. "github.com/syncthing/syncthing/lib/protocol"
  20. "golang.org/x/text/unicode/norm"
  21. )
  22. type Config struct {
  23. // Folder for which the walker has been created
  24. Folder string
  25. // Limit walking to these paths within Dir, or no limit if Sub is empty
  26. Subs []string
  27. // If Matcher is not nil, it is used to identify files to ignore which were specified by the user.
  28. Matcher *ignore.Matcher
  29. // Number of hours to keep temporary files for
  30. TempLifetime time.Duration
  31. // If CurrentFiler is not nil, it is queried for the current file before rescanning.
  32. CurrentFiler CurrentFiler
  33. // The Filesystem provides an abstraction on top of the actual filesystem.
  34. Filesystem fs.Filesystem
  35. // If IgnorePerms is true, changes to permission bits will not be
  36. // detected. Scanned files will get zero permission bits and the
  37. // NoPermissionBits flag set.
  38. IgnorePerms bool
  39. // When AutoNormalize is set, file names that are in UTF8 but incorrect
  40. // normalization form will be corrected.
  41. AutoNormalize bool
  42. // Number of routines to use for hashing
  43. Hashers int
  44. // Our vector clock id
  45. ShortID protocol.ShortID
  46. // Optional progress tick interval which defines how often FolderScanProgress
  47. // events are emitted. Negative number means disabled.
  48. ProgressTickIntervalS int
  49. // Whether to use large blocks for large files or the old standard of 128KiB for everything.
  50. UseLargeBlocks bool
  51. // Local flags to set on scanned files
  52. LocalFlags uint32
  53. }
  54. type CurrentFiler interface {
  55. // CurrentFile returns the file as seen at last scan.
  56. CurrentFile(name string) (protocol.FileInfo, bool)
  57. }
  58. func Walk(ctx context.Context, cfg Config) chan protocol.FileInfo {
  59. w := walker{cfg}
  60. if w.CurrentFiler == nil {
  61. w.CurrentFiler = noCurrentFiler{}
  62. }
  63. if w.Filesystem == nil {
  64. panic("no filesystem specified")
  65. }
  66. if w.Matcher == nil {
  67. w.Matcher = ignore.New(w.Filesystem)
  68. }
  69. return w.walk(ctx)
  70. }
  71. type walker struct {
  72. Config
  73. }
  74. // Walk returns the list of files found in the local folder by scanning the
  75. // file system. Files are blockwise hashed.
  76. func (w *walker) walk(ctx context.Context) chan protocol.FileInfo {
  77. l.Debugln("Walk", w.Subs, w.Matcher)
  78. toHashChan := make(chan protocol.FileInfo)
  79. finishedChan := make(chan protocol.FileInfo)
  80. // A routine which walks the filesystem tree, and sends files which have
  81. // been modified to the counter routine.
  82. go func() {
  83. hashFiles := w.walkAndHashFiles(ctx, toHashChan, finishedChan)
  84. if len(w.Subs) == 0 {
  85. w.Filesystem.Walk(".", hashFiles)
  86. } else {
  87. for _, sub := range w.Subs {
  88. w.Filesystem.Walk(sub, hashFiles)
  89. }
  90. }
  91. close(toHashChan)
  92. }()
  93. // We're not required to emit scan progress events, just kick off hashers,
  94. // and feed inputs directly from the walker.
  95. if w.ProgressTickIntervalS < 0 {
  96. newParallelHasher(ctx, w.Filesystem, w.Hashers, finishedChan, toHashChan, nil, nil)
  97. return finishedChan
  98. }
  99. // Defaults to every 2 seconds.
  100. if w.ProgressTickIntervalS == 0 {
  101. w.ProgressTickIntervalS = 2
  102. }
  103. ticker := time.NewTicker(time.Duration(w.ProgressTickIntervalS) * time.Second)
  104. // We need to emit progress events, hence we create a routine which buffers
  105. // the list of files to be hashed, counts the total number of
  106. // bytes to hash, and once no more files need to be hashed (chan gets closed),
  107. // start a routine which periodically emits FolderScanProgress events,
  108. // until a stop signal is sent by the parallel hasher.
  109. // Parallel hasher is stopped by this routine when we close the channel over
  110. // which it receives the files we ask it to hash.
  111. go func() {
  112. var filesToHash []protocol.FileInfo
  113. var total int64 = 1
  114. for file := range toHashChan {
  115. filesToHash = append(filesToHash, file)
  116. total += file.Size
  117. }
  118. realToHashChan := make(chan protocol.FileInfo)
  119. done := make(chan struct{})
  120. progress := newByteCounter()
  121. newParallelHasher(ctx, w.Filesystem, w.Hashers, finishedChan, realToHashChan, progress, done)
  122. // A routine which actually emits the FolderScanProgress events
  123. // every w.ProgressTicker ticks, until the hasher routines terminate.
  124. go func() {
  125. defer progress.Close()
  126. for {
  127. select {
  128. case <-done:
  129. l.Debugln("Walk progress done", w.Folder, w.Subs, w.Matcher)
  130. ticker.Stop()
  131. return
  132. case <-ticker.C:
  133. current := progress.Total()
  134. rate := progress.Rate()
  135. l.Debugf("Walk %s %s current progress %d/%d at %.01f MiB/s (%d%%)", w.Folder, w.Subs, current, total, rate/1024/1024, current*100/total)
  136. events.Default.Log(events.FolderScanProgress, map[string]interface{}{
  137. "folder": w.Folder,
  138. "current": current,
  139. "total": total,
  140. "rate": rate, // bytes per second
  141. })
  142. case <-ctx.Done():
  143. ticker.Stop()
  144. return
  145. }
  146. }
  147. }()
  148. loop:
  149. for _, file := range filesToHash {
  150. l.Debugln("real to hash:", file.Name)
  151. select {
  152. case realToHashChan <- file:
  153. case <-ctx.Done():
  154. break loop
  155. }
  156. }
  157. close(realToHashChan)
  158. }()
  159. return finishedChan
  160. }
  161. func (w *walker) walkAndHashFiles(ctx context.Context, fchan, dchan chan protocol.FileInfo) fs.WalkFunc {
  162. now := time.Now()
  163. ignoredParent := ""
  164. return func(path string, info fs.FileInfo, err error) error {
  165. select {
  166. case <-ctx.Done():
  167. return ctx.Err()
  168. default:
  169. }
  170. // Return value used when we are returning early and don't want to
  171. // process the item. For directories, this means do-not-descend.
  172. var skip error // nil
  173. // info nil when error is not nil
  174. if info != nil && info.IsDir() {
  175. skip = fs.SkipDir
  176. }
  177. if err != nil {
  178. l.Debugln("error:", path, info, err)
  179. return skip
  180. }
  181. if path == "." {
  182. return nil
  183. }
  184. if fs.IsTemporary(path) {
  185. l.Debugln("temporary:", path)
  186. if info.IsRegular() && info.ModTime().Add(w.TempLifetime).Before(now) {
  187. w.Filesystem.Remove(path)
  188. l.Debugln("removing temporary:", path, info.ModTime())
  189. }
  190. return nil
  191. }
  192. if fs.IsInternal(path) {
  193. l.Debugln("ignored (internal):", path)
  194. return skip
  195. }
  196. if !utf8.ValidString(path) {
  197. l.Warnf("File name %q is not in UTF8 encoding; skipping.", path)
  198. return skip
  199. }
  200. if w.Matcher.Match(path).IsIgnored() {
  201. l.Debugln("ignored (patterns):", path)
  202. // Only descend if matcher says so and the current file is not a symlink.
  203. if w.Matcher.SkipIgnoredDirs() || info.IsSymlink() {
  204. return skip
  205. }
  206. // If the parent wasn't ignored already, set this path as the "highest" ignored parent
  207. if info.IsDir() && (ignoredParent == "" || !strings.HasPrefix(path, ignoredParent+string(fs.PathSeparator))) {
  208. ignoredParent = path
  209. }
  210. return nil
  211. }
  212. if ignoredParent == "" {
  213. // parent isn't ignored, nothing special
  214. return w.handleItem(ctx, path, fchan, dchan, skip)
  215. }
  216. // Part of current path below the ignored (potential) parent
  217. rel := strings.TrimPrefix(path, ignoredParent+string(fs.PathSeparator))
  218. // ignored path isn't actually a parent of the current path
  219. if rel == path {
  220. ignoredParent = ""
  221. return w.handleItem(ctx, path, fchan, dchan, skip)
  222. }
  223. // The previously ignored parent directories of the current, not
  224. // ignored path need to be handled as well.
  225. if err = w.handleItem(ctx, ignoredParent, fchan, dchan, skip); err != nil {
  226. return err
  227. }
  228. for _, name := range strings.Split(rel, string(fs.PathSeparator)) {
  229. ignoredParent = filepath.Join(ignoredParent, name)
  230. if err = w.handleItem(ctx, ignoredParent, fchan, dchan, skip); err != nil {
  231. return err
  232. }
  233. }
  234. ignoredParent = ""
  235. return nil
  236. }
  237. }
  238. func (w *walker) handleItem(ctx context.Context, path string, fchan, dchan chan protocol.FileInfo, skip error) error {
  239. info, err := w.Filesystem.Lstat(path)
  240. // An error here would be weird as we've already gotten to this point, but act on it nonetheless
  241. if err != nil {
  242. return skip
  243. }
  244. path, shouldSkip := w.normalizePath(path, info)
  245. if shouldSkip {
  246. return skip
  247. }
  248. switch {
  249. case info.IsSymlink():
  250. if err := w.walkSymlink(ctx, path, dchan); err != nil {
  251. return err
  252. }
  253. if info.IsDir() {
  254. // under no circumstances shall we descend into a symlink
  255. return fs.SkipDir
  256. }
  257. return nil
  258. case info.IsDir():
  259. err = w.walkDir(ctx, path, info, dchan)
  260. case info.IsRegular():
  261. err = w.walkRegular(ctx, path, info, fchan)
  262. }
  263. return err
  264. }
  265. func (w *walker) walkRegular(ctx context.Context, relPath string, info fs.FileInfo, fchan chan protocol.FileInfo) error {
  266. curFile, hasCurFile := w.CurrentFiler.CurrentFile(relPath)
  267. newMode := uint32(info.Mode())
  268. if runtime.GOOS == "windows" && hasCurFile {
  269. // If we have an existing index entry, copy the executable bits
  270. // from there.
  271. newMode |= (curFile.Permissions & 0111)
  272. }
  273. blockSize := protocol.MinBlockSize
  274. if w.UseLargeBlocks {
  275. blockSize = protocol.BlockSize(info.Size())
  276. if hasCurFile {
  277. // Check if we should retain current block size.
  278. curBlockSize := curFile.BlockSize()
  279. if blockSize > curBlockSize && blockSize/curBlockSize <= 2 {
  280. // New block size is larger, but not more than twice larger.
  281. // Retain.
  282. blockSize = curBlockSize
  283. } else if curBlockSize > blockSize && curBlockSize/blockSize <= 2 {
  284. // Old block size is larger, but not more than twice larger.
  285. // Retain.
  286. blockSize = curBlockSize
  287. }
  288. }
  289. }
  290. f := protocol.FileInfo{
  291. Name: relPath,
  292. Type: protocol.FileInfoTypeFile,
  293. Version: curFile.Version.Update(w.ShortID),
  294. Permissions: newMode & uint32(fs.ModePerm),
  295. NoPermissions: w.IgnorePerms,
  296. ModifiedS: info.ModTime().Unix(),
  297. ModifiedNs: int32(info.ModTime().Nanosecond()),
  298. ModifiedBy: w.ShortID,
  299. Size: info.Size(),
  300. RawBlockSize: int32(blockSize),
  301. LocalFlags: w.LocalFlags,
  302. }
  303. if hasCurFile {
  304. if curFile.IsEquivalentOptional(f, w.IgnorePerms, true, w.LocalFlags) {
  305. return nil
  306. }
  307. if curFile.ShouldConflict() {
  308. // The old file was invalid for whatever reason and probably not
  309. // up to date with what was out there in the cluster. Drop all
  310. // others from the version vector to indicate that we haven't
  311. // taken their version into account, and possibly cause a
  312. // conflict.
  313. f.Version = f.Version.DropOthers(w.ShortID)
  314. }
  315. l.Debugln("rescan:", curFile, info.ModTime().Unix(), info.Mode()&fs.ModePerm)
  316. }
  317. l.Debugln("to hash:", relPath, f)
  318. select {
  319. case fchan <- f:
  320. case <-ctx.Done():
  321. return ctx.Err()
  322. }
  323. return nil
  324. }
  325. func (w *walker) walkDir(ctx context.Context, relPath string, info fs.FileInfo, dchan chan protocol.FileInfo) error {
  326. cf, ok := w.CurrentFiler.CurrentFile(relPath)
  327. f := protocol.FileInfo{
  328. Name: relPath,
  329. Type: protocol.FileInfoTypeDirectory,
  330. Version: cf.Version.Update(w.ShortID),
  331. Permissions: uint32(info.Mode() & fs.ModePerm),
  332. NoPermissions: w.IgnorePerms,
  333. ModifiedS: info.ModTime().Unix(),
  334. ModifiedNs: int32(info.ModTime().Nanosecond()),
  335. ModifiedBy: w.ShortID,
  336. LocalFlags: w.LocalFlags,
  337. }
  338. if ok {
  339. if cf.IsEquivalentOptional(f, w.IgnorePerms, true, w.LocalFlags) {
  340. return nil
  341. }
  342. if cf.ShouldConflict() {
  343. // The old file was invalid for whatever reason and probably not
  344. // up to date with what was out there in the cluster. Drop all
  345. // others from the version vector to indicate that we haven't
  346. // taken their version into account, and possibly cause a
  347. // conflict.
  348. f.Version = f.Version.DropOthers(w.ShortID)
  349. }
  350. }
  351. l.Debugln("dir:", relPath, f)
  352. select {
  353. case dchan <- f:
  354. case <-ctx.Done():
  355. return ctx.Err()
  356. }
  357. return nil
  358. }
  359. // walkSymlink returns nil or an error, if the error is of the nature that
  360. // it should stop the entire walk.
  361. func (w *walker) walkSymlink(ctx context.Context, relPath string, dchan chan protocol.FileInfo) error {
  362. // Symlinks are not supported on Windows. We ignore instead of returning
  363. // an error.
  364. if runtime.GOOS == "windows" {
  365. return nil
  366. }
  367. // We always rehash symlinks as they have no modtime or
  368. // permissions. We check if they point to the old target by
  369. // checking that their existing blocks match with the blocks in
  370. // the index.
  371. target, err := w.Filesystem.ReadSymlink(relPath)
  372. if err != nil {
  373. l.Debugln("readlink error:", relPath, err)
  374. return nil
  375. }
  376. cf, ok := w.CurrentFiler.CurrentFile(relPath)
  377. f := protocol.FileInfo{
  378. Name: relPath,
  379. Type: protocol.FileInfoTypeSymlink,
  380. Version: cf.Version.Update(w.ShortID),
  381. NoPermissions: true, // Symlinks don't have permissions of their own
  382. SymlinkTarget: target,
  383. ModifiedBy: w.ShortID,
  384. LocalFlags: w.LocalFlags,
  385. }
  386. if ok {
  387. if cf.IsEquivalentOptional(f, w.IgnorePerms, true, w.LocalFlags) {
  388. return nil
  389. }
  390. if cf.ShouldConflict() {
  391. // The old file was invalid for whatever reason and probably not
  392. // up to date with what was out there in the cluster. Drop all
  393. // others from the version vector to indicate that we haven't
  394. // taken their version into account, and possibly cause a
  395. // conflict.
  396. f.Version = f.Version.DropOthers(w.ShortID)
  397. }
  398. }
  399. l.Debugln("symlink changedb:", relPath, f)
  400. select {
  401. case dchan <- f:
  402. case <-ctx.Done():
  403. return ctx.Err()
  404. }
  405. return nil
  406. }
  407. // normalizePath returns the normalized relative path (possibly after fixing
  408. // it on disk), or skip is true.
  409. func (w *walker) normalizePath(path string, info fs.FileInfo) (normPath string, skip bool) {
  410. if runtime.GOOS == "darwin" {
  411. // Mac OS X file names should always be NFD normalized.
  412. normPath = norm.NFD.String(path)
  413. } else {
  414. // Every other OS in the known universe uses NFC or just plain
  415. // doesn't bother to define an encoding. In our case *we* do care,
  416. // so we enforce NFC regardless.
  417. normPath = norm.NFC.String(path)
  418. }
  419. if path == normPath {
  420. // The file name is already normalized: nothing to do
  421. return path, false
  422. }
  423. if !w.AutoNormalize {
  424. // We're not authorized to do anything about it, so complain and skip.
  425. l.Warnf("File name %q is not in the correct UTF8 normalization form; skipping.", path)
  426. return "", true
  427. }
  428. // We will attempt to normalize it.
  429. normInfo, err := w.Filesystem.Lstat(normPath)
  430. if fs.IsNotExist(err) {
  431. // Nothing exists with the normalized filename. Good.
  432. if err = w.Filesystem.Rename(path, normPath); err != nil {
  433. l.Infof(`Error normalizing UTF8 encoding of file "%s": %v`, path, err)
  434. return "", true
  435. }
  436. l.Infof(`Normalized UTF8 encoding of file name "%s".`, path)
  437. } else if w.Filesystem.SameFile(info, normInfo) {
  438. // With some filesystems (ZFS), if there is an un-normalized path and you ask whether the normalized
  439. // version exists, it responds with true. Therefore we need to check fs.SameFile as well.
  440. // In this case, a call to Rename won't do anything, so we have to rename via a temp file.
  441. // We don't want to use the standard syncthing prefix here, as that will result in the file being ignored
  442. // and eventually deleted by Syncthing if the rename back fails.
  443. tempPath := fs.TempNameWithPrefix(normPath, "")
  444. if err = w.Filesystem.Rename(path, tempPath); err != nil {
  445. l.Infof(`Error during normalizing UTF8 encoding of file "%s" (renamed to "%s"): %v`, path, tempPath, err)
  446. return "", true
  447. }
  448. if err = w.Filesystem.Rename(tempPath, normPath); err != nil {
  449. // I don't ever expect this to happen, but if it does, we should probably tell our caller that the normalized
  450. // path is the temp path: that way at least the user's data still gets synced.
  451. l.Warnf(`Error renaming "%s" to "%s" while normalizating UTF8 encoding: %v. You will want to rename this file back manually`, tempPath, normPath, err)
  452. return tempPath, false
  453. }
  454. } else {
  455. // There is something already in the way at the normalized
  456. // file name.
  457. l.Infof(`File "%s" path has UTF8 encoding conflict with another file; ignoring.`, path)
  458. return "", true
  459. }
  460. return normPath, false
  461. }
  462. // A byteCounter gets bytes added to it via Update() and then provides the
  463. // Total() and one minute moving average Rate() in bytes per second.
  464. type byteCounter struct {
  465. total int64
  466. metrics.EWMA
  467. stop chan struct{}
  468. }
  469. func newByteCounter() *byteCounter {
  470. c := &byteCounter{
  471. EWMA: metrics.NewEWMA1(), // a one minute exponentially weighted moving average
  472. stop: make(chan struct{}),
  473. }
  474. go c.ticker()
  475. return c
  476. }
  477. func (c *byteCounter) ticker() {
  478. // The metrics.EWMA expects clock ticks every five seconds in order to
  479. // decay the average properly.
  480. t := time.NewTicker(5 * time.Second)
  481. for {
  482. select {
  483. case <-t.C:
  484. c.Tick()
  485. case <-c.stop:
  486. t.Stop()
  487. return
  488. }
  489. }
  490. }
  491. func (c *byteCounter) Update(bytes int64) {
  492. atomic.AddInt64(&c.total, bytes)
  493. c.EWMA.Update(bytes)
  494. }
  495. func (c *byteCounter) Total() int64 {
  496. return atomic.LoadInt64(&c.total)
  497. }
  498. func (c *byteCounter) Close() {
  499. close(c.stop)
  500. }
  501. // A no-op CurrentFiler
  502. type noCurrentFiler struct{}
  503. func (noCurrentFiler) CurrentFile(name string) (protocol.FileInfo, bool) {
  504. return protocol.FileInfo{}, false
  505. }
  506. func CreateFileInfo(fi fs.FileInfo, name string, filesystem fs.Filesystem) (protocol.FileInfo, error) {
  507. f := protocol.FileInfo{
  508. Name: name,
  509. Type: protocol.FileInfoTypeFile,
  510. Permissions: uint32(fi.Mode() & fs.ModePerm),
  511. ModifiedS: fi.ModTime().Unix(),
  512. ModifiedNs: int32(fi.ModTime().Nanosecond()),
  513. Size: fi.Size(),
  514. }
  515. switch {
  516. case fi.IsDir():
  517. f.Type = protocol.FileInfoTypeDirectory
  518. case fi.IsSymlink():
  519. f.Type = protocol.FileInfoTypeSymlink
  520. target, err := filesystem.ReadSymlink(name)
  521. if err != nil {
  522. return protocol.FileInfo{}, err
  523. }
  524. f.SymlinkTarget = target
  525. }
  526. return f, nil
  527. }