model.go 110 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481
  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. //go:generate -command counterfeiter go run github.com/maxbrunsfeld/counterfeiter/v6
  7. //go:generate counterfeiter -o mocks/model.go --fake-name Model . Model
  8. package model
  9. import (
  10. "bytes"
  11. "context"
  12. "encoding/json"
  13. "errors"
  14. "fmt"
  15. "io"
  16. "iter"
  17. "net"
  18. "os"
  19. "path/filepath"
  20. "reflect"
  21. "runtime"
  22. "slices"
  23. "strings"
  24. stdsync "sync"
  25. "sync/atomic"
  26. "time"
  27. "github.com/thejerf/suture/v4"
  28. "github.com/syncthing/syncthing/internal/db"
  29. "github.com/syncthing/syncthing/internal/itererr"
  30. "github.com/syncthing/syncthing/lib/build"
  31. "github.com/syncthing/syncthing/lib/config"
  32. "github.com/syncthing/syncthing/lib/connections"
  33. "github.com/syncthing/syncthing/lib/events"
  34. "github.com/syncthing/syncthing/lib/fs"
  35. "github.com/syncthing/syncthing/lib/ignore"
  36. "github.com/syncthing/syncthing/lib/osutil"
  37. "github.com/syncthing/syncthing/lib/protocol"
  38. "github.com/syncthing/syncthing/lib/rand"
  39. "github.com/syncthing/syncthing/lib/scanner"
  40. "github.com/syncthing/syncthing/lib/semaphore"
  41. "github.com/syncthing/syncthing/lib/stats"
  42. "github.com/syncthing/syncthing/lib/svcutil"
  43. "github.com/syncthing/syncthing/lib/sync"
  44. "github.com/syncthing/syncthing/lib/ur/contract"
  45. "github.com/syncthing/syncthing/lib/versioner"
  46. )
  47. type service interface {
  48. suture.Service
  49. BringToFront(string)
  50. Override()
  51. Revert()
  52. DelayScan(d time.Duration)
  53. ScheduleScan()
  54. SchedulePull() // something relevant changed, we should try a pull
  55. Jobs(page, perpage int) ([]string, []string, int) // In progress, Queued, skipped
  56. Scan(subs []string) error
  57. Errors() []FileError
  58. WatchError() error
  59. ScheduleForceRescan(path string)
  60. GetStatistics() (stats.FolderStatistics, error)
  61. getState() (folderState, time.Time, error)
  62. }
  63. type Availability struct {
  64. ID protocol.DeviceID `json:"id"`
  65. FromTemporary bool `json:"fromTemporary"`
  66. }
  67. type Model interface {
  68. suture.Service
  69. connections.Model
  70. ResetFolder(folder string) error
  71. DelayScan(folder string, next time.Duration)
  72. ScanFolder(folder string) error
  73. ScanFolders() map[string]error
  74. ScanFolderSubdirs(folder string, subs []string) error
  75. State(folder string) (string, time.Time, error)
  76. FolderErrors(folder string) ([]FileError, error)
  77. WatchError(folder string) error
  78. Override(folder string)
  79. Revert(folder string)
  80. BringToFront(folder, file string)
  81. LoadIgnores(folder string) ([]string, []string, error)
  82. CurrentIgnores(folder string) ([]string, []string, error)
  83. SetIgnores(folder string, content []string) error
  84. GetFolderVersions(folder string) (map[string][]versioner.FileVersion, error)
  85. RestoreFolderVersions(folder string, versions map[string]time.Time) (map[string]error, error)
  86. LocalFiles(folder string, device protocol.DeviceID) (iter.Seq[protocol.FileInfo], func() error)
  87. LocalFilesSequenced(folder string, device protocol.DeviceID, startSet int64) (iter.Seq[protocol.FileInfo], func() error)
  88. LocalSize(folder string, device protocol.DeviceID) (db.Counts, error)
  89. GlobalSize(folder string) (db.Counts, error)
  90. NeedSize(folder string, device protocol.DeviceID) (db.Counts, error)
  91. ReceiveOnlySize(folder string) (db.Counts, error)
  92. Sequence(folder string, device protocol.DeviceID) (int64, error)
  93. AllGlobalFiles(folder string) (iter.Seq[db.FileMetadata], func() error)
  94. RemoteSequences(folder string) (map[protocol.DeviceID]int64, error)
  95. NeedFolderFiles(folder string, page, perpage int) ([]protocol.FileInfo, []protocol.FileInfo, []protocol.FileInfo, error)
  96. RemoteNeedFolderFiles(folder string, device protocol.DeviceID, page, perpage int) ([]protocol.FileInfo, error)
  97. LocalChangedFolderFiles(folder string, page, perpage int) ([]protocol.FileInfo, error)
  98. FolderProgressBytesCompleted(folder string) int64
  99. CurrentFolderFile(folder string, file string) (protocol.FileInfo, bool, error)
  100. CurrentGlobalFile(folder string, file string) (protocol.FileInfo, bool, error)
  101. Availability(folder string, file protocol.FileInfo, block protocol.BlockInfo) ([]Availability, error)
  102. Completion(device protocol.DeviceID, folder string) (FolderCompletion, error)
  103. ConnectionStats() map[string]interface{}
  104. DeviceStatistics() (map[protocol.DeviceID]stats.DeviceStatistics, error)
  105. FolderStatistics() (map[string]stats.FolderStatistics, error)
  106. UsageReportingStats(report *contract.Report, version int, preview bool)
  107. ConnectedTo(remoteID protocol.DeviceID) bool
  108. PendingDevices() (map[protocol.DeviceID]db.ObservedDevice, error)
  109. PendingFolders(device protocol.DeviceID) (map[string]db.PendingFolder, error)
  110. DismissPendingDevice(device protocol.DeviceID) error
  111. DismissPendingFolder(device protocol.DeviceID, folder string) error
  112. GlobalDirectoryTree(folder, prefix string, levels int, dirsOnly bool) ([]*TreeEntry, error)
  113. RequestGlobal(ctx context.Context, deviceID protocol.DeviceID, folder, name string, blockNo int, offset int64, size int, hash []byte, fromTemporary bool) ([]byte, error)
  114. }
  115. type model struct {
  116. *suture.Supervisor
  117. // constructor parameters
  118. cfg config.Wrapper
  119. id protocol.DeviceID
  120. sdb db.DB
  121. protectedFiles []string
  122. evLogger events.Logger
  123. // constant or concurrency safe fields
  124. progressEmitter *ProgressEmitter
  125. shortID protocol.ShortID
  126. // globalRequestLimiter limits the amount of data in concurrent incoming
  127. // requests
  128. globalRequestLimiter *semaphore.Semaphore
  129. // folderIOLimiter limits the number of concurrent I/O heavy operations,
  130. // such as scans and pulls.
  131. folderIOLimiter *semaphore.Semaphore
  132. fatalChan chan error
  133. started chan struct{}
  134. keyGen *protocol.KeyGenerator
  135. promotionTimer *time.Timer
  136. observed *db.ObservedDB
  137. // fields protected by mut
  138. mut sync.RWMutex
  139. folderCfgs map[string]config.FolderConfiguration // folder -> cfg
  140. deviceStatRefs map[protocol.DeviceID]*stats.DeviceStatisticsReference // deviceID -> statsRef
  141. folderIgnores map[string]*ignore.Matcher // folder -> matcher object
  142. folderRunners *serviceMap[string, service] // folder -> puller or scanner
  143. folderRestartMuts syncMutexMap // folder -> restart mutex
  144. folderVersioners map[string]versioner.Versioner // folder -> versioner (may be nil)
  145. folderEncryptionPasswordTokens map[string][]byte // folder -> encryption token (may be missing, and only for encryption type folders)
  146. folderEncryptionFailures map[string]map[protocol.DeviceID]error // folder -> device -> error regarding encryption consistency (may be missing)
  147. connections map[string]protocol.Connection // connection ID -> connection
  148. deviceConnIDs map[protocol.DeviceID][]string // device -> connection IDs (invariant: if the key exists, the value is len >= 1, with the primary connection at the start of the slice)
  149. promotedConnID map[protocol.DeviceID]string // device -> latest promoted connection ID
  150. connRequestLimiters map[protocol.DeviceID]*semaphore.Semaphore
  151. closed map[string]chan struct{} // connection ID -> closed channel
  152. helloMessages map[protocol.DeviceID]protocol.Hello
  153. deviceDownloads map[protocol.DeviceID]*deviceDownloadState
  154. remoteFolderStates map[protocol.DeviceID]map[string]remoteFolderState // deviceID -> folders
  155. indexHandlers *serviceMap[protocol.DeviceID, *indexHandlerRegistry]
  156. // for testing only
  157. foldersRunning atomic.Int32
  158. }
  159. var _ config.Verifier = &model{}
  160. type folderFactory func(*model, *ignore.Matcher, config.FolderConfiguration, versioner.Versioner, events.Logger, *semaphore.Semaphore) service
  161. var folderFactories = make(map[config.FolderType]folderFactory)
  162. var (
  163. errDeviceUnknown = errors.New("unknown device")
  164. errDevicePaused = errors.New("device is paused")
  165. ErrFolderPaused = errors.New("folder is paused")
  166. ErrFolderNotRunning = errors.New("folder is not running")
  167. ErrFolderMissing = errors.New("no such folder")
  168. errNoVersioner = errors.New("folder has no versioner")
  169. // errors about why a connection is closed
  170. errStopped = errors.New("Syncthing is being stopped")
  171. errEncryptionInvConfigLocal = errors.New("can't encrypt outgoing data because local data is encrypted (folder-type receive-encrypted)")
  172. errEncryptionInvConfigRemote = errors.New("remote has encrypted data and encrypts that data for us - this is impossible")
  173. errEncryptionNotEncryptedLocal = errors.New("remote expects to exchange encrypted data, but is configured for plain data")
  174. errEncryptionPlainForReceiveEncrypted = errors.New("remote expects to exchange plain data, but is configured to be encrypted")
  175. errEncryptionPlainForRemoteEncrypted = errors.New("remote expects to exchange plain data, but local data is encrypted (folder-type receive-encrypted)")
  176. errEncryptionNotEncryptedUntrusted = errors.New("device is untrusted, but configured to receive plain data")
  177. errEncryptionPassword = errors.New("different encryption passwords used")
  178. errEncryptionTokenRead = errors.New("failed to read encryption token")
  179. errEncryptionTokenWrite = errors.New("failed to write encryption token")
  180. errMissingRemoteInClusterConfig = errors.New("remote device missing in cluster config")
  181. errMissingLocalInClusterConfig = errors.New("local device missing in cluster config")
  182. )
  183. // NewModel creates and starts a new model. The model starts in read-only mode,
  184. // where it sends index information to connected peers and responds to requests
  185. // for file data without altering the local folder in any way.
  186. func NewModel(cfg config.Wrapper, id protocol.DeviceID, sdb db.DB, protectedFiles []string, evLogger events.Logger, keyGen *protocol.KeyGenerator) Model {
  187. spec := svcutil.SpecWithDebugLogger(l)
  188. m := &model{
  189. Supervisor: suture.New("model", spec),
  190. // constructor parameters
  191. cfg: cfg,
  192. id: id,
  193. sdb: sdb,
  194. protectedFiles: protectedFiles,
  195. evLogger: evLogger,
  196. // constant or concurrency safe fields
  197. progressEmitter: NewProgressEmitter(cfg, evLogger),
  198. shortID: id.Short(),
  199. globalRequestLimiter: semaphore.New(1024 * cfg.Options().MaxConcurrentIncomingRequestKiB()),
  200. folderIOLimiter: semaphore.New(cfg.Options().MaxFolderConcurrency()),
  201. fatalChan: make(chan error),
  202. started: make(chan struct{}),
  203. keyGen: keyGen,
  204. promotionTimer: time.NewTimer(0),
  205. observed: db.NewObservedDB(sdb),
  206. // fields protected by mut
  207. mut: sync.NewRWMutex(),
  208. folderCfgs: make(map[string]config.FolderConfiguration),
  209. deviceStatRefs: make(map[protocol.DeviceID]*stats.DeviceStatisticsReference),
  210. folderIgnores: make(map[string]*ignore.Matcher),
  211. folderRunners: newServiceMap[string, service](evLogger),
  212. folderVersioners: make(map[string]versioner.Versioner),
  213. folderEncryptionPasswordTokens: make(map[string][]byte),
  214. folderEncryptionFailures: make(map[string]map[protocol.DeviceID]error),
  215. connections: make(map[string]protocol.Connection),
  216. deviceConnIDs: make(map[protocol.DeviceID][]string),
  217. promotedConnID: make(map[protocol.DeviceID]string),
  218. connRequestLimiters: make(map[protocol.DeviceID]*semaphore.Semaphore),
  219. closed: make(map[string]chan struct{}),
  220. helloMessages: make(map[protocol.DeviceID]protocol.Hello),
  221. deviceDownloads: make(map[protocol.DeviceID]*deviceDownloadState),
  222. remoteFolderStates: make(map[protocol.DeviceID]map[string]remoteFolderState),
  223. indexHandlers: newServiceMap[protocol.DeviceID, *indexHandlerRegistry](evLogger),
  224. }
  225. for devID, cfg := range cfg.Devices() {
  226. m.deviceStatRefs[devID] = stats.NewDeviceStatisticsReference(db.NewTyped(sdb, "devicestats/"+devID.String()))
  227. m.setConnRequestLimitersLocked(cfg)
  228. }
  229. m.Add(m.folderRunners)
  230. m.Add(m.progressEmitter)
  231. m.Add(m.indexHandlers)
  232. m.Add(svcutil.AsService(m.serve, m.String()))
  233. return m
  234. }
  235. func (m *model) serve(ctx context.Context) error {
  236. defer m.closeAllConnectionsAndWait()
  237. cfg := m.cfg.Subscribe(m)
  238. defer m.cfg.Unsubscribe(m)
  239. if err := m.initFolders(cfg); err != nil {
  240. close(m.started)
  241. return svcutil.AsFatalErr(err, svcutil.ExitError)
  242. }
  243. close(m.started)
  244. for {
  245. select {
  246. case <-ctx.Done():
  247. l.Debugln(m, "context closed, stopping", ctx.Err())
  248. return ctx.Err()
  249. case err := <-m.fatalChan:
  250. l.Debugln(m, "fatal error, stopping", err)
  251. return svcutil.AsFatalErr(err, svcutil.ExitError)
  252. case <-m.promotionTimer.C:
  253. l.Debugln("promotion timer fired")
  254. m.promoteConnections()
  255. }
  256. }
  257. }
  258. func (m *model) initFolders(cfg config.Configuration) error {
  259. clusterConfigDevices := make(deviceIDSet, len(cfg.Devices))
  260. for _, folderCfg := range cfg.Folders {
  261. if folderCfg.Paused {
  262. folderCfg.CreateRoot()
  263. continue
  264. }
  265. err := m.newFolder(folderCfg, cfg.Options.CacheIgnoredFiles)
  266. if err != nil {
  267. return err
  268. }
  269. clusterConfigDevices.add(folderCfg.DeviceIDs())
  270. }
  271. ignoredDevices := observedDeviceSet(m.cfg.IgnoredDevices())
  272. m.cleanPending(cfg.DeviceMap(), cfg.FolderMap(), ignoredDevices, nil)
  273. m.sendClusterConfig(clusterConfigDevices.AsSlice())
  274. return nil
  275. }
  276. func (m *model) closeAllConnectionsAndWait() {
  277. m.mut.RLock()
  278. closed := make([]chan struct{}, 0, len(m.connections))
  279. for connID, conn := range m.connections {
  280. closed = append(closed, m.closed[connID])
  281. go conn.Close(errStopped)
  282. }
  283. m.mut.RUnlock()
  284. for _, c := range closed {
  285. <-c
  286. }
  287. }
  288. func (m *model) fatal(err error) {
  289. select {
  290. case m.fatalChan <- err:
  291. default:
  292. }
  293. }
  294. // Need to hold lock on m.mut when calling this.
  295. func (m *model) addAndStartFolderLocked(cfg config.FolderConfiguration, cacheIgnoredFiles bool) {
  296. ignores := ignore.New(cfg.Filesystem(), ignore.WithCache(cacheIgnoredFiles))
  297. if cfg.Type != config.FolderTypeReceiveEncrypted {
  298. if err := ignores.Load(".stignore"); err != nil && !fs.IsNotExist(err) {
  299. l.Warnln("Loading ignores:", err)
  300. }
  301. }
  302. m.addAndStartFolderLockedWithIgnores(cfg, ignores)
  303. }
  304. // Only needed for testing, use addAndStartFolderLocked instead.
  305. func (m *model) addAndStartFolderLockedWithIgnores(cfg config.FolderConfiguration, ignores *ignore.Matcher) {
  306. m.folderCfgs[cfg.ID] = cfg
  307. m.folderIgnores[cfg.ID] = ignores
  308. _, ok := m.folderRunners.Get(cfg.ID)
  309. if ok {
  310. l.Warnln("Cannot start already running folder", cfg.Description())
  311. panic("cannot start already running folder")
  312. }
  313. folderFactory, ok := folderFactories[cfg.Type]
  314. if !ok {
  315. panic(fmt.Sprintf("unknown folder type 0x%x", cfg.Type))
  316. }
  317. folder := cfg.ID
  318. // Find any devices for which we hold the index in the db, but the folder
  319. // is not shared, and drop it.
  320. expected := mapDevices(cfg.DeviceIDs())
  321. devs, _ := m.sdb.ListDevicesForFolder(cfg.ID)
  322. for _, available := range devs {
  323. if _, ok := expected[available]; !ok {
  324. l.Debugln("dropping", folder, "state for", available)
  325. _ = m.sdb.DropAllFiles(folder, available)
  326. }
  327. }
  328. seq, err := m.sdb.GetDeviceSequence(folder, protocol.LocalDeviceID)
  329. if err != nil {
  330. panic(fmt.Errorf("error getting sequence number: %w", err))
  331. }
  332. if seq == 0 {
  333. // It's a blank folder, so this may the first time we're looking at
  334. // it. Attempt to create and tag with our marker as appropriate. We
  335. // don't really do anything with errors at this point except warn -
  336. // if these things don't work, we still want to start the folder and
  337. // it'll show up as errored later.
  338. if err := cfg.CreateRoot(); err != nil {
  339. l.Warnln("Failed to create folder root directory:", err)
  340. } else if err = cfg.CreateMarker(); err != nil {
  341. l.Warnln("Failed to create folder marker:", err)
  342. }
  343. }
  344. if cfg.Type == config.FolderTypeReceiveEncrypted {
  345. if encryptionToken, err := readEncryptionToken(cfg); err == nil {
  346. m.folderEncryptionPasswordTokens[folder] = encryptionToken
  347. } else if !fs.IsNotExist(err) {
  348. l.Warnf("Failed to read encryption token: %v", err)
  349. }
  350. }
  351. // These are our metadata files, and they should always be hidden.
  352. ffs := cfg.Filesystem()
  353. _ = ffs.Hide(config.DefaultMarkerName)
  354. _ = ffs.Hide(versioner.DefaultPath)
  355. _ = ffs.Hide(".stignore")
  356. var ver versioner.Versioner
  357. if cfg.Versioning.Type != "" {
  358. var err error
  359. ver, err = versioner.New(cfg)
  360. if err != nil {
  361. panic(fmt.Errorf("creating versioner: %w", err))
  362. }
  363. }
  364. m.folderVersioners[folder] = ver
  365. m.warnAboutOverwritingProtectedFiles(cfg, ignores)
  366. p := folderFactory(m, ignores, cfg, ver, m.evLogger, m.folderIOLimiter)
  367. m.folderRunners.Add(folder, p)
  368. l.Infof("Ready to synchronize %s (%s)", cfg.Description(), cfg.Type)
  369. }
  370. func (m *model) warnAboutOverwritingProtectedFiles(cfg config.FolderConfiguration, ignores *ignore.Matcher) {
  371. if cfg.Type == config.FolderTypeSendOnly {
  372. return
  373. }
  374. // This is a bit of a hack.
  375. ffs := cfg.Filesystem()
  376. if ffs.Type() != fs.FilesystemTypeBasic {
  377. return
  378. }
  379. folderLocation := ffs.URI()
  380. var filesAtRisk []string
  381. for _, protectedFilePath := range m.protectedFiles {
  382. // check if file is synced in this folder
  383. if protectedFilePath != folderLocation && !fs.IsParent(protectedFilePath, folderLocation) {
  384. continue
  385. }
  386. // check if file is ignored
  387. relPath, _ := filepath.Rel(folderLocation, protectedFilePath)
  388. if ignores.Match(relPath).IsIgnored() {
  389. continue
  390. }
  391. filesAtRisk = append(filesAtRisk, protectedFilePath)
  392. }
  393. if len(filesAtRisk) > 0 {
  394. l.Warnln("Some protected files may be overwritten and cause issues. See https://docs.syncthing.net/users/config.html#syncing-configuration-files for more information. The at risk files are:", strings.Join(filesAtRisk, ", "))
  395. }
  396. }
  397. func (m *model) removeFolder(cfg config.FolderConfiguration) {
  398. m.mut.RLock()
  399. wait := m.folderRunners.StopAndWaitChan(cfg.ID, 0)
  400. m.mut.RUnlock()
  401. <-wait
  402. m.mut.Lock()
  403. isPathUnique := true
  404. for folderID, folderCfg := range m.folderCfgs {
  405. if folderID != cfg.ID && folderCfg.Path == cfg.Path {
  406. isPathUnique = false
  407. break
  408. }
  409. }
  410. if isPathUnique {
  411. // Remove (if empty and removable) or move away (if non-empty or
  412. // otherwise not removable) Syncthing-specific marker files.
  413. if err := cfg.RemoveMarker(); err != nil && !errors.Is(err, os.ErrNotExist) {
  414. moved := config.DefaultMarkerName + time.Now().Format(".removed-20060102-150405")
  415. fs := cfg.Filesystem()
  416. _ = fs.Rename(config.DefaultMarkerName, moved)
  417. }
  418. }
  419. m.cleanupFolderLocked(cfg)
  420. m.indexHandlers.Each(func(_ protocol.DeviceID, r *indexHandlerRegistry) error {
  421. r.Remove(cfg.ID)
  422. return nil
  423. })
  424. m.mut.Unlock()
  425. // Remove it from the database
  426. _ = m.sdb.DropFolder(cfg.ID)
  427. }
  428. // Need to hold lock on m.mut when calling this.
  429. func (m *model) cleanupFolderLocked(cfg config.FolderConfiguration) {
  430. // clear up our config maps
  431. m.folderRunners.Remove(cfg.ID)
  432. delete(m.folderCfgs, cfg.ID)
  433. delete(m.folderIgnores, cfg.ID)
  434. delete(m.folderVersioners, cfg.ID)
  435. delete(m.folderEncryptionPasswordTokens, cfg.ID)
  436. delete(m.folderEncryptionFailures, cfg.ID)
  437. }
  438. func (m *model) restartFolder(from, to config.FolderConfiguration, cacheIgnoredFiles bool) error {
  439. if to.ID == "" {
  440. panic("bug: cannot restart empty folder ID")
  441. }
  442. if to.ID != from.ID {
  443. l.Warnf("bug: folder restart cannot change ID %q -> %q", from.ID, to.ID)
  444. panic("bug: folder restart cannot change ID")
  445. }
  446. folder := to.ID
  447. // This mutex protects the entirety of the restart operation, preventing
  448. // there from being more than one folder restart operation in progress
  449. // at any given time. The usual locking stuff doesn't cover this,
  450. // because those locks are released while we are waiting for the folder
  451. // to shut down (and must be so because the folder might need them as
  452. // part of its operations before shutting down).
  453. restartMut := m.folderRestartMuts.Get(folder)
  454. restartMut.Lock()
  455. defer restartMut.Unlock()
  456. m.mut.RLock()
  457. wait := m.folderRunners.StopAndWaitChan(from.ID, 0)
  458. m.mut.RUnlock()
  459. <-wait
  460. m.mut.Lock()
  461. defer m.mut.Unlock()
  462. m.cleanupFolderLocked(from)
  463. if !to.Paused {
  464. m.addAndStartFolderLocked(to, cacheIgnoredFiles)
  465. }
  466. runner, _ := m.folderRunners.Get(to.ID)
  467. m.indexHandlers.Each(func(_ protocol.DeviceID, r *indexHandlerRegistry) error {
  468. r.RegisterFolderState(to, runner)
  469. return nil
  470. })
  471. var infoMsg string
  472. switch {
  473. case to.Paused:
  474. infoMsg = "Paused"
  475. case from.Paused:
  476. infoMsg = "Unpaused"
  477. default:
  478. infoMsg = "Restarted"
  479. }
  480. l.Infof("%v folder %v (%v)", infoMsg, to.Description(), to.Type)
  481. return nil
  482. }
  483. func (m *model) newFolder(cfg config.FolderConfiguration, cacheIgnoredFiles bool) error {
  484. m.mut.Lock()
  485. defer m.mut.Unlock()
  486. m.addAndStartFolderLocked(cfg, cacheIgnoredFiles)
  487. // Cluster configs might be received and processed before reaching this
  488. // point, i.e. before the folder is started. If that's the case, start
  489. // index senders here.
  490. m.indexHandlers.Each(func(_ protocol.DeviceID, r *indexHandlerRegistry) error {
  491. runner, _ := m.folderRunners.Get(cfg.ID)
  492. r.RegisterFolderState(cfg, runner)
  493. return nil
  494. })
  495. return nil
  496. }
  497. func (m *model) UsageReportingStats(report *contract.Report, version int, preview bool) {
  498. if version >= 3 {
  499. // Block stats
  500. blockStatsMut.Lock()
  501. for k, v := range blockStats {
  502. switch k {
  503. case "total":
  504. report.BlockStats.Total = v
  505. case "renamed":
  506. report.BlockStats.Renamed = v
  507. case "reused":
  508. report.BlockStats.Reused = v
  509. case "pulled":
  510. report.BlockStats.Pulled = v
  511. case "copyOrigin":
  512. report.BlockStats.CopyOrigin = v
  513. case "copyElsewhere":
  514. report.BlockStats.CopyElsewhere = v
  515. }
  516. // Reset counts, as these are incremental
  517. if !preview {
  518. blockStats[k] = 0
  519. }
  520. }
  521. blockStatsMut.Unlock()
  522. // Transport stats
  523. m.mut.RLock()
  524. for _, conn := range m.connections {
  525. report.TransportStats[conn.Transport()]++
  526. }
  527. m.mut.RUnlock()
  528. // Ignore stats
  529. var seenPrefix [3]bool
  530. for folder := range m.cfg.Folders() {
  531. lines, _, err := m.CurrentIgnores(folder)
  532. if err != nil {
  533. continue
  534. }
  535. report.IgnoreStats.Lines += len(lines)
  536. for _, line := range lines {
  537. // Allow prefixes to be specified in any order, but only once.
  538. for {
  539. if strings.HasPrefix(line, "!") && !seenPrefix[0] {
  540. seenPrefix[0] = true
  541. line = line[1:]
  542. report.IgnoreStats.Inverts++
  543. } else if strings.HasPrefix(line, "(?i)") && !seenPrefix[1] {
  544. seenPrefix[1] = true
  545. line = line[4:]
  546. report.IgnoreStats.Folded++
  547. } else if strings.HasPrefix(line, "(?d)") && !seenPrefix[2] {
  548. seenPrefix[2] = true
  549. line = line[4:]
  550. report.IgnoreStats.Deletable++
  551. } else {
  552. seenPrefix[0] = false
  553. seenPrefix[1] = false
  554. seenPrefix[2] = false
  555. break
  556. }
  557. }
  558. // Noops, remove
  559. line = strings.TrimSuffix(line, "**")
  560. line = strings.TrimPrefix(line, "**/")
  561. if strings.HasPrefix(line, "/") {
  562. report.IgnoreStats.Rooted++
  563. } else if strings.HasPrefix(line, "#include ") {
  564. report.IgnoreStats.Includes++
  565. if strings.Contains(line, "..") {
  566. report.IgnoreStats.EscapedIncludes++
  567. }
  568. }
  569. if strings.Contains(line, "**") {
  570. report.IgnoreStats.DoubleStars++
  571. // Remove not to trip up star checks.
  572. line = strings.ReplaceAll(line, "**", "")
  573. }
  574. if strings.Contains(line, "*") {
  575. report.IgnoreStats.Stars++
  576. }
  577. }
  578. }
  579. }
  580. }
  581. type ConnectionStats struct {
  582. protocol.Statistics // Total for primary + secondaries
  583. Connected bool `json:"connected"`
  584. Paused bool `json:"paused"`
  585. ClientVersion string `json:"clientVersion"`
  586. Address string `json:"address"` // mirror values from Primary, for compatibility with <1.24.0
  587. Type string `json:"type"` // mirror values from Primary, for compatibility with <1.24.0
  588. IsLocal bool `json:"isLocal"` // mirror values from Primary, for compatibility with <1.24.0
  589. Crypto string `json:"crypto"` // mirror values from Primary, for compatibility with <1.24.0
  590. Primary ConnectionInfo `json:"primary,omitempty"`
  591. Secondary []ConnectionInfo `json:"secondary,omitempty"`
  592. }
  593. type ConnectionInfo struct {
  594. protocol.Statistics
  595. Address string `json:"address"`
  596. Type string `json:"type"`
  597. IsLocal bool `json:"isLocal"`
  598. Crypto string `json:"crypto"`
  599. }
  600. // ConnectionStats returns a map with connection statistics for each device.
  601. func (m *model) ConnectionStats() map[string]interface{} {
  602. m.mut.RLock()
  603. defer m.mut.RUnlock()
  604. res := make(map[string]interface{})
  605. devs := m.cfg.Devices()
  606. conns := make(map[string]ConnectionStats, len(devs))
  607. for device, deviceCfg := range devs {
  608. if device == m.id {
  609. continue
  610. }
  611. hello := m.helloMessages[device]
  612. versionString := hello.ClientVersion
  613. if hello.ClientName != "syncthing" {
  614. versionString = hello.ClientName + " " + hello.ClientVersion
  615. }
  616. connIDs, ok := m.deviceConnIDs[device]
  617. cs := ConnectionStats{
  618. Connected: ok,
  619. Paused: deviceCfg.Paused,
  620. ClientVersion: strings.TrimSpace(versionString),
  621. }
  622. if ok {
  623. conn := m.connections[connIDs[0]]
  624. cs.Primary.Type = conn.Type()
  625. cs.Primary.IsLocal = conn.IsLocal()
  626. cs.Primary.Crypto = conn.Crypto()
  627. cs.Primary.Statistics = conn.Statistics()
  628. cs.Primary.Address = conn.RemoteAddr().String()
  629. cs.Type = cs.Primary.Type
  630. cs.IsLocal = cs.Primary.IsLocal
  631. cs.Crypto = cs.Primary.Crypto
  632. cs.Address = cs.Primary.Address
  633. cs.Statistics = cs.Primary.Statistics
  634. for _, connID := range connIDs[1:] {
  635. conn = m.connections[connID]
  636. sec := ConnectionInfo{
  637. Statistics: conn.Statistics(),
  638. Address: conn.RemoteAddr().String(),
  639. Type: conn.Type(),
  640. IsLocal: conn.IsLocal(),
  641. Crypto: conn.Crypto(),
  642. }
  643. if sec.At.After(cs.At) {
  644. cs.At = sec.At
  645. }
  646. if sec.StartedAt.Before(cs.StartedAt) {
  647. cs.StartedAt = sec.StartedAt
  648. }
  649. cs.InBytesTotal += sec.InBytesTotal
  650. cs.OutBytesTotal += sec.OutBytesTotal
  651. cs.Secondary = append(cs.Secondary, sec)
  652. }
  653. }
  654. conns[device.String()] = cs
  655. }
  656. res["connections"] = conns
  657. in, out := protocol.TotalInOut()
  658. res["total"] = map[string]interface{}{
  659. "at": time.Now().Truncate(time.Second),
  660. "inBytesTotal": in,
  661. "outBytesTotal": out,
  662. }
  663. return res
  664. }
  665. // DeviceStatistics returns statistics about each device
  666. func (m *model) DeviceStatistics() (map[protocol.DeviceID]stats.DeviceStatistics, error) {
  667. m.mut.RLock()
  668. defer m.mut.RUnlock()
  669. res := make(map[protocol.DeviceID]stats.DeviceStatistics, len(m.deviceStatRefs))
  670. for id, sr := range m.deviceStatRefs {
  671. stats, err := sr.GetStatistics()
  672. if err != nil {
  673. return nil, err
  674. }
  675. if len(m.deviceConnIDs[id]) > 0 {
  676. // If a device is currently connected, we can see them right
  677. // now.
  678. stats.LastSeen = time.Now().Truncate(time.Second)
  679. }
  680. res[id] = stats
  681. }
  682. return res, nil
  683. }
  684. // FolderStatistics returns statistics about each folder
  685. func (m *model) FolderStatistics() (map[string]stats.FolderStatistics, error) {
  686. res := make(map[string]stats.FolderStatistics)
  687. m.mut.RLock()
  688. defer m.mut.RUnlock()
  689. err := m.folderRunners.Each(func(id string, runner service) error {
  690. stats, err := runner.GetStatistics()
  691. if err != nil {
  692. return err
  693. }
  694. res[id] = stats
  695. return nil
  696. })
  697. if err != nil {
  698. return nil, err
  699. }
  700. return res, nil
  701. }
  702. type FolderCompletion struct {
  703. CompletionPct float64
  704. GlobalBytes int64
  705. NeedBytes int64
  706. GlobalItems int
  707. NeedItems int
  708. NeedDeletes int
  709. Sequence int64
  710. RemoteState remoteFolderState
  711. }
  712. func newFolderCompletion(global, need db.Counts, sequence int64, state remoteFolderState) FolderCompletion {
  713. comp := FolderCompletion{
  714. GlobalBytes: global.Bytes,
  715. NeedBytes: need.Bytes,
  716. GlobalItems: global.Files + global.Directories + global.Symlinks,
  717. NeedItems: need.Files + need.Directories + need.Symlinks,
  718. NeedDeletes: need.Deleted,
  719. Sequence: sequence,
  720. RemoteState: state,
  721. }
  722. comp.setCompletionPct()
  723. return comp
  724. }
  725. func (comp *FolderCompletion) add(other FolderCompletion) {
  726. comp.GlobalBytes += other.GlobalBytes
  727. comp.NeedBytes += other.NeedBytes
  728. comp.GlobalItems += other.GlobalItems
  729. comp.NeedItems += other.NeedItems
  730. comp.NeedDeletes += other.NeedDeletes
  731. comp.setCompletionPct()
  732. }
  733. func (comp *FolderCompletion) setCompletionPct() {
  734. if comp.GlobalBytes == 0 {
  735. comp.CompletionPct = 100
  736. } else {
  737. needRatio := float64(comp.NeedBytes) / float64(comp.GlobalBytes)
  738. comp.CompletionPct = 100 * (1 - needRatio)
  739. }
  740. // If the completion is 100% but there are deletes we need to handle,
  741. // drop it down a notch. Hack for consumers that look only at the
  742. // percentage (our own GUI does the same calculation as here on its own
  743. // and needs the same fixup).
  744. if comp.NeedBytes == 0 && comp.NeedDeletes > 0 {
  745. comp.CompletionPct = 95 // chosen by fair dice roll
  746. }
  747. }
  748. // Map returns the members as a map, e.g. used in api to serialize as JSON.
  749. func (comp *FolderCompletion) Map() map[string]interface{} {
  750. return map[string]interface{}{
  751. "completion": comp.CompletionPct,
  752. "globalBytes": comp.GlobalBytes,
  753. "needBytes": comp.NeedBytes,
  754. "globalItems": comp.GlobalItems,
  755. "needItems": comp.NeedItems,
  756. "needDeletes": comp.NeedDeletes,
  757. "sequence": comp.Sequence,
  758. "remoteState": comp.RemoteState,
  759. }
  760. }
  761. // Completion returns the completion status, in percent with some counters,
  762. // for the given device and folder. The device can be any known device ID
  763. // (including the local device) or explicitly protocol.LocalDeviceID. An
  764. // empty folder string means the aggregate of all folders shared with the
  765. // given device.
  766. func (m *model) Completion(device protocol.DeviceID, folder string) (FolderCompletion, error) {
  767. // The user specifically asked for our own device ID. Internally that is
  768. // known as protocol.LocalDeviceID so translate.
  769. if device == m.id {
  770. device = protocol.LocalDeviceID
  771. }
  772. if folder != "" {
  773. // We want completion for a specific folder.
  774. return m.folderCompletion(device, folder)
  775. }
  776. // We want completion for all (shared) folders as an aggregate.
  777. var comp FolderCompletion
  778. for _, fcfg := range m.cfg.FolderList() {
  779. if fcfg.Paused {
  780. continue
  781. }
  782. if device == protocol.LocalDeviceID || fcfg.SharedWith(device) {
  783. folderComp, err := m.folderCompletion(device, fcfg.ID)
  784. if errors.Is(err, ErrFolderPaused) {
  785. continue
  786. } else if err != nil {
  787. return FolderCompletion{}, err
  788. }
  789. comp.add(folderComp)
  790. }
  791. }
  792. return comp, nil
  793. }
  794. func (m *model) folderCompletion(device protocol.DeviceID, folder string) (FolderCompletion, error) {
  795. m.mut.RLock()
  796. err := m.checkFolderRunningRLocked(folder)
  797. m.mut.RUnlock()
  798. if err != nil {
  799. return FolderCompletion{}, err
  800. }
  801. m.mut.RLock()
  802. state := m.remoteFolderStates[device][folder]
  803. downloaded := m.deviceDownloads[device].BytesDownloaded(folder)
  804. m.mut.RUnlock()
  805. need, err := m.sdb.CountNeed(folder, device)
  806. if err != nil {
  807. return FolderCompletion{}, err
  808. }
  809. need.Bytes -= downloaded
  810. // This might be more than it really is, because some blocks can be of a smaller size.
  811. if need.Bytes < 0 {
  812. need.Bytes = 0
  813. }
  814. seq, err := m.sdb.GetDeviceSequence(folder, device)
  815. if err != nil {
  816. return FolderCompletion{}, err
  817. }
  818. glob, err := m.sdb.CountGlobal(folder)
  819. if err != nil {
  820. return FolderCompletion{}, err
  821. }
  822. comp := newFolderCompletion(glob, need, seq, state)
  823. l.Debugf("%v Completion(%s, %q): %v", m, device, folder, comp.Map())
  824. return comp, nil
  825. }
  826. func (m *model) LocalFiles(folder string, device protocol.DeviceID) (iter.Seq[protocol.FileInfo], func() error) {
  827. return m.sdb.AllLocalFiles(folder, device)
  828. }
  829. func (m *model) LocalFilesSequenced(folder string, device protocol.DeviceID, startSeq int64) (iter.Seq[protocol.FileInfo], func() error) {
  830. return m.sdb.AllLocalFilesBySequence(folder, device, startSeq, 0)
  831. }
  832. func (m *model) AllForBlocksHash(folder string, h []byte) (iter.Seq[db.FileMetadata], func() error) {
  833. return m.sdb.AllLocalFilesWithBlocksHash(folder, h)
  834. }
  835. func (m *model) LocalSize(folder string, device protocol.DeviceID) (db.Counts, error) {
  836. return m.sdb.CountLocal(folder, device)
  837. }
  838. func (m *model) GlobalSize(folder string) (db.Counts, error) {
  839. return m.sdb.CountGlobal(folder)
  840. }
  841. func (m *model) NeedSize(folder string, device protocol.DeviceID) (db.Counts, error) {
  842. return m.sdb.CountNeed(folder, device)
  843. }
  844. func (m *model) ReceiveOnlySize(folder string) (db.Counts, error) {
  845. return m.sdb.CountReceiveOnlyChanged(folder)
  846. }
  847. func (m *model) Sequence(folder string, device protocol.DeviceID) (int64, error) {
  848. return m.sdb.GetDeviceSequence(folder, device)
  849. }
  850. func (m *model) AllGlobalFiles(folder string) (iter.Seq[db.FileMetadata], func() error) {
  851. return m.sdb.AllGlobalFiles(folder)
  852. }
  853. func (m *model) RemoteSequences(folder string) (map[protocol.DeviceID]int64, error) {
  854. return m.sdb.RemoteSequences(folder)
  855. }
  856. func (m *model) FolderProgressBytesCompleted(folder string) int64 {
  857. return m.progressEmitter.BytesCompleted(folder)
  858. }
  859. // NeedFolderFiles returns paginated list of currently needed files in
  860. // progress, queued, and to be queued on next puller iteration.
  861. func (m *model) NeedFolderFiles(folder string, page, perpage int) ([]protocol.FileInfo, []protocol.FileInfo, []protocol.FileInfo, error) {
  862. m.mut.RLock()
  863. runner, runnerOk := m.folderRunners.Get(folder)
  864. cfg, cfgOK := m.folderCfgs[folder]
  865. m.mut.RUnlock()
  866. if !cfgOK {
  867. return nil, nil, nil, ErrFolderMissing
  868. }
  869. var progress, queued, rest []protocol.FileInfo
  870. var seen map[string]struct{}
  871. p := newPager(page, perpage)
  872. if runnerOk {
  873. progressNames, queuedNames, skipped := runner.Jobs(page, perpage)
  874. progress = make([]protocol.FileInfo, len(progressNames))
  875. queued = make([]protocol.FileInfo, len(queuedNames))
  876. seen = make(map[string]struct{}, len(progressNames)+len(queuedNames))
  877. for i, name := range progressNames {
  878. if f, ok, err := m.sdb.GetGlobalFile(folder, name); err == nil && ok {
  879. progress[i] = f
  880. seen[name] = struct{}{}
  881. }
  882. }
  883. for i, name := range queuedNames {
  884. if f, ok, err := m.sdb.GetGlobalFile(folder, name); err == nil && ok {
  885. queued[i] = f
  886. seen[name] = struct{}{}
  887. }
  888. }
  889. p.get -= len(seen)
  890. if p.get == 0 {
  891. return progress, queued, nil, nil
  892. }
  893. p.toSkip -= skipped
  894. }
  895. if p.get > 0 {
  896. rest = make([]protocol.FileInfo, 0, p.get)
  897. it, errFn := m.sdb.AllNeededGlobalFiles(folder, protocol.LocalDeviceID, config.PullOrderAlphabetic, 0, 0)
  898. for f := range it {
  899. if cfg.IgnoreDelete && f.IsDeleted() {
  900. continue
  901. }
  902. if p.skip() {
  903. continue
  904. }
  905. if _, ok := seen[f.Name]; !ok {
  906. rest = append(rest, f)
  907. p.get--
  908. }
  909. if p.get == 0 {
  910. break
  911. }
  912. }
  913. if err := errFn(); err != nil {
  914. return nil, nil, nil, err
  915. }
  916. }
  917. return progress, queued, rest, nil
  918. }
  919. // RemoteNeedFolderFiles returns paginated list of currently needed files for a
  920. // remote device to become synced with a folder.
  921. func (m *model) RemoteNeedFolderFiles(folder string, device protocol.DeviceID, page, perpage int) ([]protocol.FileInfo, error) {
  922. m.mut.RLock()
  923. _, ok := m.folderCfgs[folder]
  924. m.mut.RUnlock()
  925. if !ok {
  926. return nil, ErrFolderMissing
  927. }
  928. it, errFn := m.sdb.AllNeededGlobalFiles(folder, device, config.PullOrderAlphabetic, perpage, (page-1)*perpage)
  929. files := slices.Collect(it)
  930. return files, errFn()
  931. }
  932. func (m *model) LocalChangedFolderFiles(folder string, page, perpage int) ([]protocol.FileInfo, error) {
  933. m.mut.RLock()
  934. _, ok := m.folderCfgs[folder]
  935. m.mut.RUnlock()
  936. if !ok {
  937. return nil, ErrFolderMissing
  938. }
  939. ros, err := m.sdb.CountReceiveOnlyChanged(folder)
  940. if err != nil {
  941. return nil, err
  942. }
  943. if ros.TotalItems() == 0 {
  944. return nil, nil
  945. }
  946. p := newPager(page, perpage)
  947. files := make([]protocol.FileInfo, 0, perpage)
  948. // This could be made more efficient with a specifically targeted DB
  949. // call
  950. it, errFn := m.sdb.AllLocalFiles(folder, protocol.LocalDeviceID)
  951. for f := range it {
  952. if !f.IsReceiveOnlyChanged() {
  953. continue
  954. }
  955. if p.skip() {
  956. continue
  957. }
  958. files = append(files, f)
  959. if p.done() {
  960. break
  961. }
  962. }
  963. if err := errFn(); err != nil {
  964. return nil, err
  965. }
  966. return files, nil
  967. }
  968. type pager struct {
  969. toSkip, get int
  970. }
  971. func newPager(page, perpage int) *pager {
  972. return &pager{
  973. toSkip: (page - 1) * perpage,
  974. get: perpage,
  975. }
  976. }
  977. func (p *pager) skip() bool {
  978. if p.toSkip == 0 {
  979. return false
  980. }
  981. p.toSkip--
  982. return true
  983. }
  984. func (p *pager) done() bool {
  985. if p.get > 0 {
  986. p.get--
  987. }
  988. return p.get == 0
  989. }
  990. // Index is called when a new device is connected and we receive their full index.
  991. // Implements the protocol.Model interface.
  992. func (m *model) Index(conn protocol.Connection, idx *protocol.Index) error {
  993. return m.handleIndex(conn, idx.Folder, idx.Files, false, 0, idx.LastSequence)
  994. }
  995. // IndexUpdate is called for incremental updates to connected devices' indexes.
  996. // Implements the protocol.Model interface.
  997. func (m *model) IndexUpdate(conn protocol.Connection, idxUp *protocol.IndexUpdate) error {
  998. return m.handleIndex(conn, idxUp.Folder, idxUp.Files, true, idxUp.PrevSequence, idxUp.LastSequence)
  999. }
  1000. func (m *model) handleIndex(conn protocol.Connection, folder string, fs []protocol.FileInfo, update bool, prevSequence, lastSequence int64) error {
  1001. op := "Index"
  1002. if update {
  1003. op += " update"
  1004. }
  1005. deviceID := conn.DeviceID()
  1006. l.Debugf("%v (in): %s / %q: %d files", op, deviceID, folder, len(fs))
  1007. if cfg, ok := m.cfg.Folder(folder); !ok || !cfg.SharedWith(deviceID) {
  1008. l.Warnf("%v for unexpected folder ID %q sent from device %q; ensure that the folder exists and that this device is selected under \"Share With\" in the folder configuration.", op, folder, deviceID)
  1009. return fmt.Errorf("%s: %w", folder, ErrFolderMissing)
  1010. } else if cfg.Paused {
  1011. l.Debugf("%v for paused folder (ID %q) sent from device %q.", op, folder, deviceID)
  1012. return fmt.Errorf("%s: %w", folder, ErrFolderPaused)
  1013. }
  1014. m.mut.RLock()
  1015. indexHandler, ok := m.getIndexHandlerRLocked(conn)
  1016. m.mut.RUnlock()
  1017. if !ok {
  1018. // This should be impossible, as an index handler is registered when
  1019. // we send a cluster config, and that is what triggers index
  1020. // sending.
  1021. m.evLogger.Log(events.Failure, "index sender does not exist for connection on which indexes were received")
  1022. l.Debugf("%v for folder (ID %q) sent from device %q: missing index handler", op, folder, deviceID)
  1023. return fmt.Errorf("%s: %w", folder, ErrFolderNotRunning)
  1024. }
  1025. return indexHandler.ReceiveIndex(folder, fs, update, op, prevSequence, lastSequence)
  1026. }
  1027. type clusterConfigDeviceInfo struct {
  1028. local, remote protocol.Device
  1029. }
  1030. type ClusterConfigReceivedEventData struct {
  1031. Device protocol.DeviceID `json:"device"`
  1032. }
  1033. func (m *model) ClusterConfig(conn protocol.Connection, cm *protocol.ClusterConfig) error {
  1034. deviceID := conn.DeviceID()
  1035. if cm.Secondary {
  1036. // No handling of secondary connection ClusterConfigs; they merely
  1037. // indicate the connection is ready to start.
  1038. l.Debugf("Skipping secondary ClusterConfig from %v at %s", deviceID.Short(), conn)
  1039. return nil
  1040. }
  1041. // Check the peer device's announced folders against our own. Emits events
  1042. // for folders that we don't expect (unknown or not shared).
  1043. // Also, collect a list of folders we do share, and if he's interested in
  1044. // temporary indexes, subscribe the connection.
  1045. l.Debugf("Handling ClusterConfig from %v at %s", deviceID.Short(), conn)
  1046. indexHandlerRegistry := m.ensureIndexHandler(conn)
  1047. deviceCfg, ok := m.cfg.Device(deviceID)
  1048. if !ok {
  1049. l.Debugf("Device %s disappeared from config while processing cluster-config", deviceID.Short())
  1050. return errDeviceUnknown
  1051. }
  1052. // Assemble the device information from the connected device about
  1053. // themselves and us for all folders.
  1054. ccDeviceInfos := make(map[string]*clusterConfigDeviceInfo, len(cm.Folders))
  1055. for _, folder := range cm.Folders {
  1056. info := &clusterConfigDeviceInfo{}
  1057. for _, dev := range folder.Devices {
  1058. if dev.ID == m.id {
  1059. info.local = dev
  1060. } else if dev.ID == deviceID {
  1061. info.remote = dev
  1062. }
  1063. if info.local.ID != protocol.EmptyDeviceID && info.remote.ID != protocol.EmptyDeviceID {
  1064. break
  1065. }
  1066. }
  1067. if info.remote.ID == protocol.EmptyDeviceID {
  1068. l.Infof("Device %v sent cluster-config without the device info for the remote on folder %v", deviceID.Short(), folder.Description())
  1069. return errMissingRemoteInClusterConfig
  1070. }
  1071. if info.local.ID == protocol.EmptyDeviceID {
  1072. l.Infof("Device %v sent cluster-config without the device info for us locally on folder %v", deviceID.Short(), folder.Description())
  1073. return errMissingLocalInClusterConfig
  1074. }
  1075. ccDeviceInfos[folder.ID] = info
  1076. }
  1077. for _, info := range ccDeviceInfos {
  1078. if deviceCfg.Introducer && info.local.Introducer {
  1079. l.Warnf("Remote %v is an introducer to us, and we are to them - only one should be introducer to the other, see https://docs.syncthing.net/users/introducer.html", deviceCfg.Description())
  1080. }
  1081. break
  1082. }
  1083. // Needs to happen outside of the mut, as can cause CommitConfiguration
  1084. if deviceCfg.AutoAcceptFolders {
  1085. w, _ := m.cfg.Modify(func(cfg *config.Configuration) {
  1086. changedFcfg := make(map[string]config.FolderConfiguration)
  1087. haveFcfg := cfg.FolderMap()
  1088. for _, folder := range cm.Folders {
  1089. from, ok := haveFcfg[folder.ID]
  1090. if to, changed := m.handleAutoAccepts(deviceID, folder, ccDeviceInfos[folder.ID], from, ok, cfg.Defaults.Folder); changed {
  1091. changedFcfg[folder.ID] = to
  1092. }
  1093. }
  1094. if len(changedFcfg) == 0 {
  1095. return
  1096. }
  1097. for i := range cfg.Folders {
  1098. if fcfg, ok := changedFcfg[cfg.Folders[i].ID]; ok {
  1099. cfg.Folders[i] = fcfg
  1100. delete(changedFcfg, cfg.Folders[i].ID)
  1101. }
  1102. }
  1103. for _, fcfg := range changedFcfg {
  1104. cfg.Folders = append(cfg.Folders, fcfg)
  1105. }
  1106. })
  1107. // Need to wait for the waiter, as this calls CommitConfiguration,
  1108. // which sets up the folder and as we return from this call,
  1109. // ClusterConfig starts poking at m.folderFiles and other things
  1110. // that might not exist until the config is committed.
  1111. w.Wait()
  1112. }
  1113. tempIndexFolders, states, err := m.ccHandleFolders(cm.Folders, deviceCfg, ccDeviceInfos, indexHandlerRegistry)
  1114. if err != nil {
  1115. return err
  1116. }
  1117. m.mut.Lock()
  1118. m.remoteFolderStates[deviceID] = states
  1119. m.mut.Unlock()
  1120. m.evLogger.Log(events.ClusterConfigReceived, ClusterConfigReceivedEventData{
  1121. Device: deviceID,
  1122. })
  1123. if len(tempIndexFolders) > 0 {
  1124. var connOK bool
  1125. var conn protocol.Connection
  1126. m.mut.RLock()
  1127. if connIDs, connIDOK := m.deviceConnIDs[deviceID]; connIDOK {
  1128. conn, connOK = m.connections[connIDs[0]]
  1129. }
  1130. m.mut.RUnlock()
  1131. // In case we've got ClusterConfig, and the connection disappeared
  1132. // from infront of our nose.
  1133. if connOK {
  1134. m.progressEmitter.temporaryIndexSubscribe(conn, tempIndexFolders)
  1135. }
  1136. }
  1137. if deviceCfg.Introducer {
  1138. m.cfg.Modify(func(cfg *config.Configuration) {
  1139. folders, devices, foldersDevices, introduced := m.handleIntroductions(deviceCfg, cm, cfg.FolderMap(), cfg.DeviceMap())
  1140. folders, devices, deintroduced := m.handleDeintroductions(deviceCfg, foldersDevices, folders, devices)
  1141. if !introduced && !deintroduced {
  1142. return
  1143. }
  1144. cfg.Folders = make([]config.FolderConfiguration, 0, len(folders))
  1145. for _, fcfg := range folders {
  1146. cfg.Folders = append(cfg.Folders, fcfg)
  1147. }
  1148. cfg.Devices = make([]config.DeviceConfiguration, 0, len(devices))
  1149. for _, dcfg := range devices {
  1150. cfg.Devices = append(cfg.Devices, dcfg)
  1151. }
  1152. })
  1153. }
  1154. return nil
  1155. }
  1156. func (m *model) ensureIndexHandler(conn protocol.Connection) *indexHandlerRegistry {
  1157. deviceID := conn.DeviceID()
  1158. connID := conn.ConnectionID()
  1159. m.mut.Lock()
  1160. defer m.mut.Unlock()
  1161. indexHandlerRegistry, ok := m.indexHandlers.Get(deviceID)
  1162. if ok && indexHandlerRegistry.conn.ConnectionID() == connID {
  1163. // This is an existing and proper index handler for this connection.
  1164. return indexHandlerRegistry
  1165. }
  1166. if ok {
  1167. // A handler exists, but it's for another connection than the one we
  1168. // now got a ClusterConfig on. This should be unusual as it means
  1169. // the other side has decided to start using a new primary
  1170. // connection but we haven't seen it close yet. Ideally it will
  1171. // close shortly by itself...
  1172. l.Infof("Abandoning old index handler for %s (%s) in favour of %s", deviceID.Short(), indexHandlerRegistry.conn.ConnectionID(), connID)
  1173. m.indexHandlers.RemoveAndWait(deviceID, 0)
  1174. }
  1175. // Create a new index handler for this device.
  1176. indexHandlerRegistry = newIndexHandlerRegistry(conn, m.sdb, m.deviceDownloads[deviceID], m.evLogger)
  1177. for id, fcfg := range m.folderCfgs {
  1178. l.Debugln("Registering folder", id, "for", deviceID.Short())
  1179. runner, _ := m.folderRunners.Get(id)
  1180. indexHandlerRegistry.RegisterFolderState(fcfg, runner)
  1181. }
  1182. m.indexHandlers.Add(deviceID, indexHandlerRegistry)
  1183. return indexHandlerRegistry
  1184. }
  1185. func (m *model) getIndexHandlerRLocked(conn protocol.Connection) (*indexHandlerRegistry, bool) {
  1186. // Reads from index handlers, which requires the mutex to be read locked
  1187. deviceID := conn.DeviceID()
  1188. connID := conn.ConnectionID()
  1189. indexHandlerRegistry, ok := m.indexHandlers.Get(deviceID)
  1190. if ok && indexHandlerRegistry.conn.ConnectionID() == connID {
  1191. // This is an existing and proper index handler for this connection.
  1192. return indexHandlerRegistry, true
  1193. }
  1194. // There is no index handler, or it's not registered for this connection.
  1195. return nil, false
  1196. }
  1197. func (m *model) ccHandleFolders(folders []protocol.Folder, deviceCfg config.DeviceConfiguration, ccDeviceInfos map[string]*clusterConfigDeviceInfo, indexHandlers *indexHandlerRegistry) ([]string, map[string]remoteFolderState, error) {
  1198. var folderDevice config.FolderDeviceConfiguration
  1199. tempIndexFolders := make([]string, 0, len(folders))
  1200. seenFolders := make(map[string]remoteFolderState, len(folders))
  1201. updatedPending := make([]updatedPendingFolder, 0, len(folders))
  1202. deviceID := deviceCfg.DeviceID
  1203. expiredPending, err := m.observed.PendingFoldersForDevice(deviceID)
  1204. if err != nil {
  1205. l.Infof("Could not get pending folders for cleanup: %v", err)
  1206. }
  1207. of := db.ObservedFolder{Time: time.Now().Truncate(time.Second)}
  1208. for _, folder := range folders {
  1209. seenFolders[folder.ID] = remoteFolderValid
  1210. cfg, ok := m.cfg.Folder(folder.ID)
  1211. if ok {
  1212. folderDevice, ok = cfg.Device(deviceID)
  1213. }
  1214. if !ok {
  1215. indexHandlers.Remove(folder.ID)
  1216. if deviceCfg.IgnoredFolder(folder.ID) {
  1217. l.Infof("Ignoring folder %s from device %s since it is in the list of ignored folders", folder.Description(), deviceID)
  1218. continue
  1219. }
  1220. delete(expiredPending, folder.ID)
  1221. of.Label = folder.Label
  1222. of.ReceiveEncrypted = len(ccDeviceInfos[folder.ID].local.EncryptionPasswordToken) > 0
  1223. of.RemoteEncrypted = len(ccDeviceInfos[folder.ID].remote.EncryptionPasswordToken) > 0
  1224. if err := m.observed.AddOrUpdatePendingFolder(folder.ID, of, deviceID); err != nil {
  1225. l.Warnf("Failed to persist pending folder entry to database: %v", err)
  1226. }
  1227. if !folder.Paused {
  1228. indexHandlers.AddIndexInfo(folder.ID, ccDeviceInfos[folder.ID])
  1229. }
  1230. updatedPending = append(updatedPending, updatedPendingFolder{
  1231. FolderID: folder.ID,
  1232. FolderLabel: folder.Label,
  1233. DeviceID: deviceID,
  1234. ReceiveEncrypted: of.ReceiveEncrypted,
  1235. RemoteEncrypted: of.RemoteEncrypted,
  1236. })
  1237. // DEPRECATED: Only for backwards compatibility, should be removed.
  1238. m.evLogger.Log(events.FolderRejected, map[string]string{
  1239. "folder": folder.ID,
  1240. "folderLabel": folder.Label,
  1241. "device": deviceID.String(),
  1242. })
  1243. l.Infof("Unexpected folder %s sent from device %q; ensure that the folder exists and that this device is selected under \"Share With\" in the folder configuration.", folder.Description(), deviceID)
  1244. continue
  1245. }
  1246. if folder.Paused {
  1247. indexHandlers.Remove(folder.ID)
  1248. seenFolders[cfg.ID] = remoteFolderPaused
  1249. continue
  1250. }
  1251. if cfg.Paused {
  1252. indexHandlers.AddIndexInfo(folder.ID, ccDeviceInfos[folder.ID])
  1253. continue
  1254. }
  1255. if err := m.ccCheckEncryption(cfg, folderDevice, ccDeviceInfos[folder.ID], deviceCfg.Untrusted); err != nil {
  1256. sameError := false
  1257. m.mut.Lock()
  1258. if devs, ok := m.folderEncryptionFailures[folder.ID]; ok {
  1259. sameError = devs[deviceID] == err
  1260. } else {
  1261. m.folderEncryptionFailures[folder.ID] = make(map[protocol.DeviceID]error)
  1262. }
  1263. m.folderEncryptionFailures[folder.ID][deviceID] = err
  1264. m.mut.Unlock()
  1265. msg := fmt.Sprintf("Failure checking encryption consistency with device %v for folder %v: %v", deviceID, cfg.Description(), err)
  1266. if sameError {
  1267. l.Debugln(msg)
  1268. } else {
  1269. if rerr, ok := err.(*redactedError); ok {
  1270. err = rerr.redacted
  1271. }
  1272. m.evLogger.Log(events.Failure, err.Error())
  1273. l.Warnln(msg)
  1274. }
  1275. return tempIndexFolders, seenFolders, err
  1276. }
  1277. m.mut.Lock()
  1278. if devErrs, ok := m.folderEncryptionFailures[folder.ID]; ok {
  1279. if len(devErrs) == 1 {
  1280. delete(m.folderEncryptionFailures, folder.ID)
  1281. } else {
  1282. delete(m.folderEncryptionFailures[folder.ID], deviceID)
  1283. }
  1284. }
  1285. m.mut.Unlock()
  1286. // Handle indexes
  1287. if !folder.DisableTempIndexes {
  1288. tempIndexFolders = append(tempIndexFolders, folder.ID)
  1289. }
  1290. indexHandlers.AddIndexInfo(folder.ID, ccDeviceInfos[folder.ID])
  1291. }
  1292. indexHandlers.RemoveAllExcept(seenFolders)
  1293. // Explicitly mark folders we offer, but the remote has not accepted
  1294. for folderID, cfg := range m.cfg.Folders() {
  1295. if _, seen := seenFolders[folderID]; !seen && cfg.SharedWith(deviceID) {
  1296. l.Debugf("Remote device %v has not accepted sharing folder %s", deviceID.Short(), cfg.Description())
  1297. seenFolders[folderID] = remoteFolderNotSharing
  1298. }
  1299. }
  1300. expiredPendingList := make([]map[string]string, 0, len(expiredPending))
  1301. for folder := range expiredPending {
  1302. if err = m.observed.RemovePendingFolderForDevice(folder, deviceID); err != nil {
  1303. msg := "Failed to remove pending folder-device entry"
  1304. l.Warnf("%v (%v, %v): %v", msg, folder, deviceID, err)
  1305. m.evLogger.Log(events.Failure, msg)
  1306. continue
  1307. }
  1308. expiredPendingList = append(expiredPendingList, map[string]string{
  1309. "folderID": folder,
  1310. "deviceID": deviceID.String(),
  1311. })
  1312. }
  1313. if len(updatedPending) > 0 || len(expiredPendingList) > 0 {
  1314. m.evLogger.Log(events.PendingFoldersChanged, map[string]interface{}{
  1315. "added": updatedPending,
  1316. "removed": expiredPendingList,
  1317. })
  1318. }
  1319. return tempIndexFolders, seenFolders, nil
  1320. }
  1321. func (m *model) ccCheckEncryption(fcfg config.FolderConfiguration, folderDevice config.FolderDeviceConfiguration, ccDeviceInfos *clusterConfigDeviceInfo, deviceUntrusted bool) error {
  1322. hasTokenRemote := len(ccDeviceInfos.remote.EncryptionPasswordToken) > 0
  1323. hasTokenLocal := len(ccDeviceInfos.local.EncryptionPasswordToken) > 0
  1324. isEncryptedRemote := folderDevice.EncryptionPassword != ""
  1325. isEncryptedLocal := fcfg.Type == config.FolderTypeReceiveEncrypted
  1326. if !isEncryptedRemote && !isEncryptedLocal && deviceUntrusted {
  1327. return errEncryptionNotEncryptedUntrusted
  1328. }
  1329. if !(hasTokenRemote || hasTokenLocal || isEncryptedRemote || isEncryptedLocal) {
  1330. // No one cares about encryption here
  1331. return nil
  1332. }
  1333. if isEncryptedRemote && isEncryptedLocal {
  1334. // Should never happen, but config racyness and be safe.
  1335. return errEncryptionInvConfigLocal
  1336. }
  1337. if hasTokenRemote && hasTokenLocal {
  1338. return errEncryptionInvConfigRemote
  1339. }
  1340. if !(hasTokenRemote || hasTokenLocal) {
  1341. if isEncryptedRemote {
  1342. return errEncryptionPlainForRemoteEncrypted
  1343. } else {
  1344. return errEncryptionPlainForReceiveEncrypted
  1345. }
  1346. }
  1347. if !(isEncryptedRemote || isEncryptedLocal) {
  1348. return errEncryptionNotEncryptedLocal
  1349. }
  1350. if isEncryptedRemote {
  1351. passwordToken := protocol.PasswordToken(m.keyGen, fcfg.ID, folderDevice.EncryptionPassword)
  1352. var match bool
  1353. if hasTokenLocal {
  1354. match = bytes.Equal(passwordToken, ccDeviceInfos.local.EncryptionPasswordToken)
  1355. } else {
  1356. // hasTokenRemote == true
  1357. match = bytes.Equal(passwordToken, ccDeviceInfos.remote.EncryptionPasswordToken)
  1358. }
  1359. if !match {
  1360. return errEncryptionPassword
  1361. }
  1362. return nil
  1363. }
  1364. // isEncryptedLocal == true
  1365. var ccToken []byte
  1366. if hasTokenLocal {
  1367. ccToken = ccDeviceInfos.local.EncryptionPasswordToken
  1368. } else {
  1369. // hasTokenRemote == true
  1370. ccToken = ccDeviceInfos.remote.EncryptionPasswordToken
  1371. }
  1372. m.mut.RLock()
  1373. token, ok := m.folderEncryptionPasswordTokens[fcfg.ID]
  1374. m.mut.RUnlock()
  1375. if !ok {
  1376. var err error
  1377. token, err = readEncryptionToken(fcfg)
  1378. if err != nil && !fs.IsNotExist(err) {
  1379. if rerr, ok := redactPathError(err); ok {
  1380. return rerr
  1381. }
  1382. return &redactedError{
  1383. error: err,
  1384. redacted: errEncryptionTokenRead,
  1385. }
  1386. }
  1387. if err == nil {
  1388. m.mut.Lock()
  1389. m.folderEncryptionPasswordTokens[fcfg.ID] = token
  1390. m.mut.Unlock()
  1391. } else {
  1392. if err := writeEncryptionToken(ccToken, fcfg); err != nil {
  1393. if rerr, ok := redactPathError(err); ok {
  1394. return rerr
  1395. } else {
  1396. return &redactedError{
  1397. error: err,
  1398. redacted: errEncryptionTokenWrite,
  1399. }
  1400. }
  1401. }
  1402. m.mut.Lock()
  1403. m.folderEncryptionPasswordTokens[fcfg.ID] = ccToken
  1404. m.mut.Unlock()
  1405. // We can only announce ourselves once we have the token,
  1406. // thus we need to resend CCs now that we have it.
  1407. m.sendClusterConfig(fcfg.DeviceIDs())
  1408. return nil
  1409. }
  1410. }
  1411. if !bytes.Equal(token, ccToken) {
  1412. return errEncryptionPassword
  1413. }
  1414. return nil
  1415. }
  1416. func (m *model) sendClusterConfig(ids []protocol.DeviceID) {
  1417. if len(ids) == 0 {
  1418. return
  1419. }
  1420. ccConns := make([]protocol.Connection, 0, len(ids))
  1421. m.mut.RLock()
  1422. for _, id := range ids {
  1423. if connIDs, ok := m.deviceConnIDs[id]; ok {
  1424. ccConns = append(ccConns, m.connections[connIDs[0]])
  1425. }
  1426. }
  1427. m.mut.RUnlock()
  1428. // Generating cluster-configs acquires the mutex.
  1429. for _, conn := range ccConns {
  1430. cm, passwords := m.generateClusterConfig(conn.DeviceID())
  1431. go conn.ClusterConfig(cm, passwords)
  1432. }
  1433. }
  1434. // handleIntroductions handles adding devices/folders that are shared by an introducer device
  1435. func (m *model) handleIntroductions(introducerCfg config.DeviceConfiguration, cm *protocol.ClusterConfig, folders map[string]config.FolderConfiguration, devices map[protocol.DeviceID]config.DeviceConfiguration) (map[string]config.FolderConfiguration, map[protocol.DeviceID]config.DeviceConfiguration, folderDeviceSet, bool) {
  1436. changed := false
  1437. foldersDevices := make(folderDeviceSet)
  1438. for _, folder := range cm.Folders {
  1439. // Adds devices which we do not have, but the introducer has
  1440. // for the folders that we have in common. Also, shares folders
  1441. // with devices that we have in common, yet are currently not sharing
  1442. // the folder.
  1443. fcfg, ok := folders[folder.ID]
  1444. if !ok {
  1445. // Don't have this folder, carry on.
  1446. continue
  1447. }
  1448. folderChanged := false
  1449. for _, device := range folder.Devices {
  1450. // No need to share with self.
  1451. if device.ID == m.id {
  1452. continue
  1453. }
  1454. foldersDevices.set(device.ID, folder.ID)
  1455. if _, ok := devices[device.ID]; !ok {
  1456. // The device is currently unknown. Add it to the config.
  1457. devices[device.ID] = m.introduceDevice(device, introducerCfg)
  1458. } else if fcfg.SharedWith(device.ID) {
  1459. // We already share the folder with this device, so
  1460. // nothing to do.
  1461. continue
  1462. }
  1463. if fcfg.Type != config.FolderTypeReceiveEncrypted && device.EncryptionPasswordToken != nil {
  1464. l.Infof("Cannot share folder %s with %v because the introducer %v encrypts data, which requires a password", folder.Description(), device.ID, introducerCfg.DeviceID)
  1465. continue
  1466. }
  1467. // We don't yet share this folder with this device. Add the device
  1468. // to sharing list of the folder.
  1469. l.Infof("Sharing folder %s with %v (vouched for by introducer %v)", folder.Description(), device.ID, introducerCfg.DeviceID)
  1470. fcfg.Devices = append(fcfg.Devices, config.FolderDeviceConfiguration{
  1471. DeviceID: device.ID,
  1472. IntroducedBy: introducerCfg.DeviceID,
  1473. })
  1474. folderChanged = true
  1475. }
  1476. if folderChanged {
  1477. folders[fcfg.ID] = fcfg
  1478. changed = true
  1479. }
  1480. }
  1481. return folders, devices, foldersDevices, changed
  1482. }
  1483. // handleDeintroductions handles removals of devices/shares that are removed by an introducer device
  1484. func (*model) handleDeintroductions(introducerCfg config.DeviceConfiguration, foldersDevices folderDeviceSet, folders map[string]config.FolderConfiguration, devices map[protocol.DeviceID]config.DeviceConfiguration) (map[string]config.FolderConfiguration, map[protocol.DeviceID]config.DeviceConfiguration, bool) {
  1485. if introducerCfg.SkipIntroductionRemovals {
  1486. return folders, devices, false
  1487. }
  1488. changed := false
  1489. devicesNotIntroduced := make(map[protocol.DeviceID]struct{})
  1490. // Check if we should unshare some folders, if the introducer has unshared them.
  1491. for folderID, folderCfg := range folders {
  1492. for k := 0; k < len(folderCfg.Devices); k++ {
  1493. if folderCfg.Devices[k].IntroducedBy != introducerCfg.DeviceID {
  1494. devicesNotIntroduced[folderCfg.Devices[k].DeviceID] = struct{}{}
  1495. continue
  1496. }
  1497. if !foldersDevices.has(folderCfg.Devices[k].DeviceID, folderCfg.ID) {
  1498. // We could not find that folder shared on the
  1499. // introducer with the device that was introduced to us.
  1500. // We should follow and unshare as well.
  1501. l.Infof("Unsharing folder %s with %v as introducer %v no longer shares the folder with that device", folderCfg.Description(), folderCfg.Devices[k].DeviceID, folderCfg.Devices[k].IntroducedBy)
  1502. folderCfg.Devices = append(folderCfg.Devices[:k], folderCfg.Devices[k+1:]...)
  1503. folders[folderID] = folderCfg
  1504. k--
  1505. changed = true
  1506. }
  1507. }
  1508. }
  1509. // Check if we should remove some devices, if the introducer no longer
  1510. // shares any folder with them. Yet do not remove if we share other
  1511. // folders that haven't been introduced by the introducer.
  1512. for deviceID, device := range devices {
  1513. if device.IntroducedBy == introducerCfg.DeviceID {
  1514. if !foldersDevices.hasDevice(deviceID) {
  1515. if _, ok := devicesNotIntroduced[deviceID]; !ok {
  1516. // The introducer no longer shares any folder with the
  1517. // device, remove the device.
  1518. l.Infof("Removing device %v as introducer %v no longer shares any folders with that device", deviceID, device.IntroducedBy)
  1519. changed = true
  1520. delete(devices, deviceID)
  1521. continue
  1522. }
  1523. l.Infof("Would have removed %v as %v no longer shares any folders, yet there are other folders that are shared with this device that haven't been introduced by this introducer.", deviceID, device.IntroducedBy)
  1524. }
  1525. }
  1526. }
  1527. return folders, devices, changed
  1528. }
  1529. // handleAutoAccepts handles adding and sharing folders for devices that have
  1530. // AutoAcceptFolders set to true.
  1531. func (m *model) handleAutoAccepts(deviceID protocol.DeviceID, folder protocol.Folder, ccDeviceInfos *clusterConfigDeviceInfo, cfg config.FolderConfiguration, haveCfg bool, defaultFolderCfg config.FolderConfiguration) (config.FolderConfiguration, bool) {
  1532. if !haveCfg {
  1533. defaultPathFs := fs.NewFilesystem(defaultFolderCfg.FilesystemType.ToFS(), defaultFolderCfg.Path)
  1534. var pathAlternatives []string
  1535. if alt := fs.SanitizePath(folder.Label); alt != "" {
  1536. pathAlternatives = append(pathAlternatives, alt)
  1537. }
  1538. if alt := fs.SanitizePath(folder.ID); alt != "" {
  1539. pathAlternatives = append(pathAlternatives, alt)
  1540. }
  1541. if len(pathAlternatives) == 0 {
  1542. l.Infof("Failed to auto-accept folder %s from %s due to lack of path alternatives", folder.Description(), deviceID)
  1543. return config.FolderConfiguration{}, false
  1544. }
  1545. for _, path := range pathAlternatives {
  1546. // Make sure the folder path doesn't already exist.
  1547. if _, err := defaultPathFs.Lstat(path); !fs.IsNotExist(err) {
  1548. continue
  1549. }
  1550. // Attempt to create it to make sure it does, now.
  1551. fullPath := filepath.Join(defaultFolderCfg.Path, path)
  1552. if err := defaultPathFs.MkdirAll(path, 0o700); err != nil {
  1553. l.Warnf("Failed to create path for auto-accepted folder %s at path %s: %v", folder.Description(), fullPath, err)
  1554. continue
  1555. }
  1556. fcfg := newFolderConfiguration(m.cfg, folder.ID, folder.Label, defaultFolderCfg.FilesystemType, fullPath)
  1557. fcfg.Devices = append(fcfg.Devices, config.FolderDeviceConfiguration{
  1558. DeviceID: deviceID,
  1559. })
  1560. if len(ccDeviceInfos.remote.EncryptionPasswordToken) > 0 || len(ccDeviceInfos.local.EncryptionPasswordToken) > 0 {
  1561. fcfg.Type = config.FolderTypeReceiveEncrypted
  1562. // Override the user-configured defaults, as normally done by the GUI
  1563. fcfg.FSWatcherEnabled = false
  1564. if fcfg.RescanIntervalS != 0 {
  1565. minRescanInterval := 3600 * 24
  1566. if fcfg.RescanIntervalS < minRescanInterval {
  1567. fcfg.RescanIntervalS = minRescanInterval
  1568. }
  1569. }
  1570. fcfg.Versioning.Reset()
  1571. // Other necessary settings are ensured by FolderConfiguration itself
  1572. } else {
  1573. ignores := m.cfg.DefaultIgnores()
  1574. if err := m.setIgnores(fcfg, ignores.Lines); err != nil {
  1575. l.Warnf("Failed to apply default ignores to auto-accepted folder %s at path %s: %v", folder.Description(), fcfg.Path, err)
  1576. }
  1577. }
  1578. l.Infof("Auto-accepted %s folder %s at path %s", deviceID, folder.Description(), fcfg.Path)
  1579. return fcfg, true
  1580. }
  1581. l.Infof("Failed to auto-accept folder %s from %s due to path conflict", folder.Description(), deviceID)
  1582. return config.FolderConfiguration{}, false
  1583. } else {
  1584. if slices.Contains(cfg.DeviceIDs(), deviceID) {
  1585. // Already shared nothing todo.
  1586. return config.FolderConfiguration{}, false
  1587. }
  1588. if cfg.Type == config.FolderTypeReceiveEncrypted {
  1589. if len(ccDeviceInfos.remote.EncryptionPasswordToken) == 0 && len(ccDeviceInfos.local.EncryptionPasswordToken) == 0 {
  1590. l.Infof("Failed to auto-accept device %s on existing folder %s as the remote wants to send us unencrypted data, but the folder type is receive-encrypted", folder.Description(), deviceID)
  1591. return config.FolderConfiguration{}, false
  1592. }
  1593. } else {
  1594. if len(ccDeviceInfos.remote.EncryptionPasswordToken) > 0 || len(ccDeviceInfos.local.EncryptionPasswordToken) > 0 {
  1595. l.Infof("Failed to auto-accept device %s on existing folder %s as the remote wants to send us encrypted data, but the folder type is not receive-encrypted", folder.Description(), deviceID)
  1596. return config.FolderConfiguration{}, false
  1597. }
  1598. }
  1599. cfg.Devices = append(cfg.Devices, config.FolderDeviceConfiguration{
  1600. DeviceID: deviceID,
  1601. })
  1602. l.Infof("Shared %s with %s due to auto-accept", folder.ID, deviceID)
  1603. return cfg, true
  1604. }
  1605. }
  1606. func (m *model) introduceDevice(device protocol.Device, introducerCfg config.DeviceConfiguration) config.DeviceConfiguration {
  1607. addresses := []string{"dynamic"}
  1608. for _, addr := range device.Addresses {
  1609. if addr != "dynamic" {
  1610. addresses = append(addresses, addr)
  1611. }
  1612. }
  1613. l.Infof("Adding device %v to config (vouched for by introducer %v)", device.ID, introducerCfg.DeviceID)
  1614. newDeviceCfg := m.cfg.DefaultDevice()
  1615. newDeviceCfg.DeviceID = device.ID
  1616. newDeviceCfg.Name = device.Name
  1617. newDeviceCfg.Compression = introducerCfg.Compression
  1618. newDeviceCfg.Addresses = addresses
  1619. newDeviceCfg.CertName = device.CertName
  1620. newDeviceCfg.IntroducedBy = introducerCfg.DeviceID
  1621. // The introducers' introducers are also our introducers.
  1622. if device.Introducer {
  1623. l.Infof("Device %v is now also an introducer", device.ID)
  1624. newDeviceCfg.Introducer = true
  1625. newDeviceCfg.SkipIntroductionRemovals = device.SkipIntroductionRemovals
  1626. }
  1627. return newDeviceCfg
  1628. }
  1629. // Closed is called when a connection has been closed
  1630. func (m *model) Closed(conn protocol.Connection, err error) {
  1631. connID := conn.ConnectionID()
  1632. deviceID := conn.DeviceID()
  1633. m.mut.Lock()
  1634. conn, ok := m.connections[connID]
  1635. if !ok {
  1636. m.mut.Unlock()
  1637. return
  1638. }
  1639. closed := m.closed[connID]
  1640. delete(m.closed, connID)
  1641. delete(m.connections, connID)
  1642. removedIsPrimary := m.promotedConnID[deviceID] == connID
  1643. remainingConns := without(m.deviceConnIDs[deviceID], connID)
  1644. var wait <-chan error
  1645. if removedIsPrimary {
  1646. m.progressEmitter.temporaryIndexUnsubscribe(conn)
  1647. if idxh, ok := m.indexHandlers.Get(deviceID); ok && idxh.conn.ConnectionID() == connID {
  1648. wait = m.indexHandlers.RemoveAndWaitChan(deviceID, 0)
  1649. }
  1650. m.scheduleConnectionPromotion()
  1651. }
  1652. if len(remainingConns) == 0 {
  1653. // All device connections closed
  1654. delete(m.deviceConnIDs, deviceID)
  1655. delete(m.promotedConnID, deviceID)
  1656. delete(m.connRequestLimiters, deviceID)
  1657. delete(m.helloMessages, deviceID)
  1658. delete(m.remoteFolderStates, deviceID)
  1659. delete(m.deviceDownloads, deviceID)
  1660. } else {
  1661. // Some connections remain
  1662. m.deviceConnIDs[deviceID] = remainingConns
  1663. }
  1664. m.mut.Unlock()
  1665. if wait != nil {
  1666. <-wait
  1667. }
  1668. m.mut.RLock()
  1669. m.deviceDidCloseRLocked(deviceID, time.Since(conn.EstablishedAt()))
  1670. m.mut.RUnlock()
  1671. k := map[bool]string{false: "secondary", true: "primary"}[removedIsPrimary]
  1672. l.Infof("Lost %s connection to %s at %s: %v (%d remain)", k, deviceID.Short(), conn, err, len(remainingConns))
  1673. if len(remainingConns) == 0 {
  1674. l.Infof("Connection to %s at %s closed: %v", deviceID.Short(), conn, err)
  1675. m.evLogger.Log(events.DeviceDisconnected, map[string]string{
  1676. "id": deviceID.String(),
  1677. "error": err.Error(),
  1678. })
  1679. }
  1680. close(closed)
  1681. }
  1682. // Implements protocol.RequestResponse
  1683. type requestResponse struct {
  1684. data []byte
  1685. closed chan struct{}
  1686. once stdsync.Once
  1687. }
  1688. func newRequestResponse(size int) *requestResponse {
  1689. return &requestResponse{
  1690. data: protocol.BufferPool.Get(size),
  1691. closed: make(chan struct{}),
  1692. }
  1693. }
  1694. func (r *requestResponse) Data() []byte {
  1695. return r.data
  1696. }
  1697. func (r *requestResponse) Close() {
  1698. r.once.Do(func() {
  1699. protocol.BufferPool.Put(r.data)
  1700. close(r.closed)
  1701. })
  1702. }
  1703. func (r *requestResponse) Wait() {
  1704. <-r.closed
  1705. }
  1706. // Request returns the specified data segment by reading it from local disk.
  1707. // Implements the protocol.Model interface.
  1708. func (m *model) Request(conn protocol.Connection, req *protocol.Request) (out protocol.RequestResponse, err error) {
  1709. if req.Size < 0 || req.Offset < 0 {
  1710. return nil, protocol.ErrInvalid
  1711. }
  1712. deviceID := conn.DeviceID()
  1713. m.mut.RLock()
  1714. folderCfg, ok := m.folderCfgs[req.Folder]
  1715. folderIgnores := m.folderIgnores[req.Folder]
  1716. m.mut.RUnlock()
  1717. if !ok {
  1718. // The folder might be already unpaused in the config, but not yet
  1719. // in the model.
  1720. l.Debugf("Request from %s for file %s in unstarted folder %q", deviceID.Short(), req.Name, req.Folder)
  1721. return nil, protocol.ErrGeneric
  1722. }
  1723. if !folderCfg.SharedWith(deviceID) {
  1724. l.Warnf("Request from %s for file %s in unshared folder %q", deviceID.Short(), req.Name, req.Folder)
  1725. return nil, protocol.ErrGeneric
  1726. }
  1727. if folderCfg.Paused {
  1728. l.Debugf("Request from %s for file %s in paused folder %q", deviceID.Short(), req.Name, req.Folder)
  1729. return nil, protocol.ErrGeneric
  1730. }
  1731. // Make sure the path is valid and in canonical form
  1732. if name, err := fs.Canonicalize(req.Name); err != nil {
  1733. l.Debugf("Request from %s in folder %q for invalid filename %s", deviceID.Short(), req.Folder, req.Name)
  1734. return nil, protocol.ErrGeneric
  1735. } else {
  1736. req.Name = name
  1737. }
  1738. if deviceID != protocol.LocalDeviceID {
  1739. l.Debugf("%v REQ(in): %s: %q / %q o=%d s=%d t=%v", m, deviceID.Short(), req.Folder, req.Name, req.Offset, req.Size, req.FromTemporary)
  1740. }
  1741. if fs.IsInternal(req.Name) {
  1742. l.Debugf("%v REQ(in) for internal file: %s: %q / %q o=%d s=%d", m, deviceID.Short(), req.Folder, req.Name, req.Offset, req.Size)
  1743. return nil, protocol.ErrInvalid
  1744. }
  1745. if folderIgnores.Match(req.Name).IsIgnored() {
  1746. l.Debugf("%v REQ(in) for ignored file: %s: %q / %q o=%d s=%d", m, deviceID.Short(), req.Folder, req.Name, req.Offset, req.Size)
  1747. return nil, protocol.ErrInvalid
  1748. }
  1749. // Restrict parallel requests by connection/device
  1750. m.mut.RLock()
  1751. limiter := m.connRequestLimiters[deviceID]
  1752. m.mut.RUnlock()
  1753. // The requestResponse releases the bytes to the buffer pool and the
  1754. // limiters when its Close method is called.
  1755. res := newLimitedRequestResponse(int(req.Size), limiter, m.globalRequestLimiter)
  1756. defer func() {
  1757. // Close it ourselves if it isn't returned due to an error
  1758. if err != nil {
  1759. res.Close()
  1760. }
  1761. }()
  1762. // Grab the FS after limiting, as it causes I/O and we want to minimize
  1763. // the race time between the symlink check and the read.
  1764. folderFs := folderCfg.Filesystem()
  1765. if err := osutil.TraversesSymlink(folderFs, filepath.Dir(req.Name)); err != nil {
  1766. l.Debugf("%v REQ(in) traversal check: %s - %s: %q / %q o=%d s=%d", m, err, deviceID.Short(), req.Folder, req.Name, req.Offset, req.Size)
  1767. return nil, protocol.ErrNoSuchFile
  1768. }
  1769. // Only check temp files if the flag is set, and if we are set to advertise
  1770. // the temp indexes.
  1771. if req.FromTemporary && !folderCfg.DisableTempIndexes {
  1772. tempFn := fs.TempName(req.Name)
  1773. if info, err := folderFs.Lstat(tempFn); err != nil || !info.IsRegular() {
  1774. // Reject reads for anything that doesn't exist or is something
  1775. // other than a regular file.
  1776. l.Debugf("%v REQ(in) failed stating temp file (%v): %s: %q / %q o=%d s=%d", m, err, deviceID.Short(), req.Folder, req.Name, req.Offset, req.Size)
  1777. return nil, protocol.ErrNoSuchFile
  1778. }
  1779. _, err := readOffsetIntoBuf(folderFs, tempFn, req.Offset, res.data)
  1780. if err == nil && scanner.Validate(res.data, req.Hash) {
  1781. return res, nil
  1782. }
  1783. // Fall through to reading from a non-temp file, just in case the temp
  1784. // file has finished downloading.
  1785. }
  1786. if info, err := folderFs.Lstat(req.Name); err != nil || !info.IsRegular() {
  1787. // Reject reads for anything that doesn't exist or is something
  1788. // other than a regular file.
  1789. l.Debugf("%v REQ(in) failed stating file (%v): %s: %q / %q o=%d s=%d", m, err, deviceID.Short(), req.Folder, req.Name, req.Offset, req.Size)
  1790. return nil, protocol.ErrNoSuchFile
  1791. }
  1792. n, err := readOffsetIntoBuf(folderFs, req.Name, req.Offset, res.data)
  1793. if fs.IsNotExist(err) {
  1794. l.Debugf("%v REQ(in) file doesn't exist: %s: %q / %q o=%d s=%d", m, deviceID.Short(), req.Folder, req.Name, req.Offset, req.Size)
  1795. return nil, protocol.ErrNoSuchFile
  1796. } else if err == io.EOF {
  1797. // Read beyond end of file. This might indicate a problem, or it
  1798. // might be a short block that gets padded when read for encrypted
  1799. // folders. We ignore the error and let the hash validation in the
  1800. // next step take care of it, by only hashing the part we actually
  1801. // managed to read.
  1802. } else if err != nil {
  1803. l.Debugf("%v REQ(in) failed reading file (%v): %s: %q / %q o=%d s=%d", m, err, deviceID.Short(), req.Folder, req.Name, req.Offset, req.Size)
  1804. return nil, protocol.ErrGeneric
  1805. }
  1806. if folderCfg.Type != config.FolderTypeReceiveEncrypted && len(req.Hash) > 0 && !scanner.Validate(res.data[:n], req.Hash) {
  1807. m.recheckFile(deviceID, req.Folder, req.Name, req.Offset, req.Hash)
  1808. l.Debugf("%v REQ(in) failed validating data: %s: %q / %q o=%d s=%d", m, deviceID.Short(), req.Folder, req.Name, req.Offset, req.Size)
  1809. return nil, protocol.ErrNoSuchFile
  1810. }
  1811. return res, nil
  1812. }
  1813. // newLimitedRequestResponse takes size bytes from the limiters in order,
  1814. // skipping nil limiters, then returns a requestResponse of the given size.
  1815. // When the requestResponse is closed the limiters are given back the bytes,
  1816. // in reverse order.
  1817. func newLimitedRequestResponse(size int, limiters ...*semaphore.Semaphore) *requestResponse {
  1818. multi := semaphore.MultiSemaphore(limiters)
  1819. multi.Take(size)
  1820. res := newRequestResponse(size)
  1821. go func() {
  1822. res.Wait()
  1823. multi.Give(size)
  1824. }()
  1825. return res
  1826. }
  1827. func (m *model) recheckFile(deviceID protocol.DeviceID, folder, name string, offset int64, hash []byte) {
  1828. cf, ok, err := m.CurrentFolderFile(folder, name)
  1829. if err != nil {
  1830. l.Debugf("%v recheckFile: %s: %q / %q: current file error: %v", m, deviceID, folder, name, err)
  1831. return
  1832. }
  1833. if !ok {
  1834. l.Debugf("%v recheckFile: %s: %q / %q: no current file", m, deviceID, folder, name)
  1835. return
  1836. }
  1837. if cf.IsDeleted() || cf.IsInvalid() || cf.IsSymlink() || cf.IsDirectory() {
  1838. l.Debugf("%v recheckFile: %s: %q / %q: not a regular file", m, deviceID, folder, name)
  1839. return
  1840. }
  1841. blockIndex := int(offset / int64(cf.BlockSize()))
  1842. if blockIndex >= len(cf.Blocks) {
  1843. l.Debugf("%v recheckFile: %s: %q / %q i=%d: block index too far", m, deviceID, folder, name, blockIndex)
  1844. return
  1845. }
  1846. block := cf.Blocks[blockIndex]
  1847. // Seems to want a different version of the file, whatever.
  1848. if !bytes.Equal(block.Hash, hash) {
  1849. l.Debugf("%v recheckFile: %s: %q / %q i=%d: hash mismatch %x != %x", m, deviceID, folder, name, blockIndex, block.Hash, hash)
  1850. return
  1851. }
  1852. // The hashes provided part of the request match what we expect to find according
  1853. // to what we have in the database, yet the content we've read off the filesystem doesn't
  1854. // Something is fishy, invalidate the file and rescan it.
  1855. // The file will temporarily become invalid, which is ok as the content is messed up.
  1856. m.mut.RLock()
  1857. runner, ok := m.folderRunners.Get(folder)
  1858. m.mut.RUnlock()
  1859. if !ok {
  1860. l.Debugf("%v recheckFile: %s: %q / %q: Folder stopped before rescan could be scheduled", m, deviceID, folder, name)
  1861. return
  1862. }
  1863. runner.ScheduleForceRescan(name)
  1864. l.Debugf("%v recheckFile: %s: %q / %q", m, deviceID, folder, name)
  1865. }
  1866. func (m *model) CurrentFolderFile(folder string, file string) (protocol.FileInfo, bool, error) {
  1867. return m.sdb.GetDeviceFile(folder, protocol.LocalDeviceID, file)
  1868. }
  1869. func (m *model) CurrentGlobalFile(folder string, file string) (protocol.FileInfo, bool, error) {
  1870. return m.sdb.GetGlobalFile(folder, file)
  1871. }
  1872. // Connection returns if we are connected to the given device.
  1873. func (m *model) ConnectedTo(deviceID protocol.DeviceID) bool {
  1874. m.mut.RLock()
  1875. _, ok := m.deviceConnIDs[deviceID]
  1876. m.mut.RUnlock()
  1877. return ok
  1878. }
  1879. // LoadIgnores loads or refreshes the ignore patterns from disk, if the
  1880. // folder is healthy, and returns the refreshed lines and patterns.
  1881. func (m *model) LoadIgnores(folder string) ([]string, []string, error) {
  1882. m.mut.RLock()
  1883. cfg, cfgOk := m.folderCfgs[folder]
  1884. ignores, ignoresOk := m.folderIgnores[folder]
  1885. m.mut.RUnlock()
  1886. if !cfgOk {
  1887. cfg, cfgOk = m.cfg.Folder(folder)
  1888. if !cfgOk {
  1889. return nil, nil, fmt.Errorf("folder %s does not exist", folder)
  1890. }
  1891. }
  1892. if cfg.Type == config.FolderTypeReceiveEncrypted {
  1893. return nil, nil, nil
  1894. }
  1895. if !ignoresOk {
  1896. ignores = ignore.New(cfg.Filesystem())
  1897. }
  1898. err := ignores.Load(".stignore")
  1899. if fs.IsNotExist(err) {
  1900. // Having no ignores is not an error.
  1901. return nil, nil, nil
  1902. }
  1903. // Return lines and patterns, which may have some meaning even when err
  1904. // != nil, depending on the specific error.
  1905. return ignores.Lines(), ignores.Patterns(), err
  1906. }
  1907. // CurrentIgnores returns the currently loaded set of ignore patterns,
  1908. // whichever it may be. No attempt is made to load or refresh ignore
  1909. // patterns from disk.
  1910. func (m *model) CurrentIgnores(folder string) ([]string, []string, error) {
  1911. m.mut.RLock()
  1912. _, cfgOk := m.folderCfgs[folder]
  1913. ignores, ignoresOk := m.folderIgnores[folder]
  1914. m.mut.RUnlock()
  1915. if !cfgOk {
  1916. return nil, nil, fmt.Errorf("folder %s does not exist", folder)
  1917. }
  1918. if !ignoresOk {
  1919. // Empty ignore patterns
  1920. return []string{}, []string{}, nil
  1921. }
  1922. return ignores.Lines(), ignores.Patterns(), nil
  1923. }
  1924. func (m *model) SetIgnores(folder string, content []string) error {
  1925. cfg, ok := m.cfg.Folder(folder)
  1926. if !ok {
  1927. return fmt.Errorf("folder %s does not exist", cfg.Description())
  1928. }
  1929. return m.setIgnores(cfg, content)
  1930. }
  1931. func (m *model) setIgnores(cfg config.FolderConfiguration, content []string) error {
  1932. err := cfg.CheckPath()
  1933. if err == config.ErrPathMissing {
  1934. if err = cfg.CreateRoot(); err != nil {
  1935. return fmt.Errorf("failed to create folder root: %w", err)
  1936. }
  1937. err = cfg.CheckPath()
  1938. }
  1939. if err != nil && err != config.ErrMarkerMissing {
  1940. return err
  1941. }
  1942. if err := ignore.WriteIgnores(cfg.Filesystem(), ".stignore", content); err != nil {
  1943. l.Warnln("Saving .stignore:", err)
  1944. return err
  1945. }
  1946. m.mut.RLock()
  1947. runner, ok := m.folderRunners.Get(cfg.ID)
  1948. m.mut.RUnlock()
  1949. if ok {
  1950. runner.ScheduleScan()
  1951. }
  1952. return nil
  1953. }
  1954. // OnHello is called when an device connects to us.
  1955. // This allows us to extract some information from the Hello message
  1956. // and add it to a list of known devices ahead of any checks.
  1957. func (m *model) OnHello(remoteID protocol.DeviceID, addr net.Addr, hello protocol.Hello) error {
  1958. if _, ok := m.cfg.Device(remoteID); !ok {
  1959. if err := m.observed.AddOrUpdatePendingDevice(remoteID, hello.DeviceName, addr.String()); err != nil {
  1960. l.Warnf("Failed to persist pending device entry to database: %v", err)
  1961. }
  1962. m.evLogger.Log(events.PendingDevicesChanged, map[string][]interface{}{
  1963. "added": {map[string]string{
  1964. "deviceID": remoteID.String(),
  1965. "name": hello.DeviceName,
  1966. "address": addr.String(),
  1967. }},
  1968. })
  1969. // DEPRECATED: Only for backwards compatibility, should be removed.
  1970. m.evLogger.Log(events.DeviceRejected, map[string]string{
  1971. "name": hello.DeviceName,
  1972. "device": remoteID.String(),
  1973. "address": addr.String(),
  1974. })
  1975. return errDeviceUnknown
  1976. }
  1977. return nil
  1978. }
  1979. // AddConnection adds a new peer connection to the model. An initial index will
  1980. // be sent to the connected peer, thereafter index updates whenever the local
  1981. // folder changes.
  1982. func (m *model) AddConnection(conn protocol.Connection, hello protocol.Hello) {
  1983. deviceID := conn.DeviceID()
  1984. deviceCfg, ok := m.cfg.Device(deviceID)
  1985. if !ok {
  1986. l.Infoln("Trying to add connection to unknown device")
  1987. return
  1988. }
  1989. connID := conn.ConnectionID()
  1990. closed := make(chan struct{})
  1991. m.mut.Lock()
  1992. m.connections[connID] = conn
  1993. m.closed[connID] = closed
  1994. m.helloMessages[deviceID] = hello
  1995. m.deviceConnIDs[deviceID] = append(m.deviceConnIDs[deviceID], connID)
  1996. if m.deviceDownloads[deviceID] == nil {
  1997. m.deviceDownloads[deviceID] = newDeviceDownloadState()
  1998. }
  1999. event := map[string]string{
  2000. "id": deviceID.String(),
  2001. "deviceName": hello.DeviceName,
  2002. "clientName": hello.ClientName,
  2003. "clientVersion": hello.ClientVersion,
  2004. "type": conn.Type(),
  2005. }
  2006. addr := conn.RemoteAddr()
  2007. if addr != nil {
  2008. event["addr"] = addr.String()
  2009. }
  2010. m.evLogger.Log(events.DeviceConnected, event)
  2011. if len(m.deviceConnIDs[deviceID]) == 1 {
  2012. l.Infof(`Device %s client is "%s %s" named "%s" at %s`, deviceID.Short(), hello.ClientName, hello.ClientVersion, hello.DeviceName, conn)
  2013. } else {
  2014. l.Infof(`Additional connection (+%d) for device %s at %s`, len(m.deviceConnIDs[deviceID])-1, deviceID.Short(), conn)
  2015. }
  2016. m.mut.Unlock()
  2017. if (deviceCfg.Name == "" || m.cfg.Options().OverwriteRemoteDevNames) && hello.DeviceName != "" {
  2018. m.cfg.Modify(func(cfg *config.Configuration) {
  2019. for i := range cfg.Devices {
  2020. if cfg.Devices[i].DeviceID == deviceID {
  2021. if cfg.Devices[i].Name == "" || cfg.Options.OverwriteRemoteDevNames {
  2022. cfg.Devices[i].Name = hello.DeviceName
  2023. }
  2024. return
  2025. }
  2026. }
  2027. })
  2028. }
  2029. m.deviceWasSeen(deviceID)
  2030. m.scheduleConnectionPromotion()
  2031. }
  2032. func (m *model) scheduleConnectionPromotion() {
  2033. // Keeps deferring to prevent multiple executions in quick succession,
  2034. // e.g. if multiple connections to a single device are closed.
  2035. m.promotionTimer.Reset(time.Second)
  2036. }
  2037. // promoteConnections checks for devices that have connections, but where
  2038. // the primary connection hasn't started index handlers etc. yet, and
  2039. // promotes the primary connection to be the index handling one. This should
  2040. // be called after adding new connections, and after closing a primary
  2041. // device connection.
  2042. func (m *model) promoteConnections() {
  2043. // Slice of actions to take on connections after releasing the main
  2044. // mutex. We do this so that we do not perform blocking network actions
  2045. // inside the loop, and also to avoid a possible deadlock with calling
  2046. // Start() on connections that are already executing a Close() with a
  2047. // callback into the model...
  2048. var postLockActions []func()
  2049. m.mut.Lock()
  2050. for deviceID, connIDs := range m.deviceConnIDs {
  2051. cm, passwords := m.generateClusterConfigRLocked(deviceID)
  2052. if m.promotedConnID[deviceID] != connIDs[0] {
  2053. // The previously promoted connection is not the current
  2054. // primary; we should promote the primary connection to be the
  2055. // index handling one. We do this by sending a ClusterConfig on
  2056. // it, which will cause the other side to start sending us index
  2057. // messages there. (On our side, we manage index handlers based
  2058. // on where we get ClusterConfigs from the peer.)
  2059. conn := m.connections[connIDs[0]]
  2060. l.Debugf("Promoting connection to %s at %s", deviceID.Short(), conn)
  2061. postLockActions = append(postLockActions, func() {
  2062. if conn.Statistics().StartedAt.IsZero() {
  2063. conn.Start()
  2064. }
  2065. conn.ClusterConfig(cm, passwords)
  2066. })
  2067. m.promotedConnID[deviceID] = connIDs[0]
  2068. }
  2069. // Make sure any other new connections also get started, and that
  2070. // they get a secondary-marked ClusterConfig.
  2071. for _, connID := range connIDs[1:] {
  2072. conn := m.connections[connID]
  2073. if conn.Statistics().StartedAt.IsZero() {
  2074. postLockActions = append(postLockActions, func() {
  2075. conn.Start()
  2076. conn.ClusterConfig(&protocol.ClusterConfig{Secondary: true}, passwords)
  2077. })
  2078. }
  2079. }
  2080. }
  2081. m.mut.Unlock()
  2082. for _, action := range postLockActions {
  2083. action()
  2084. }
  2085. }
  2086. func (m *model) DownloadProgress(conn protocol.Connection, p *protocol.DownloadProgress) error {
  2087. deviceID := conn.DeviceID()
  2088. m.mut.RLock()
  2089. cfg, ok := m.folderCfgs[p.Folder]
  2090. m.mut.RUnlock()
  2091. if !ok || cfg.DisableTempIndexes || !cfg.SharedWith(deviceID) {
  2092. return nil
  2093. }
  2094. m.mut.RLock()
  2095. downloads := m.deviceDownloads[deviceID]
  2096. m.mut.RUnlock()
  2097. downloads.Update(p.Folder, p.Updates)
  2098. state := downloads.GetBlockCounts(p.Folder)
  2099. m.evLogger.Log(events.RemoteDownloadProgress, map[string]interface{}{
  2100. "device": deviceID.String(),
  2101. "folder": p.Folder,
  2102. "state": state,
  2103. })
  2104. return nil
  2105. }
  2106. func (m *model) deviceWasSeen(deviceID protocol.DeviceID) {
  2107. m.mut.RLock()
  2108. sr, ok := m.deviceStatRefs[deviceID]
  2109. m.mut.RUnlock()
  2110. if ok {
  2111. _ = sr.WasSeen()
  2112. }
  2113. }
  2114. func (m *model) deviceDidCloseRLocked(deviceID protocol.DeviceID, duration time.Duration) {
  2115. if sr, ok := m.deviceStatRefs[deviceID]; ok {
  2116. _ = sr.LastConnectionDuration(duration)
  2117. _ = sr.WasSeen()
  2118. }
  2119. }
  2120. func (m *model) RequestGlobal(ctx context.Context, deviceID protocol.DeviceID, folder, name string, blockNo int, offset int64, size int, hash []byte, fromTemporary bool) ([]byte, error) {
  2121. conn, connOK := m.requestConnectionForDevice(deviceID)
  2122. if !connOK {
  2123. return nil, fmt.Errorf("requestGlobal: no connection to device: %s", deviceID.Short())
  2124. }
  2125. l.Debugf("%v REQ(out): %s (%s): %q / %q b=%d o=%d s=%d h=%x ft=%t", m, deviceID.Short(), conn, folder, name, blockNo, offset, size, hash, fromTemporary)
  2126. return conn.Request(ctx, &protocol.Request{Folder: folder, Name: name, BlockNo: blockNo, Offset: offset, Size: size, Hash: hash, FromTemporary: fromTemporary})
  2127. }
  2128. // requestConnectionForDevice returns a connection to the given device, to
  2129. // be used for sending a request. If there is only one device connection,
  2130. // this is the one to use. If there are multiple then we avoid the first
  2131. // ("primary") connection, which is dedicated to index data, and pick a
  2132. // random one of the others.
  2133. func (m *model) requestConnectionForDevice(deviceID protocol.DeviceID) (protocol.Connection, bool) {
  2134. m.mut.RLock()
  2135. defer m.mut.RUnlock()
  2136. connIDs, ok := m.deviceConnIDs[deviceID]
  2137. if !ok {
  2138. return nil, false
  2139. }
  2140. // If there is an entry in deviceConns, it always contains at least one
  2141. // connection.
  2142. connID := connIDs[0]
  2143. if len(connIDs) > 1 {
  2144. // Pick a random connection of the non-primary ones
  2145. idx := rand.Intn(len(connIDs)-1) + 1
  2146. connID = connIDs[idx]
  2147. }
  2148. conn, connOK := m.connections[connID]
  2149. return conn, connOK
  2150. }
  2151. func (m *model) ScanFolders() map[string]error {
  2152. m.mut.RLock()
  2153. folders := make([]string, 0, len(m.folderCfgs))
  2154. for folder := range m.folderCfgs {
  2155. folders = append(folders, folder)
  2156. }
  2157. m.mut.RUnlock()
  2158. errors := make(map[string]error, len(m.folderCfgs))
  2159. errorsMut := sync.NewMutex()
  2160. wg := sync.NewWaitGroup()
  2161. wg.Add(len(folders))
  2162. for _, folder := range folders {
  2163. folder := folder
  2164. go func() {
  2165. err := m.ScanFolder(folder)
  2166. if err != nil {
  2167. errorsMut.Lock()
  2168. errors[folder] = err
  2169. errorsMut.Unlock()
  2170. }
  2171. wg.Done()
  2172. }()
  2173. }
  2174. wg.Wait()
  2175. return errors
  2176. }
  2177. func (m *model) ScanFolder(folder string) error {
  2178. return m.ScanFolderSubdirs(folder, nil)
  2179. }
  2180. func (m *model) ScanFolderSubdirs(folder string, subs []string) error {
  2181. m.mut.RLock()
  2182. err := m.checkFolderRunningRLocked(folder)
  2183. runner, _ := m.folderRunners.Get(folder)
  2184. m.mut.RUnlock()
  2185. if err != nil {
  2186. return err
  2187. }
  2188. return runner.Scan(subs)
  2189. }
  2190. func (m *model) DelayScan(folder string, next time.Duration) {
  2191. m.mut.RLock()
  2192. runner, ok := m.folderRunners.Get(folder)
  2193. m.mut.RUnlock()
  2194. if !ok {
  2195. return
  2196. }
  2197. runner.DelayScan(next)
  2198. }
  2199. // numHashers returns the number of hasher routines to use for a given folder,
  2200. // taking into account configuration and available CPU cores.
  2201. func (m *model) numHashers(folder string) int {
  2202. m.mut.RLock()
  2203. folderCfg := m.folderCfgs[folder]
  2204. numFolders := max(1, len(m.folderCfgs))
  2205. m.mut.RUnlock()
  2206. if folderCfg.Hashers > 0 {
  2207. // Specific value set in the config, use that.
  2208. return folderCfg.Hashers
  2209. }
  2210. if build.IsWindows || build.IsDarwin || build.IsIOS || build.IsAndroid {
  2211. // Interactive operating systems; don't load the system too heavily by
  2212. // default.
  2213. return 1
  2214. }
  2215. // For other operating systems and architectures, lets try to get some
  2216. // work done... Divide the available CPU cores among the configured
  2217. // folders.
  2218. if perFolder := runtime.GOMAXPROCS(-1) / numFolders; perFolder > 0 {
  2219. return perFolder
  2220. }
  2221. return 1
  2222. }
  2223. // generateClusterConfig returns a ClusterConfigMessage that is correct and the
  2224. // set of folder passwords for the given peer device
  2225. func (m *model) generateClusterConfig(device protocol.DeviceID) (*protocol.ClusterConfig, map[string]string) {
  2226. m.mut.RLock()
  2227. defer m.mut.RUnlock()
  2228. return m.generateClusterConfigRLocked(device)
  2229. }
  2230. func (m *model) generateClusterConfigRLocked(device protocol.DeviceID) (*protocol.ClusterConfig, map[string]string) {
  2231. message := &protocol.ClusterConfig{}
  2232. folders := m.cfg.FolderList()
  2233. passwords := make(map[string]string, len(folders))
  2234. for _, folderCfg := range folders {
  2235. if !folderCfg.SharedWith(device) {
  2236. continue
  2237. }
  2238. encryptionToken, hasEncryptionToken := m.folderEncryptionPasswordTokens[folderCfg.ID]
  2239. if folderCfg.Type == config.FolderTypeReceiveEncrypted && !hasEncryptionToken {
  2240. // We haven't gotten a token for us yet and without one the other
  2241. // side can't validate us - pretend we don't have the folder yet.
  2242. continue
  2243. }
  2244. protocolFolder := protocol.Folder{
  2245. ID: folderCfg.ID,
  2246. Label: folderCfg.Label,
  2247. ReadOnly: folderCfg.Type == config.FolderTypeSendOnly,
  2248. IgnorePermissions: folderCfg.IgnorePerms,
  2249. IgnoreDelete: folderCfg.IgnoreDelete,
  2250. DisableTempIndexes: folderCfg.DisableTempIndexes,
  2251. }
  2252. // Even if we aren't paused, if we haven't started the folder yet
  2253. // pretend we are. Otherwise the remote might get confused about
  2254. // the missing index info (and drop all the info). We will send
  2255. // another cluster config once the folder is started.
  2256. protocolFolder.Paused = folderCfg.Paused
  2257. for _, folderDevice := range folderCfg.Devices {
  2258. deviceCfg, _ := m.cfg.Device(folderDevice.DeviceID)
  2259. protocolDevice := protocol.Device{
  2260. ID: deviceCfg.DeviceID,
  2261. Name: deviceCfg.Name,
  2262. Addresses: deviceCfg.Addresses,
  2263. Compression: deviceCfg.Compression.ToProtocol(),
  2264. CertName: deviceCfg.CertName,
  2265. Introducer: deviceCfg.Introducer,
  2266. }
  2267. if deviceCfg.DeviceID == m.id && hasEncryptionToken {
  2268. protocolDevice.EncryptionPasswordToken = encryptionToken
  2269. } else if folderDevice.EncryptionPassword != "" {
  2270. protocolDevice.EncryptionPasswordToken = protocol.PasswordToken(m.keyGen, folderCfg.ID, folderDevice.EncryptionPassword)
  2271. if folderDevice.DeviceID == device {
  2272. passwords[folderCfg.ID] = folderDevice.EncryptionPassword
  2273. }
  2274. }
  2275. if deviceCfg.DeviceID == m.id {
  2276. protocolDevice.IndexID, _ = m.sdb.GetIndexID(folderCfg.ID, protocol.LocalDeviceID)
  2277. protocolDevice.MaxSequence, _ = m.sdb.GetDeviceSequence(folderCfg.ID, protocol.LocalDeviceID)
  2278. } else {
  2279. protocolDevice.IndexID, _ = m.sdb.GetIndexID(folderCfg.ID, deviceCfg.DeviceID)
  2280. protocolDevice.MaxSequence, _ = m.sdb.GetDeviceSequence(folderCfg.ID, deviceCfg.DeviceID)
  2281. }
  2282. protocolFolder.Devices = append(protocolFolder.Devices, protocolDevice)
  2283. }
  2284. message.Folders = append(message.Folders, protocolFolder)
  2285. }
  2286. return message, passwords
  2287. }
  2288. func (m *model) State(folder string) (string, time.Time, error) {
  2289. m.mut.RLock()
  2290. runner, ok := m.folderRunners.Get(folder)
  2291. m.mut.RUnlock()
  2292. if !ok {
  2293. // The returned error should be an actual folder error, so returning
  2294. // errors.New("does not exist") or similar here would be
  2295. // inappropriate.
  2296. return "", time.Time{}, nil
  2297. }
  2298. state, changed, err := runner.getState()
  2299. return state.String(), changed, err
  2300. }
  2301. func (m *model) FolderErrors(folder string) ([]FileError, error) {
  2302. m.mut.RLock()
  2303. err := m.checkFolderRunningRLocked(folder)
  2304. runner, _ := m.folderRunners.Get(folder)
  2305. m.mut.RUnlock()
  2306. if err != nil {
  2307. return nil, err
  2308. }
  2309. return runner.Errors(), nil
  2310. }
  2311. func (m *model) WatchError(folder string) error {
  2312. m.mut.RLock()
  2313. err := m.checkFolderRunningRLocked(folder)
  2314. runner, _ := m.folderRunners.Get(folder)
  2315. m.mut.RUnlock()
  2316. if err != nil {
  2317. return nil // If the folder isn't running, there's no error to report.
  2318. }
  2319. return runner.WatchError()
  2320. }
  2321. func (m *model) Override(folder string) {
  2322. // Grab the runner and the file set.
  2323. m.mut.RLock()
  2324. runner, ok := m.folderRunners.Get(folder)
  2325. m.mut.RUnlock()
  2326. if !ok {
  2327. return
  2328. }
  2329. // Run the override, taking updates as if they came from scanning.
  2330. runner.Override()
  2331. }
  2332. func (m *model) Revert(folder string) {
  2333. // Grab the runner and the file set.
  2334. m.mut.RLock()
  2335. runner, ok := m.folderRunners.Get(folder)
  2336. m.mut.RUnlock()
  2337. if !ok {
  2338. return
  2339. }
  2340. // Run the revert, taking updates as if they came from scanning.
  2341. runner.Revert()
  2342. }
  2343. type TreeEntry struct {
  2344. Name string `json:"name"`
  2345. ModTime time.Time `json:"modTime"`
  2346. Size int64 `json:"size"`
  2347. Type string `json:"type"`
  2348. Children []*TreeEntry `json:"children,omitempty"`
  2349. }
  2350. func findByName(slice []*TreeEntry, name string) *TreeEntry {
  2351. for _, child := range slice {
  2352. if child.Name == name {
  2353. return child
  2354. }
  2355. }
  2356. return nil
  2357. }
  2358. func (m *model) GlobalDirectoryTree(folder, prefix string, levels int, dirsOnly bool) ([]*TreeEntry, error) {
  2359. m.mut.RLock()
  2360. _, ok := m.folderCfgs[folder]
  2361. m.mut.RUnlock()
  2362. if !ok {
  2363. return nil, ErrFolderMissing
  2364. }
  2365. root := &TreeEntry{
  2366. Children: make([]*TreeEntry, 0),
  2367. }
  2368. sep := string(filepath.Separator)
  2369. prefix = osutil.NativeFilename(prefix)
  2370. if prefix != "" && !strings.HasSuffix(prefix, sep) {
  2371. prefix = prefix + sep
  2372. }
  2373. for f, err := range itererr.Zip(m.sdb.AllGlobalFilesPrefix(folder, prefix)) {
  2374. if err != nil {
  2375. return nil, err
  2376. }
  2377. // Don't include the prefix itself.
  2378. if f.Invalid || f.Deleted || strings.HasPrefix(prefix, f.Name) {
  2379. continue
  2380. }
  2381. f.Name = strings.Replace(f.Name, prefix, "", 1)
  2382. dir := filepath.Dir(f.Name)
  2383. base := filepath.Base(f.Name)
  2384. if levels > -1 && strings.Count(f.Name, sep) > levels {
  2385. continue
  2386. }
  2387. parent := root
  2388. if dir != "." {
  2389. for _, path := range strings.Split(dir, sep) {
  2390. child := findByName(parent.Children, path)
  2391. if child == nil {
  2392. return nil, fmt.Errorf("could not find child '%s' for path '%s' in parent '%s'", path, f.Name, parent.Name)
  2393. }
  2394. parent = child
  2395. }
  2396. }
  2397. if dirsOnly && !f.IsDirectory() {
  2398. continue
  2399. }
  2400. parent.Children = append(parent.Children, &TreeEntry{
  2401. Name: base,
  2402. Type: f.Type.String(),
  2403. ModTime: f.ModTime(),
  2404. Size: f.Size,
  2405. })
  2406. }
  2407. return root.Children, nil
  2408. }
  2409. func (m *model) GetFolderVersions(folder string) (map[string][]versioner.FileVersion, error) {
  2410. m.mut.RLock()
  2411. err := m.checkFolderRunningRLocked(folder)
  2412. ver := m.folderVersioners[folder]
  2413. m.mut.RUnlock()
  2414. if err != nil {
  2415. return nil, err
  2416. }
  2417. if ver == nil {
  2418. return nil, errNoVersioner
  2419. }
  2420. return ver.GetVersions()
  2421. }
  2422. func (m *model) RestoreFolderVersions(folder string, versions map[string]time.Time) (map[string]error, error) {
  2423. m.mut.RLock()
  2424. err := m.checkFolderRunningRLocked(folder)
  2425. fcfg := m.folderCfgs[folder]
  2426. ver := m.folderVersioners[folder]
  2427. m.mut.RUnlock()
  2428. if err != nil {
  2429. return nil, err
  2430. }
  2431. if ver == nil {
  2432. return nil, errNoVersioner
  2433. }
  2434. restoreErrors := make(map[string]error)
  2435. for file, version := range versions {
  2436. if err := ver.Restore(file, version); err != nil {
  2437. restoreErrors[file] = err
  2438. }
  2439. }
  2440. // Trigger scan
  2441. if !fcfg.FSWatcherEnabled {
  2442. go func() { _ = m.ScanFolder(folder) }()
  2443. }
  2444. return restoreErrors, nil
  2445. }
  2446. func (m *model) Availability(folder string, file protocol.FileInfo, block protocol.BlockInfo) ([]Availability, error) {
  2447. m.mut.RLock()
  2448. defer m.mut.RUnlock()
  2449. cfg, ok := m.folderCfgs[folder]
  2450. if !ok {
  2451. return nil, ErrFolderMissing
  2452. }
  2453. return m.blockAvailabilityRLocked(cfg, file, block), nil
  2454. }
  2455. func (m *model) blockAvailability(cfg config.FolderConfiguration, file protocol.FileInfo, block protocol.BlockInfo) []Availability {
  2456. m.mut.RLock()
  2457. defer m.mut.RUnlock()
  2458. return m.blockAvailabilityRLocked(cfg, file, block)
  2459. }
  2460. func (m *model) blockAvailabilityRLocked(cfg config.FolderConfiguration, file protocol.FileInfo, block protocol.BlockInfo) []Availability {
  2461. var candidates []Availability
  2462. candidates = append(candidates, m.fileAvailabilityRLocked(cfg, file)...)
  2463. candidates = append(candidates, m.blockAvailabilityFromTemporaryRLocked(cfg, file, block)...)
  2464. return candidates
  2465. }
  2466. func (m *model) fileAvailability(cfg config.FolderConfiguration, file protocol.FileInfo) []Availability {
  2467. m.mut.RLock()
  2468. defer m.mut.RUnlock()
  2469. return m.fileAvailabilityRLocked(cfg, file)
  2470. }
  2471. func (m *model) fileAvailabilityRLocked(cfg config.FolderConfiguration, file protocol.FileInfo) []Availability {
  2472. var availabilities []Availability
  2473. devs, err := m.sdb.GetGlobalAvailability(cfg.ID, file.Name)
  2474. if err != nil {
  2475. return nil
  2476. }
  2477. for _, device := range devs {
  2478. if _, ok := m.remoteFolderStates[device]; !ok {
  2479. continue
  2480. }
  2481. if state := m.remoteFolderStates[device][cfg.ID]; state != remoteFolderValid {
  2482. continue
  2483. }
  2484. _, ok := m.deviceConnIDs[device]
  2485. if ok {
  2486. availabilities = append(availabilities, Availability{ID: device, FromTemporary: false})
  2487. }
  2488. }
  2489. return availabilities
  2490. }
  2491. func (m *model) blockAvailabilityFromTemporaryRLocked(cfg config.FolderConfiguration, file protocol.FileInfo, block protocol.BlockInfo) []Availability {
  2492. var availabilities []Availability
  2493. for _, device := range cfg.Devices {
  2494. if m.deviceDownloads[device.DeviceID].Has(cfg.ID, file.Name, file.Version, int(block.Offset/int64(file.BlockSize()))) {
  2495. availabilities = append(availabilities, Availability{ID: device.DeviceID, FromTemporary: true})
  2496. }
  2497. }
  2498. return availabilities
  2499. }
  2500. // BringToFront bumps the given files priority in the job queue.
  2501. func (m *model) BringToFront(folder, file string) {
  2502. m.mut.RLock()
  2503. runner, ok := m.folderRunners.Get(folder)
  2504. m.mut.RUnlock()
  2505. if ok {
  2506. runner.BringToFront(file)
  2507. }
  2508. }
  2509. func (m *model) ResetFolder(folder string) error {
  2510. m.mut.Lock()
  2511. defer m.mut.Unlock()
  2512. _, ok := m.folderRunners.Get(folder)
  2513. if ok {
  2514. return errors.New("folder must be paused when resetting")
  2515. }
  2516. l.Infof("Cleaning metadata for reset folder %q", folder)
  2517. return m.sdb.DropFolder(folder)
  2518. }
  2519. func (m *model) String() string {
  2520. return fmt.Sprintf("model@%p", m)
  2521. }
  2522. func (*model) VerifyConfiguration(from, to config.Configuration) error {
  2523. toFolders := to.FolderMap()
  2524. for _, from := range from.Folders {
  2525. to, ok := toFolders[from.ID]
  2526. if ok && from.Type != to.Type && (from.Type == config.FolderTypeReceiveEncrypted || to.Type == config.FolderTypeReceiveEncrypted) {
  2527. return errors.New("folder type must not be changed from/to receive-encrypted")
  2528. }
  2529. }
  2530. // Verify that any requested versioning is possible to construct, or we
  2531. // will panic later when starting the folder.
  2532. for _, to := range to.Folders {
  2533. if to.Versioning.Type != "" {
  2534. if _, err := versioner.New(to); err != nil {
  2535. return err
  2536. }
  2537. }
  2538. }
  2539. return nil
  2540. }
  2541. func (m *model) CommitConfiguration(from, to config.Configuration) bool {
  2542. // TODO: This should not use reflect, and should take more care to try to handle stuff without restart.
  2543. // Delay processing config changes until after the initial setup
  2544. <-m.started
  2545. // Go through the folder configs and figure out if we need to restart or not.
  2546. // Tracks devices affected by any configuration change to resend ClusterConfig.
  2547. clusterConfigDevices := make(deviceIDSet, len(from.Devices)+len(to.Devices))
  2548. closeDevices := make([]protocol.DeviceID, 0, len(to.Devices))
  2549. fromFolders := mapFolders(from.Folders)
  2550. toFolders := mapFolders(to.Folders)
  2551. for folderID, cfg := range toFolders {
  2552. if _, ok := fromFolders[folderID]; !ok {
  2553. // A folder was added.
  2554. if cfg.Paused {
  2555. l.Infoln("Paused folder", cfg.Description())
  2556. } else {
  2557. l.Infoln("Adding folder", cfg.Description())
  2558. if err := m.newFolder(cfg, to.Options.CacheIgnoredFiles); err != nil {
  2559. m.fatal(err)
  2560. return true
  2561. }
  2562. }
  2563. clusterConfigDevices.add(cfg.DeviceIDs())
  2564. }
  2565. }
  2566. removedFolders := make(map[string]struct{})
  2567. for folderID, fromCfg := range fromFolders {
  2568. toCfg, ok := toFolders[folderID]
  2569. if !ok {
  2570. // The folder was removed.
  2571. m.removeFolder(fromCfg)
  2572. clusterConfigDevices.add(fromCfg.DeviceIDs())
  2573. removedFolders[fromCfg.ID] = struct{}{}
  2574. continue
  2575. }
  2576. if fromCfg.Paused && toCfg.Paused {
  2577. continue
  2578. }
  2579. // This folder exists on both sides. Settings might have changed.
  2580. // Check if anything differs that requires a restart.
  2581. if !reflect.DeepEqual(fromCfg.RequiresRestartOnly(), toCfg.RequiresRestartOnly()) || from.Options.CacheIgnoredFiles != to.Options.CacheIgnoredFiles {
  2582. if err := m.restartFolder(fromCfg, toCfg, to.Options.CacheIgnoredFiles); err != nil {
  2583. m.fatal(err)
  2584. return true
  2585. }
  2586. clusterConfigDevices.add(fromCfg.DeviceIDs())
  2587. if toCfg.Type != config.FolderTypeReceiveEncrypted {
  2588. clusterConfigDevices.add(toCfg.DeviceIDs())
  2589. } else {
  2590. // If we don't have the encryption token yet, we need to drop
  2591. // the connection to make the remote re-send the cluster-config
  2592. // and with it the token.
  2593. m.mut.RLock()
  2594. _, ok := m.folderEncryptionPasswordTokens[toCfg.ID]
  2595. m.mut.RUnlock()
  2596. if !ok {
  2597. closeDevices = append(closeDevices, toCfg.DeviceIDs()...)
  2598. } else {
  2599. clusterConfigDevices.add(toCfg.DeviceIDs())
  2600. }
  2601. }
  2602. }
  2603. // Emit the folder pause/resume event
  2604. if fromCfg.Paused != toCfg.Paused {
  2605. eventType := events.FolderResumed
  2606. if toCfg.Paused {
  2607. eventType = events.FolderPaused
  2608. }
  2609. m.evLogger.Log(eventType, map[string]string{"id": toCfg.ID, "label": toCfg.Label})
  2610. }
  2611. }
  2612. // Pausing a device, unpausing is handled by the connection service.
  2613. fromDevices := from.DeviceMap()
  2614. toDevices := to.DeviceMap()
  2615. for deviceID, toCfg := range toDevices {
  2616. fromCfg, ok := fromDevices[deviceID]
  2617. if !ok {
  2618. sr := stats.NewDeviceStatisticsReference(db.NewTyped(m.sdb, "devicestats/"+deviceID.String()))
  2619. m.mut.Lock()
  2620. m.deviceStatRefs[deviceID] = sr
  2621. m.mut.Unlock()
  2622. continue
  2623. }
  2624. delete(fromDevices, deviceID)
  2625. if fromCfg.Paused == toCfg.Paused {
  2626. continue
  2627. }
  2628. if toCfg.Paused {
  2629. l.Infoln("Pausing", deviceID)
  2630. closeDevices = append(closeDevices, deviceID)
  2631. m.evLogger.Log(events.DevicePaused, map[string]string{"device": deviceID.String()})
  2632. } else {
  2633. // Ignored folder was removed, reconnect to retrigger the prompt.
  2634. if len(fromCfg.IgnoredFolders) > len(toCfg.IgnoredFolders) {
  2635. closeDevices = append(closeDevices, deviceID)
  2636. }
  2637. l.Infoln("Resuming", deviceID)
  2638. m.evLogger.Log(events.DeviceResumed, map[string]string{"device": deviceID.String()})
  2639. }
  2640. if toCfg.MaxRequestKiB != fromCfg.MaxRequestKiB {
  2641. m.mut.Lock()
  2642. m.setConnRequestLimitersLocked(toCfg)
  2643. m.mut.Unlock()
  2644. }
  2645. }
  2646. // Clean up after removed devices
  2647. removedDevices := make([]protocol.DeviceID, 0, len(fromDevices))
  2648. m.mut.Lock()
  2649. for deviceID := range fromDevices {
  2650. delete(m.deviceStatRefs, deviceID)
  2651. removedDevices = append(removedDevices, deviceID)
  2652. delete(clusterConfigDevices, deviceID)
  2653. }
  2654. m.mut.Unlock()
  2655. m.mut.RLock()
  2656. for _, id := range closeDevices {
  2657. delete(clusterConfigDevices, id)
  2658. if conns, ok := m.deviceConnIDs[id]; ok {
  2659. for _, connID := range conns {
  2660. go m.connections[connID].Close(errDevicePaused)
  2661. }
  2662. }
  2663. }
  2664. for _, id := range removedDevices {
  2665. delete(clusterConfigDevices, id)
  2666. if conns, ok := m.deviceConnIDs[id]; ok {
  2667. for _, connID := range conns {
  2668. go m.connections[connID].Close(errDevicePaused)
  2669. }
  2670. }
  2671. }
  2672. m.mut.RUnlock()
  2673. // Generating cluster-configs acquires the mutex.
  2674. m.sendClusterConfig(clusterConfigDevices.AsSlice())
  2675. ignoredDevices := observedDeviceSet(to.IgnoredDevices)
  2676. m.cleanPending(toDevices, toFolders, ignoredDevices, removedFolders)
  2677. m.globalRequestLimiter.SetCapacity(1024 * to.Options.MaxConcurrentIncomingRequestKiB())
  2678. m.folderIOLimiter.SetCapacity(to.Options.MaxFolderConcurrency())
  2679. // Some options don't require restart as those components handle it fine
  2680. // by themselves. Compare the options structs containing only the
  2681. // attributes that require restart and act apprioriately.
  2682. if !reflect.DeepEqual(from.Options.RequiresRestartOnly(), to.Options.RequiresRestartOnly()) {
  2683. l.Debugln(m, "requires restart, options differ")
  2684. return false
  2685. }
  2686. return true
  2687. }
  2688. func (m *model) setConnRequestLimitersLocked(cfg config.DeviceConfiguration) {
  2689. // Touches connRequestLimiters which is protected by the mutex.
  2690. // 0: default, <0: no limiting
  2691. switch {
  2692. case cfg.MaxRequestKiB > 0:
  2693. m.connRequestLimiters[cfg.DeviceID] = semaphore.New(1024 * cfg.MaxRequestKiB)
  2694. case cfg.MaxRequestKiB == 0:
  2695. m.connRequestLimiters[cfg.DeviceID] = semaphore.New(1024 * defaultPullerPendingKiB)
  2696. }
  2697. }
  2698. func (m *model) cleanPending(existingDevices map[protocol.DeviceID]config.DeviceConfiguration, existingFolders map[string]config.FolderConfiguration, ignoredDevices deviceIDSet, removedFolders map[string]struct{}) {
  2699. var removedPendingFolders []map[string]string
  2700. pendingFolders, err := m.observed.PendingFolders()
  2701. if err != nil {
  2702. msg := "Could not iterate through pending folder entries for cleanup"
  2703. l.Warnf("%v: %v", msg, err)
  2704. m.evLogger.Log(events.Failure, msg)
  2705. // Continue with pending devices below, loop is skipped.
  2706. }
  2707. for folderID, pf := range pendingFolders {
  2708. if _, ok := removedFolders[folderID]; ok {
  2709. // Forget pending folder device associations for recently removed
  2710. // folders as well, assuming the folder is no longer of interest
  2711. // at all (but might become pending again).
  2712. l.Debugf("Discarding pending removed folder %v from all devices", folderID)
  2713. if err := m.observed.RemovePendingFolder(folderID); err != nil {
  2714. msg := "Failed to remove pending folder entry"
  2715. l.Warnf("%v (%v): %v", msg, folderID, err)
  2716. m.evLogger.Log(events.Failure, msg)
  2717. } else {
  2718. removedPendingFolders = append(removedPendingFolders, map[string]string{
  2719. "folderID": folderID,
  2720. })
  2721. }
  2722. continue
  2723. }
  2724. for deviceID := range pf.OfferedBy {
  2725. if dev, ok := existingDevices[deviceID]; !ok {
  2726. l.Debugf("Discarding pending folder %v from unknown device %v", folderID, deviceID)
  2727. goto removeFolderForDevice
  2728. } else if dev.IgnoredFolder(folderID) {
  2729. l.Debugf("Discarding now ignored pending folder %v for device %v", folderID, deviceID)
  2730. goto removeFolderForDevice
  2731. }
  2732. if folderCfg, ok := existingFolders[folderID]; ok {
  2733. if folderCfg.SharedWith(deviceID) {
  2734. l.Debugf("Discarding now shared pending folder %v for device %v", folderID, deviceID)
  2735. goto removeFolderForDevice
  2736. }
  2737. }
  2738. continue
  2739. removeFolderForDevice:
  2740. if err := m.observed.RemovePendingFolderForDevice(folderID, deviceID); err != nil {
  2741. msg := "Failed to remove pending folder-device entry"
  2742. l.Warnf("%v (%v, %v): %v", msg, folderID, deviceID, err)
  2743. m.evLogger.Log(events.Failure, msg)
  2744. continue
  2745. }
  2746. removedPendingFolders = append(removedPendingFolders, map[string]string{
  2747. "folderID": folderID,
  2748. "deviceID": deviceID.String(),
  2749. })
  2750. }
  2751. }
  2752. if len(removedPendingFolders) > 0 {
  2753. m.evLogger.Log(events.PendingFoldersChanged, map[string]interface{}{
  2754. "removed": removedPendingFolders,
  2755. })
  2756. }
  2757. var removedPendingDevices []map[string]string
  2758. pendingDevices, err := m.observed.PendingDevices()
  2759. if err != nil {
  2760. msg := "Could not iterate through pending device entries for cleanup"
  2761. l.Warnf("%v: %v", msg, err)
  2762. m.evLogger.Log(events.Failure, msg)
  2763. return
  2764. }
  2765. for deviceID := range pendingDevices {
  2766. if _, ok := ignoredDevices[deviceID]; ok {
  2767. l.Debugf("Discarding now ignored pending device %v", deviceID)
  2768. goto removeDevice
  2769. }
  2770. if _, ok := existingDevices[deviceID]; ok {
  2771. l.Debugf("Discarding now added pending device %v", deviceID)
  2772. goto removeDevice
  2773. }
  2774. continue
  2775. removeDevice:
  2776. if err := m.observed.RemovePendingDevice(deviceID); err != nil {
  2777. msg := "Failed to remove pending device entry"
  2778. l.Warnf("%v: %v", msg, err)
  2779. m.evLogger.Log(events.Failure, msg)
  2780. continue
  2781. }
  2782. removedPendingDevices = append(removedPendingDevices, map[string]string{
  2783. "deviceID": deviceID.String(),
  2784. })
  2785. }
  2786. if len(removedPendingDevices) > 0 {
  2787. m.evLogger.Log(events.PendingDevicesChanged, map[string]interface{}{
  2788. "removed": removedPendingDevices,
  2789. })
  2790. }
  2791. }
  2792. // checkFolderRunningRLocked returns nil if the folder is up and running and a
  2793. // descriptive error if not.
  2794. // Need to hold (read) lock on m.mut when calling this.
  2795. func (m *model) checkFolderRunningRLocked(folder string) error {
  2796. _, ok := m.folderRunners.Get(folder)
  2797. if ok {
  2798. return nil
  2799. }
  2800. if cfg, ok := m.cfg.Folder(folder); !ok {
  2801. return ErrFolderMissing
  2802. } else if cfg.Paused {
  2803. return ErrFolderPaused
  2804. }
  2805. return ErrFolderNotRunning
  2806. }
  2807. // PendingDevices lists unknown devices that tried to connect.
  2808. func (m *model) PendingDevices() (map[protocol.DeviceID]db.ObservedDevice, error) {
  2809. return m.observed.PendingDevices()
  2810. }
  2811. // PendingFolders lists folders that we don't yet share with the offering devices. It
  2812. // returns the entries grouped by folder and filters for a given device unless the
  2813. // argument is specified as EmptyDeviceID.
  2814. func (m *model) PendingFolders(device protocol.DeviceID) (map[string]db.PendingFolder, error) {
  2815. return m.observed.PendingFoldersForDevice(device)
  2816. }
  2817. // DismissPendingDevices removes the record of a specific pending device.
  2818. func (m *model) DismissPendingDevice(device protocol.DeviceID) error {
  2819. l.Debugf("Discarding pending device %v", device)
  2820. err := m.observed.RemovePendingDevice(device)
  2821. if err != nil {
  2822. return err
  2823. }
  2824. removedPendingDevices := []map[string]string{
  2825. {"deviceID": device.String()},
  2826. }
  2827. m.evLogger.Log(events.PendingDevicesChanged, map[string]interface{}{
  2828. "removed": removedPendingDevices,
  2829. })
  2830. return nil
  2831. }
  2832. // DismissPendingFolders removes records of pending folders. Either a specific folder /
  2833. // device combination, or all matching a specific folder ID if the device argument is
  2834. // specified as EmptyDeviceID.
  2835. func (m *model) DismissPendingFolder(device protocol.DeviceID, folder string) error {
  2836. var removedPendingFolders []map[string]string
  2837. if device == protocol.EmptyDeviceID {
  2838. l.Debugf("Discarding pending removed folder %s from all devices", folder)
  2839. err := m.observed.RemovePendingFolder(folder)
  2840. if err != nil {
  2841. return err
  2842. }
  2843. removedPendingFolders = []map[string]string{
  2844. {"folderID": folder},
  2845. }
  2846. } else {
  2847. l.Debugf("Discarding pending folder %s from device %v", folder, device)
  2848. err := m.observed.RemovePendingFolderForDevice(folder, device)
  2849. if err != nil {
  2850. return err
  2851. }
  2852. removedPendingFolders = []map[string]string{
  2853. {
  2854. "folderID": folder,
  2855. "deviceID": device.String(),
  2856. },
  2857. }
  2858. }
  2859. if len(removedPendingFolders) > 0 {
  2860. m.evLogger.Log(events.PendingFoldersChanged, map[string]interface{}{
  2861. "removed": removedPendingFolders,
  2862. })
  2863. }
  2864. return nil
  2865. }
  2866. // mapFolders returns a map of folder ID to folder configuration for the given
  2867. // slice of folder configurations.
  2868. func mapFolders(folders []config.FolderConfiguration) map[string]config.FolderConfiguration {
  2869. m := make(map[string]config.FolderConfiguration, len(folders))
  2870. for _, cfg := range folders {
  2871. m[cfg.ID] = cfg
  2872. }
  2873. return m
  2874. }
  2875. // mapDevices returns a map of device ID to nothing for the given slice of
  2876. // device IDs.
  2877. func mapDevices(devices []protocol.DeviceID) map[protocol.DeviceID]struct{} {
  2878. m := make(map[protocol.DeviceID]struct{}, len(devices))
  2879. for _, dev := range devices {
  2880. m[dev] = struct{}{}
  2881. }
  2882. return m
  2883. }
  2884. func observedDeviceSet(devices []config.ObservedDevice) deviceIDSet {
  2885. res := make(deviceIDSet, len(devices))
  2886. for _, dev := range devices {
  2887. res[dev.ID] = struct{}{}
  2888. }
  2889. return res
  2890. }
  2891. func readOffsetIntoBuf(fs fs.Filesystem, file string, offset int64, buf []byte) (int, error) {
  2892. fd, err := fs.Open(file)
  2893. if err != nil {
  2894. l.Debugln("readOffsetIntoBuf.Open", file, err)
  2895. return 0, err
  2896. }
  2897. defer fd.Close()
  2898. n, err := fd.ReadAt(buf, offset)
  2899. if err != nil {
  2900. l.Debugln("readOffsetIntoBuf.ReadAt", file, err)
  2901. }
  2902. return n, err
  2903. }
  2904. // folderDeviceSet is a set of (folder, deviceID) pairs
  2905. type folderDeviceSet map[string]map[protocol.DeviceID]struct{}
  2906. // set adds the (dev, folder) pair to the set
  2907. func (s folderDeviceSet) set(dev protocol.DeviceID, folder string) {
  2908. devs, ok := s[folder]
  2909. if !ok {
  2910. devs = make(map[protocol.DeviceID]struct{})
  2911. s[folder] = devs
  2912. }
  2913. devs[dev] = struct{}{}
  2914. }
  2915. // has returns true if the (dev, folder) pair is in the set
  2916. func (s folderDeviceSet) has(dev protocol.DeviceID, folder string) bool {
  2917. _, ok := s[folder][dev]
  2918. return ok
  2919. }
  2920. // hasDevice returns true if the device is set on any folder
  2921. func (s folderDeviceSet) hasDevice(dev protocol.DeviceID) bool {
  2922. for _, devices := range s {
  2923. if _, ok := devices[dev]; ok {
  2924. return true
  2925. }
  2926. }
  2927. return false
  2928. }
  2929. // syncMutexMap is a type safe wrapper for a sync.Map that holds mutexes
  2930. type syncMutexMap struct {
  2931. inner stdsync.Map
  2932. }
  2933. func (m *syncMutexMap) Get(key string) sync.Mutex {
  2934. v, _ := m.inner.LoadOrStore(key, sync.NewMutex())
  2935. return v.(sync.Mutex)
  2936. }
  2937. type deviceIDSet map[protocol.DeviceID]struct{}
  2938. func (s deviceIDSet) add(ids []protocol.DeviceID) {
  2939. for _, id := range ids {
  2940. if _, ok := s[id]; !ok {
  2941. s[id] = struct{}{}
  2942. }
  2943. }
  2944. }
  2945. func (s deviceIDSet) AsSlice() []protocol.DeviceID {
  2946. ids := make([]protocol.DeviceID, 0, len(s))
  2947. for id := range s {
  2948. ids = append(ids, id)
  2949. }
  2950. return ids
  2951. }
  2952. func encryptionTokenPath(cfg config.FolderConfiguration) string {
  2953. return filepath.Join(cfg.MarkerName, config.EncryptionTokenName)
  2954. }
  2955. type storedEncryptionToken struct {
  2956. FolderID string
  2957. Token []byte
  2958. }
  2959. func readEncryptionToken(cfg config.FolderConfiguration) ([]byte, error) {
  2960. fd, err := cfg.Filesystem().Open(encryptionTokenPath(cfg))
  2961. if err != nil {
  2962. return nil, err
  2963. }
  2964. defer fd.Close()
  2965. var stored storedEncryptionToken
  2966. if err := json.NewDecoder(fd).Decode(&stored); err != nil {
  2967. return nil, err
  2968. }
  2969. return stored.Token, nil
  2970. }
  2971. func writeEncryptionToken(token []byte, cfg config.FolderConfiguration) error {
  2972. tokenName := encryptionTokenPath(cfg)
  2973. fd, err := cfg.Filesystem().OpenFile(tokenName, fs.OptReadWrite|fs.OptCreate, 0o666)
  2974. if err != nil {
  2975. return err
  2976. }
  2977. defer fd.Close()
  2978. return json.NewEncoder(fd).Encode(storedEncryptionToken{
  2979. FolderID: cfg.ID,
  2980. Token: token,
  2981. })
  2982. }
  2983. func newFolderConfiguration(w config.Wrapper, id, label string, fsType config.FilesystemType, path string) config.FolderConfiguration {
  2984. fcfg := w.DefaultFolder()
  2985. fcfg.ID = id
  2986. fcfg.Label = label
  2987. fcfg.FilesystemType = fsType
  2988. fcfg.Path = path
  2989. return fcfg
  2990. }
  2991. type updatedPendingFolder struct {
  2992. FolderID string `json:"folderID"`
  2993. FolderLabel string `json:"folderLabel"`
  2994. DeviceID protocol.DeviceID `json:"deviceID"`
  2995. ReceiveEncrypted bool `json:"receiveEncrypted"`
  2996. RemoteEncrypted bool `json:"remoteEncrypted"`
  2997. }
  2998. // redactPathError checks if the error is actually a os.PathError, and if yes
  2999. // returns a redactedError with the path removed.
  3000. func redactPathError(err error) (error, bool) {
  3001. perr, ok := err.(*os.PathError)
  3002. if !ok {
  3003. return nil, false
  3004. }
  3005. return &redactedError{
  3006. error: err,
  3007. redacted: fmt.Errorf("%v: %w", perr.Op, perr.Err),
  3008. }, true
  3009. }
  3010. type redactedError struct {
  3011. error
  3012. redacted error
  3013. }
  3014. func without[E comparable, S ~[]E](s S, e E) S {
  3015. for i, x := range s {
  3016. if x == e {
  3017. return append(s[:i], s[i+1:]...)
  3018. }
  3019. }
  3020. return s
  3021. }