folder.go 35 KB

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