walk.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  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. "context"
  9. "runtime"
  10. "sync/atomic"
  11. "time"
  12. "unicode/utf8"
  13. "github.com/rcrowley/go-metrics"
  14. "github.com/syncthing/syncthing/lib/events"
  15. "github.com/syncthing/syncthing/lib/fs"
  16. "github.com/syncthing/syncthing/lib/ignore"
  17. "github.com/syncthing/syncthing/lib/osutil"
  18. "github.com/syncthing/syncthing/lib/protocol"
  19. "golang.org/x/text/unicode/norm"
  20. )
  21. var maskModePerm fs.FileMode
  22. func init() {
  23. if runtime.GOOS == "windows" {
  24. // There is no user/group/others in Windows' read-only
  25. // attribute, and all "w" bits are set in fs.FileMode
  26. // if the file is not read-only. Do not send these
  27. // group/others-writable bits to other devices in order to
  28. // avoid unexpected world-writable files on other platforms.
  29. maskModePerm = fs.ModePerm & 0755
  30. } else {
  31. maskModePerm = fs.ModePerm
  32. }
  33. }
  34. type Config struct {
  35. // Folder for which the walker has been created
  36. Folder string
  37. // Limit walking to these paths within Dir, or no limit if Sub is empty
  38. Subs []string
  39. // BlockSize controls the size of the block used when hashing.
  40. BlockSize int
  41. // If Matcher is not nil, it is used to identify files to ignore which were specified by the user.
  42. Matcher *ignore.Matcher
  43. // Number of hours to keep temporary files for
  44. TempLifetime time.Duration
  45. // If CurrentFiler is not nil, it is queried for the current file before rescanning.
  46. CurrentFiler CurrentFiler
  47. // The Filesystem provides an abstraction on top of the actual filesystem.
  48. Filesystem fs.Filesystem
  49. // If IgnorePerms is true, changes to permission bits will not be
  50. // detected. Scanned files will get zero permission bits and the
  51. // NoPermissionBits flag set.
  52. IgnorePerms bool
  53. // When AutoNormalize is set, file names that are in UTF8 but incorrect
  54. // normalization form will be corrected.
  55. AutoNormalize bool
  56. // Number of routines to use for hashing
  57. Hashers int
  58. // Our vector clock id
  59. ShortID protocol.ShortID
  60. // Optional progress tick interval which defines how often FolderScanProgress
  61. // events are emitted. Negative number means disabled.
  62. ProgressTickIntervalS int
  63. // Whether or not we should also compute weak hashes
  64. UseWeakHashes bool
  65. }
  66. type CurrentFiler interface {
  67. // CurrentFile returns the file as seen at last scan.
  68. CurrentFile(name string) (protocol.FileInfo, bool)
  69. }
  70. func Walk(ctx context.Context, cfg Config) chan protocol.FileInfo {
  71. w := walker{cfg}
  72. if w.CurrentFiler == nil {
  73. w.CurrentFiler = noCurrentFiler{}
  74. }
  75. if w.Filesystem == nil {
  76. panic("no filesystem specified")
  77. }
  78. if w.Matcher == nil {
  79. w.Matcher = ignore.New(w.Filesystem)
  80. }
  81. return w.walk(ctx)
  82. }
  83. type walker struct {
  84. Config
  85. }
  86. // Walk returns the list of files found in the local folder by scanning the
  87. // file system. Files are blockwise hashed.
  88. func (w *walker) walk(ctx context.Context) chan protocol.FileInfo {
  89. l.Debugln("Walk", w.Subs, w.BlockSize, w.Matcher)
  90. toHashChan := make(chan protocol.FileInfo)
  91. finishedChan := make(chan protocol.FileInfo)
  92. // A routine which walks the filesystem tree, and sends files which have
  93. // been modified to the counter routine.
  94. go func() {
  95. hashFiles := w.walkAndHashFiles(ctx, toHashChan, finishedChan)
  96. if len(w.Subs) == 0 {
  97. w.Filesystem.Walk(".", hashFiles)
  98. } else {
  99. for _, sub := range w.Subs {
  100. w.Filesystem.Walk(sub, hashFiles)
  101. }
  102. }
  103. close(toHashChan)
  104. }()
  105. // We're not required to emit scan progress events, just kick off hashers,
  106. // and feed inputs directly from the walker.
  107. if w.ProgressTickIntervalS < 0 {
  108. newParallelHasher(ctx, w.Filesystem, w.BlockSize, w.Hashers, finishedChan, toHashChan, nil, nil, w.UseWeakHashes)
  109. return finishedChan
  110. }
  111. // Defaults to every 2 seconds.
  112. if w.ProgressTickIntervalS == 0 {
  113. w.ProgressTickIntervalS = 2
  114. }
  115. ticker := time.NewTicker(time.Duration(w.ProgressTickIntervalS) * time.Second)
  116. // We need to emit progress events, hence we create a routine which buffers
  117. // the list of files to be hashed, counts the total number of
  118. // bytes to hash, and once no more files need to be hashed (chan gets closed),
  119. // start a routine which periodically emits FolderScanProgress events,
  120. // until a stop signal is sent by the parallel hasher.
  121. // Parallel hasher is stopped by this routine when we close the channel over
  122. // which it receives the files we ask it to hash.
  123. go func() {
  124. var filesToHash []protocol.FileInfo
  125. var total int64 = 1
  126. for file := range toHashChan {
  127. filesToHash = append(filesToHash, file)
  128. total += file.Size
  129. }
  130. realToHashChan := make(chan protocol.FileInfo)
  131. done := make(chan struct{})
  132. progress := newByteCounter()
  133. newParallelHasher(ctx, w.Filesystem, w.BlockSize, w.Hashers, finishedChan, realToHashChan, progress, done, w.UseWeakHashes)
  134. // A routine which actually emits the FolderScanProgress events
  135. // every w.ProgressTicker ticks, until the hasher routines terminate.
  136. go func() {
  137. defer progress.Close()
  138. for {
  139. select {
  140. case <-done:
  141. l.Debugln("Walk progress done", w.Folder, w.Subs, w.BlockSize, w.Matcher)
  142. ticker.Stop()
  143. return
  144. case <-ticker.C:
  145. current := progress.Total()
  146. rate := progress.Rate()
  147. l.Debugf("Walk %s %s current progress %d/%d at %.01f MiB/s (%d%%)", w.Folder, w.Subs, current, total, rate/1024/1024, current*100/total)
  148. events.Default.Log(events.FolderScanProgress, map[string]interface{}{
  149. "folder": w.Folder,
  150. "current": current,
  151. "total": total,
  152. "rate": rate, // bytes per second
  153. })
  154. case <-ctx.Done():
  155. ticker.Stop()
  156. return
  157. }
  158. }
  159. }()
  160. loop:
  161. for _, file := range filesToHash {
  162. l.Debugln("real to hash:", file.Name)
  163. select {
  164. case realToHashChan <- file:
  165. case <-ctx.Done():
  166. break loop
  167. }
  168. }
  169. close(realToHashChan)
  170. }()
  171. return finishedChan
  172. }
  173. func (w *walker) walkAndHashFiles(ctx context.Context, fchan, dchan chan protocol.FileInfo) fs.WalkFunc {
  174. now := time.Now()
  175. return func(path string, info fs.FileInfo, err error) error {
  176. select {
  177. case <-ctx.Done():
  178. return ctx.Err()
  179. default:
  180. }
  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:", path, info, err)
  190. return skip
  191. }
  192. if path == "." {
  193. return nil
  194. }
  195. info, err = w.Filesystem.Lstat(path)
  196. // An error here would be weird as we've already gotten to this point, but act on it nonetheless
  197. if err != nil {
  198. return skip
  199. }
  200. if fs.IsTemporary(path) {
  201. l.Debugln("temporary:", path)
  202. if info.IsRegular() && info.ModTime().Add(w.TempLifetime).Before(now) {
  203. w.Filesystem.Remove(path)
  204. l.Debugln("removing temporary:", path, info.ModTime())
  205. }
  206. return nil
  207. }
  208. if fs.IsInternal(path) {
  209. l.Debugln("ignored (internal):", path)
  210. return skip
  211. }
  212. if w.Matcher.Match(path).IsIgnored() {
  213. l.Debugln("ignored (patterns):", path)
  214. return skip
  215. }
  216. if !utf8.ValidString(path) {
  217. l.Warnf("File name %q is not in UTF8 encoding; skipping.", path)
  218. return skip
  219. }
  220. path, shouldSkip := w.normalizePath(path, info)
  221. if shouldSkip {
  222. return skip
  223. }
  224. switch {
  225. case info.IsSymlink():
  226. if err := w.walkSymlink(ctx, path, dchan); err != nil {
  227. return err
  228. }
  229. if info.IsDir() {
  230. // under no circumstances shall we descend into a symlink
  231. return fs.SkipDir
  232. }
  233. return nil
  234. case info.IsDir():
  235. err = w.walkDir(ctx, path, info, dchan)
  236. case info.IsRegular():
  237. err = w.walkRegular(ctx, path, info, fchan)
  238. }
  239. return err
  240. }
  241. }
  242. func (w *walker) walkRegular(ctx context.Context, relPath string, info fs.FileInfo, fchan chan protocol.FileInfo) error {
  243. curMode := uint32(info.Mode())
  244. if runtime.GOOS == "windows" && osutil.IsWindowsExecutable(relPath) {
  245. curMode |= 0111
  246. }
  247. // A file is "unchanged", if it
  248. // - exists
  249. // - has the same permissions as previously, unless we are ignoring permissions
  250. // - was not marked deleted (since it apparently exists now)
  251. // - had the same modification time as it has now
  252. // - was not a directory previously (since it's a file now)
  253. // - was not a symlink (since it's a file now)
  254. // - was not invalid (since it looks valid now)
  255. // - has the same size as previously
  256. cf, ok := w.CurrentFiler.CurrentFile(relPath)
  257. permUnchanged := w.IgnorePerms || !cf.HasPermissionBits() || PermsEqual(cf.Permissions, curMode)
  258. if ok && permUnchanged && !cf.IsDeleted() && cf.ModTime().Equal(info.ModTime()) && !cf.IsDirectory() &&
  259. !cf.IsSymlink() && !cf.IsInvalid() && cf.Size == info.Size() {
  260. return nil
  261. }
  262. if ok {
  263. l.Debugln("rescan:", cf, info.ModTime().Unix(), info.Mode()&fs.ModePerm)
  264. }
  265. f := protocol.FileInfo{
  266. Name: relPath,
  267. Type: protocol.FileInfoTypeFile,
  268. Version: cf.Version.Update(w.ShortID),
  269. Permissions: curMode & uint32(maskModePerm),
  270. NoPermissions: w.IgnorePerms,
  271. ModifiedS: info.ModTime().Unix(),
  272. ModifiedNs: int32(info.ModTime().Nanosecond()),
  273. ModifiedBy: w.ShortID,
  274. Size: info.Size(),
  275. }
  276. l.Debugln("to hash:", relPath, f)
  277. select {
  278. case fchan <- f:
  279. case <-ctx.Done():
  280. return ctx.Err()
  281. }
  282. return nil
  283. }
  284. func (w *walker) walkDir(ctx context.Context, relPath string, info fs.FileInfo, dchan chan protocol.FileInfo) error {
  285. // A directory is "unchanged", if it
  286. // - exists
  287. // - has the same permissions as previously, unless we are ignoring permissions
  288. // - was not marked deleted (since it apparently exists now)
  289. // - was a directory previously (not a file or something else)
  290. // - was not a symlink (since it's a directory now)
  291. // - was not invalid (since it looks valid now)
  292. cf, ok := w.CurrentFiler.CurrentFile(relPath)
  293. permUnchanged := w.IgnorePerms || !cf.HasPermissionBits() || PermsEqual(cf.Permissions, uint32(info.Mode()))
  294. if ok && permUnchanged && !cf.IsDeleted() && cf.IsDirectory() && !cf.IsSymlink() && !cf.IsInvalid() {
  295. return nil
  296. }
  297. f := protocol.FileInfo{
  298. Name: relPath,
  299. Type: protocol.FileInfoTypeDirectory,
  300. Version: cf.Version.Update(w.ShortID),
  301. Permissions: uint32(info.Mode() & maskModePerm),
  302. NoPermissions: w.IgnorePerms,
  303. ModifiedS: info.ModTime().Unix(),
  304. ModifiedNs: int32(info.ModTime().Nanosecond()),
  305. ModifiedBy: w.ShortID,
  306. }
  307. l.Debugln("dir:", relPath, f)
  308. select {
  309. case dchan <- f:
  310. case <-ctx.Done():
  311. return ctx.Err()
  312. }
  313. return nil
  314. }
  315. // walkSymlink returns nil or an error, if the error is of the nature that
  316. // it should stop the entire walk.
  317. func (w *walker) walkSymlink(ctx context.Context, relPath string, dchan chan protocol.FileInfo) error {
  318. // Symlinks are not supported on Windows. We ignore instead of returning
  319. // an error.
  320. if runtime.GOOS == "windows" {
  321. return nil
  322. }
  323. // We always rehash symlinks as they have no modtime or
  324. // permissions. We check if they point to the old target by
  325. // checking that their existing blocks match with the blocks in
  326. // the index.
  327. target, err := w.Filesystem.ReadSymlink(relPath)
  328. if err != nil {
  329. l.Debugln("readlink error:", relPath, err)
  330. return nil
  331. }
  332. // A symlink is "unchanged", if
  333. // - it exists
  334. // - it wasn't deleted (because it isn't now)
  335. // - it was a symlink
  336. // - it wasn't invalid
  337. // - the target was the same
  338. cf, ok := w.CurrentFiler.CurrentFile(relPath)
  339. if ok && !cf.IsDeleted() && cf.IsSymlink() && !cf.IsInvalid() && cf.SymlinkTarget == target {
  340. return nil
  341. }
  342. f := protocol.FileInfo{
  343. Name: relPath,
  344. Type: protocol.FileInfoTypeSymlink,
  345. Version: cf.Version.Update(w.ShortID),
  346. NoPermissions: true, // Symlinks don't have permissions of their own
  347. SymlinkTarget: target,
  348. }
  349. l.Debugln("symlink changedb:", relPath, f)
  350. select {
  351. case dchan <- f:
  352. case <-ctx.Done():
  353. return ctx.Err()
  354. }
  355. return nil
  356. }
  357. // normalizePath returns the normalized relative path (possibly after fixing
  358. // it on disk), or skip is true.
  359. func (w *walker) normalizePath(path string, info fs.FileInfo) (normPath string, skip bool) {
  360. if runtime.GOOS == "darwin" {
  361. // Mac OS X file names should always be NFD normalized.
  362. normPath = norm.NFD.String(path)
  363. } else {
  364. // Every other OS in the known universe uses NFC or just plain
  365. // doesn't bother to define an encoding. In our case *we* do care,
  366. // so we enforce NFC regardless.
  367. normPath = norm.NFC.String(path)
  368. }
  369. if path == normPath {
  370. // The file name is already normalized: nothing to do
  371. return path, false
  372. }
  373. if !w.AutoNormalize {
  374. // We're not authorized to do anything about it, so complain and skip.
  375. l.Warnf("File name %q is not in the correct UTF8 normalization form; skipping.", path)
  376. return "", true
  377. }
  378. // We will attempt to normalize it.
  379. normInfo, err := w.Filesystem.Lstat(normPath)
  380. if fs.IsNotExist(err) {
  381. // Nothing exists with the normalized filename. Good.
  382. if err = w.Filesystem.Rename(path, normPath); err != nil {
  383. l.Infof(`Error normalizing UTF8 encoding of file "%s": %v`, path, err)
  384. return "", true
  385. }
  386. l.Infof(`Normalized UTF8 encoding of file name "%s".`, path)
  387. } else if w.Filesystem.SameFile(info, normInfo) {
  388. // With some filesystems (ZFS), if there is an un-normalized path and you ask whether the normalized
  389. // version exists, it responds with true. Therefore we need to check fs.SameFile as well.
  390. // In this case, a call to Rename won't do anything, so we have to rename via a temp file.
  391. // We don't want to use the standard syncthing prefix here, as that will result in the file being ignored
  392. // and eventually deleted by Syncthing if the rename back fails.
  393. tempPath := fs.TempNameWithPrefix(normPath, "")
  394. if err = w.Filesystem.Rename(path, tempPath); err != nil {
  395. l.Infof(`Error during normalizing UTF8 encoding of file "%s" (renamed to "%s"): %v`, path, tempPath, err)
  396. return "", true
  397. }
  398. if err = w.Filesystem.Rename(tempPath, normPath); err != nil {
  399. // I don't ever expect this to happen, but if it does, we should probably tell our caller that the normalized
  400. // path is the temp path: that way at least the user's data still gets synced.
  401. l.Warnf(`Error renaming "%s" to "%s" while normalizating UTF8 encoding: %v. You will want to rename this file back manually`, tempPath, normPath, err)
  402. return tempPath, false
  403. }
  404. } else {
  405. // There is something already in the way at the normalized
  406. // file name.
  407. l.Infof(`File "%s" path has UTF8 encoding conflict with another file; ignoring.`, path)
  408. return "", true
  409. }
  410. return normPath, false
  411. }
  412. func PermsEqual(a, b uint32) bool {
  413. switch runtime.GOOS {
  414. case "windows":
  415. // There is only writeable and read only, represented for user, group
  416. // and other equally. We only compare against user.
  417. return a&0600 == b&0600
  418. default:
  419. // All bits count
  420. return a&0777 == b&0777
  421. }
  422. }
  423. // A byteCounter gets bytes added to it via Update() and then provides the
  424. // Total() and one minute moving average Rate() in bytes per second.
  425. type byteCounter struct {
  426. total int64
  427. metrics.EWMA
  428. stop chan struct{}
  429. }
  430. func newByteCounter() *byteCounter {
  431. c := &byteCounter{
  432. EWMA: metrics.NewEWMA1(), // a one minute exponentially weighted moving average
  433. stop: make(chan struct{}),
  434. }
  435. go c.ticker()
  436. return c
  437. }
  438. func (c *byteCounter) ticker() {
  439. // The metrics.EWMA expects clock ticks every five seconds in order to
  440. // decay the average properly.
  441. t := time.NewTicker(5 * time.Second)
  442. for {
  443. select {
  444. case <-t.C:
  445. c.Tick()
  446. case <-c.stop:
  447. t.Stop()
  448. return
  449. }
  450. }
  451. }
  452. func (c *byteCounter) Update(bytes int64) {
  453. atomic.AddInt64(&c.total, bytes)
  454. c.EWMA.Update(bytes)
  455. }
  456. func (c *byteCounter) Total() int64 {
  457. return atomic.LoadInt64(&c.total)
  458. }
  459. func (c *byteCounter) Close() {
  460. close(c.stop)
  461. }
  462. // A no-op CurrentFiler
  463. type noCurrentFiler struct{}
  464. func (noCurrentFiler) CurrentFile(name string) (protocol.FileInfo, bool) {
  465. return protocol.FileInfo{}, false
  466. }