walk.go 17 KB

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