model.go 109 KB

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