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. "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/osutil"
  20. "github.com/syncthing/syncthing/lib/protocol"
  21. "golang.org/x/text/unicode/norm"
  22. )
  23. var maskModePerm fs.FileMode
  24. func init() {
  25. if runtime.GOOS == "windows" {
  26. // There is no user/group/others in Windows' read-only
  27. // attribute, and all "w" bits are set in fs.FileMode
  28. // if the file is not read-only. Do not send these
  29. // group/others-writable bits to other devices in order to
  30. // avoid unexpected world-writable files on other platforms.
  31. maskModePerm = fs.ModePerm & 0755
  32. } else {
  33. maskModePerm = fs.ModePerm
  34. }
  35. }
  36. type Config struct {
  37. // Folder for which the walker has been created
  38. Folder string
  39. // Limit walking to these paths within Dir, or no limit if Sub is empty
  40. Subs []string
  41. // If Matcher is not nil, it is used to identify files to ignore which were specified by the user.
  42. Matcher *ignore.Matcher
  43. // Number of hours to keep temporary files for
  44. TempLifetime time.Duration
  45. // If CurrentFiler is not nil, it is queried for the current file before rescanning.
  46. CurrentFiler CurrentFiler
  47. // The Filesystem provides an abstraction on top of the actual filesystem.
  48. Filesystem fs.Filesystem
  49. // If IgnorePerms is true, changes to permission bits will not be
  50. // detected. Scanned files will get zero permission bits and the
  51. // NoPermissionBits flag set.
  52. IgnorePerms bool
  53. // When AutoNormalize is set, file names that are in UTF8 but incorrect
  54. // normalization form will be corrected.
  55. AutoNormalize bool
  56. // Number of routines to use for hashing
  57. Hashers int
  58. // Our vector clock id
  59. ShortID protocol.ShortID
  60. // Optional progress tick interval which defines how often FolderScanProgress
  61. // events are emitted. Negative number means disabled.
  62. ProgressTickIntervalS int
  63. // Whether to use large blocks for large files or the old standard of 128KiB for everything.
  64. UseLargeBlocks bool
  65. // Local flags to set on scanned files
  66. LocalFlags uint32
  67. }
  68. type CurrentFiler interface {
  69. // CurrentFile returns the file as seen at last scan.
  70. CurrentFile(name string) (protocol.FileInfo, bool)
  71. }
  72. func Walk(ctx context.Context, cfg Config) chan protocol.FileInfo {
  73. w := walker{cfg}
  74. if w.CurrentFiler == nil {
  75. w.CurrentFiler = noCurrentFiler{}
  76. }
  77. if w.Filesystem == nil {
  78. panic("no filesystem specified")
  79. }
  80. if w.Matcher == nil {
  81. w.Matcher = ignore.New(w.Filesystem)
  82. }
  83. return w.walk(ctx)
  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 protocol.FileInfo {
  91. l.Debugln("Walk", w.Subs, w.Matcher)
  92. toHashChan := make(chan protocol.FileInfo)
  93. finishedChan := make(chan protocol.FileInfo)
  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. events.Default.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, fchan, dchan chan protocol.FileInfo) 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 err != nil {
  192. l.Debugln("error:", path, info, err)
  193. return skip
  194. }
  195. if path == "." {
  196. return nil
  197. }
  198. if fs.IsTemporary(path) {
  199. l.Debugln("temporary:", path)
  200. if info.IsRegular() && info.ModTime().Add(w.TempLifetime).Before(now) {
  201. w.Filesystem.Remove(path)
  202. l.Debugln("removing temporary:", path, info.ModTime())
  203. }
  204. return nil
  205. }
  206. if fs.IsInternal(path) {
  207. l.Debugln("ignored (internal):", path)
  208. return skip
  209. }
  210. if !utf8.ValidString(path) {
  211. l.Warnf("File name %q is not in UTF8 encoding; skipping.", path)
  212. return skip
  213. }
  214. if w.Matcher.Match(path).IsIgnored() {
  215. l.Debugln("ignored (patterns):", path)
  216. // Only descend if matcher says so and the current file is not a symlink.
  217. if w.Matcher.SkipIgnoredDirs() || info.IsSymlink() {
  218. return skip
  219. }
  220. // If the parent wasn't ignored already, set this path as the "highest" ignored parent
  221. if info.IsDir() && (ignoredParent == "" || !strings.HasPrefix(path, ignoredParent+string(fs.PathSeparator))) {
  222. ignoredParent = path
  223. }
  224. return nil
  225. }
  226. if ignoredParent == "" {
  227. // parent isn't ignored, nothing special
  228. return w.handleItem(ctx, path, fchan, dchan, 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, fchan, dchan, 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, fchan, dchan, 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, fchan, dchan, 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, fchan, dchan chan protocol.FileInfo, 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. return skip
  257. }
  258. path, shouldSkip := w.normalizePath(path, info)
  259. if shouldSkip {
  260. return skip
  261. }
  262. switch {
  263. case info.IsSymlink():
  264. if err := w.walkSymlink(ctx, path, dchan); err != nil {
  265. return err
  266. }
  267. if info.IsDir() {
  268. // under no circumstances shall we descend into a symlink
  269. return fs.SkipDir
  270. }
  271. return nil
  272. case info.IsDir():
  273. err = w.walkDir(ctx, path, info, dchan)
  274. case info.IsRegular():
  275. err = w.walkRegular(ctx, path, info, fchan)
  276. }
  277. return err
  278. }
  279. func (w *walker) walkRegular(ctx context.Context, relPath string, info fs.FileInfo, fchan chan protocol.FileInfo) error {
  280. curFile, hasCurFile := w.CurrentFiler.CurrentFile(relPath)
  281. newMode := uint32(info.Mode())
  282. if runtime.GOOS == "windows" {
  283. if osutil.IsWindowsExecutable(relPath) {
  284. // Set executable bits on files with executable extenions (.exe,
  285. // .bat, etc).
  286. newMode |= 0111
  287. } else if hasCurFile {
  288. // If we have an existing index entry, copy the executable bits
  289. // from there.
  290. newMode |= (curFile.Permissions & 0111)
  291. }
  292. }
  293. blockSize := protocol.MinBlockSize
  294. if w.UseLargeBlocks {
  295. blockSize = protocol.BlockSize(info.Size())
  296. if hasCurFile {
  297. // Check if we should retain current block size.
  298. curBlockSize := curFile.BlockSize()
  299. if blockSize > curBlockSize && blockSize/curBlockSize <= 2 {
  300. // New block size is larger, but not more than twice larger.
  301. // Retain.
  302. blockSize = curBlockSize
  303. } else if curBlockSize > blockSize && curBlockSize/blockSize <= 2 {
  304. // Old block size is larger, but not more than twice larger.
  305. // Retain.
  306. blockSize = curBlockSize
  307. }
  308. }
  309. }
  310. f := protocol.FileInfo{
  311. Name: relPath,
  312. Type: protocol.FileInfoTypeFile,
  313. Version: curFile.Version.Update(w.ShortID),
  314. Permissions: newMode & uint32(maskModePerm),
  315. NoPermissions: w.IgnorePerms,
  316. ModifiedS: info.ModTime().Unix(),
  317. ModifiedNs: int32(info.ModTime().Nanosecond()),
  318. ModifiedBy: w.ShortID,
  319. Size: info.Size(),
  320. RawBlockSize: int32(blockSize),
  321. LocalFlags: w.LocalFlags,
  322. }
  323. if hasCurFile {
  324. if curFile.IsEquivalentOptional(f, w.IgnorePerms, true, w.LocalFlags) {
  325. return nil
  326. }
  327. if curFile.ShouldConflict() {
  328. // The old file was invalid for whatever reason and probably not
  329. // up to date with what was out there in the cluster. Drop all
  330. // others from the version vector to indicate that we haven't
  331. // taken their version into account, and possibly cause a
  332. // conflict.
  333. f.Version = f.Version.DropOthers(w.ShortID)
  334. }
  335. l.Debugln("rescan:", curFile, info.ModTime().Unix(), info.Mode()&fs.ModePerm)
  336. }
  337. l.Debugln("to hash:", relPath, f)
  338. select {
  339. case fchan <- f:
  340. case <-ctx.Done():
  341. return ctx.Err()
  342. }
  343. return nil
  344. }
  345. func (w *walker) walkDir(ctx context.Context, relPath string, info fs.FileInfo, dchan chan protocol.FileInfo) error {
  346. cf, ok := w.CurrentFiler.CurrentFile(relPath)
  347. f := protocol.FileInfo{
  348. Name: relPath,
  349. Type: protocol.FileInfoTypeDirectory,
  350. Version: cf.Version.Update(w.ShortID),
  351. Permissions: uint32(info.Mode() & maskModePerm),
  352. NoPermissions: w.IgnorePerms,
  353. ModifiedS: info.ModTime().Unix(),
  354. ModifiedNs: int32(info.ModTime().Nanosecond()),
  355. ModifiedBy: w.ShortID,
  356. LocalFlags: w.LocalFlags,
  357. }
  358. if ok {
  359. if cf.IsEquivalentOptional(f, w.IgnorePerms, true, w.LocalFlags) {
  360. return nil
  361. }
  362. if cf.ShouldConflict() {
  363. // The old file was invalid for whatever reason and probably not
  364. // up to date with what was out there in the cluster. Drop all
  365. // others from the version vector to indicate that we haven't
  366. // taken their version into account, and possibly cause a
  367. // conflict.
  368. f.Version = f.Version.DropOthers(w.ShortID)
  369. }
  370. }
  371. l.Debugln("dir:", relPath, f)
  372. select {
  373. case dchan <- f:
  374. case <-ctx.Done():
  375. return ctx.Err()
  376. }
  377. return nil
  378. }
  379. // walkSymlink returns nil or an error, if the error is of the nature that
  380. // it should stop the entire walk.
  381. func (w *walker) walkSymlink(ctx context.Context, relPath string, dchan chan protocol.FileInfo) error {
  382. // Symlinks are not supported on Windows. We ignore instead of returning
  383. // an error.
  384. if runtime.GOOS == "windows" {
  385. return nil
  386. }
  387. // We always rehash symlinks as they have no modtime or
  388. // permissions. We check if they point to the old target by
  389. // checking that their existing blocks match with the blocks in
  390. // the index.
  391. target, err := w.Filesystem.ReadSymlink(relPath)
  392. if err != nil {
  393. l.Debugln("readlink error:", relPath, err)
  394. return nil
  395. }
  396. cf, ok := w.CurrentFiler.CurrentFile(relPath)
  397. f := protocol.FileInfo{
  398. Name: relPath,
  399. Type: protocol.FileInfoTypeSymlink,
  400. Version: cf.Version.Update(w.ShortID),
  401. NoPermissions: true, // Symlinks don't have permissions of their own
  402. SymlinkTarget: target,
  403. ModifiedBy: w.ShortID,
  404. LocalFlags: w.LocalFlags,
  405. }
  406. if ok {
  407. if cf.IsEquivalentOptional(f, w.IgnorePerms, true, w.LocalFlags) {
  408. return nil
  409. }
  410. if cf.ShouldConflict() {
  411. // The old file was invalid for whatever reason and probably not
  412. // up to date with what was out there in the cluster. Drop all
  413. // others from the version vector to indicate that we haven't
  414. // taken their version into account, and possibly cause a
  415. // conflict.
  416. f.Version = f.Version.DropOthers(w.ShortID)
  417. }
  418. }
  419. l.Debugln("symlink changedb:", relPath, f)
  420. select {
  421. case dchan <- f:
  422. case <-ctx.Done():
  423. return ctx.Err()
  424. }
  425. return nil
  426. }
  427. // normalizePath returns the normalized relative path (possibly after fixing
  428. // it on disk), or skip is true.
  429. func (w *walker) normalizePath(path string, info fs.FileInfo) (normPath string, skip bool) {
  430. if runtime.GOOS == "darwin" {
  431. // Mac OS X file names should always be NFD normalized.
  432. normPath = norm.NFD.String(path)
  433. } else {
  434. // Every other OS in the known universe uses NFC or just plain
  435. // doesn't bother to define an encoding. In our case *we* do care,
  436. // so we enforce NFC regardless.
  437. normPath = norm.NFC.String(path)
  438. }
  439. if path == normPath {
  440. // The file name is already normalized: nothing to do
  441. return path, false
  442. }
  443. if !w.AutoNormalize {
  444. // We're not authorized to do anything about it, so complain and skip.
  445. l.Warnf("File name %q is not in the correct UTF8 normalization form; skipping.", path)
  446. return "", true
  447. }
  448. // We will attempt to normalize it.
  449. normInfo, err := w.Filesystem.Lstat(normPath)
  450. if fs.IsNotExist(err) {
  451. // Nothing exists with the normalized filename. Good.
  452. if err = w.Filesystem.Rename(path, normPath); err != nil {
  453. l.Infof(`Error normalizing UTF8 encoding of file "%s": %v`, path, err)
  454. return "", true
  455. }
  456. l.Infof(`Normalized UTF8 encoding of file name "%s".`, path)
  457. } else if w.Filesystem.SameFile(info, normInfo) {
  458. // With some filesystems (ZFS), if there is an un-normalized path and you ask whether the normalized
  459. // version exists, it responds with true. Therefore we need to check fs.SameFile as well.
  460. // In this case, a call to Rename won't do anything, so we have to rename via a temp file.
  461. // We don't want to use the standard syncthing prefix here, as that will result in the file being ignored
  462. // and eventually deleted by Syncthing if the rename back fails.
  463. tempPath := fs.TempNameWithPrefix(normPath, "")
  464. if err = w.Filesystem.Rename(path, tempPath); err != nil {
  465. l.Infof(`Error during normalizing UTF8 encoding of file "%s" (renamed to "%s"): %v`, path, tempPath, err)
  466. return "", true
  467. }
  468. if err = w.Filesystem.Rename(tempPath, normPath); err != nil {
  469. // I don't ever expect this to happen, but if it does, we should probably tell our caller that the normalized
  470. // path is the temp path: that way at least the user's data still gets synced.
  471. l.Warnf(`Error renaming "%s" to "%s" while normalizating UTF8 encoding: %v. You will want to rename this file back manually`, tempPath, normPath, err)
  472. return tempPath, false
  473. }
  474. } else {
  475. // There is something already in the way at the normalized
  476. // file name.
  477. l.Infof(`File "%s" path has UTF8 encoding conflict with another file; ignoring.`, path)
  478. return "", true
  479. }
  480. return normPath, false
  481. }
  482. // A byteCounter gets bytes added to it via Update() and then provides the
  483. // Total() and one minute moving average Rate() in bytes per second.
  484. type byteCounter struct {
  485. total int64
  486. metrics.EWMA
  487. stop chan struct{}
  488. }
  489. func newByteCounter() *byteCounter {
  490. c := &byteCounter{
  491. EWMA: metrics.NewEWMA1(), // a one minute exponentially weighted moving average
  492. stop: make(chan struct{}),
  493. }
  494. go c.ticker()
  495. return c
  496. }
  497. func (c *byteCounter) ticker() {
  498. // The metrics.EWMA expects clock ticks every five seconds in order to
  499. // decay the average properly.
  500. t := time.NewTicker(5 * time.Second)
  501. for {
  502. select {
  503. case <-t.C:
  504. c.Tick()
  505. case <-c.stop:
  506. t.Stop()
  507. return
  508. }
  509. }
  510. }
  511. func (c *byteCounter) Update(bytes int64) {
  512. atomic.AddInt64(&c.total, bytes)
  513. c.EWMA.Update(bytes)
  514. }
  515. func (c *byteCounter) Total() int64 {
  516. return atomic.LoadInt64(&c.total)
  517. }
  518. func (c *byteCounter) Close() {
  519. close(c.stop)
  520. }
  521. // A no-op CurrentFiler
  522. type noCurrentFiler struct{}
  523. func (noCurrentFiler) CurrentFile(name string) (protocol.FileInfo, bool) {
  524. return protocol.FileInfo{}, false
  525. }