walk.go 18 KB

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