folder.go 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369
  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. "sync/atomic"
  15. "time"
  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 fmt.Errorf("loading ignores: %w", err)
  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 (b.f.Type == config.FolderTypeReceiveOnly || b.f.Type == config.FolderTypeReceiveEncrypted) &&
  500. gf.IsEquivalentOptional(fi, protocol.FileInfoComparison{
  501. ModTimeWindow: b.f.modTimeWindow,
  502. IgnorePerms: b.f.IgnorePerms,
  503. IgnoreBlocks: true,
  504. IgnoreFlags: protocol.FlagLocalReceiveOnly,
  505. IgnoreOwnership: !b.f.SyncOwnership && !b.f.SendOwnership,
  506. IgnoreXattrs: !b.f.SyncXattrs && !b.f.SendXattrs,
  507. }):
  508. // What we have locally is equivalent to the global file.
  509. l.Debugf("%v scanning: Merging identical locally changed item with global", b.f, fi)
  510. fi = gf
  511. }
  512. b.updateBatch.Append(fi)
  513. return true
  514. }
  515. func (f *folder) scanSubdirsChangedAndNew(subDirs []string, batch *scanBatch) (int, error) {
  516. changes := 0
  517. snap, err := f.dbSnapshot()
  518. if err != nil {
  519. return changes, err
  520. }
  521. defer snap.Release()
  522. // If we return early e.g. due to a folder health error, the scan needs
  523. // to be cancelled.
  524. scanCtx, scanCancel := context.WithCancel(f.ctx)
  525. defer scanCancel()
  526. scanConfig := scanner.Config{
  527. Folder: f.ID,
  528. Subs: subDirs,
  529. Matcher: f.ignores,
  530. TempLifetime: time.Duration(f.model.cfg.Options().KeepTemporariesH) * time.Hour,
  531. CurrentFiler: cFiler{snap},
  532. Filesystem: f.mtimefs,
  533. IgnorePerms: f.IgnorePerms,
  534. AutoNormalize: f.AutoNormalize,
  535. Hashers: f.model.numHashers(f.ID),
  536. ShortID: f.shortID,
  537. ProgressTickIntervalS: f.ScanProgressIntervalS,
  538. LocalFlags: f.localFlags,
  539. ModTimeWindow: f.modTimeWindow,
  540. EventLogger: f.evLogger,
  541. ScanOwnership: f.SendOwnership || f.SyncOwnership,
  542. ScanXattrs: f.SendXattrs || f.SyncXattrs,
  543. XattrFilter: f.XattrFilter,
  544. }
  545. var fchan chan scanner.ScanResult
  546. if f.Type == config.FolderTypeReceiveEncrypted {
  547. fchan = scanner.WalkWithoutHashing(scanCtx, scanConfig)
  548. } else {
  549. fchan = scanner.Walk(scanCtx, scanConfig)
  550. }
  551. alreadyUsedOrExisting := make(map[string]struct{})
  552. for res := range fchan {
  553. if res.Err != nil {
  554. f.newScanError(res.Path, res.Err)
  555. continue
  556. }
  557. if err := batch.FlushIfFull(); err != nil {
  558. // Prevent a race between the scan aborting due to context
  559. // cancellation and releasing the snapshot in defer here.
  560. scanCancel()
  561. for range fchan {
  562. }
  563. return changes, err
  564. }
  565. if batch.Update(res.File, snap) {
  566. changes++
  567. }
  568. switch f.Type {
  569. case config.FolderTypeReceiveOnly, config.FolderTypeReceiveEncrypted:
  570. default:
  571. if nf, ok := f.findRename(snap, res.File, alreadyUsedOrExisting); ok {
  572. if batch.Update(nf, snap) {
  573. changes++
  574. }
  575. }
  576. }
  577. }
  578. return changes, nil
  579. }
  580. func (f *folder) scanSubdirsDeletedAndIgnored(subDirs []string, batch *scanBatch) (int, error) {
  581. var toIgnore []db.FileInfoTruncated
  582. ignoredParent := ""
  583. changes := 0
  584. snap, err := f.dbSnapshot()
  585. if err != nil {
  586. return 0, err
  587. }
  588. defer snap.Release()
  589. for _, sub := range subDirs {
  590. var iterError error
  591. snap.WithPrefixedHaveTruncated(protocol.LocalDeviceID, sub, func(fi protocol.FileIntf) bool {
  592. select {
  593. case <-f.ctx.Done():
  594. return false
  595. default:
  596. }
  597. file := fi.(db.FileInfoTruncated)
  598. if err := batch.FlushIfFull(); err != nil {
  599. iterError = err
  600. return false
  601. }
  602. if ignoredParent != "" && !fs.IsParent(file.Name, ignoredParent) {
  603. for _, file := range toIgnore {
  604. l.Debugln("marking file as ignored", file)
  605. nf := file.ConvertToIgnoredFileInfo()
  606. if batch.Update(nf, snap) {
  607. changes++
  608. }
  609. if err := batch.FlushIfFull(); err != nil {
  610. iterError = err
  611. return false
  612. }
  613. }
  614. toIgnore = toIgnore[:0]
  615. ignoredParent = ""
  616. }
  617. switch ignored := f.ignores.Match(file.Name).IsIgnored(); {
  618. case file.IsIgnored() && ignored:
  619. return true
  620. case !file.IsIgnored() && ignored:
  621. // File was not ignored at last pass but has been ignored.
  622. if file.IsDirectory() {
  623. // Delay ignoring as a child might be unignored.
  624. toIgnore = append(toIgnore, file)
  625. if ignoredParent == "" {
  626. // If the parent wasn't ignored already, set
  627. // this path as the "highest" ignored parent
  628. ignoredParent = file.Name
  629. }
  630. return true
  631. }
  632. l.Debugln("marking file as ignored", file)
  633. nf := file.ConvertToIgnoredFileInfo()
  634. if batch.Update(nf, snap) {
  635. changes++
  636. }
  637. case file.IsIgnored() && !ignored:
  638. // Successfully scanned items are already un-ignored during
  639. // the scan, so check whether it is deleted.
  640. fallthrough
  641. case !file.IsIgnored() && !file.IsDeleted() && !file.IsUnsupported():
  642. // The file is not ignored, deleted or unsupported. Lets check if
  643. // it's still here. Simply stat:ing it wont do as there are
  644. // tons of corner cases (e.g. parent dir->symlink, missing
  645. // permissions)
  646. if !osutil.IsDeleted(f.mtimefs, file.Name) {
  647. if ignoredParent != "" {
  648. // Don't ignore parents of this not ignored item
  649. toIgnore = toIgnore[:0]
  650. ignoredParent = ""
  651. }
  652. return true
  653. }
  654. nf := file.ConvertToDeletedFileInfo(f.shortID)
  655. nf.LocalFlags = f.localFlags
  656. if file.ShouldConflict() {
  657. // We do not want to override the global version with
  658. // the deleted file. Setting to an empty version makes
  659. // sure the file gets in sync on the following pull.
  660. nf.Version = protocol.Vector{}
  661. }
  662. l.Debugln("marking file as deleted", nf)
  663. if batch.Update(nf, snap) {
  664. changes++
  665. }
  666. case file.IsDeleted() && file.IsReceiveOnlyChanged():
  667. switch f.Type {
  668. case config.FolderTypeReceiveOnly, config.FolderTypeReceiveEncrypted:
  669. switch gf, ok := snap.GetGlobal(file.Name); {
  670. case !ok:
  671. case gf.IsReceiveOnlyChanged():
  672. l.Debugln("removing deleted, receive-only item that is globally receive-only from db", file)
  673. batch.Remove(file.Name)
  674. changes++
  675. case gf.IsDeleted():
  676. // Our item is deleted and the global item is deleted too. We just
  677. // pretend it is a normal deleted file (nobody cares about that).
  678. l.Debugf("%v scanning: Marking globally deleted item as not locally changed: %v", f, file.Name)
  679. file.LocalFlags &^= protocol.FlagLocalReceiveOnly
  680. if batch.Update(file.ConvertDeletedToFileInfo(), snap) {
  681. changes++
  682. }
  683. }
  684. default:
  685. // No need to bump the version for a file that was and is
  686. // deleted and just the folder type/local flags changed.
  687. file.LocalFlags &^= protocol.FlagLocalReceiveOnly
  688. l.Debugln("removing receive-only flag on deleted item", file)
  689. if batch.Update(file.ConvertDeletedToFileInfo(), snap) {
  690. changes++
  691. }
  692. }
  693. }
  694. return true
  695. })
  696. select {
  697. case <-f.ctx.Done():
  698. return changes, f.ctx.Err()
  699. default:
  700. }
  701. if iterError == nil && len(toIgnore) > 0 {
  702. for _, file := range toIgnore {
  703. l.Debugln("marking file as ignored", f)
  704. nf := file.ConvertToIgnoredFileInfo()
  705. if batch.Update(nf, snap) {
  706. changes++
  707. }
  708. if iterError = batch.FlushIfFull(); iterError != nil {
  709. break
  710. }
  711. }
  712. toIgnore = toIgnore[:0]
  713. }
  714. if iterError != nil {
  715. return changes, iterError
  716. }
  717. }
  718. return changes, nil
  719. }
  720. func (f *folder) findRename(snap *db.Snapshot, file protocol.FileInfo, alreadyUsedOrExisting map[string]struct{}) (protocol.FileInfo, bool) {
  721. if len(file.Blocks) == 0 || file.Size == 0 {
  722. return protocol.FileInfo{}, false
  723. }
  724. found := false
  725. nf := protocol.FileInfo{}
  726. snap.WithBlocksHash(file.BlocksHash, func(ifi protocol.FileIntf) bool {
  727. fi := ifi.(protocol.FileInfo)
  728. select {
  729. case <-f.ctx.Done():
  730. return false
  731. default:
  732. }
  733. if fi.Name == file.Name {
  734. alreadyUsedOrExisting[fi.Name] = struct{}{}
  735. return true
  736. }
  737. if _, ok := alreadyUsedOrExisting[fi.Name]; ok {
  738. return true
  739. }
  740. if fi.ShouldConflict() {
  741. return true
  742. }
  743. if f.ignores.Match(fi.Name).IsIgnored() {
  744. return true
  745. }
  746. // Only check the size.
  747. // No point checking block equality, as that uses BlocksHash comparison if that is set (which it will be).
  748. // No point checking BlocksHash comparison as WithBlocksHash already does that.
  749. if file.Size != fi.Size {
  750. return true
  751. }
  752. alreadyUsedOrExisting[fi.Name] = struct{}{}
  753. if !osutil.IsDeleted(f.mtimefs, fi.Name) {
  754. return true
  755. }
  756. nf = fi
  757. nf.SetDeleted(f.shortID)
  758. nf.LocalFlags = f.localFlags
  759. found = true
  760. return false
  761. })
  762. return nf, found
  763. }
  764. func (f *folder) scanTimerFired() error {
  765. err := f.scanSubdirs(nil)
  766. select {
  767. case <-f.initialScanFinished:
  768. default:
  769. status := "Completed"
  770. if err != nil {
  771. status = "Failed"
  772. }
  773. l.Infoln(status, "initial scan of", f.Type.String(), "folder", f.Description())
  774. close(f.initialScanFinished)
  775. }
  776. f.Reschedule()
  777. return err
  778. }
  779. func (f *folder) versionCleanupTimerFired() {
  780. f.setState(FolderCleanWaiting)
  781. defer f.setState(FolderIdle)
  782. if err := f.ioLimiter.TakeWithContext(f.ctx, 1); err != nil {
  783. return
  784. }
  785. defer f.ioLimiter.Give(1)
  786. f.setState(FolderCleaning)
  787. if err := f.versioner.Clean(f.ctx); err != nil {
  788. l.Infoln("Failed to clean versions in %s: %v", f.Description(), err)
  789. }
  790. f.versionCleanupTimer.Reset(f.versionCleanupInterval)
  791. }
  792. func (f *folder) WatchError() error {
  793. f.watchMut.Lock()
  794. defer f.watchMut.Unlock()
  795. return f.watchErr
  796. }
  797. // stopWatch immediately aborts watching and may be called asynchronously
  798. func (f *folder) stopWatch() {
  799. f.watchMut.Lock()
  800. f.watchCancel()
  801. f.watchMut.Unlock()
  802. f.setWatchError(nil, 0)
  803. }
  804. // scheduleWatchRestart makes sure watching is restarted from the main for loop
  805. // in a folder's Serve and thus may be called asynchronously (e.g. when ignores change).
  806. func (f *folder) scheduleWatchRestart() {
  807. select {
  808. case f.restartWatchChan <- struct{}{}:
  809. default:
  810. // We might be busy doing a pull and thus not reading from this
  811. // channel. The channel is 1-buffered, so one notification will be
  812. // queued to ensure we recheck after the pull.
  813. }
  814. }
  815. // restartWatch should only ever be called synchronously. If you want to use
  816. // this asynchronously, you should probably use scheduleWatchRestart instead.
  817. func (f *folder) restartWatch() error {
  818. f.stopWatch()
  819. f.startWatch()
  820. return f.scanSubdirs(nil)
  821. }
  822. // startWatch should only ever be called synchronously. If you want to use
  823. // this asynchronously, you should probably use scheduleWatchRestart instead.
  824. func (f *folder) startWatch() {
  825. ctx, cancel := context.WithCancel(f.ctx)
  826. f.watchMut.Lock()
  827. f.watchChan = make(chan []string)
  828. f.watchCancel = cancel
  829. f.watchMut.Unlock()
  830. go f.monitorWatch(ctx)
  831. }
  832. // monitorWatch starts the filesystem watching and retries every minute on failure.
  833. // It should not be used except in startWatch.
  834. func (f *folder) monitorWatch(ctx context.Context) {
  835. failTimer := time.NewTimer(0)
  836. aggrCtx, aggrCancel := context.WithCancel(ctx)
  837. var err error
  838. var eventChan <-chan fs.Event
  839. var errChan <-chan error
  840. warnedOutside := false
  841. var lastWatch time.Time
  842. pause := time.Minute
  843. // Subscribe to folder summaries only on kqueue systems, to warn about potential high resource usage
  844. var summarySub events.Subscription
  845. var summaryChan <-chan events.Event
  846. if fs.WatchKqueue && !f.warnedKqueue {
  847. summarySub = f.evLogger.Subscribe(events.FolderSummary)
  848. summaryChan = summarySub.C()
  849. }
  850. defer func() {
  851. aggrCancel() // aggrCancel might e re-assigned -> call within closure
  852. if summaryChan != nil {
  853. summarySub.Unsubscribe()
  854. }
  855. }()
  856. for {
  857. select {
  858. case <-failTimer.C:
  859. eventChan, errChan, err = f.mtimefs.Watch(".", f.ignores, ctx, f.IgnorePerms)
  860. // We do this once per minute initially increased to
  861. // max one hour in case of repeat failures.
  862. f.scanOnWatchErr()
  863. f.setWatchError(err, pause)
  864. if err != nil {
  865. failTimer.Reset(pause)
  866. if pause < 60*time.Minute {
  867. pause *= 2
  868. }
  869. continue
  870. }
  871. lastWatch = time.Now()
  872. watchaggregator.Aggregate(aggrCtx, eventChan, f.watchChan, f.FolderConfiguration, f.model.cfg, f.evLogger)
  873. l.Debugln("Started filesystem watcher for folder", f.Description())
  874. case err = <-errChan:
  875. var next time.Duration
  876. if dur := time.Since(lastWatch); dur > pause {
  877. pause = time.Minute
  878. next = 0
  879. } else {
  880. next = pause - dur
  881. if pause < 60*time.Minute {
  882. pause *= 2
  883. }
  884. }
  885. failTimer.Reset(next)
  886. f.setWatchError(err, next)
  887. // This error was previously a panic and should never occur, so generate
  888. // a warning, but don't do it repetitively.
  889. var errOutside *fs.ErrWatchEventOutsideRoot
  890. if errors.As(err, &errOutside) {
  891. if !warnedOutside {
  892. l.Warnln(err)
  893. warnedOutside = true
  894. }
  895. f.evLogger.Log(events.Failure, "watching for changes encountered an event outside of the filesystem root")
  896. }
  897. aggrCancel()
  898. errChan = nil
  899. aggrCtx, aggrCancel = context.WithCancel(ctx)
  900. case ev := <-summaryChan:
  901. if data, ok := ev.Data.(FolderSummaryEventData); !ok {
  902. f.evLogger.Log(events.Failure, "Unexpected type of folder-summary event in folder.monitorWatch")
  903. } else if data.Summary.LocalTotalItems-data.Summary.LocalDeleted > kqueueItemCountThreshold {
  904. f.warnedKqueue = true
  905. summarySub.Unsubscribe()
  906. summaryChan = nil
  907. 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())
  908. }
  909. case <-ctx.Done():
  910. aggrCancel() // for good measure and keeping the linters happy
  911. return
  912. }
  913. }
  914. }
  915. // setWatchError sets the current error state of the watch and should be called
  916. // regardless of whether err is nil or not.
  917. func (f *folder) setWatchError(err error, nextTryIn time.Duration) {
  918. f.watchMut.Lock()
  919. prevErr := f.watchErr
  920. f.watchErr = err
  921. f.watchMut.Unlock()
  922. if err != prevErr {
  923. data := map[string]interface{}{
  924. "folder": f.ID,
  925. }
  926. if prevErr != nil {
  927. data["from"] = prevErr.Error()
  928. }
  929. if err != nil {
  930. data["to"] = err.Error()
  931. }
  932. f.evLogger.Log(events.FolderWatchStateChanged, data)
  933. }
  934. if err == nil {
  935. return
  936. }
  937. msg := fmt.Sprintf("Error while trying to start filesystem watcher for folder %s, trying again in %v: %v", f.Description(), nextTryIn, err)
  938. if prevErr != err {
  939. l.Infof(msg)
  940. return
  941. }
  942. l.Debugf(msg)
  943. }
  944. // scanOnWatchErr schedules a full scan immediately if an error occurred while watching.
  945. func (f *folder) scanOnWatchErr() {
  946. f.watchMut.Lock()
  947. err := f.watchErr
  948. f.watchMut.Unlock()
  949. if err != nil {
  950. f.DelayScan(0)
  951. }
  952. }
  953. func (f *folder) setError(err error) {
  954. select {
  955. case <-f.ctx.Done():
  956. return
  957. default:
  958. }
  959. _, _, oldErr := f.getState()
  960. if (err != nil && oldErr != nil && oldErr.Error() == err.Error()) || (err == nil && oldErr == nil) {
  961. return
  962. }
  963. if err != nil {
  964. if oldErr == nil {
  965. l.Warnf("Error on folder %s: %v", f.Description(), err)
  966. } else {
  967. l.Infof("Error on folder %s changed: %q -> %q", f.Description(), oldErr, err)
  968. }
  969. } else {
  970. l.Infoln("Cleared error on folder", f.Description())
  971. f.SchedulePull()
  972. }
  973. if f.FSWatcherEnabled {
  974. if err != nil {
  975. f.stopWatch()
  976. } else {
  977. f.scheduleWatchRestart()
  978. }
  979. }
  980. f.stateTracker.setError(err)
  981. }
  982. func (f *folder) pullBasePause() time.Duration {
  983. if f.PullerPauseS == 0 {
  984. return defaultPullerPause
  985. }
  986. return time.Duration(f.PullerPauseS) * time.Second
  987. }
  988. func (f *folder) String() string {
  989. return fmt.Sprintf("%s/%s@%p", f.Type, f.folderID, f)
  990. }
  991. func (f *folder) newScanError(path string, err error) {
  992. f.errorsMut.Lock()
  993. l.Infof("Scanner (folder %s, item %q): %v", f.Description(), path, err)
  994. f.scanErrors = append(f.scanErrors, FileError{
  995. Err: err.Error(),
  996. Path: path,
  997. })
  998. f.errorsMut.Unlock()
  999. }
  1000. func (f *folder) clearScanErrors(subDirs []string) {
  1001. f.errorsMut.Lock()
  1002. defer f.errorsMut.Unlock()
  1003. if len(subDirs) == 0 {
  1004. f.scanErrors = nil
  1005. return
  1006. }
  1007. filtered := f.scanErrors[:0]
  1008. outer:
  1009. for _, fe := range f.scanErrors {
  1010. for _, sub := range subDirs {
  1011. if fe.Path == sub || fs.IsParent(fe.Path, sub) {
  1012. continue outer
  1013. }
  1014. }
  1015. filtered = append(filtered, fe)
  1016. }
  1017. f.scanErrors = filtered
  1018. }
  1019. func (f *folder) Errors() []FileError {
  1020. f.errorsMut.Lock()
  1021. defer f.errorsMut.Unlock()
  1022. scanLen := len(f.scanErrors)
  1023. errors := make([]FileError, scanLen+len(f.pullErrors))
  1024. copy(errors[:scanLen], f.scanErrors)
  1025. copy(errors[scanLen:], f.pullErrors)
  1026. sort.Sort(fileErrorList(errors))
  1027. return errors
  1028. }
  1029. // ScheduleForceRescan marks the file such that it gets rehashed on next scan, and schedules a scan.
  1030. func (f *folder) ScheduleForceRescan(path string) {
  1031. f.forcedRescanPathsMut.Lock()
  1032. f.forcedRescanPaths[path] = struct{}{}
  1033. f.forcedRescanPathsMut.Unlock()
  1034. select {
  1035. case f.forcedRescanRequested <- struct{}{}:
  1036. default:
  1037. }
  1038. }
  1039. func (f *folder) updateLocalsFromScanning(fs []protocol.FileInfo) {
  1040. f.updateLocals(fs)
  1041. f.emitDiskChangeEvents(fs, events.LocalChangeDetected)
  1042. }
  1043. func (f *folder) updateLocalsFromPulling(fs []protocol.FileInfo) {
  1044. f.updateLocals(fs)
  1045. f.emitDiskChangeEvents(fs, events.RemoteChangeDetected)
  1046. }
  1047. func (f *folder) updateLocals(fs []protocol.FileInfo) {
  1048. f.fset.Update(protocol.LocalDeviceID, fs)
  1049. filenames := make([]string, len(fs))
  1050. f.forcedRescanPathsMut.Lock()
  1051. for i, file := range fs {
  1052. filenames[i] = file.Name
  1053. // No need to rescan a file that was changed since anyway.
  1054. delete(f.forcedRescanPaths, file.Name)
  1055. }
  1056. f.forcedRescanPathsMut.Unlock()
  1057. seq := f.fset.Sequence(protocol.LocalDeviceID)
  1058. f.evLogger.Log(events.LocalIndexUpdated, map[string]interface{}{
  1059. "folder": f.ID,
  1060. "items": len(fs),
  1061. "filenames": filenames,
  1062. "sequence": seq,
  1063. "version": seq, // legacy for sequence
  1064. })
  1065. }
  1066. func (f *folder) emitDiskChangeEvents(fs []protocol.FileInfo, typeOfEvent events.EventType) {
  1067. for _, file := range fs {
  1068. if file.IsInvalid() {
  1069. continue
  1070. }
  1071. objType := "file"
  1072. action := "modified"
  1073. if file.IsDeleted() {
  1074. action = "deleted"
  1075. }
  1076. if file.IsSymlink() {
  1077. objType = "symlink"
  1078. } else if file.IsDirectory() {
  1079. objType = "dir"
  1080. }
  1081. // Two different events can be fired here based on what EventType is passed into function
  1082. f.evLogger.Log(typeOfEvent, map[string]string{
  1083. "folder": f.ID,
  1084. "folderID": f.ID, // incorrect, deprecated, kept for historical compliance
  1085. "label": f.Label,
  1086. "action": action,
  1087. "type": objType,
  1088. "path": filepath.FromSlash(file.Name),
  1089. "modifiedBy": file.ModifiedBy.String(),
  1090. })
  1091. }
  1092. }
  1093. func (f *folder) handleForcedRescans() error {
  1094. f.forcedRescanPathsMut.Lock()
  1095. paths := make([]string, 0, len(f.forcedRescanPaths))
  1096. for path := range f.forcedRescanPaths {
  1097. paths = append(paths, path)
  1098. }
  1099. f.forcedRescanPaths = make(map[string]struct{})
  1100. f.forcedRescanPathsMut.Unlock()
  1101. if len(paths) == 0 {
  1102. return nil
  1103. }
  1104. batch := db.NewFileInfoBatch(func(fs []protocol.FileInfo) error {
  1105. f.fset.Update(protocol.LocalDeviceID, fs)
  1106. return nil
  1107. })
  1108. snap, err := f.dbSnapshot()
  1109. if err != nil {
  1110. return err
  1111. }
  1112. defer snap.Release()
  1113. for _, path := range paths {
  1114. if err := batch.FlushIfFull(); err != nil {
  1115. return err
  1116. }
  1117. fi, ok := snap.Get(protocol.LocalDeviceID, path)
  1118. if !ok {
  1119. continue
  1120. }
  1121. fi.SetMustRescan()
  1122. batch.Append(fi)
  1123. }
  1124. if err = batch.Flush(); err != nil {
  1125. return err
  1126. }
  1127. return f.scanSubdirs(paths)
  1128. }
  1129. // dbSnapshots gets a snapshot from the fileset, and wraps any error
  1130. // in a svcutil.FatalErr.
  1131. func (f *folder) dbSnapshot() (*db.Snapshot, error) {
  1132. snap, err := f.fset.Snapshot()
  1133. if err != nil {
  1134. return nil, svcutil.AsFatalErr(err, svcutil.ExitError)
  1135. }
  1136. return snap, nil
  1137. }
  1138. // The exists function is expected to return true for all known paths
  1139. // (excluding "" and ".")
  1140. func unifySubs(dirs []string, exists func(dir string) bool) []string {
  1141. if len(dirs) == 0 {
  1142. return nil
  1143. }
  1144. sort.Strings(dirs)
  1145. if dirs[0] == "" || dirs[0] == "." || dirs[0] == string(fs.PathSeparator) {
  1146. return nil
  1147. }
  1148. prev := "./" // Anything that can't be parent of a clean path
  1149. for i := 0; i < len(dirs); {
  1150. dir, err := fs.Canonicalize(dirs[i])
  1151. if err != nil {
  1152. l.Debugf("Skipping %v for scan: %s", dirs[i], err)
  1153. dirs = append(dirs[:i], dirs[i+1:]...)
  1154. continue
  1155. }
  1156. if dir == prev || fs.IsParent(dir, prev) {
  1157. dirs = append(dirs[:i], dirs[i+1:]...)
  1158. continue
  1159. }
  1160. parent := filepath.Dir(dir)
  1161. for parent != "." && parent != string(fs.PathSeparator) && !exists(parent) {
  1162. dir = parent
  1163. parent = filepath.Dir(dir)
  1164. }
  1165. dirs[i] = dir
  1166. prev = dir
  1167. i++
  1168. }
  1169. return dirs
  1170. }
  1171. type cFiler struct {
  1172. *db.Snapshot
  1173. }
  1174. // Implements scanner.CurrentFiler
  1175. func (cf cFiler) CurrentFile(file string) (protocol.FileInfo, bool) {
  1176. return cf.Get(protocol.LocalDeviceID, file)
  1177. }