walk.go 15 KB

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