folder.go 35 KB

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