walk.go 18 KB

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