walk.go 18 KB

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