walk.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  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/db"
  18. "github.com/syncthing/syncthing/lib/events"
  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 Walker 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 IgnoreMatcher
  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. // If MtimeRepo is not nil, it is used to provide mtimes on systems that don't support setting arbirtary mtimes.
  55. MtimeRepo *db.VirtualMtimeRepo
  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 uint64
  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. // Temporary returns a temporary name for the filed referred to by filepath.
  75. TempName(path string) string
  76. // IsTemporary returns true if path refers to the name of temporary file.
  77. IsTemporary(path string) bool
  78. }
  79. type CurrentFiler interface {
  80. // CurrentFile returns the file as seen at last scan.
  81. CurrentFile(name string) (protocol.FileInfo, bool)
  82. }
  83. type IgnoreMatcher interface {
  84. // Match returns true if the file should be ignored.
  85. Match(filename string) bool
  86. }
  87. // Walk returns the list of files found in the local folder by scanning the
  88. // file system. Files are blockwise hashed.
  89. func (w *Walker) Walk() (chan protocol.FileInfo, error) {
  90. l.Debugln("Walk", w.Dir, w.Subs, w.BlockSize, w.Matcher)
  91. err := checkDir(w.Dir)
  92. if 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. filepath.Walk(w.Dir, hashFiles)
  103. } else {
  104. for _, sub := range w.Subs {
  105. filepath.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.Dir, w.BlockSize, w.Hashers, finishedChan, toHashChan, nil, nil, w.Cancel)
  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 += int64(file.CachedSize)
  134. }
  135. realToHashChan := make(chan protocol.FileInfo)
  136. done := make(chan struct{})
  137. progress := newByteCounter()
  138. defer progress.Close()
  139. newParallelHasher(w.Dir, w.BlockSize, w.Hashers, finishedChan, realToHashChan, progress, done, w.Cancel)
  140. // A routine which actually emits the FolderScanProgress events
  141. // every w.ProgressTicker ticks, until the hasher routines terminate.
  142. go func() {
  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 MB/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) filepath.WalkFunc {
  179. now := time.Now()
  180. return func(p string, info os.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 = filepath.SkipDir
  187. }
  188. if err != nil {
  189. l.Debugln("error:", p, info, err)
  190. return skip
  191. }
  192. rn, err := filepath.Rel(w.Dir, p)
  193. if err != nil {
  194. l.Debugln("rel error:", p, err)
  195. return skip
  196. }
  197. if rn == "." {
  198. return nil
  199. }
  200. mtime := info.ModTime()
  201. if w.MtimeRepo != nil {
  202. mtime = w.MtimeRepo.GetMtime(rn, mtime)
  203. }
  204. if w.TempNamer != nil && w.TempNamer.IsTemporary(rn) {
  205. // A temporary file
  206. l.Debugln("temporary:", rn)
  207. if info.Mode().IsRegular() && mtime.Add(w.TempLifetime).Before(now) {
  208. os.Remove(p)
  209. l.Debugln("removing temporary:", rn, mtime)
  210. }
  211. return nil
  212. }
  213. if sn := filepath.Base(rn); sn == ".stignore" || sn == ".stfolder" ||
  214. strings.HasPrefix(rn, ".stversions") || (w.Matcher != nil && w.Matcher.Match(rn)) {
  215. // An ignored file
  216. l.Debugln("ignored:", rn)
  217. return skip
  218. }
  219. if !utf8.ValidString(rn) {
  220. l.Warnf("File name %q is not in UTF8 encoding; skipping.", rn)
  221. return skip
  222. }
  223. var normalizedRn string
  224. if runtime.GOOS == "darwin" {
  225. // Mac OS X file names should always be NFD normalized.
  226. normalizedRn = norm.NFD.String(rn)
  227. } else {
  228. // Every other OS in the known universe uses NFC or just plain
  229. // doesn't bother to define an encoding. In our case *we* do care,
  230. // so we enforce NFC regardless.
  231. normalizedRn = norm.NFC.String(rn)
  232. }
  233. if rn != normalizedRn {
  234. // The file name was not normalized.
  235. if !w.AutoNormalize {
  236. // We're not authorized to do anything about it, so complain and skip.
  237. l.Warnf("File name %q is not in the correct UTF8 normalization form; skipping.", rn)
  238. return skip
  239. }
  240. // We will attempt to normalize it.
  241. normalizedPath := filepath.Join(w.Dir, normalizedRn)
  242. if _, err := osutil.Lstat(normalizedPath); os.IsNotExist(err) {
  243. // Nothing exists with the normalized filename. Good.
  244. if err = os.Rename(p, normalizedPath); err != nil {
  245. l.Infof(`Error normalizing UTF8 encoding of file "%s": %v`, rn, err)
  246. return skip
  247. }
  248. l.Infof(`Normalized UTF8 encoding of file name "%s".`, rn)
  249. } else {
  250. // There is something already in the way at the normalized
  251. // file name.
  252. l.Infof(`File "%s" has UTF8 encoding conflict with another file; ignoring.`, rn)
  253. return skip
  254. }
  255. rn = normalizedRn
  256. }
  257. var cf protocol.FileInfo
  258. var ok bool
  259. // Index wise symlinks are always files, regardless of what the target
  260. // is, because symlinks carry their target path as their content.
  261. if info.Mode()&os.ModeSymlink == os.ModeSymlink {
  262. // If the target is a directory, do NOT descend down there. This
  263. // will cause files to get tracked, and removing the symlink will
  264. // as a result remove files in their real location.
  265. if !symlinks.Supported {
  266. return skip
  267. }
  268. // We always rehash symlinks as they have no modtime or
  269. // permissions. We check if they point to the old target by
  270. // checking that their existing blocks match with the blocks in
  271. // the index.
  272. target, targetType, err := symlinks.Read(p)
  273. if err != nil {
  274. l.Debugln("readlink error:", p, err)
  275. return skip
  276. }
  277. blocks, err := Blocks(strings.NewReader(target), w.BlockSize, 0, nil)
  278. if err != nil {
  279. l.Debugln("hash link error:", p, err)
  280. return skip
  281. }
  282. if w.CurrentFiler != nil {
  283. // A symlink is "unchanged", if
  284. // - it exists
  285. // - it wasn't deleted (because it isn't now)
  286. // - it was a symlink
  287. // - it wasn't invalid
  288. // - the symlink type (file/dir) was the same
  289. // - the block list (i.e. hash of target) was the same
  290. cf, ok = w.CurrentFiler.CurrentFile(rn)
  291. if ok && !cf.IsDeleted() && cf.IsSymlink() && !cf.IsInvalid() && SymlinkTypeEqual(targetType, cf) && BlocksEqual(cf.Blocks, blocks) {
  292. return skip
  293. }
  294. }
  295. f := protocol.FileInfo{
  296. Name: rn,
  297. Version: cf.Version.Update(w.ShortID),
  298. Flags: uint32(protocol.FlagSymlink | protocol.FlagNoPermBits | 0666 | SymlinkFlags(targetType)),
  299. Modified: 0,
  300. Blocks: blocks,
  301. }
  302. l.Debugln("symlink changedb:", p, f)
  303. select {
  304. case dchan <- f:
  305. case <-w.Cancel:
  306. return errors.New("cancelled")
  307. }
  308. return skip
  309. }
  310. if info.Mode().IsDir() {
  311. if w.CurrentFiler != nil {
  312. // A directory is "unchanged", if it
  313. // - exists
  314. // - has the same permissions as previously, unless we are ignoring permissions
  315. // - was not marked deleted (since it apparently exists now)
  316. // - was a directory previously (not a file or something else)
  317. // - was not a symlink (since it's a directory now)
  318. // - was not invalid (since it looks valid now)
  319. cf, ok = w.CurrentFiler.CurrentFile(rn)
  320. permUnchanged := w.IgnorePerms || !cf.HasPermissionBits() || PermsEqual(cf.Flags, uint32(info.Mode()))
  321. if ok && permUnchanged && !cf.IsDeleted() && cf.IsDirectory() && !cf.IsSymlink() && !cf.IsInvalid() {
  322. return nil
  323. }
  324. }
  325. flags := uint32(protocol.FlagDirectory)
  326. if w.IgnorePerms {
  327. flags |= protocol.FlagNoPermBits | 0777
  328. } else {
  329. flags |= uint32(info.Mode() & maskModePerm)
  330. }
  331. f := protocol.FileInfo{
  332. Name: rn,
  333. Version: cf.Version.Update(w.ShortID),
  334. Flags: flags,
  335. Modified: mtime.Unix(),
  336. }
  337. l.Debugln("dir:", p, f)
  338. select {
  339. case dchan <- f:
  340. case <-w.Cancel:
  341. return errors.New("cancelled")
  342. }
  343. return nil
  344. }
  345. if info.Mode().IsRegular() {
  346. curMode := uint32(info.Mode())
  347. if runtime.GOOS == "windows" && osutil.IsWindowsExecutable(rn) {
  348. curMode |= 0111
  349. }
  350. if w.CurrentFiler != nil {
  351. // A file is "unchanged", if it
  352. // - exists
  353. // - has the same permissions as previously, unless we are ignoring permissions
  354. // - was not marked deleted (since it apparently exists now)
  355. // - had the same modification time as it has now
  356. // - was not a directory previously (since it's a file now)
  357. // - was not a symlink (since it's a file now)
  358. // - was not invalid (since it looks valid now)
  359. // - has the same size as previously
  360. cf, ok = w.CurrentFiler.CurrentFile(rn)
  361. permUnchanged := w.IgnorePerms || !cf.HasPermissionBits() || PermsEqual(cf.Flags, curMode)
  362. if ok && permUnchanged && !cf.IsDeleted() && cf.Modified == mtime.Unix() && !cf.IsDirectory() &&
  363. !cf.IsSymlink() && !cf.IsInvalid() && cf.Size() == info.Size() {
  364. return nil
  365. }
  366. l.Debugln("rescan:", cf, mtime.Unix(), info.Mode()&os.ModePerm)
  367. }
  368. var flags = curMode & uint32(maskModePerm)
  369. if w.IgnorePerms {
  370. flags = protocol.FlagNoPermBits | 0666
  371. }
  372. f := protocol.FileInfo{
  373. Name: rn,
  374. Version: cf.Version.Update(w.ShortID),
  375. Flags: flags,
  376. Modified: mtime.Unix(),
  377. CachedSize: info.Size(),
  378. }
  379. l.Debugln("to hash:", p, f)
  380. select {
  381. case fchan <- f:
  382. case <-w.Cancel:
  383. return errors.New("cancelled")
  384. }
  385. }
  386. return nil
  387. }
  388. }
  389. func checkDir(dir string) error {
  390. if info, err := osutil.Lstat(dir); err != nil {
  391. return err
  392. } else if !info.IsDir() {
  393. return errors.New(dir + ": not a directory")
  394. } else {
  395. l.Debugln("checkDir", dir, info)
  396. }
  397. return nil
  398. }
  399. func PermsEqual(a, b uint32) bool {
  400. switch runtime.GOOS {
  401. case "windows":
  402. // There is only writeable and read only, represented for user, group
  403. // and other equally. We only compare against user.
  404. return a&0600 == b&0600
  405. default:
  406. // All bits count
  407. return a&0777 == b&0777
  408. }
  409. }
  410. func SymlinkTypeEqual(disk symlinks.TargetType, f protocol.FileInfo) bool {
  411. // If the target is missing, Unix never knows what type of symlink it is
  412. // and Windows always knows even if there is no target. Which means that
  413. // without this special check a Unix node would be fighting with a Windows
  414. // node about whether or not the target is known. Basically, if you don't
  415. // know and someone else knows, just accept it. The fact that you don't
  416. // know means you are on Unix, and on Unix you don't really care what the
  417. // target type is. The moment you do know, and if something doesn't match,
  418. // that will propagate through the cluster.
  419. switch disk {
  420. case symlinks.TargetUnknown:
  421. return true
  422. case symlinks.TargetDirectory:
  423. return f.IsDirectory() && f.Flags&protocol.FlagSymlinkMissingTarget == 0
  424. case symlinks.TargetFile:
  425. return !f.IsDirectory() && f.Flags&protocol.FlagSymlinkMissingTarget == 0
  426. }
  427. panic("unknown symlink TargetType")
  428. }
  429. func SymlinkFlags(t symlinks.TargetType) uint32 {
  430. switch t {
  431. case symlinks.TargetFile:
  432. return 0
  433. case symlinks.TargetDirectory:
  434. return protocol.FlagDirectory
  435. case symlinks.TargetUnknown:
  436. return protocol.FlagSymlinkMissingTarget
  437. }
  438. panic("unknown symlink TargetType")
  439. }
  440. // A byteCounter gets bytes added to it via Update() and then provides the
  441. // Total() and one minute moving average Rate() in bytes per second.
  442. type byteCounter struct {
  443. total int64
  444. metrics.EWMA
  445. stop chan struct{}
  446. }
  447. func newByteCounter() *byteCounter {
  448. c := &byteCounter{
  449. EWMA: metrics.NewEWMA1(), // a one minute exponentially weighted moving average
  450. stop: make(chan struct{}),
  451. }
  452. go c.ticker()
  453. return c
  454. }
  455. func (c *byteCounter) ticker() {
  456. // The metrics.EWMA expects clock ticks every five seconds in order to
  457. // decay the average properly.
  458. t := time.NewTicker(5 * time.Second)
  459. for {
  460. select {
  461. case <-t.C:
  462. c.Tick()
  463. case <-c.stop:
  464. t.Stop()
  465. return
  466. }
  467. }
  468. }
  469. func (c *byteCounter) Update(bytes int64) {
  470. atomic.AddInt64(&c.total, bytes)
  471. c.EWMA.Update(bytes)
  472. }
  473. func (c *byteCounter) Total() int64 {
  474. return atomic.LoadInt64(&c.total)
  475. }
  476. func (c *byteCounter) Close() {
  477. close(c.stop)
  478. }