folder.go 35 KB

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