model.go 111 KB

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