walk.go 17 KB

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