folder.go 35 KB

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