folder.go 35 KB

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