1
0

indexhandler.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675
  1. // Copyright (C) 2020 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. "fmt"
  10. "sync"
  11. "time"
  12. "github.com/syncthing/syncthing/lib/config"
  13. "github.com/syncthing/syncthing/lib/db"
  14. "github.com/syncthing/syncthing/lib/events"
  15. "github.com/syncthing/syncthing/lib/protocol"
  16. "github.com/syncthing/syncthing/lib/svcutil"
  17. "github.com/syncthing/syncthing/lib/ur"
  18. )
  19. type indexHandler struct {
  20. conn protocol.Connection
  21. downloads *deviceDownloadState
  22. folder string
  23. folderIsReceiveEncrypted bool
  24. prevSequence int64
  25. evLogger events.Logger
  26. cond *sync.Cond
  27. paused bool
  28. fset *db.FileSet
  29. runner service
  30. }
  31. func newIndexHandler(conn protocol.Connection, downloads *deviceDownloadState, folder config.FolderConfiguration, fset *db.FileSet, runner service, startInfo *clusterConfigDeviceInfo, evLogger events.Logger) *indexHandler {
  32. myIndexID := fset.IndexID(protocol.LocalDeviceID)
  33. mySequence := fset.Sequence(protocol.LocalDeviceID)
  34. var startSequence int64
  35. // This is the other side's description of what it knows
  36. // about us. Lets check to see if we can start sending index
  37. // updates directly or need to send the index from start...
  38. if startInfo.local.IndexID == myIndexID {
  39. // They say they've seen our index ID before, so we can
  40. // send a delta update only.
  41. if startInfo.local.MaxSequence > mySequence {
  42. // Safety check. They claim to have more or newer
  43. // index data than we have - either we have lost
  44. // index data, or reset the index without resetting
  45. // the IndexID, or something else weird has
  46. // happened. We send a full index to reset the
  47. // situation.
  48. l.Infof("Device %v folder %s is delta index compatible, but seems out of sync with reality", conn.DeviceID().Short(), folder.Description())
  49. startSequence = 0
  50. } else {
  51. l.Debugf("Device %v folder %s is delta index compatible (mlv=%d)", conn.DeviceID().Short(), folder.Description(), startInfo.local.MaxSequence)
  52. startSequence = startInfo.local.MaxSequence
  53. }
  54. } else if startInfo.local.IndexID != 0 {
  55. // They say they've seen an index ID from us, but it's
  56. // not the right one. Either they are confused or we
  57. // must have reset our database since last talking to
  58. // them. We'll start with a full index transfer.
  59. l.Infof("Device %v folder %s has mismatching index ID for us (%v != %v)", conn.DeviceID().Short(), folder.Description(), startInfo.local.IndexID, myIndexID)
  60. startSequence = 0
  61. } else {
  62. l.Debugf("Device %v folder %s has no index ID for us", conn.DeviceID().Short(), folder.Description())
  63. }
  64. // This is the other side's description of themselves. We
  65. // check to see that it matches the IndexID we have on file,
  66. // otherwise we drop our old index data and expect to get a
  67. // completely new set.
  68. theirIndexID := fset.IndexID(conn.DeviceID())
  69. if startInfo.remote.IndexID == 0 {
  70. // They're not announcing an index ID. This means they
  71. // do not support delta indexes and we should clear any
  72. // information we have from them before accepting their
  73. // index, which will presumably be a full index.
  74. l.Debugf("Device %v folder %s does not announce an index ID", conn.DeviceID().Short(), folder.Description())
  75. fset.Drop(conn.DeviceID())
  76. } else if startInfo.remote.IndexID != theirIndexID {
  77. // The index ID we have on file is not what they're
  78. // announcing. They must have reset their database and
  79. // will probably send us a full index. We drop any
  80. // information we have and remember this new index ID
  81. // instead.
  82. l.Infof("Device %v folder %s has a new index ID (%v)", conn.DeviceID().Short(), folder.Description(), startInfo.remote.IndexID)
  83. fset.Drop(conn.DeviceID())
  84. fset.SetIndexID(conn.DeviceID(), startInfo.remote.IndexID)
  85. }
  86. return &indexHandler{
  87. conn: conn,
  88. downloads: downloads,
  89. folder: folder.ID,
  90. folderIsReceiveEncrypted: folder.Type == config.FolderTypeReceiveEncrypted,
  91. prevSequence: startSequence,
  92. evLogger: evLogger,
  93. fset: fset,
  94. runner: runner,
  95. cond: sync.NewCond(new(sync.Mutex)),
  96. }
  97. }
  98. // waitForFileset waits for the handler to resume and fetches the current fileset.
  99. func (s *indexHandler) waitForFileset(ctx context.Context) (*db.FileSet, error) {
  100. s.cond.L.Lock()
  101. defer s.cond.L.Unlock()
  102. for s.paused {
  103. select {
  104. case <-ctx.Done():
  105. return nil, ctx.Err()
  106. default:
  107. s.cond.Wait()
  108. }
  109. }
  110. return s.fset, nil
  111. }
  112. func (s *indexHandler) Serve(ctx context.Context) (err error) {
  113. l.Debugf("Starting index handler for %s to %s at %s (slv=%d)", s.folder, s.conn.DeviceID().Short(), s.conn, s.prevSequence)
  114. stop := make(chan struct{})
  115. defer func() {
  116. err = svcutil.NoRestartErr(err)
  117. l.Debugf("Exiting index handler for %s to %s at %s: %v", s.folder, s.conn.DeviceID().Short(), s.conn, err)
  118. close(stop)
  119. }()
  120. // Broadcast the pause cond when the context quits
  121. go func() {
  122. select {
  123. case <-ctx.Done():
  124. s.cond.Broadcast()
  125. case <-stop:
  126. }
  127. }()
  128. // We need to send one index, regardless of whether there is something to send or not
  129. fset, err := s.waitForFileset(ctx)
  130. if err != nil {
  131. return err
  132. }
  133. err = s.sendIndexTo(ctx, fset)
  134. // Subscribe to LocalIndexUpdated (we have new information to send) and
  135. // DeviceDisconnected (it might be us who disconnected, so we should
  136. // exit).
  137. sub := s.evLogger.Subscribe(events.LocalIndexUpdated | events.DeviceDisconnected)
  138. defer sub.Unsubscribe()
  139. evChan := sub.C()
  140. ticker := time.NewTicker(time.Minute)
  141. defer ticker.Stop()
  142. for err == nil {
  143. fset, err = s.waitForFileset(ctx)
  144. if err != nil {
  145. return err
  146. }
  147. // While we have sent a sequence at least equal to the one
  148. // currently in the database, wait for the local index to update. The
  149. // local index may update for other folders than the one we are
  150. // sending for.
  151. if fset.Sequence(protocol.LocalDeviceID) <= s.prevSequence {
  152. select {
  153. case <-ctx.Done():
  154. return ctx.Err()
  155. case <-evChan:
  156. case <-ticker.C:
  157. }
  158. continue
  159. }
  160. err = s.sendIndexTo(ctx, fset)
  161. // Wait a short amount of time before entering the next loop. If there
  162. // are continuous changes happening to the local index, this gives us
  163. // time to batch them up a little.
  164. select {
  165. case <-ctx.Done():
  166. return ctx.Err()
  167. case <-time.After(250 * time.Millisecond):
  168. }
  169. }
  170. return err
  171. }
  172. // resume might be called because the folder was actually resumed, or just
  173. // because the folder config changed (and thus the runner and potentially fset).
  174. func (s *indexHandler) resume(fset *db.FileSet, runner service) {
  175. s.cond.L.Lock()
  176. s.paused = false
  177. s.fset = fset
  178. s.runner = runner
  179. s.cond.Broadcast()
  180. s.cond.L.Unlock()
  181. }
  182. func (s *indexHandler) pause() {
  183. s.cond.L.Lock()
  184. if s.paused {
  185. s.evLogger.Log(events.Failure, "index handler got paused while already paused")
  186. }
  187. s.paused = true
  188. s.fset = nil
  189. s.runner = nil
  190. s.cond.Broadcast()
  191. s.cond.L.Unlock()
  192. }
  193. // sendIndexTo sends file infos with a sequence number higher than prevSequence and
  194. // returns the highest sent sequence number.
  195. func (s *indexHandler) sendIndexTo(ctx context.Context, fset *db.FileSet) error {
  196. // Keep track of the previous sequence we sent. This is separate from
  197. // s.prevSequence because the latter will skip over holes in the
  198. // sequence numberings, while sentPrevSequence should always be
  199. // precisely the highest previously sent sequence.
  200. sentPrevSequence := s.prevSequence
  201. initial := s.prevSequence == 0
  202. batch := db.NewFileInfoBatch(nil)
  203. var batchError error
  204. batch.SetFlushFunc(func(fs []protocol.FileInfo) error {
  205. if len(fs) == 0 {
  206. // can't happen, flush is not called with an empty batch
  207. panic("bug: flush called with empty batch (race condition?)")
  208. }
  209. if batchError != nil {
  210. // can't happen, once an error is returned the index sender exits
  211. panic(fmt.Sprintf("bug: once failed it should stay failed (%v)", batchError))
  212. }
  213. l.Debugf("%v: Sending %d files (<%d bytes)", s, len(fs), batch.Size())
  214. lastSequence := fs[len(fs)-1].Sequence
  215. var err error
  216. if initial {
  217. initial = false
  218. err = s.conn.Index(ctx, &protocol.Index{
  219. Folder: s.folder,
  220. Files: fs,
  221. LastSequence: lastSequence,
  222. })
  223. } else {
  224. err = s.conn.IndexUpdate(ctx, &protocol.IndexUpdate{
  225. Folder: s.folder,
  226. Files: fs,
  227. PrevSequence: sentPrevSequence,
  228. LastSequence: lastSequence,
  229. })
  230. }
  231. if err != nil {
  232. batchError = err
  233. return err
  234. }
  235. sentPrevSequence = lastSequence
  236. return nil
  237. })
  238. var err error
  239. var f protocol.FileInfo
  240. snap, err := fset.Snapshot()
  241. if err != nil {
  242. return svcutil.AsFatalErr(err, svcutil.ExitError)
  243. }
  244. defer snap.Release()
  245. previousWasDelete := false
  246. snap.WithHaveSequence(s.prevSequence+1, func(fi protocol.FileIntf) bool {
  247. // This is to make sure that renames (which is an add followed by a delete) land in the same batch.
  248. // Even if the batch is full, we allow a last delete to slip in, we do this by making sure that
  249. // the batch ends with a non-delete, or that the last item in the batch is already a delete
  250. if batch.Full() && (!fi.IsDeleted() || previousWasDelete) {
  251. if err = batch.Flush(); err != nil {
  252. return false
  253. }
  254. }
  255. if fi.SequenceNo() < s.prevSequence+1 {
  256. s.logSequenceAnomaly("database returned sequence lower than requested", map[string]any{
  257. "sequence": fi.SequenceNo(),
  258. "start": s.prevSequence + 1,
  259. })
  260. }
  261. if f.Sequence > 0 && fi.SequenceNo() <= f.Sequence {
  262. s.logSequenceAnomaly("database returned non-increasing sequence", map[string]any{
  263. "sequence": fi.SequenceNo(),
  264. "start": s.prevSequence + 1,
  265. "previous": f.Sequence,
  266. })
  267. // Abort this round of index sending - the next one will pick
  268. // up from the last successful one with the repeaired db.
  269. defer func() {
  270. if fixed, dbErr := fset.RepairSequence(); dbErr != nil {
  271. l.Warnln("Failed repairing sequence entries:", dbErr)
  272. panic("Failed repairing sequence entries")
  273. } else {
  274. s.evLogger.Log(events.Failure, "detected and repaired non-increasing sequence")
  275. l.Infof("Repaired %v sequence entries in database", fixed)
  276. }
  277. }()
  278. return false
  279. }
  280. f = fi.(protocol.FileInfo)
  281. // If this is a folder receiving encrypted files only, we
  282. // mustn't ever send locally changed file infos. Those aren't
  283. // encrypted and thus would be a protocol error at the remote.
  284. if s.folderIsReceiveEncrypted && fi.IsReceiveOnlyChanged() {
  285. return true
  286. }
  287. f = prepareFileInfoForIndex(f)
  288. previousWasDelete = f.IsDeleted()
  289. batch.Append(f)
  290. return true
  291. })
  292. if err != nil {
  293. return err
  294. }
  295. if err := batch.Flush(); err != nil {
  296. return err
  297. }
  298. // Use the sequence of the snapshot we iterated as a starting point for the
  299. // next run. Previously we used the sequence of the last file we sent,
  300. // however it's possible that a higher sequence exists, just doesn't need to
  301. // be sent (e.g. in a receive-only folder, when a local change was
  302. // reverted). No point trying to send nothing again.
  303. s.prevSequence = snap.Sequence(protocol.LocalDeviceID)
  304. return nil
  305. }
  306. func (s *indexHandler) receive(fs []protocol.FileInfo, update bool, op string, prevSequence, lastSequence int64) error {
  307. deviceID := s.conn.DeviceID()
  308. s.cond.L.Lock()
  309. paused := s.paused
  310. fset := s.fset
  311. runner := s.runner
  312. s.cond.L.Unlock()
  313. if paused {
  314. l.Infof("%v for paused folder %q", op, s.folder)
  315. return fmt.Errorf("%v: %w", s.folder, ErrFolderPaused)
  316. }
  317. defer runner.SchedulePull()
  318. s.downloads.Update(s.folder, makeForgetUpdate(fs))
  319. if !update {
  320. fset.Drop(deviceID)
  321. }
  322. l.Debugf("Received %d files for %s from %s, prevSeq=%d, lastSeq=%d", len(fs), s.folder, deviceID.Short(), prevSequence, lastSequence)
  323. // Verify that the previous sequence number matches what we expected
  324. if exp := fset.Sequence(deviceID); prevSequence > 0 && prevSequence != exp {
  325. s.logSequenceAnomaly("index update with unexpected sequence", map[string]any{
  326. "prevSeq": prevSequence,
  327. "lastSeq": lastSequence,
  328. "batch": len(fs),
  329. "expectedPrev": exp,
  330. })
  331. }
  332. for i := range fs {
  333. // Verify index in relation to the claimed sequence boundaries
  334. if fs[i].Sequence < prevSequence {
  335. s.logSequenceAnomaly("file with sequence before prevSequence", map[string]any{
  336. "prevSeq": prevSequence,
  337. "lastSeq": lastSequence,
  338. "batch": len(fs),
  339. "seenSeq": fs[i].Sequence,
  340. "atIndex": i,
  341. })
  342. }
  343. if lastSequence > 0 && fs[i].Sequence > lastSequence {
  344. s.logSequenceAnomaly("file with sequence after lastSequence", map[string]any{
  345. "prevSeq": prevSequence,
  346. "lastSeq": lastSequence,
  347. "batch": len(fs),
  348. "seenSeq": fs[i].Sequence,
  349. "atIndex": i,
  350. })
  351. }
  352. if i > 0 && fs[i].Sequence <= fs[i-1].Sequence {
  353. s.logSequenceAnomaly("index update with non-increasing sequence", map[string]any{
  354. "prevSeq": prevSequence,
  355. "lastSeq": lastSequence,
  356. "batch": len(fs),
  357. "seenSeq": fs[i].Sequence,
  358. "atIndex": i,
  359. "precedingSeq": fs[i-1].Sequence,
  360. })
  361. }
  362. // The local attributes should never be transmitted over the wire.
  363. // Make sure they look like they weren't.
  364. fs[i].LocalFlags = 0
  365. fs[i].VersionHash = nil
  366. }
  367. // Verify the claimed last sequence number
  368. if lastSequence > 0 && len(fs) > 0 && lastSequence != fs[len(fs)-1].Sequence {
  369. s.logSequenceAnomaly("index update with unexpected last sequence", map[string]any{
  370. "prevSeq": prevSequence,
  371. "lastSeq": lastSequence,
  372. "batch": len(fs),
  373. "seenSeq": fs[len(fs)-1].Sequence,
  374. })
  375. }
  376. fset.Update(deviceID, fs)
  377. seq := fset.Sequence(deviceID)
  378. s.evLogger.Log(events.RemoteIndexUpdated, map[string]interface{}{
  379. "device": deviceID.String(),
  380. "folder": s.folder,
  381. "items": len(fs),
  382. "sequence": seq,
  383. "version": seq, // legacy for sequence
  384. })
  385. return nil
  386. }
  387. var warnSequenceAnomalyOnce sync.Once
  388. func (s *indexHandler) logSequenceAnomaly(msg string, extra map[string]any) {
  389. warnSequenceAnomalyOnce.Do(func() {
  390. l.Warnf("Index sequence anomaly detected (please report at https://forum.syncthing.net/t/22660): %s (%v)", msg, extra)
  391. })
  392. extraStrs := make(map[string]string, len(extra))
  393. for k, v := range extra {
  394. extraStrs[k] = fmt.Sprint(v)
  395. }
  396. s.evLogger.Log(events.Failure, ur.FailureData{
  397. Description: msg,
  398. Extra: extraStrs,
  399. })
  400. }
  401. func prepareFileInfoForIndex(f protocol.FileInfo) protocol.FileInfo {
  402. // Mark the file as invalid if any of the local bad stuff flags are set.
  403. f.RawInvalid = f.IsInvalid()
  404. // If the file is marked LocalReceive (i.e., changed locally on a
  405. // receive only folder) we do not want it to ever become the
  406. // globally best version, invalid or not.
  407. if f.IsReceiveOnlyChanged() {
  408. f.Version = protocol.Vector{}
  409. }
  410. // The trailer with the encrypted fileinfo is device local, don't send info
  411. // about that to remotes
  412. f.Size -= int64(f.EncryptionTrailerSize)
  413. f.EncryptionTrailerSize = 0
  414. // never sent externally
  415. f.LocalFlags = 0
  416. f.VersionHash = nil
  417. f.InodeChangeNs = 0
  418. return f
  419. }
  420. func (s *indexHandler) String() string {
  421. return fmt.Sprintf("indexHandler@%p for %s to %s at %s", s, s.folder, s.conn.DeviceID().Short(), s.conn)
  422. }
  423. type indexHandlerRegistry struct {
  424. evLogger events.Logger
  425. conn protocol.Connection
  426. downloads *deviceDownloadState
  427. indexHandlers *serviceMap[string, *indexHandler]
  428. startInfos map[string]*clusterConfigDeviceInfo
  429. folderStates map[string]*indexHandlerFolderState
  430. mut sync.Mutex
  431. }
  432. type indexHandlerFolderState struct {
  433. cfg config.FolderConfiguration
  434. fset *db.FileSet
  435. runner service
  436. }
  437. func newIndexHandlerRegistry(conn protocol.Connection, downloads *deviceDownloadState, evLogger events.Logger) *indexHandlerRegistry {
  438. r := &indexHandlerRegistry{
  439. evLogger: evLogger,
  440. conn: conn,
  441. downloads: downloads,
  442. indexHandlers: newServiceMap[string, *indexHandler](evLogger),
  443. startInfos: make(map[string]*clusterConfigDeviceInfo),
  444. folderStates: make(map[string]*indexHandlerFolderState),
  445. mut: sync.Mutex{},
  446. }
  447. return r
  448. }
  449. func (r *indexHandlerRegistry) String() string {
  450. return fmt.Sprintf("indexHandlerRegistry/%v", r.conn.DeviceID().Short())
  451. }
  452. func (r *indexHandlerRegistry) Serve(ctx context.Context) error {
  453. // Running the index handler registry means running the individual index
  454. // handler children.
  455. return r.indexHandlers.Serve(ctx)
  456. }
  457. func (r *indexHandlerRegistry) startLocked(folder config.FolderConfiguration, fset *db.FileSet, runner service, startInfo *clusterConfigDeviceInfo) {
  458. r.indexHandlers.RemoveAndWait(folder.ID, 0)
  459. delete(r.startInfos, folder.ID)
  460. is := newIndexHandler(r.conn, r.downloads, folder, fset, runner, startInfo, r.evLogger)
  461. r.indexHandlers.Add(folder.ID, is)
  462. // This new connection might help us get in sync.
  463. runner.SchedulePull()
  464. }
  465. // AddIndexInfo starts an index handler for given folder, unless it is paused.
  466. // If it is paused, the given startInfo is stored to start the sender once the
  467. // folder is resumed.
  468. // If an index handler is already running, it will be stopped first.
  469. func (r *indexHandlerRegistry) AddIndexInfo(folder string, startInfo *clusterConfigDeviceInfo) {
  470. r.mut.Lock()
  471. defer r.mut.Unlock()
  472. if r.indexHandlers.RemoveAndWait(folder, 0) == nil {
  473. l.Debugf("Removed index sender for device %v and folder %v due to added pending", r.conn.DeviceID().Short(), folder)
  474. }
  475. folderState, ok := r.folderStates[folder]
  476. if !ok {
  477. l.Debugf("Pending index handler for device %v and folder %v", r.conn.DeviceID().Short(), folder)
  478. r.startInfos[folder] = startInfo
  479. return
  480. }
  481. r.startLocked(folderState.cfg, folderState.fset, folderState.runner, startInfo)
  482. }
  483. // Remove stops a running index handler or removes one pending to be started.
  484. // It is a noop if the folder isn't known.
  485. func (r *indexHandlerRegistry) Remove(folder string) {
  486. r.mut.Lock()
  487. defer r.mut.Unlock()
  488. l.Debugf("Removing index handler for device %v and folder %v", r.conn.DeviceID().Short(), folder)
  489. r.indexHandlers.RemoveAndWait(folder, 0)
  490. delete(r.startInfos, folder)
  491. l.Debugf("Removed index handler for device %v and folder %v", r.conn.DeviceID().Short(), folder)
  492. }
  493. // RemoveAllExcept stops all running index handlers and removes those pending to be started,
  494. // except mentioned ones.
  495. // It is a noop if the folder isn't known.
  496. func (r *indexHandlerRegistry) RemoveAllExcept(except map[string]remoteFolderState) {
  497. r.mut.Lock()
  498. defer r.mut.Unlock()
  499. r.indexHandlers.Each(func(folder string, is *indexHandler) error {
  500. if _, ok := except[folder]; !ok {
  501. r.indexHandlers.RemoveAndWait(folder, 0)
  502. l.Debugf("Removed index handler for device %v and folder %v (removeAllExcept)", r.conn.DeviceID().Short(), folder)
  503. }
  504. return nil
  505. })
  506. for folder := range r.startInfos {
  507. if _, ok := except[folder]; !ok {
  508. delete(r.startInfos, folder)
  509. l.Debugf("Removed pending index handler for device %v and folder %v (removeAllExcept)", r.conn.DeviceID().Short(), folder)
  510. }
  511. }
  512. }
  513. // RegisterFolderState must be called whenever something about the folder
  514. // changes. The exception being if the folder is removed entirely, then call
  515. // Remove. The fset and runner arguments may be nil, if given folder is paused.
  516. func (r *indexHandlerRegistry) RegisterFolderState(folder config.FolderConfiguration, fset *db.FileSet, runner service) {
  517. if !folder.SharedWith(r.conn.DeviceID()) {
  518. r.Remove(folder.ID)
  519. return
  520. }
  521. r.mut.Lock()
  522. if folder.Paused {
  523. r.folderPausedLocked(folder.ID)
  524. } else {
  525. r.folderRunningLocked(folder, fset, runner)
  526. }
  527. r.mut.Unlock()
  528. }
  529. // folderPausedLocked stops a running index handler.
  530. // It is a noop if the folder isn't known or has not been started yet.
  531. func (r *indexHandlerRegistry) folderPausedLocked(folder string) {
  532. l.Debugf("Pausing index handler for device %v and folder %v", r.conn.DeviceID().Short(), folder)
  533. delete(r.folderStates, folder)
  534. if is, ok := r.indexHandlers.Get(folder); ok {
  535. is.pause()
  536. l.Debugf("Paused index handler for device %v and folder %v", r.conn.DeviceID().Short(), folder)
  537. } else {
  538. l.Debugf("No index handler for device %v and folder %v to pause", r.conn.DeviceID().Short(), folder)
  539. }
  540. }
  541. // folderRunningLocked resumes an already running index handler or starts it, if it
  542. // was added while paused.
  543. // It is a noop if the folder isn't known.
  544. func (r *indexHandlerRegistry) folderRunningLocked(folder config.FolderConfiguration, fset *db.FileSet, runner service) {
  545. r.folderStates[folder.ID] = &indexHandlerFolderState{
  546. cfg: folder,
  547. fset: fset,
  548. runner: runner,
  549. }
  550. is, isOk := r.indexHandlers.Get(folder.ID)
  551. if info, ok := r.startInfos[folder.ID]; ok {
  552. if isOk {
  553. r.indexHandlers.RemoveAndWait(folder.ID, 0)
  554. l.Debugf("Removed index handler for device %v and folder %v in resume", r.conn.DeviceID().Short(), folder.ID)
  555. }
  556. r.startLocked(folder, fset, runner, info)
  557. delete(r.startInfos, folder.ID)
  558. l.Debugf("Started index handler for device %v and folder %v in resume", r.conn.DeviceID().Short(), folder.ID)
  559. } else if isOk {
  560. l.Debugf("Resuming index handler for device %v and folder %v", r.conn.DeviceID().Short(), folder)
  561. is.resume(fset, runner)
  562. } else {
  563. l.Debugf("Not resuming index handler for device %v and folder %v as none is paused and there is no start info", r.conn.DeviceID().Short(), folder.ID)
  564. }
  565. }
  566. func (r *indexHandlerRegistry) ReceiveIndex(folder string, fs []protocol.FileInfo, update bool, op string, prevSequence, lastSequence int64) error {
  567. r.mut.Lock()
  568. defer r.mut.Unlock()
  569. is, isOk := r.indexHandlers.Get(folder)
  570. if !isOk {
  571. l.Infof("%v for nonexistent or paused folder %q", op, folder)
  572. return fmt.Errorf("%s: %w", folder, ErrFolderMissing)
  573. }
  574. return is.receive(fs, update, op, prevSequence, lastSequence)
  575. }
  576. // makeForgetUpdate takes an index update and constructs a download progress update
  577. // causing to forget any progress for files which we've just been sent.
  578. func makeForgetUpdate(files []protocol.FileInfo) []protocol.FileDownloadProgressUpdate {
  579. updates := make([]protocol.FileDownloadProgressUpdate, 0, len(files))
  580. for _, file := range files {
  581. if file.IsSymlink() || file.IsDirectory() || file.IsDeleted() {
  582. continue
  583. }
  584. updates = append(updates, protocol.FileDownloadProgressUpdate{
  585. Name: file.Name,
  586. Version: file.Version,
  587. UpdateType: protocol.FileDownloadProgressUpdateTypeForget,
  588. })
  589. }
  590. return updates
  591. }