walk.go 17 KB

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