walk.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  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. "errors"
  9. "path/filepath"
  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. // Dir is the base directory for the walk
  39. Dir string
  40. // Limit walking to these paths within Dir, or no limit if Sub is empty
  41. Subs []string
  42. // BlockSize controls the size of the block used when hashing.
  43. BlockSize int
  44. // If Matcher is not nil, it is used to identify files to ignore which were specified by the user.
  45. Matcher *ignore.Matcher
  46. // Number of hours to keep temporary files for
  47. TempLifetime time.Duration
  48. // If CurrentFiler is not nil, it is queried for the current file before rescanning.
  49. CurrentFiler CurrentFiler
  50. // The Filesystem provides an abstraction on top of the actual filesystem.
  51. Filesystem fs.Filesystem
  52. // If IgnorePerms is true, changes to permission bits will not be
  53. // detected. Scanned files will get zero permission bits and the
  54. // NoPermissionBits flag set.
  55. IgnorePerms bool
  56. // When AutoNormalize is set, file names that are in UTF8 but incorrect
  57. // normalization form will be corrected.
  58. AutoNormalize bool
  59. // Number of routines to use for hashing
  60. Hashers int
  61. // Our vector clock id
  62. ShortID protocol.ShortID
  63. // Optional progress tick interval which defines how often FolderScanProgress
  64. // events are emitted. Negative number means disabled.
  65. ProgressTickIntervalS int
  66. // Signals cancel from the outside - when closed, we should stop walking.
  67. Cancel chan struct{}
  68. // Whether or not we should also compute weak hashes
  69. UseWeakHashes bool
  70. }
  71. type CurrentFiler interface {
  72. // CurrentFile returns the file as seen at last scan.
  73. CurrentFile(name string) (protocol.FileInfo, bool)
  74. }
  75. func Walk(cfg Config) (chan protocol.FileInfo, error) {
  76. w := walker{cfg}
  77. if w.CurrentFiler == nil {
  78. w.CurrentFiler = noCurrentFiler{}
  79. }
  80. if w.Filesystem == nil {
  81. w.Filesystem = fs.DefaultFilesystem
  82. }
  83. return w.walk()
  84. }
  85. type walker struct {
  86. Config
  87. }
  88. // Walk returns the list of files found in the local folder by scanning the
  89. // file system. Files are blockwise hashed.
  90. func (w *walker) walk() (chan protocol.FileInfo, error) {
  91. l.Debugln("Walk", w.Dir, w.Subs, w.BlockSize, w.Matcher)
  92. if err := w.checkDir(); 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. w.Filesystem.Walk(w.Dir, hashFiles)
  103. } else {
  104. for _, sub := range w.Subs {
  105. w.Filesystem.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.Filesystem, w.Dir, w.BlockSize, w.Hashers, finishedChan, toHashChan, nil, nil, w.Cancel, w.UseWeakHashes)
  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 += file.Size
  134. }
  135. realToHashChan := make(chan protocol.FileInfo)
  136. done := make(chan struct{})
  137. progress := newByteCounter()
  138. newParallelHasher(w.Filesystem, w.Dir, w.BlockSize, w.Hashers, finishedChan, realToHashChan, progress, done, w.Cancel, w.UseWeakHashes)
  139. // A routine which actually emits the FolderScanProgress events
  140. // every w.ProgressTicker ticks, until the hasher routines terminate.
  141. go func() {
  142. defer progress.Close()
  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 MiB/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) fs.WalkFunc {
  179. now := time.Now()
  180. return func(absPath string, info fs.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 = fs.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. info, err = w.Filesystem.Lstat(absPath)
  201. // An error here would be weird as we've already gotten to this point, but act on it nonetheless
  202. if err != nil {
  203. return skip
  204. }
  205. if ignore.IsTemporary(relPath) {
  206. l.Debugln("temporary:", relPath)
  207. if info.IsRegular() && info.ModTime().Add(w.TempLifetime).Before(now) {
  208. w.Filesystem.Remove(absPath)
  209. l.Debugln("removing temporary:", relPath, info.ModTime())
  210. }
  211. return nil
  212. }
  213. if ignore.IsInternal(relPath) {
  214. l.Debugln("ignored (internal):", relPath)
  215. return skip
  216. }
  217. if w.Matcher.Match(relPath).IsIgnored() {
  218. l.Debugln("ignored (patterns):", relPath)
  219. return skip
  220. }
  221. if !utf8.ValidString(relPath) {
  222. l.Warnf("File name %q is not in UTF8 encoding; skipping.", relPath)
  223. return skip
  224. }
  225. relPath, shouldSkip := w.normalizePath(absPath, relPath)
  226. if shouldSkip {
  227. return skip
  228. }
  229. switch {
  230. case info.IsSymlink():
  231. if err := w.walkSymlink(absPath, relPath, dchan); err != nil {
  232. return err
  233. }
  234. if info.IsDir() {
  235. // under no circumstances shall we descend into a symlink
  236. return fs.SkipDir
  237. }
  238. return nil
  239. case info.IsDir():
  240. err = w.walkDir(relPath, info, dchan)
  241. case info.IsRegular():
  242. err = w.walkRegular(relPath, info, fchan)
  243. }
  244. return err
  245. }
  246. }
  247. func (w *walker) walkRegular(relPath string, info fs.FileInfo, fchan chan protocol.FileInfo) error {
  248. curMode := uint32(info.Mode())
  249. if runtime.GOOS == "windows" && osutil.IsWindowsExecutable(relPath) {
  250. curMode |= 0111
  251. }
  252. // A file is "unchanged", if it
  253. // - exists
  254. // - has the same permissions as previously, unless we are ignoring permissions
  255. // - was not marked deleted (since it apparently exists now)
  256. // - had the same modification time as it has now
  257. // - was not a directory previously (since it's a file now)
  258. // - was not a symlink (since it's a file now)
  259. // - was not invalid (since it looks valid now)
  260. // - has the same size as previously
  261. cf, ok := w.CurrentFiler.CurrentFile(relPath)
  262. permUnchanged := w.IgnorePerms || !cf.HasPermissionBits() || PermsEqual(cf.Permissions, curMode)
  263. if ok && permUnchanged && !cf.IsDeleted() && cf.ModTime().Equal(info.ModTime()) && !cf.IsDirectory() &&
  264. !cf.IsSymlink() && !cf.IsInvalid() && cf.Size == info.Size() {
  265. return nil
  266. }
  267. if ok {
  268. l.Debugln("rescan:", cf, info.ModTime().Unix(), info.Mode()&fs.ModePerm)
  269. }
  270. f := protocol.FileInfo{
  271. Name: relPath,
  272. Type: protocol.FileInfoTypeFile,
  273. Version: cf.Version.Update(w.ShortID),
  274. Permissions: curMode & uint32(maskModePerm),
  275. NoPermissions: w.IgnorePerms,
  276. ModifiedS: info.ModTime().Unix(),
  277. ModifiedNs: int32(info.ModTime().Nanosecond()),
  278. ModifiedBy: w.ShortID,
  279. Size: info.Size(),
  280. }
  281. l.Debugln("to hash:", relPath, f)
  282. select {
  283. case fchan <- f:
  284. case <-w.Cancel:
  285. return errors.New("cancelled")
  286. }
  287. return nil
  288. }
  289. func (w *walker) walkDir(relPath string, info fs.FileInfo, dchan chan protocol.FileInfo) error {
  290. // A directory is "unchanged", if it
  291. // - exists
  292. // - has the same permissions as previously, unless we are ignoring permissions
  293. // - was not marked deleted (since it apparently exists now)
  294. // - was a directory previously (not a file or something else)
  295. // - was not a symlink (since it's a directory now)
  296. // - was not invalid (since it looks valid now)
  297. cf, ok := w.CurrentFiler.CurrentFile(relPath)
  298. permUnchanged := w.IgnorePerms || !cf.HasPermissionBits() || PermsEqual(cf.Permissions, uint32(info.Mode()))
  299. if ok && permUnchanged && !cf.IsDeleted() && cf.IsDirectory() && !cf.IsSymlink() && !cf.IsInvalid() {
  300. return nil
  301. }
  302. f := protocol.FileInfo{
  303. Name: relPath,
  304. Type: protocol.FileInfoTypeDirectory,
  305. Version: cf.Version.Update(w.ShortID),
  306. Permissions: uint32(info.Mode() & maskModePerm),
  307. NoPermissions: w.IgnorePerms,
  308. ModifiedS: info.ModTime().Unix(),
  309. ModifiedNs: int32(info.ModTime().Nanosecond()),
  310. ModifiedBy: w.ShortID,
  311. }
  312. l.Debugln("dir:", relPath, f)
  313. select {
  314. case dchan <- f:
  315. case <-w.Cancel:
  316. return errors.New("cancelled")
  317. }
  318. return nil
  319. }
  320. // walkSymlink returns nil or an error, if the error is of the nature that
  321. // it should stop the entire walk.
  322. func (w *walker) walkSymlink(absPath, relPath string, dchan chan protocol.FileInfo) error {
  323. // Symlinks are not supported on Windows. We ignore instead of returning
  324. // an error.
  325. if runtime.GOOS == "windows" {
  326. return nil
  327. }
  328. // We always rehash symlinks as they have no modtime or
  329. // permissions. We check if they point to the old target by
  330. // checking that their existing blocks match with the blocks in
  331. // the index.
  332. target, err := w.Filesystem.ReadSymlink(absPath)
  333. if err != nil {
  334. l.Debugln("readlink error:", absPath, err)
  335. return nil
  336. }
  337. // A symlink is "unchanged", if
  338. // - it exists
  339. // - it wasn't deleted (because it isn't now)
  340. // - it was a symlink
  341. // - it wasn't invalid
  342. // - the symlink type (file/dir) was the same
  343. // - the target was the same
  344. cf, ok := w.CurrentFiler.CurrentFile(relPath)
  345. if ok && !cf.IsDeleted() && cf.IsSymlink() && !cf.IsInvalid() && cf.SymlinkTarget == target {
  346. return nil
  347. }
  348. f := protocol.FileInfo{
  349. Name: relPath,
  350. Type: protocol.FileInfoTypeSymlink,
  351. Version: cf.Version.Update(w.ShortID),
  352. NoPermissions: true, // Symlinks don't have permissions of their own
  353. SymlinkTarget: target,
  354. }
  355. l.Debugln("symlink changedb:", absPath, f)
  356. select {
  357. case dchan <- f:
  358. case <-w.Cancel:
  359. return errors.New("cancelled")
  360. }
  361. return nil
  362. }
  363. // normalizePath returns the normalized relative path (possibly after fixing
  364. // it on disk), or skip is true.
  365. func (w *walker) normalizePath(absPath, relPath string) (normPath string, skip bool) {
  366. if runtime.GOOS == "darwin" {
  367. // Mac OS X file names should always be NFD normalized.
  368. normPath = norm.NFD.String(relPath)
  369. } else {
  370. // Every other OS in the known universe uses NFC or just plain
  371. // doesn't bother to define an encoding. In our case *we* do care,
  372. // so we enforce NFC regardless.
  373. normPath = norm.NFC.String(relPath)
  374. }
  375. if relPath != normPath {
  376. // The file name was not normalized.
  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.", relPath)
  380. return "", true
  381. }
  382. // We will attempt to normalize it.
  383. normalizedPath := filepath.Join(w.Dir, normPath)
  384. if _, err := w.Filesystem.Lstat(normalizedPath); fs.IsNotExist(err) {
  385. // Nothing exists with the normalized filename. Good.
  386. if err = w.Filesystem.Rename(absPath, normalizedPath); err != nil {
  387. l.Infof(`Error normalizing UTF8 encoding of file "%s": %v`, relPath, err)
  388. return "", true
  389. }
  390. l.Infof(`Normalized UTF8 encoding of file name "%s".`, relPath)
  391. } else {
  392. // There is something already in the way at the normalized
  393. // file name.
  394. l.Infof(`File "%s" has UTF8 encoding conflict with another file; ignoring.`, relPath)
  395. return "", true
  396. }
  397. }
  398. return normPath, false
  399. }
  400. func (w *walker) checkDir() error {
  401. if info, err := w.Filesystem.Lstat(w.Dir); err != nil {
  402. return err
  403. } else if !info.IsDir() {
  404. return errors.New(w.Dir + ": not a directory")
  405. } else {
  406. l.Debugln("checkDir", w.Dir, info)
  407. }
  408. return nil
  409. }
  410. func PermsEqual(a, b uint32) bool {
  411. switch runtime.GOOS {
  412. case "windows":
  413. // There is only writeable and read only, represented for user, group
  414. // and other equally. We only compare against user.
  415. return a&0600 == b&0600
  416. default:
  417. // All bits count
  418. return a&0777 == b&0777
  419. }
  420. }
  421. // A byteCounter gets bytes added to it via Update() and then provides the
  422. // Total() and one minute moving average Rate() in bytes per second.
  423. type byteCounter struct {
  424. total int64
  425. metrics.EWMA
  426. stop chan struct{}
  427. }
  428. func newByteCounter() *byteCounter {
  429. c := &byteCounter{
  430. EWMA: metrics.NewEWMA1(), // a one minute exponentially weighted moving average
  431. stop: make(chan struct{}),
  432. }
  433. go c.ticker()
  434. return c
  435. }
  436. func (c *byteCounter) ticker() {
  437. // The metrics.EWMA expects clock ticks every five seconds in order to
  438. // decay the average properly.
  439. t := time.NewTicker(5 * time.Second)
  440. for {
  441. select {
  442. case <-t.C:
  443. c.Tick()
  444. case <-c.stop:
  445. t.Stop()
  446. return
  447. }
  448. }
  449. }
  450. func (c *byteCounter) Update(bytes int64) {
  451. atomic.AddInt64(&c.total, bytes)
  452. c.EWMA.Update(bytes)
  453. }
  454. func (c *byteCounter) Total() int64 {
  455. return atomic.LoadInt64(&c.total)
  456. }
  457. func (c *byteCounter) Close() {
  458. close(c.stop)
  459. }
  460. // A no-op CurrentFiler
  461. type noCurrentFiler struct{}
  462. func (noCurrentFiler) CurrentFile(name string) (protocol.FileInfo, bool) {
  463. return protocol.FileInfo{}, false
  464. }