walk.go 18 KB

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