walk.go 17 KB

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