walk.go 17 KB

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