folder.go 35 KB

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