model.go 110 KB

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