walk.go 16 KB

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