folder.go 37 KB

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