folder.go 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365
  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 model
  7. import (
  8. "context"
  9. "fmt"
  10. "math/rand"
  11. "path/filepath"
  12. "sort"
  13. "sync/atomic"
  14. "time"
  15. "github.com/pkg/errors"
  16. "github.com/syncthing/syncthing/lib/config"
  17. "github.com/syncthing/syncthing/lib/db"
  18. "github.com/syncthing/syncthing/lib/events"
  19. "github.com/syncthing/syncthing/lib/fs"
  20. "github.com/syncthing/syncthing/lib/ignore"
  21. "github.com/syncthing/syncthing/lib/locations"
  22. "github.com/syncthing/syncthing/lib/osutil"
  23. "github.com/syncthing/syncthing/lib/protocol"
  24. "github.com/syncthing/syncthing/lib/scanner"
  25. "github.com/syncthing/syncthing/lib/stats"
  26. "github.com/syncthing/syncthing/lib/svcutil"
  27. "github.com/syncthing/syncthing/lib/sync"
  28. "github.com/syncthing/syncthing/lib/util"
  29. "github.com/syncthing/syncthing/lib/versioner"
  30. "github.com/syncthing/syncthing/lib/watchaggregator"
  31. )
  32. // Arbitrary limit that triggers a warning on kqueue systems
  33. const kqueueItemCountThreshold = 10000
  34. type folder struct {
  35. stateTracker
  36. config.FolderConfiguration
  37. *stats.FolderStatisticsReference
  38. ioLimiter *util.Semaphore
  39. localFlags uint32
  40. model *model
  41. shortID protocol.ShortID
  42. fset *db.FileSet
  43. ignores *ignore.Matcher
  44. mtimefs fs.Filesystem
  45. modTimeWindow time.Duration
  46. ctx context.Context // used internally, only accessible on serve lifetime
  47. done chan struct{} // used externally, accessible regardless of serve
  48. scanInterval time.Duration
  49. scanTimer *time.Timer
  50. scanDelay chan time.Duration
  51. initialScanFinished chan struct{}
  52. scanScheduled chan struct{}
  53. versionCleanupInterval time.Duration
  54. versionCleanupTimer *time.Timer
  55. pullScheduled chan struct{}
  56. pullPause time.Duration
  57. pullFailTimer *time.Timer
  58. scanErrors []FileError
  59. pullErrors []FileError
  60. errorsMut sync.Mutex
  61. doInSyncChan chan syncRequest
  62. forcedRescanRequested chan struct{}
  63. forcedRescanPaths map[string]struct{}
  64. forcedRescanPathsMut sync.Mutex
  65. watchCancel context.CancelFunc
  66. watchChan chan []string
  67. restartWatchChan chan struct{}
  68. watchErr error
  69. watchMut sync.Mutex
  70. puller puller
  71. versioner versioner.Versioner
  72. warnedKqueue bool
  73. }
  74. type syncRequest struct {
  75. fn func() error
  76. err chan error
  77. }
  78. type puller interface {
  79. pull() (bool, error) // true when successful and should not be retried
  80. }
  81. func newFolder(model *model, fset *db.FileSet, ignores *ignore.Matcher, cfg config.FolderConfiguration, evLogger events.Logger, ioLimiter *util.Semaphore, ver versioner.Versioner) folder {
  82. f := folder{
  83. stateTracker: newStateTracker(cfg.ID, evLogger),
  84. FolderConfiguration: cfg,
  85. FolderStatisticsReference: stats.NewFolderStatisticsReference(model.db, cfg.ID),
  86. ioLimiter: ioLimiter,
  87. model: model,
  88. shortID: model.shortID,
  89. fset: fset,
  90. ignores: ignores,
  91. mtimefs: cfg.Filesystem(fset),
  92. modTimeWindow: cfg.ModTimeWindow(),
  93. done: make(chan struct{}),
  94. scanInterval: time.Duration(cfg.RescanIntervalS) * time.Second,
  95. scanTimer: time.NewTimer(0), // The first scan should be done immediately.
  96. scanDelay: make(chan time.Duration),
  97. initialScanFinished: make(chan struct{}),
  98. scanScheduled: make(chan struct{}, 1),
  99. versionCleanupInterval: time.Duration(cfg.Versioning.CleanupIntervalS) * time.Second,
  100. versionCleanupTimer: time.NewTimer(time.Duration(cfg.Versioning.CleanupIntervalS) * time.Second),
  101. pullScheduled: make(chan struct{}, 1), // This needs to be 1-buffered so that we queue a pull if we're busy when it comes.
  102. errorsMut: sync.NewMutex(),
  103. doInSyncChan: make(chan syncRequest),
  104. forcedRescanRequested: make(chan struct{}, 1),
  105. forcedRescanPaths: make(map[string]struct{}),
  106. forcedRescanPathsMut: sync.NewMutex(),
  107. watchCancel: func() {},
  108. restartWatchChan: make(chan struct{}, 1),
  109. watchMut: sync.NewMutex(),
  110. versioner: ver,
  111. }
  112. f.pullPause = f.pullBasePause()
  113. f.pullFailTimer = time.NewTimer(0)
  114. <-f.pullFailTimer.C
  115. return f
  116. }
  117. func (f *folder) Serve(ctx context.Context) error {
  118. atomic.AddInt32(&f.model.foldersRunning, 1)
  119. defer atomic.AddInt32(&f.model.foldersRunning, -1)
  120. f.ctx = ctx
  121. l.Debugln(f, "starting")
  122. defer l.Debugln(f, "exiting")
  123. defer func() {
  124. f.scanTimer.Stop()
  125. f.versionCleanupTimer.Stop()
  126. f.setState(FolderIdle)
  127. }()
  128. if f.FSWatcherEnabled && f.getHealthErrorAndLoadIgnores() == nil {
  129. f.startWatch()
  130. }
  131. // If we're configured to not do version cleanup, or we don't have a
  132. // versioner, cancel and drain that timer now.
  133. if f.versionCleanupInterval == 0 || f.versioner == nil {
  134. if !f.versionCleanupTimer.Stop() {
  135. <-f.versionCleanupTimer.C
  136. }
  137. }
  138. initialCompleted := f.initialScanFinished
  139. for {
  140. var err error
  141. select {
  142. case <-f.ctx.Done():
  143. close(f.done)
  144. return nil
  145. case <-f.pullScheduled:
  146. _, err = f.pull()
  147. case <-f.pullFailTimer.C:
  148. var success bool
  149. success, err = f.pull()
  150. if (err != nil || !success) && f.pullPause < 60*f.pullBasePause() {
  151. // Back off from retrying to pull
  152. f.pullPause *= 2
  153. }
  154. case <-initialCompleted:
  155. // Initial scan has completed, we should do a pull
  156. initialCompleted = nil // never hit this case again
  157. _, err = f.pull()
  158. case <-f.forcedRescanRequested:
  159. err = f.handleForcedRescans()
  160. case <-f.scanTimer.C:
  161. l.Debugln(f, "Scanning due to timer")
  162. err = f.scanTimerFired()
  163. case req := <-f.doInSyncChan:
  164. l.Debugln(f, "Running something due to request")
  165. err = req.fn()
  166. req.err <- err
  167. case next := <-f.scanDelay:
  168. l.Debugln(f, "Delaying scan")
  169. f.scanTimer.Reset(next)
  170. case <-f.scanScheduled:
  171. l.Debugln(f, "Scan was scheduled")
  172. f.scanTimer.Reset(0)
  173. case fsEvents := <-f.watchChan:
  174. l.Debugln(f, "Scan due to watcher")
  175. err = f.scanSubdirs(fsEvents)
  176. case <-f.restartWatchChan:
  177. l.Debugln(f, "Restart watcher")
  178. err = f.restartWatch()
  179. case <-f.versionCleanupTimer.C:
  180. l.Debugln(f, "Doing version cleanup")
  181. f.versionCleanupTimerFired()
  182. }
  183. if err != nil {
  184. if svcutil.IsFatal(err) {
  185. return err
  186. }
  187. f.setError(err)
  188. }
  189. }
  190. }
  191. func (*folder) BringToFront(string) {}
  192. func (*folder) Override() {}
  193. func (*folder) Revert() {}
  194. func (f *folder) DelayScan(next time.Duration) {
  195. select {
  196. case f.scanDelay <- next:
  197. case <-f.done:
  198. }
  199. }
  200. func (f *folder) ScheduleScan() {
  201. // 1-buffered chan
  202. select {
  203. case f.scanScheduled <- struct{}{}:
  204. default:
  205. }
  206. }
  207. func (f *folder) ignoresUpdated() {
  208. if f.FSWatcherEnabled {
  209. f.scheduleWatchRestart()
  210. }
  211. }
  212. func (f *folder) SchedulePull() {
  213. select {
  214. case f.pullScheduled <- struct{}{}:
  215. default:
  216. // We might be busy doing a pull and thus not reading from this
  217. // channel. The channel is 1-buffered, so one notification will be
  218. // queued to ensure we recheck after the pull, but beyond that we must
  219. // make sure to not block index receiving.
  220. }
  221. }
  222. func (*folder) Jobs(_, _ int) ([]string, []string, int) {
  223. return nil, nil, 0
  224. }
  225. func (f *folder) Scan(subdirs []string) error {
  226. <-f.initialScanFinished
  227. return f.doInSync(func() error { return f.scanSubdirs(subdirs) })
  228. }
  229. // doInSync allows to run functions synchronously in folder.serve from exported,
  230. // asynchronously called methods.
  231. func (f *folder) doInSync(fn func() error) error {
  232. req := syncRequest{
  233. fn: fn,
  234. err: make(chan error, 1),
  235. }
  236. select {
  237. case f.doInSyncChan <- req:
  238. return <-req.err
  239. case <-f.done:
  240. return context.Canceled
  241. }
  242. }
  243. func (f *folder) Reschedule() {
  244. if f.scanInterval == 0 {
  245. return
  246. }
  247. // Sleep a random time between 3/4 and 5/4 of the configured interval.
  248. sleepNanos := (f.scanInterval.Nanoseconds()*3 + rand.Int63n(2*f.scanInterval.Nanoseconds())) / 4
  249. interval := time.Duration(sleepNanos) * time.Nanosecond
  250. l.Debugln(f, "next rescan in", interval)
  251. f.scanTimer.Reset(interval)
  252. }
  253. func (f *folder) getHealthErrorAndLoadIgnores() error {
  254. if err := f.getHealthErrorWithoutIgnores(); err != nil {
  255. return err
  256. }
  257. if f.Type != config.FolderTypeReceiveEncrypted {
  258. if err := f.ignores.Load(".stignore"); err != nil && !fs.IsNotExist(err) {
  259. return errors.Wrap(err, "loading ignores")
  260. }
  261. }
  262. return nil
  263. }
  264. func (f *folder) getHealthErrorWithoutIgnores() error {
  265. // Check for folder errors, with the most serious and specific first and
  266. // generic ones like out of space on the home disk later.
  267. if err := f.CheckPath(); err != nil {
  268. return err
  269. }
  270. dbPath := locations.Get(locations.Database)
  271. if usage, err := fs.NewFilesystem(fs.FilesystemTypeBasic, dbPath).Usage("."); err == nil {
  272. if err = config.CheckFreeSpace(f.model.cfg.Options().MinHomeDiskFree, usage); err != nil {
  273. return fmt.Errorf("insufficient space on disk for database (%v): %w", dbPath, err)
  274. }
  275. }
  276. return nil
  277. }
  278. func (f *folder) pull() (success bool, err error) {
  279. f.pullFailTimer.Stop()
  280. select {
  281. case <-f.pullFailTimer.C:
  282. default:
  283. }
  284. select {
  285. case <-f.initialScanFinished:
  286. default:
  287. // Once the initial scan finished, a pull will be scheduled
  288. return true, nil
  289. }
  290. defer func() {
  291. if success {
  292. // We're good, reset the pause interval.
  293. f.pullPause = f.pullBasePause()
  294. }
  295. }()
  296. // If there is nothing to do, don't even enter sync-waiting state.
  297. abort := true
  298. snap, err := f.dbSnapshot()
  299. if err != nil {
  300. return false, err
  301. }
  302. snap.WithNeed(protocol.LocalDeviceID, func(intf protocol.FileIntf) bool {
  303. abort = false
  304. return false
  305. })
  306. snap.Release()
  307. if abort {
  308. // Clears pull failures on items that were needed before, but aren't anymore.
  309. f.errorsMut.Lock()
  310. f.pullErrors = nil
  311. f.errorsMut.Unlock()
  312. return true, nil
  313. }
  314. // Abort early (before acquiring a token) if there's a folder error
  315. err = f.getHealthErrorWithoutIgnores()
  316. if err != nil {
  317. l.Debugln("Skipping pull of", f.Description(), "due to folder error:", err)
  318. return false, err
  319. }
  320. // Send only folder doesn't do any io, it only checks for out-of-sync
  321. // items that differ in metadata and updates those.
  322. if f.Type != config.FolderTypeSendOnly {
  323. f.setState(FolderSyncWaiting)
  324. if err := f.ioLimiter.TakeWithContext(f.ctx, 1); err != nil {
  325. return true, err
  326. }
  327. defer f.ioLimiter.Give(1)
  328. }
  329. startTime := time.Now()
  330. // Check if the ignore patterns changed.
  331. oldHash := f.ignores.Hash()
  332. defer func() {
  333. if f.ignores.Hash() != oldHash {
  334. f.ignoresUpdated()
  335. }
  336. }()
  337. err = f.getHealthErrorAndLoadIgnores()
  338. if err != nil {
  339. l.Debugln("Skipping pull of", f.Description(), "due to folder error:", err)
  340. return false, err
  341. }
  342. f.setError(nil)
  343. success, err = f.puller.pull()
  344. if success && err == nil {
  345. return true, nil
  346. }
  347. // Pulling failed, try again later.
  348. delay := f.pullPause + time.Since(startTime)
  349. l.Infof("Folder %v isn't making sync progress - retrying in %v.", f.Description(), util.NiceDurationString(delay))
  350. f.pullFailTimer.Reset(delay)
  351. return false, err
  352. }
  353. func (f *folder) scanSubdirs(subDirs []string) error {
  354. l.Debugf("%v scanning", f)
  355. oldHash := f.ignores.Hash()
  356. err := f.getHealthErrorAndLoadIgnores()
  357. if err != nil {
  358. return err
  359. }
  360. f.setError(nil)
  361. // Check on the way out if the ignore patterns changed as part of scanning
  362. // this folder. If they did we should schedule a pull of the folder so that
  363. // we request things we might have suddenly become unignored and so on.
  364. defer func() {
  365. if f.ignores.Hash() != oldHash {
  366. l.Debugln("Folder", f.Description(), "ignore patterns change detected while scanning; triggering puller")
  367. f.ignoresUpdated()
  368. f.SchedulePull()
  369. }
  370. }()
  371. f.setState(FolderScanWaiting)
  372. defer f.setState(FolderIdle)
  373. if err := f.ioLimiter.TakeWithContext(f.ctx, 1); err != nil {
  374. return err
  375. }
  376. defer f.ioLimiter.Give(1)
  377. for i := range subDirs {
  378. sub := osutil.NativeFilename(subDirs[i])
  379. if sub == "" {
  380. // A blank subdirs means to scan the entire folder. We can trim
  381. // the subDirs list and go on our way.
  382. subDirs = nil
  383. break
  384. }
  385. subDirs[i] = sub
  386. }
  387. // Clean the list of subitems to ensure that we start at a known
  388. // directory, and don't scan subdirectories of things we've already
  389. // scanned.
  390. snap, err := f.dbSnapshot()
  391. if err != nil {
  392. return err
  393. }
  394. subDirs = unifySubs(subDirs, func(file string) bool {
  395. _, ok := snap.Get(protocol.LocalDeviceID, file)
  396. return ok
  397. })
  398. snap.Release()
  399. f.setState(FolderScanning)
  400. f.clearScanErrors(subDirs)
  401. batch := f.newScanBatch()
  402. // Schedule a pull after scanning, but only if we actually detected any
  403. // changes.
  404. changes := 0
  405. defer func() {
  406. l.Debugf("%v finished scanning, detected %v changes", f, changes)
  407. if changes > 0 {
  408. f.SchedulePull()
  409. }
  410. }()
  411. changesHere, err := f.scanSubdirsChangedAndNew(subDirs, batch)
  412. changes += changesHere
  413. if err != nil {
  414. return err
  415. }
  416. if err := batch.Flush(); err != nil {
  417. return err
  418. }
  419. if len(subDirs) == 0 {
  420. // If we have no specific subdirectories to traverse, set it to one
  421. // empty prefix so we traverse the entire folder contents once.
  422. subDirs = []string{""}
  423. }
  424. // Do a scan of the database for each prefix, to check for deleted and
  425. // ignored files.
  426. changesHere, err = f.scanSubdirsDeletedAndIgnored(subDirs, batch)
  427. changes += changesHere
  428. if err != nil {
  429. return err
  430. }
  431. if err := batch.Flush(); err != nil {
  432. return err
  433. }
  434. f.ScanCompleted()
  435. return nil
  436. }
  437. const maxToRemove = 1000
  438. type scanBatch struct {
  439. f *folder
  440. updateBatch *db.FileInfoBatch
  441. toRemove []string
  442. }
  443. func (f *folder) newScanBatch() *scanBatch {
  444. b := &scanBatch{
  445. f: f,
  446. toRemove: make([]string, 0, maxToRemove),
  447. }
  448. b.updateBatch = db.NewFileInfoBatch(func(fs []protocol.FileInfo) error {
  449. if err := b.f.getHealthErrorWithoutIgnores(); err != nil {
  450. l.Debugf("Stopping scan of folder %s due to: %s", b.f.Description(), err)
  451. return err
  452. }
  453. b.f.updateLocalsFromScanning(fs)
  454. return nil
  455. })
  456. return b
  457. }
  458. func (b *scanBatch) Remove(item string) {
  459. b.toRemove = append(b.toRemove, item)
  460. }
  461. func (b *scanBatch) flushToRemove() {
  462. if len(b.toRemove) > 0 {
  463. b.f.fset.RemoveLocalItems(b.toRemove)
  464. b.toRemove = b.toRemove[:0]
  465. }
  466. }
  467. func (b *scanBatch) Flush() error {
  468. b.flushToRemove()
  469. return b.updateBatch.Flush()
  470. }
  471. func (b *scanBatch) FlushIfFull() error {
  472. if len(b.toRemove) >= maxToRemove {
  473. b.flushToRemove()
  474. }
  475. return b.updateBatch.FlushIfFull()
  476. }
  477. // Update adds the fileinfo to the batch for updating, and does a few checks.
  478. // It returns false if the checks result in the file not going to be updated or removed.
  479. func (b *scanBatch) Update(fi protocol.FileInfo, snap *db.Snapshot) bool {
  480. // Check for a "virtual" parent directory of encrypted files. We don't track
  481. // it, but check if anything still exists within and delete it otherwise.
  482. if b.f.Type == config.FolderTypeReceiveEncrypted && fi.IsDirectory() && protocol.IsEncryptedParent(fs.PathComponents(fi.Name)) {
  483. if names, err := b.f.mtimefs.DirNames(fi.Name); err == nil && len(names) == 0 {
  484. b.f.mtimefs.Remove(fi.Name)
  485. }
  486. return false
  487. }
  488. // Resolve receive-only items which are identical with the global state or
  489. // the global item is our own receive-only item.
  490. switch gf, ok := snap.GetGlobal(fi.Name); {
  491. case !ok:
  492. case gf.IsReceiveOnlyChanged():
  493. if fi.IsDeleted() {
  494. // Our item is deleted and the global item is our own receive only
  495. // file. No point in keeping track of that.
  496. b.Remove(fi.Name)
  497. return true
  498. }
  499. case gf.IsEquivalentOptional(fi, protocol.FileInfoComparison{
  500. ModTimeWindow: b.f.modTimeWindow,
  501. IgnorePerms: b.f.IgnorePerms,
  502. IgnoreBlocks: true,
  503. IgnoreFlags: protocol.FlagLocalReceiveOnly,
  504. IgnoreOwnership: !b.f.SyncOwnership,
  505. }):
  506. // What we have locally is equivalent to the global file.
  507. l.Debugf("%v scanning: Merging identical locally changed item with global", b.f, fi)
  508. fi = gf
  509. }
  510. b.updateBatch.Append(fi)
  511. return true
  512. }
  513. func (f *folder) scanSubdirsChangedAndNew(subDirs []string, batch *scanBatch) (int, error) {
  514. changes := 0
  515. snap, err := f.dbSnapshot()
  516. if err != nil {
  517. return changes, err
  518. }
  519. defer snap.Release()
  520. // If we return early e.g. due to a folder health error, the scan needs
  521. // to be cancelled.
  522. scanCtx, scanCancel := context.WithCancel(f.ctx)
  523. defer scanCancel()
  524. scanConfig := scanner.Config{
  525. Folder: f.ID,
  526. Subs: subDirs,
  527. Matcher: f.ignores,
  528. TempLifetime: time.Duration(f.model.cfg.Options().KeepTemporariesH) * time.Hour,
  529. CurrentFiler: cFiler{snap},
  530. Filesystem: f.mtimefs,
  531. IgnorePerms: f.IgnorePerms,
  532. IgnoreOwnership: !f.SyncOwnership,
  533. AutoNormalize: f.AutoNormalize,
  534. Hashers: f.model.numHashers(f.ID),
  535. ShortID: f.shortID,
  536. ProgressTickIntervalS: f.ScanProgressIntervalS,
  537. LocalFlags: f.localFlags,
  538. ModTimeWindow: f.modTimeWindow,
  539. EventLogger: f.evLogger,
  540. }
  541. var fchan chan scanner.ScanResult
  542. if f.Type == config.FolderTypeReceiveEncrypted {
  543. fchan = scanner.WalkWithoutHashing(scanCtx, scanConfig)
  544. } else {
  545. fchan = scanner.Walk(scanCtx, scanConfig)
  546. }
  547. alreadyUsedOrExisting := make(map[string]struct{})
  548. for res := range fchan {
  549. if res.Err != nil {
  550. f.newScanError(res.Path, res.Err)
  551. continue
  552. }
  553. if err := batch.FlushIfFull(); err != nil {
  554. // Prevent a race between the scan aborting due to context
  555. // cancellation and releasing the snapshot in defer here.
  556. scanCancel()
  557. for range fchan {
  558. }
  559. return changes, err
  560. }
  561. if batch.Update(res.File, snap) {
  562. changes++
  563. }
  564. switch f.Type {
  565. case config.FolderTypeReceiveOnly, config.FolderTypeReceiveEncrypted:
  566. default:
  567. if nf, ok := f.findRename(snap, res.File, alreadyUsedOrExisting); ok {
  568. if batch.Update(nf, snap) {
  569. changes++
  570. }
  571. }
  572. }
  573. }
  574. return changes, nil
  575. }
  576. func (f *folder) scanSubdirsDeletedAndIgnored(subDirs []string, batch *scanBatch) (int, error) {
  577. var toIgnore []db.FileInfoTruncated
  578. ignoredParent := ""
  579. changes := 0
  580. snap, err := f.dbSnapshot()
  581. if err != nil {
  582. return 0, err
  583. }
  584. defer snap.Release()
  585. for _, sub := range subDirs {
  586. var iterError error
  587. snap.WithPrefixedHaveTruncated(protocol.LocalDeviceID, sub, func(fi protocol.FileIntf) bool {
  588. select {
  589. case <-f.ctx.Done():
  590. return false
  591. default:
  592. }
  593. file := fi.(db.FileInfoTruncated)
  594. if err := batch.FlushIfFull(); err != nil {
  595. iterError = err
  596. return false
  597. }
  598. if ignoredParent != "" && !fs.IsParent(file.Name, ignoredParent) {
  599. for _, file := range toIgnore {
  600. l.Debugln("marking file as ignored", file)
  601. nf := file.ConvertToIgnoredFileInfo()
  602. if batch.Update(nf, snap) {
  603. changes++
  604. }
  605. if err := batch.FlushIfFull(); err != nil {
  606. iterError = err
  607. return false
  608. }
  609. }
  610. toIgnore = toIgnore[:0]
  611. ignoredParent = ""
  612. }
  613. switch ignored := f.ignores.Match(file.Name).IsIgnored(); {
  614. case file.IsIgnored() && ignored:
  615. return true
  616. case !file.IsIgnored() && ignored:
  617. // File was not ignored at last pass but has been ignored.
  618. if file.IsDirectory() {
  619. // Delay ignoring as a child might be unignored.
  620. toIgnore = append(toIgnore, file)
  621. if ignoredParent == "" {
  622. // If the parent wasn't ignored already, set
  623. // this path as the "highest" ignored parent
  624. ignoredParent = file.Name
  625. }
  626. return true
  627. }
  628. l.Debugln("marking file as ignored", file)
  629. nf := file.ConvertToIgnoredFileInfo()
  630. if batch.Update(nf, snap) {
  631. changes++
  632. }
  633. case file.IsIgnored() && !ignored:
  634. // Successfully scanned items are already un-ignored during
  635. // the scan, so check whether it is deleted.
  636. fallthrough
  637. case !file.IsIgnored() && !file.IsDeleted() && !file.IsUnsupported():
  638. // The file is not ignored, deleted or unsupported. Lets check if
  639. // it's still here. Simply stat:ing it wont do as there are
  640. // tons of corner cases (e.g. parent dir->symlink, missing
  641. // permissions)
  642. if !osutil.IsDeleted(f.mtimefs, file.Name) {
  643. if ignoredParent != "" {
  644. // Don't ignore parents of this not ignored item
  645. toIgnore = toIgnore[:0]
  646. ignoredParent = ""
  647. }
  648. return true
  649. }
  650. nf := file.ConvertToDeletedFileInfo(f.shortID)
  651. nf.LocalFlags = f.localFlags
  652. if file.ShouldConflict() {
  653. // We do not want to override the global version with
  654. // the deleted file. Setting to an empty version makes
  655. // sure the file gets in sync on the following pull.
  656. nf.Version = protocol.Vector{}
  657. }
  658. l.Debugln("marking file as deleted", nf)
  659. if batch.Update(nf, snap) {
  660. changes++
  661. }
  662. case file.IsDeleted() && file.IsReceiveOnlyChanged():
  663. switch f.Type {
  664. case config.FolderTypeReceiveOnly, config.FolderTypeReceiveEncrypted:
  665. switch gf, ok := snap.GetGlobal(file.Name); {
  666. case !ok:
  667. case gf.IsReceiveOnlyChanged():
  668. l.Debugln("removing deleted, receive-only item that is globally receive-only from db", file)
  669. batch.Remove(file.Name)
  670. changes++
  671. case gf.IsDeleted():
  672. // Our item is deleted and the global item is deleted too. We just
  673. // pretend it is a normal deleted file (nobody cares about that).
  674. l.Debugf("%v scanning: Marking globally deleted item as not locally changed: %v", f, file.Name)
  675. file.LocalFlags &^= protocol.FlagLocalReceiveOnly
  676. if batch.Update(file.ConvertDeletedToFileInfo(), snap) {
  677. changes++
  678. }
  679. }
  680. default:
  681. // No need to bump the version for a file that was and is
  682. // deleted and just the folder type/local flags changed.
  683. file.LocalFlags &^= protocol.FlagLocalReceiveOnly
  684. l.Debugln("removing receive-only flag on deleted item", file)
  685. if batch.Update(file.ConvertDeletedToFileInfo(), snap) {
  686. changes++
  687. }
  688. }
  689. }
  690. return true
  691. })
  692. select {
  693. case <-f.ctx.Done():
  694. return changes, f.ctx.Err()
  695. default:
  696. }
  697. if iterError == nil && len(toIgnore) > 0 {
  698. for _, file := range toIgnore {
  699. l.Debugln("marking file as ignored", f)
  700. nf := file.ConvertToIgnoredFileInfo()
  701. if batch.Update(nf, snap) {
  702. changes++
  703. }
  704. if iterError = batch.FlushIfFull(); iterError != nil {
  705. break
  706. }
  707. }
  708. toIgnore = toIgnore[:0]
  709. }
  710. if iterError != nil {
  711. return changes, iterError
  712. }
  713. }
  714. return changes, nil
  715. }
  716. func (f *folder) findRename(snap *db.Snapshot, file protocol.FileInfo, alreadyUsedOrExisting map[string]struct{}) (protocol.FileInfo, bool) {
  717. if len(file.Blocks) == 0 || file.Size == 0 {
  718. return protocol.FileInfo{}, false
  719. }
  720. found := false
  721. nf := protocol.FileInfo{}
  722. snap.WithBlocksHash(file.BlocksHash, func(ifi protocol.FileIntf) bool {
  723. fi := ifi.(protocol.FileInfo)
  724. select {
  725. case <-f.ctx.Done():
  726. return false
  727. default:
  728. }
  729. if fi.Name == file.Name {
  730. alreadyUsedOrExisting[fi.Name] = struct{}{}
  731. return true
  732. }
  733. if _, ok := alreadyUsedOrExisting[fi.Name]; ok {
  734. return true
  735. }
  736. if fi.ShouldConflict() {
  737. return true
  738. }
  739. if f.ignores.Match(fi.Name).IsIgnored() {
  740. return true
  741. }
  742. // Only check the size.
  743. // No point checking block equality, as that uses BlocksHash comparison if that is set (which it will be).
  744. // No point checking BlocksHash comparison as WithBlocksHash already does that.
  745. if file.Size != fi.Size {
  746. return true
  747. }
  748. alreadyUsedOrExisting[fi.Name] = struct{}{}
  749. if !osutil.IsDeleted(f.mtimefs, fi.Name) {
  750. return true
  751. }
  752. nf = fi
  753. nf.SetDeleted(f.shortID)
  754. nf.LocalFlags = f.localFlags
  755. found = true
  756. return false
  757. })
  758. return nf, found
  759. }
  760. func (f *folder) scanTimerFired() error {
  761. err := f.scanSubdirs(nil)
  762. select {
  763. case <-f.initialScanFinished:
  764. default:
  765. status := "Completed"
  766. if err != nil {
  767. status = "Failed"
  768. }
  769. l.Infoln(status, "initial scan of", f.Type.String(), "folder", f.Description())
  770. close(f.initialScanFinished)
  771. }
  772. f.Reschedule()
  773. return err
  774. }
  775. func (f *folder) versionCleanupTimerFired() {
  776. f.setState(FolderCleanWaiting)
  777. defer f.setState(FolderIdle)
  778. if err := f.ioLimiter.TakeWithContext(f.ctx, 1); err != nil {
  779. return
  780. }
  781. defer f.ioLimiter.Give(1)
  782. f.setState(FolderCleaning)
  783. if err := f.versioner.Clean(f.ctx); err != nil {
  784. l.Infoln("Failed to clean versions in %s: %v", f.Description(), err)
  785. }
  786. f.versionCleanupTimer.Reset(f.versionCleanupInterval)
  787. }
  788. func (f *folder) WatchError() error {
  789. f.watchMut.Lock()
  790. defer f.watchMut.Unlock()
  791. return f.watchErr
  792. }
  793. // stopWatch immediately aborts watching and may be called asynchronously
  794. func (f *folder) stopWatch() {
  795. f.watchMut.Lock()
  796. f.watchCancel()
  797. f.watchMut.Unlock()
  798. f.setWatchError(nil, 0)
  799. }
  800. // scheduleWatchRestart makes sure watching is restarted from the main for loop
  801. // in a folder's Serve and thus may be called asynchronously (e.g. when ignores change).
  802. func (f *folder) scheduleWatchRestart() {
  803. select {
  804. case f.restartWatchChan <- struct{}{}:
  805. default:
  806. // We might be busy doing a pull and thus not reading from this
  807. // channel. The channel is 1-buffered, so one notification will be
  808. // queued to ensure we recheck after the pull.
  809. }
  810. }
  811. // restartWatch should only ever be called synchronously. If you want to use
  812. // this asynchronously, you should probably use scheduleWatchRestart instead.
  813. func (f *folder) restartWatch() error {
  814. f.stopWatch()
  815. f.startWatch()
  816. return f.scanSubdirs(nil)
  817. }
  818. // startWatch should only ever be called synchronously. If you want to use
  819. // this asynchronously, you should probably use scheduleWatchRestart instead.
  820. func (f *folder) startWatch() {
  821. ctx, cancel := context.WithCancel(f.ctx)
  822. f.watchMut.Lock()
  823. f.watchChan = make(chan []string)
  824. f.watchCancel = cancel
  825. f.watchMut.Unlock()
  826. go f.monitorWatch(ctx)
  827. }
  828. // monitorWatch starts the filesystem watching and retries every minute on failure.
  829. // It should not be used except in startWatch.
  830. func (f *folder) monitorWatch(ctx context.Context) {
  831. failTimer := time.NewTimer(0)
  832. aggrCtx, aggrCancel := context.WithCancel(ctx)
  833. var err error
  834. var eventChan <-chan fs.Event
  835. var errChan <-chan error
  836. warnedOutside := false
  837. var lastWatch time.Time
  838. pause := time.Minute
  839. // Subscribe to folder summaries only on kqueue systems, to warn about potential high resource usage
  840. var summarySub events.Subscription
  841. var summaryChan <-chan events.Event
  842. if fs.WatchKqueue && !f.warnedKqueue {
  843. summarySub = f.evLogger.Subscribe(events.FolderSummary)
  844. summaryChan = summarySub.C()
  845. }
  846. defer func() {
  847. aggrCancel() // aggrCancel might e re-assigned -> call within closure
  848. if summaryChan != nil {
  849. summarySub.Unsubscribe()
  850. }
  851. }()
  852. for {
  853. select {
  854. case <-failTimer.C:
  855. eventChan, errChan, err = f.mtimefs.Watch(".", f.ignores, ctx, f.IgnorePerms)
  856. // We do this once per minute initially increased to
  857. // max one hour in case of repeat failures.
  858. f.scanOnWatchErr()
  859. f.setWatchError(err, pause)
  860. if err != nil {
  861. failTimer.Reset(pause)
  862. if pause < 60*time.Minute {
  863. pause *= 2
  864. }
  865. continue
  866. }
  867. lastWatch = time.Now()
  868. watchaggregator.Aggregate(aggrCtx, eventChan, f.watchChan, f.FolderConfiguration, f.model.cfg, f.evLogger)
  869. l.Debugln("Started filesystem watcher for folder", f.Description())
  870. case err = <-errChan:
  871. var next time.Duration
  872. if dur := time.Since(lastWatch); dur > pause {
  873. pause = time.Minute
  874. next = 0
  875. } else {
  876. next = pause - dur
  877. if pause < 60*time.Minute {
  878. pause *= 2
  879. }
  880. }
  881. failTimer.Reset(next)
  882. f.setWatchError(err, next)
  883. // This error was previously a panic and should never occur, so generate
  884. // a warning, but don't do it repetitively.
  885. var errOutside *fs.ErrWatchEventOutsideRoot
  886. if errors.As(err, &errOutside) {
  887. if !warnedOutside {
  888. l.Warnln(err)
  889. warnedOutside = true
  890. }
  891. f.evLogger.Log(events.Failure, "watching for changes encountered an event outside of the filesystem root")
  892. }
  893. aggrCancel()
  894. errChan = nil
  895. aggrCtx, aggrCancel = context.WithCancel(ctx)
  896. case ev := <-summaryChan:
  897. if data, ok := ev.Data.(FolderSummaryEventData); !ok {
  898. f.evLogger.Log(events.Failure, "Unexpected type of folder-summary event in folder.monitorWatch")
  899. } else if data.Summary.LocalTotalItems-data.Summary.LocalDeleted > kqueueItemCountThreshold {
  900. f.warnedKqueue = true
  901. summarySub.Unsubscribe()
  902. summaryChan = nil
  903. l.Warnf("Filesystem watching (kqueue) is enabled on %v with a lot of files/directories, and that requires a lot of resources and might slow down your system significantly", f.Description())
  904. }
  905. case <-ctx.Done():
  906. return
  907. }
  908. }
  909. }
  910. // setWatchError sets the current error state of the watch and should be called
  911. // regardless of whether err is nil or not.
  912. func (f *folder) setWatchError(err error, nextTryIn time.Duration) {
  913. f.watchMut.Lock()
  914. prevErr := f.watchErr
  915. f.watchErr = err
  916. f.watchMut.Unlock()
  917. if err != prevErr {
  918. data := map[string]interface{}{
  919. "folder": f.ID,
  920. }
  921. if prevErr != nil {
  922. data["from"] = prevErr.Error()
  923. }
  924. if err != nil {
  925. data["to"] = err.Error()
  926. }
  927. f.evLogger.Log(events.FolderWatchStateChanged, data)
  928. }
  929. if err == nil {
  930. return
  931. }
  932. msg := fmt.Sprintf("Error while trying to start filesystem watcher for folder %s, trying again in %v: %v", f.Description(), nextTryIn, err)
  933. if prevErr != err {
  934. l.Infof(msg)
  935. return
  936. }
  937. l.Debugf(msg)
  938. }
  939. // scanOnWatchErr schedules a full scan immediately if an error occurred while watching.
  940. func (f *folder) scanOnWatchErr() {
  941. f.watchMut.Lock()
  942. err := f.watchErr
  943. f.watchMut.Unlock()
  944. if err != nil {
  945. f.DelayScan(0)
  946. }
  947. }
  948. func (f *folder) setError(err error) {
  949. select {
  950. case <-f.ctx.Done():
  951. return
  952. default:
  953. }
  954. _, _, oldErr := f.getState()
  955. if (err != nil && oldErr != nil && oldErr.Error() == err.Error()) || (err == nil && oldErr == nil) {
  956. return
  957. }
  958. if err != nil {
  959. if oldErr == nil {
  960. l.Warnf("Error on folder %s: %v", f.Description(), err)
  961. } else {
  962. l.Infof("Error on folder %s changed: %q -> %q", f.Description(), oldErr, err)
  963. }
  964. } else {
  965. l.Infoln("Cleared error on folder", f.Description())
  966. f.SchedulePull()
  967. }
  968. if f.FSWatcherEnabled {
  969. if err != nil {
  970. f.stopWatch()
  971. } else {
  972. f.scheduleWatchRestart()
  973. }
  974. }
  975. f.stateTracker.setError(err)
  976. }
  977. func (f *folder) pullBasePause() time.Duration {
  978. if f.PullerPauseS == 0 {
  979. return defaultPullerPause
  980. }
  981. return time.Duration(f.PullerPauseS) * time.Second
  982. }
  983. func (f *folder) String() string {
  984. return fmt.Sprintf("%s/%s@%p", f.Type, f.folderID, f)
  985. }
  986. func (f *folder) newScanError(path string, err error) {
  987. f.errorsMut.Lock()
  988. l.Infof("Scanner (folder %s, item %q): %v", f.Description(), path, err)
  989. f.scanErrors = append(f.scanErrors, FileError{
  990. Err: err.Error(),
  991. Path: path,
  992. })
  993. f.errorsMut.Unlock()
  994. }
  995. func (f *folder) clearScanErrors(subDirs []string) {
  996. f.errorsMut.Lock()
  997. defer f.errorsMut.Unlock()
  998. if len(subDirs) == 0 {
  999. f.scanErrors = nil
  1000. return
  1001. }
  1002. filtered := f.scanErrors[:0]
  1003. outer:
  1004. for _, fe := range f.scanErrors {
  1005. for _, sub := range subDirs {
  1006. if fe.Path == sub || fs.IsParent(fe.Path, sub) {
  1007. continue outer
  1008. }
  1009. }
  1010. filtered = append(filtered, fe)
  1011. }
  1012. f.scanErrors = filtered
  1013. }
  1014. func (f *folder) Errors() []FileError {
  1015. f.errorsMut.Lock()
  1016. defer f.errorsMut.Unlock()
  1017. scanLen := len(f.scanErrors)
  1018. errors := make([]FileError, scanLen+len(f.pullErrors))
  1019. copy(errors[:scanLen], f.scanErrors)
  1020. copy(errors[scanLen:], f.pullErrors)
  1021. sort.Sort(fileErrorList(errors))
  1022. return errors
  1023. }
  1024. // ScheduleForceRescan marks the file such that it gets rehashed on next scan, and schedules a scan.
  1025. func (f *folder) ScheduleForceRescan(path string) {
  1026. f.forcedRescanPathsMut.Lock()
  1027. f.forcedRescanPaths[path] = struct{}{}
  1028. f.forcedRescanPathsMut.Unlock()
  1029. select {
  1030. case f.forcedRescanRequested <- struct{}{}:
  1031. default:
  1032. }
  1033. }
  1034. func (f *folder) updateLocalsFromScanning(fs []protocol.FileInfo) {
  1035. f.updateLocals(fs)
  1036. f.emitDiskChangeEvents(fs, events.LocalChangeDetected)
  1037. }
  1038. func (f *folder) updateLocalsFromPulling(fs []protocol.FileInfo) {
  1039. f.updateLocals(fs)
  1040. f.emitDiskChangeEvents(fs, events.RemoteChangeDetected)
  1041. }
  1042. func (f *folder) updateLocals(fs []protocol.FileInfo) {
  1043. f.fset.Update(protocol.LocalDeviceID, fs)
  1044. filenames := make([]string, len(fs))
  1045. f.forcedRescanPathsMut.Lock()
  1046. for i, file := range fs {
  1047. filenames[i] = file.Name
  1048. // No need to rescan a file that was changed since anyway.
  1049. delete(f.forcedRescanPaths, file.Name)
  1050. }
  1051. f.forcedRescanPathsMut.Unlock()
  1052. seq := f.fset.Sequence(protocol.LocalDeviceID)
  1053. f.evLogger.Log(events.LocalIndexUpdated, map[string]interface{}{
  1054. "folder": f.ID,
  1055. "items": len(fs),
  1056. "filenames": filenames,
  1057. "sequence": seq,
  1058. "version": seq, // legacy for sequence
  1059. })
  1060. }
  1061. func (f *folder) emitDiskChangeEvents(fs []protocol.FileInfo, typeOfEvent events.EventType) {
  1062. for _, file := range fs {
  1063. if file.IsInvalid() {
  1064. continue
  1065. }
  1066. objType := "file"
  1067. action := "modified"
  1068. if file.IsDeleted() {
  1069. action = "deleted"
  1070. }
  1071. if file.IsSymlink() {
  1072. objType = "symlink"
  1073. } else if file.IsDirectory() {
  1074. objType = "dir"
  1075. }
  1076. // Two different events can be fired here based on what EventType is passed into function
  1077. f.evLogger.Log(typeOfEvent, map[string]string{
  1078. "folder": f.ID,
  1079. "folderID": f.ID, // incorrect, deprecated, kept for historical compliance
  1080. "label": f.Label,
  1081. "action": action,
  1082. "type": objType,
  1083. "path": filepath.FromSlash(file.Name),
  1084. "modifiedBy": file.ModifiedBy.String(),
  1085. })
  1086. }
  1087. }
  1088. func (f *folder) handleForcedRescans() error {
  1089. f.forcedRescanPathsMut.Lock()
  1090. paths := make([]string, 0, len(f.forcedRescanPaths))
  1091. for path := range f.forcedRescanPaths {
  1092. paths = append(paths, path)
  1093. }
  1094. f.forcedRescanPaths = make(map[string]struct{})
  1095. f.forcedRescanPathsMut.Unlock()
  1096. if len(paths) == 0 {
  1097. return nil
  1098. }
  1099. batch := db.NewFileInfoBatch(func(fs []protocol.FileInfo) error {
  1100. f.fset.Update(protocol.LocalDeviceID, fs)
  1101. return nil
  1102. })
  1103. snap, err := f.dbSnapshot()
  1104. if err != nil {
  1105. return err
  1106. }
  1107. defer snap.Release()
  1108. for _, path := range paths {
  1109. if err := batch.FlushIfFull(); err != nil {
  1110. return err
  1111. }
  1112. fi, ok := snap.Get(protocol.LocalDeviceID, path)
  1113. if !ok {
  1114. continue
  1115. }
  1116. fi.SetMustRescan()
  1117. batch.Append(fi)
  1118. }
  1119. if err = batch.Flush(); err != nil {
  1120. return err
  1121. }
  1122. return f.scanSubdirs(paths)
  1123. }
  1124. // dbSnapshots gets a snapshot from the fileset, and wraps any error
  1125. // in a svcutil.FatalErr.
  1126. func (f *folder) dbSnapshot() (*db.Snapshot, error) {
  1127. snap, err := f.fset.Snapshot()
  1128. if err != nil {
  1129. return nil, svcutil.AsFatalErr(err, svcutil.ExitError)
  1130. }
  1131. return snap, nil
  1132. }
  1133. // The exists function is expected to return true for all known paths
  1134. // (excluding "" and ".")
  1135. func unifySubs(dirs []string, exists func(dir string) bool) []string {
  1136. if len(dirs) == 0 {
  1137. return nil
  1138. }
  1139. sort.Strings(dirs)
  1140. if dirs[0] == "" || dirs[0] == "." || dirs[0] == string(fs.PathSeparator) {
  1141. return nil
  1142. }
  1143. prev := "./" // Anything that can't be parent of a clean path
  1144. for i := 0; i < len(dirs); {
  1145. dir, err := fs.Canonicalize(dirs[i])
  1146. if err != nil {
  1147. l.Debugf("Skipping %v for scan: %s", dirs[i], err)
  1148. dirs = append(dirs[:i], dirs[i+1:]...)
  1149. continue
  1150. }
  1151. if dir == prev || fs.IsParent(dir, prev) {
  1152. dirs = append(dirs[:i], dirs[i+1:]...)
  1153. continue
  1154. }
  1155. parent := filepath.Dir(dir)
  1156. for parent != "." && parent != string(fs.PathSeparator) && !exists(parent) {
  1157. dir = parent
  1158. parent = filepath.Dir(dir)
  1159. }
  1160. dirs[i] = dir
  1161. prev = dir
  1162. i++
  1163. }
  1164. return dirs
  1165. }
  1166. type cFiler struct {
  1167. *db.Snapshot
  1168. }
  1169. // Implements scanner.CurrentFiler
  1170. func (cf cFiler) CurrentFile(file string) (protocol.FileInfo, bool) {
  1171. return cf.Get(protocol.LocalDeviceID, file)
  1172. }