model.go 79 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694
  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. package model
  7. import (
  8. "bytes"
  9. "context"
  10. "encoding/json"
  11. "fmt"
  12. "net"
  13. "path/filepath"
  14. "reflect"
  15. "runtime"
  16. "strings"
  17. stdsync "sync"
  18. "time"
  19. "unicode"
  20. "github.com/pkg/errors"
  21. "github.com/thejerf/suture"
  22. "github.com/syncthing/syncthing/lib/config"
  23. "github.com/syncthing/syncthing/lib/connections"
  24. "github.com/syncthing/syncthing/lib/db"
  25. "github.com/syncthing/syncthing/lib/events"
  26. "github.com/syncthing/syncthing/lib/fs"
  27. "github.com/syncthing/syncthing/lib/ignore"
  28. "github.com/syncthing/syncthing/lib/osutil"
  29. "github.com/syncthing/syncthing/lib/protocol"
  30. "github.com/syncthing/syncthing/lib/scanner"
  31. "github.com/syncthing/syncthing/lib/stats"
  32. "github.com/syncthing/syncthing/lib/sync"
  33. "github.com/syncthing/syncthing/lib/util"
  34. "github.com/syncthing/syncthing/lib/versioner"
  35. )
  36. // How many files to send in each Index/IndexUpdate message.
  37. const (
  38. maxBatchSizeBytes = 250 * 1024 // Aim for making index messages no larger than 250 KiB (uncompressed)
  39. maxBatchSizeFiles = 1000 // Either way, don't include more files than this
  40. )
  41. type service interface {
  42. BringToFront(string)
  43. Override()
  44. Revert()
  45. DelayScan(d time.Duration)
  46. SchedulePull() // something relevant changed, we should try a pull
  47. Jobs(page, perpage int) ([]string, []string, int) // In progress, Queued, skipped
  48. Scan(subs []string) error
  49. Serve()
  50. Stop()
  51. Errors() []FileError
  52. WatchError() error
  53. ScheduleForceRescan(path string)
  54. GetStatistics() (stats.FolderStatistics, error)
  55. getState() (folderState, time.Time, error)
  56. }
  57. type Availability struct {
  58. ID protocol.DeviceID `json:"id"`
  59. FromTemporary bool `json:"fromTemporary"`
  60. }
  61. type Model interface {
  62. suture.Service
  63. connections.Model
  64. ResetFolder(folder string)
  65. DelayScan(folder string, next time.Duration)
  66. ScanFolder(folder string) error
  67. ScanFolders() map[string]error
  68. ScanFolderSubdirs(folder string, subs []string) error
  69. State(folder string) (string, time.Time, error)
  70. FolderErrors(folder string) ([]FileError, error)
  71. WatchError(folder string) error
  72. Override(folder string)
  73. Revert(folder string)
  74. BringToFront(folder, file string)
  75. GetIgnores(folder string) ([]string, []string, error)
  76. SetIgnores(folder string, content []string) error
  77. GetFolderVersions(folder string) (map[string][]versioner.FileVersion, error)
  78. RestoreFolderVersions(folder string, versions map[string]time.Time) (map[string]string, error)
  79. DBSnapshot(folder string) (*db.Snapshot, error)
  80. NeedFolderFiles(folder string, page, perpage int) ([]db.FileInfoTruncated, []db.FileInfoTruncated, []db.FileInfoTruncated)
  81. FolderProgressBytesCompleted(folder string) int64
  82. CurrentFolderFile(folder string, file string) (protocol.FileInfo, bool)
  83. CurrentGlobalFile(folder string, file string) (protocol.FileInfo, bool)
  84. Availability(folder string, file protocol.FileInfo, block protocol.BlockInfo) []Availability
  85. Completion(device protocol.DeviceID, folder string) FolderCompletion
  86. ConnectionStats() map[string]interface{}
  87. DeviceStatistics() (map[string]stats.DeviceStatistics, error)
  88. FolderStatistics() (map[string]stats.FolderStatistics, error)
  89. UsageReportingStats(version int, preview bool) map[string]interface{}
  90. StartDeadlockDetector(timeout time.Duration)
  91. GlobalDirectoryTree(folder, prefix string, levels int, dirsonly bool) map[string]interface{}
  92. }
  93. type model struct {
  94. *suture.Supervisor
  95. // constructor parameters
  96. cfg config.Wrapper
  97. id protocol.DeviceID
  98. clientName string
  99. clientVersion string
  100. db *db.Lowlevel
  101. protectedFiles []string
  102. evLogger events.Logger
  103. // constant or concurrency safe fields
  104. finder *db.BlockFinder
  105. progressEmitter *ProgressEmitter
  106. shortID protocol.ShortID
  107. cacheIgnoredFiles bool
  108. // globalRequestLimiter limits the amount of data in concurrent incoming
  109. // requests
  110. globalRequestLimiter *byteSemaphore
  111. // folderIOLimiter limits the number of concurrent I/O heavy operations,
  112. // such as scans and pulls.
  113. folderIOLimiter *byteSemaphore
  114. // fields protected by fmut
  115. fmut sync.RWMutex
  116. folderCfgs map[string]config.FolderConfiguration // folder -> cfg
  117. folderFiles map[string]*db.FileSet // folder -> files
  118. deviceStatRefs map[protocol.DeviceID]*stats.DeviceStatisticsReference // deviceID -> statsRef
  119. folderIgnores map[string]*ignore.Matcher // folder -> matcher object
  120. folderRunners map[string]service // folder -> puller or scanner
  121. folderRunnerTokens map[string][]suture.ServiceToken // folder -> tokens for puller or scanner
  122. folderRestartMuts syncMutexMap // folder -> restart mutex
  123. folderVersioners map[string]versioner.Versioner // folder -> versioner (may be nil)
  124. // fields protected by pmut
  125. pmut sync.RWMutex
  126. conn map[protocol.DeviceID]connections.Connection
  127. connRequestLimiters map[protocol.DeviceID]*byteSemaphore
  128. closed map[protocol.DeviceID]chan struct{}
  129. helloMessages map[protocol.DeviceID]protocol.HelloResult
  130. deviceDownloads map[protocol.DeviceID]*deviceDownloadState
  131. remotePausedFolders map[protocol.DeviceID][]string // deviceID -> folders
  132. foldersRunning int32 // for testing only
  133. }
  134. type folderFactory func(*model, *db.FileSet, *ignore.Matcher, config.FolderConfiguration, versioner.Versioner, fs.Filesystem, events.Logger, *byteSemaphore) service
  135. var (
  136. folderFactories = make(map[config.FolderType]folderFactory)
  137. )
  138. var (
  139. errDeviceUnknown = errors.New("unknown device")
  140. errDevicePaused = errors.New("device is paused")
  141. errDeviceIgnored = errors.New("device is ignored")
  142. ErrFolderPaused = errors.New("folder is paused")
  143. errFolderNotRunning = errors.New("folder is not running")
  144. errFolderMissing = errors.New("no such folder")
  145. errNetworkNotAllowed = errors.New("network not allowed")
  146. errNoVersioner = errors.New("folder has no versioner")
  147. // errors about why a connection is closed
  148. errIgnoredFolderRemoved = errors.New("folder no longer ignored")
  149. errReplacingConnection = errors.New("replacing connection")
  150. errStopped = errors.New("Syncthing is being stopped")
  151. )
  152. // NewModel creates and starts a new model. The model starts in read-only mode,
  153. // where it sends index information to connected peers and responds to requests
  154. // for file data without altering the local folder in any way.
  155. func NewModel(cfg config.Wrapper, id protocol.DeviceID, clientName, clientVersion string, ldb *db.Lowlevel, protectedFiles []string, evLogger events.Logger) Model {
  156. m := &model{
  157. Supervisor: suture.New("model", suture.Spec{
  158. Log: func(line string) {
  159. l.Debugln(line)
  160. },
  161. PassThroughPanics: true,
  162. }),
  163. // constructor parameters
  164. cfg: cfg,
  165. id: id,
  166. clientName: clientName,
  167. clientVersion: clientVersion,
  168. db: ldb,
  169. protectedFiles: protectedFiles,
  170. evLogger: evLogger,
  171. // constant or concurrency safe fields
  172. finder: db.NewBlockFinder(ldb),
  173. progressEmitter: NewProgressEmitter(cfg, evLogger),
  174. shortID: id.Short(),
  175. cacheIgnoredFiles: cfg.Options().CacheIgnoredFiles,
  176. globalRequestLimiter: newByteSemaphore(1024 * cfg.Options().MaxConcurrentIncomingRequestKiB()),
  177. folderIOLimiter: newByteSemaphore(cfg.Options().MaxFolderConcurrency()),
  178. // fields protected by fmut
  179. fmut: sync.NewRWMutex(),
  180. folderCfgs: make(map[string]config.FolderConfiguration),
  181. folderFiles: make(map[string]*db.FileSet),
  182. deviceStatRefs: make(map[protocol.DeviceID]*stats.DeviceStatisticsReference),
  183. folderIgnores: make(map[string]*ignore.Matcher),
  184. folderRunners: make(map[string]service),
  185. folderRunnerTokens: make(map[string][]suture.ServiceToken),
  186. folderVersioners: make(map[string]versioner.Versioner),
  187. // fields protected by pmut
  188. pmut: sync.NewRWMutex(),
  189. conn: make(map[protocol.DeviceID]connections.Connection),
  190. connRequestLimiters: make(map[protocol.DeviceID]*byteSemaphore),
  191. closed: make(map[protocol.DeviceID]chan struct{}),
  192. helloMessages: make(map[protocol.DeviceID]protocol.HelloResult),
  193. deviceDownloads: make(map[protocol.DeviceID]*deviceDownloadState),
  194. remotePausedFolders: make(map[protocol.DeviceID][]string),
  195. }
  196. for devID := range cfg.Devices() {
  197. m.deviceStatRefs[devID] = stats.NewDeviceStatisticsReference(m.db, devID.String())
  198. }
  199. m.Add(m.progressEmitter)
  200. return m
  201. }
  202. func (m *model) Serve() {
  203. m.onServe()
  204. m.Supervisor.Serve()
  205. }
  206. func (m *model) ServeBackground() {
  207. m.onServe()
  208. m.Supervisor.ServeBackground()
  209. }
  210. func (m *model) onServe() {
  211. // Add and start folders
  212. for _, folderCfg := range m.cfg.Folders() {
  213. if folderCfg.Paused {
  214. folderCfg.CreateRoot()
  215. continue
  216. }
  217. m.newFolder(folderCfg)
  218. }
  219. m.cfg.Subscribe(m)
  220. }
  221. func (m *model) Stop() {
  222. m.cfg.Unsubscribe(m)
  223. m.Supervisor.Stop()
  224. devs := m.cfg.Devices()
  225. ids := make([]protocol.DeviceID, 0, len(devs))
  226. for id := range devs {
  227. ids = append(ids, id)
  228. }
  229. w := m.closeConns(ids, errStopped)
  230. w.Wait()
  231. }
  232. // StartDeadlockDetector starts a deadlock detector on the models locks which
  233. // causes panics in case the locks cannot be acquired in the given timeout
  234. // period.
  235. func (m *model) StartDeadlockDetector(timeout time.Duration) {
  236. l.Infof("Starting deadlock detector with %v timeout", timeout)
  237. detector := newDeadlockDetector(timeout)
  238. detector.Watch("fmut", m.fmut)
  239. detector.Watch("pmut", m.pmut)
  240. }
  241. // Need to hold lock on m.fmut when calling this.
  242. func (m *model) addAndStartFolderLocked(cfg config.FolderConfiguration, fset *db.FileSet) {
  243. ignores := ignore.New(cfg.Filesystem(), ignore.WithCache(m.cacheIgnoredFiles))
  244. if err := ignores.Load(".stignore"); err != nil && !fs.IsNotExist(err) {
  245. l.Warnln("Loading ignores:", err)
  246. }
  247. m.addAndStartFolderLockedWithIgnores(cfg, fset, ignores)
  248. }
  249. // Only needed for testing, use addAndStartFolderLocked instead.
  250. func (m *model) addAndStartFolderLockedWithIgnores(cfg config.FolderConfiguration, fset *db.FileSet, ignores *ignore.Matcher) {
  251. m.folderCfgs[cfg.ID] = cfg
  252. m.folderFiles[cfg.ID] = fset
  253. m.folderIgnores[cfg.ID] = ignores
  254. _, ok := m.folderRunners[cfg.ID]
  255. if ok {
  256. l.Warnln("Cannot start already running folder", cfg.Description())
  257. panic("cannot start already running folder")
  258. }
  259. folderFactory, ok := folderFactories[cfg.Type]
  260. if !ok {
  261. panic(fmt.Sprintf("unknown folder type 0x%x", cfg.Type))
  262. }
  263. folder := cfg.ID
  264. // Find any devices for which we hold the index in the db, but the folder
  265. // is not shared, and drop it.
  266. expected := mapDevices(cfg.DeviceIDs())
  267. for _, available := range fset.ListDevices() {
  268. if _, ok := expected[available]; !ok {
  269. l.Debugln("dropping", folder, "state for", available)
  270. fset.Drop(available)
  271. }
  272. }
  273. v, ok := fset.Sequence(protocol.LocalDeviceID), true
  274. indexHasFiles := ok && v > 0
  275. if !indexHasFiles {
  276. // It's a blank folder, so this may the first time we're looking at
  277. // it. Attempt to create and tag with our marker as appropriate. We
  278. // don't really do anything with errors at this point except warn -
  279. // if these things don't work, we still want to start the folder and
  280. // it'll show up as errored later.
  281. if err := cfg.CreateRoot(); err != nil {
  282. l.Warnln("Failed to create folder root directory", err)
  283. } else if err = cfg.CreateMarker(); err != nil {
  284. l.Warnln("Failed to create folder marker:", err)
  285. }
  286. }
  287. ffs := fset.MtimeFS()
  288. // These are our metadata files, and they should always be hidden.
  289. _ = ffs.Hide(config.DefaultMarkerName)
  290. _ = ffs.Hide(".stversions")
  291. _ = ffs.Hide(".stignore")
  292. var ver versioner.Versioner
  293. if cfg.Versioning.Type != "" {
  294. var err error
  295. ver, err = versioner.New(ffs, cfg.Versioning)
  296. if err != nil {
  297. panic(fmt.Errorf("creating versioner: %w", err))
  298. }
  299. if service, ok := ver.(suture.Service); ok {
  300. // The versioner implements the suture.Service interface, so
  301. // expects to be run in the background in addition to being called
  302. // when files are going to be archived.
  303. token := m.Add(service)
  304. m.folderRunnerTokens[folder] = append(m.folderRunnerTokens[folder], token)
  305. }
  306. }
  307. m.folderVersioners[folder] = ver
  308. p := folderFactory(m, fset, ignores, cfg, ver, ffs, m.evLogger, m.folderIOLimiter)
  309. m.folderRunners[folder] = p
  310. m.warnAboutOverwritingProtectedFiles(cfg, ignores)
  311. token := m.Add(p)
  312. m.folderRunnerTokens[folder] = append(m.folderRunnerTokens[folder], token)
  313. l.Infof("Ready to synchronize %s (%s)", cfg.Description(), cfg.Type)
  314. }
  315. func (m *model) warnAboutOverwritingProtectedFiles(cfg config.FolderConfiguration, ignores *ignore.Matcher) {
  316. if cfg.Type == config.FolderTypeSendOnly {
  317. return
  318. }
  319. // This is a bit of a hack.
  320. ffs := cfg.Filesystem()
  321. if ffs.Type() != fs.FilesystemTypeBasic {
  322. return
  323. }
  324. folderLocation := ffs.URI()
  325. var filesAtRisk []string
  326. for _, protectedFilePath := range m.protectedFiles {
  327. // check if file is synced in this folder
  328. if protectedFilePath != folderLocation && !fs.IsParent(protectedFilePath, folderLocation) {
  329. continue
  330. }
  331. // check if file is ignored
  332. relPath, _ := filepath.Rel(folderLocation, protectedFilePath)
  333. if ignores.Match(relPath).IsIgnored() {
  334. continue
  335. }
  336. filesAtRisk = append(filesAtRisk, protectedFilePath)
  337. }
  338. if len(filesAtRisk) > 0 {
  339. 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, ", "))
  340. }
  341. }
  342. func (m *model) removeFolder(cfg config.FolderConfiguration) {
  343. m.stopFolder(cfg, fmt.Errorf("removing folder %v", cfg.Description()))
  344. m.fmut.Lock()
  345. isPathUnique := true
  346. for folderID, folderCfg := range m.folderCfgs {
  347. if folderID != cfg.ID && folderCfg.Path == cfg.Path {
  348. isPathUnique = false
  349. break
  350. }
  351. }
  352. if isPathUnique {
  353. // Delete syncthing specific files
  354. cfg.Filesystem().RemoveAll(config.DefaultMarkerName)
  355. }
  356. m.cleanupFolderLocked(cfg)
  357. m.fmut.Unlock()
  358. // Remove it from the database
  359. db.DropFolder(m.db, cfg.ID)
  360. }
  361. func (m *model) stopFolder(cfg config.FolderConfiguration, err error) {
  362. // Stop the services running for this folder and wait for them to finish
  363. // stopping to prevent races on restart.
  364. m.fmut.RLock()
  365. tokens := m.folderRunnerTokens[cfg.ID]
  366. m.fmut.RUnlock()
  367. for _, id := range tokens {
  368. m.RemoveAndWait(id, 0)
  369. }
  370. // Wait for connections to stop to ensure that no more calls to methods
  371. // expecting this folder to exist happen (e.g. .IndexUpdate).
  372. m.closeConns(cfg.DeviceIDs(), err).Wait()
  373. }
  374. // Need to hold lock on m.fmut when calling this.
  375. func (m *model) cleanupFolderLocked(cfg config.FolderConfiguration) {
  376. // Clean up our config maps
  377. delete(m.folderCfgs, cfg.ID)
  378. delete(m.folderFiles, cfg.ID)
  379. delete(m.folderIgnores, cfg.ID)
  380. delete(m.folderRunners, cfg.ID)
  381. delete(m.folderRunnerTokens, cfg.ID)
  382. delete(m.folderVersioners, cfg.ID)
  383. }
  384. func (m *model) restartFolder(from, to config.FolderConfiguration) {
  385. if len(to.ID) == 0 {
  386. panic("bug: cannot restart empty folder ID")
  387. }
  388. if to.ID != from.ID {
  389. l.Warnf("bug: folder restart cannot change ID %q -> %q", from.ID, to.ID)
  390. panic("bug: folder restart cannot change ID")
  391. }
  392. // This mutex protects the entirety of the restart operation, preventing
  393. // there from being more than one folder restart operation in progress
  394. // at any given time. The usual fmut/pmut stuff doesn't cover this,
  395. // because those locks are released while we are waiting for the folder
  396. // to shut down (and must be so because the folder might need them as
  397. // part of its operations before shutting down).
  398. restartMut := m.folderRestartMuts.Get(to.ID)
  399. restartMut.Lock()
  400. defer restartMut.Unlock()
  401. var infoMsg string
  402. var errMsg string
  403. switch {
  404. case to.Paused:
  405. infoMsg = "Paused"
  406. errMsg = "pausing"
  407. case from.Paused:
  408. infoMsg = "Unpaused"
  409. errMsg = "unpausing"
  410. default:
  411. infoMsg = "Restarted"
  412. errMsg = "restarting"
  413. }
  414. var fset *db.FileSet
  415. if !to.Paused {
  416. // Creating the fileset can take a long time (metadata calculation)
  417. // so we do it outside of the lock.
  418. fset = db.NewFileSet(to.ID, to.Filesystem(), m.db)
  419. }
  420. m.stopFolder(from, fmt.Errorf("%v folder %v", errMsg, to.Description()))
  421. m.fmut.Lock()
  422. defer m.fmut.Unlock()
  423. m.cleanupFolderLocked(from)
  424. if !to.Paused {
  425. m.addAndStartFolderLocked(to, fset)
  426. }
  427. l.Infof("%v folder %v (%v)", infoMsg, to.Description(), to.Type)
  428. }
  429. func (m *model) newFolder(cfg config.FolderConfiguration) {
  430. // Creating the fileset can take a long time (metadata calculation) so
  431. // we do it outside of the lock.
  432. fset := db.NewFileSet(cfg.ID, cfg.Filesystem(), m.db)
  433. // Close connections to affected devices
  434. m.closeConns(cfg.DeviceIDs(), fmt.Errorf("started folder %v", cfg.Description()))
  435. m.fmut.Lock()
  436. defer m.fmut.Unlock()
  437. m.addAndStartFolderLocked(cfg, fset)
  438. }
  439. func (m *model) UsageReportingStats(version int, preview bool) map[string]interface{} {
  440. stats := make(map[string]interface{})
  441. if version >= 3 {
  442. // Block stats
  443. blockStatsMut.Lock()
  444. copyBlockStats := make(map[string]int)
  445. for k, v := range blockStats {
  446. copyBlockStats[k] = v
  447. if !preview {
  448. blockStats[k] = 0
  449. }
  450. }
  451. blockStatsMut.Unlock()
  452. stats["blockStats"] = copyBlockStats
  453. // Transport stats
  454. m.pmut.RLock()
  455. transportStats := make(map[string]int)
  456. for _, conn := range m.conn {
  457. transportStats[conn.Transport()]++
  458. }
  459. m.pmut.RUnlock()
  460. stats["transportStats"] = transportStats
  461. // Ignore stats
  462. ignoreStats := map[string]int{
  463. "lines": 0,
  464. "inverts": 0,
  465. "folded": 0,
  466. "deletable": 0,
  467. "rooted": 0,
  468. "includes": 0,
  469. "escapedIncludes": 0,
  470. "doubleStars": 0,
  471. "stars": 0,
  472. }
  473. var seenPrefix [3]bool
  474. for folder := range m.cfg.Folders() {
  475. lines, _, err := m.GetIgnores(folder)
  476. if err != nil {
  477. continue
  478. }
  479. ignoreStats["lines"] += len(lines)
  480. for _, line := range lines {
  481. // Allow prefixes to be specified in any order, but only once.
  482. for {
  483. if strings.HasPrefix(line, "!") && !seenPrefix[0] {
  484. seenPrefix[0] = true
  485. line = line[1:]
  486. ignoreStats["inverts"] += 1
  487. } else if strings.HasPrefix(line, "(?i)") && !seenPrefix[1] {
  488. seenPrefix[1] = true
  489. line = line[4:]
  490. ignoreStats["folded"] += 1
  491. } else if strings.HasPrefix(line, "(?d)") && !seenPrefix[2] {
  492. seenPrefix[2] = true
  493. line = line[4:]
  494. ignoreStats["deletable"] += 1
  495. } else {
  496. seenPrefix[0] = false
  497. seenPrefix[1] = false
  498. seenPrefix[2] = false
  499. break
  500. }
  501. }
  502. // Noops, remove
  503. line = strings.TrimSuffix(line, "**")
  504. line = strings.TrimPrefix(line, "**/")
  505. if strings.HasPrefix(line, "/") {
  506. ignoreStats["rooted"] += 1
  507. } else if strings.HasPrefix(line, "#include ") {
  508. ignoreStats["includes"] += 1
  509. if strings.Contains(line, "..") {
  510. ignoreStats["escapedIncludes"] += 1
  511. }
  512. }
  513. if strings.Contains(line, "**") {
  514. ignoreStats["doubleStars"] += 1
  515. // Remove not to trip up star checks.
  516. line = strings.Replace(line, "**", "", -1)
  517. }
  518. if strings.Contains(line, "*") {
  519. ignoreStats["stars"] += 1
  520. }
  521. }
  522. }
  523. stats["ignoreStats"] = ignoreStats
  524. }
  525. return stats
  526. }
  527. type ConnectionInfo struct {
  528. protocol.Statistics
  529. Connected bool
  530. Paused bool
  531. Address string
  532. ClientVersion string
  533. Type string
  534. Crypto string
  535. }
  536. func (info ConnectionInfo) MarshalJSON() ([]byte, error) {
  537. return json.Marshal(map[string]interface{}{
  538. "at": info.At,
  539. "inBytesTotal": info.InBytesTotal,
  540. "outBytesTotal": info.OutBytesTotal,
  541. "connected": info.Connected,
  542. "paused": info.Paused,
  543. "address": info.Address,
  544. "clientVersion": info.ClientVersion,
  545. "type": info.Type,
  546. "crypto": info.Crypto,
  547. })
  548. }
  549. // ConnectionStats returns a map with connection statistics for each device.
  550. func (m *model) ConnectionStats() map[string]interface{} {
  551. m.pmut.RLock()
  552. defer m.pmut.RUnlock()
  553. res := make(map[string]interface{})
  554. devs := m.cfg.Devices()
  555. conns := make(map[string]ConnectionInfo, len(devs))
  556. for device, deviceCfg := range devs {
  557. hello := m.helloMessages[device]
  558. versionString := hello.ClientVersion
  559. if hello.ClientName != "syncthing" {
  560. versionString = hello.ClientName + " " + hello.ClientVersion
  561. }
  562. ci := ConnectionInfo{
  563. ClientVersion: strings.TrimSpace(versionString),
  564. Paused: deviceCfg.Paused,
  565. }
  566. if conn, ok := m.conn[device]; ok {
  567. ci.Type = conn.Type()
  568. ci.Crypto = conn.Crypto()
  569. ci.Connected = ok
  570. ci.Statistics = conn.Statistics()
  571. if addr := conn.RemoteAddr(); addr != nil {
  572. ci.Address = addr.String()
  573. }
  574. }
  575. conns[device.String()] = ci
  576. }
  577. res["connections"] = conns
  578. in, out := protocol.TotalInOut()
  579. res["total"] = ConnectionInfo{
  580. Statistics: protocol.Statistics{
  581. At: time.Now(),
  582. InBytesTotal: in,
  583. OutBytesTotal: out,
  584. },
  585. }
  586. return res
  587. }
  588. // DeviceStatistics returns statistics about each device
  589. func (m *model) DeviceStatistics() (map[string]stats.DeviceStatistics, error) {
  590. m.fmut.RLock()
  591. defer m.fmut.RUnlock()
  592. res := make(map[string]stats.DeviceStatistics, len(m.deviceStatRefs))
  593. for id, sr := range m.deviceStatRefs {
  594. stats, err := sr.GetStatistics()
  595. if err != nil {
  596. return nil, err
  597. }
  598. res[id.String()] = stats
  599. }
  600. return res, nil
  601. }
  602. // FolderStatistics returns statistics about each folder
  603. func (m *model) FolderStatistics() (map[string]stats.FolderStatistics, error) {
  604. res := make(map[string]stats.FolderStatistics)
  605. m.fmut.RLock()
  606. defer m.fmut.RUnlock()
  607. for id, runner := range m.folderRunners {
  608. stats, err := runner.GetStatistics()
  609. if err != nil {
  610. return nil, err
  611. }
  612. res[id] = stats
  613. }
  614. return res, nil
  615. }
  616. type FolderCompletion struct {
  617. CompletionPct float64
  618. NeedBytes int64
  619. NeedItems int64
  620. GlobalBytes int64
  621. NeedDeletes int64
  622. }
  623. // Map returns the members as a map, e.g. used in api to serialize as Json.
  624. func (comp FolderCompletion) Map() map[string]interface{} {
  625. return map[string]interface{}{
  626. "completion": comp.CompletionPct,
  627. "needBytes": comp.NeedBytes,
  628. "needItems": comp.NeedItems,
  629. "globalBytes": comp.GlobalBytes,
  630. "needDeletes": comp.NeedDeletes,
  631. }
  632. }
  633. // Completion returns the completion status, in percent, for the given device
  634. // and folder.
  635. func (m *model) Completion(device protocol.DeviceID, folder string) FolderCompletion {
  636. m.fmut.RLock()
  637. rf, ok := m.folderFiles[folder]
  638. m.fmut.RUnlock()
  639. if !ok {
  640. return FolderCompletion{} // Folder doesn't exist, so we hardly have any of it
  641. }
  642. snap := rf.Snapshot()
  643. defer snap.Release()
  644. tot := snap.GlobalSize().Bytes
  645. if tot == 0 {
  646. // Folder is empty, so we have all of it
  647. return FolderCompletion{
  648. CompletionPct: 100,
  649. }
  650. }
  651. m.pmut.RLock()
  652. counts := m.deviceDownloads[device].GetBlockCounts(folder)
  653. m.pmut.RUnlock()
  654. var need, items, fileNeed, downloaded, deletes int64
  655. snap.WithNeedTruncated(device, func(f db.FileIntf) bool {
  656. ft := f.(db.FileInfoTruncated)
  657. // If the file is deleted, we account it only in the deleted column.
  658. if ft.Deleted {
  659. deletes++
  660. return true
  661. }
  662. // This might might be more than it really is, because some blocks can be of a smaller size.
  663. downloaded = int64(counts[ft.Name]) * int64(ft.BlockSize())
  664. fileNeed = ft.FileSize() - downloaded
  665. if fileNeed < 0 {
  666. fileNeed = 0
  667. }
  668. need += fileNeed
  669. items++
  670. return true
  671. })
  672. needRatio := float64(need) / float64(tot)
  673. completionPct := 100 * (1 - needRatio)
  674. // If the completion is 100% but there are deletes we need to handle,
  675. // drop it down a notch. Hack for consumers that look only at the
  676. // percentage (our own GUI does the same calculation as here on its own
  677. // and needs the same fixup).
  678. if need == 0 && deletes > 0 {
  679. completionPct = 95 // chosen by fair dice roll
  680. }
  681. l.Debugf("%v Completion(%s, %q): %f (%d / %d = %f)", m, device, folder, completionPct, need, tot, needRatio)
  682. return FolderCompletion{
  683. CompletionPct: completionPct,
  684. NeedBytes: need,
  685. NeedItems: items,
  686. GlobalBytes: tot,
  687. NeedDeletes: deletes,
  688. }
  689. }
  690. // DBSnapshot returns a snapshot of the database content relevant to the given folder.
  691. func (m *model) DBSnapshot(folder string) (*db.Snapshot, error) {
  692. m.fmut.RLock()
  693. err := m.checkFolderRunningLocked(folder)
  694. rf := m.folderFiles[folder]
  695. m.fmut.RUnlock()
  696. if err != nil {
  697. return nil, err
  698. }
  699. return rf.Snapshot(), nil
  700. }
  701. func (m *model) FolderProgressBytesCompleted(folder string) int64 {
  702. return m.progressEmitter.BytesCompleted(folder)
  703. }
  704. // NeedFolderFiles returns paginated list of currently needed files in
  705. // progress, queued, and to be queued on next puller iteration.
  706. func (m *model) NeedFolderFiles(folder string, page, perpage int) ([]db.FileInfoTruncated, []db.FileInfoTruncated, []db.FileInfoTruncated) {
  707. m.fmut.RLock()
  708. rf, rfOk := m.folderFiles[folder]
  709. runner, runnerOk := m.folderRunners[folder]
  710. cfg := m.folderCfgs[folder]
  711. m.fmut.RUnlock()
  712. if !rfOk {
  713. return nil, nil, nil
  714. }
  715. snap := rf.Snapshot()
  716. defer snap.Release()
  717. var progress, queued, rest []db.FileInfoTruncated
  718. var seen map[string]struct{}
  719. skip := (page - 1) * perpage
  720. get := perpage
  721. if runnerOk {
  722. progressNames, queuedNames, skipped := runner.Jobs(page, perpage)
  723. progress = make([]db.FileInfoTruncated, len(progressNames))
  724. queued = make([]db.FileInfoTruncated, len(queuedNames))
  725. seen = make(map[string]struct{}, len(progressNames)+len(queuedNames))
  726. for i, name := range progressNames {
  727. if f, ok := snap.GetGlobalTruncated(name); ok {
  728. progress[i] = f
  729. seen[name] = struct{}{}
  730. }
  731. }
  732. for i, name := range queuedNames {
  733. if f, ok := snap.GetGlobalTruncated(name); ok {
  734. queued[i] = f
  735. seen[name] = struct{}{}
  736. }
  737. }
  738. get -= len(seen)
  739. if get == 0 {
  740. return progress, queued, nil
  741. }
  742. skip -= skipped
  743. }
  744. rest = make([]db.FileInfoTruncated, 0, perpage)
  745. snap.WithNeedTruncated(protocol.LocalDeviceID, func(f db.FileIntf) bool {
  746. if cfg.IgnoreDelete && f.IsDeleted() {
  747. return true
  748. }
  749. if skip > 0 {
  750. skip--
  751. return true
  752. }
  753. ft := f.(db.FileInfoTruncated)
  754. if _, ok := seen[ft.Name]; !ok {
  755. rest = append(rest, ft)
  756. get--
  757. }
  758. return get > 0
  759. })
  760. return progress, queued, rest
  761. }
  762. // Index is called when a new device is connected and we receive their full index.
  763. // Implements the protocol.Model interface.
  764. func (m *model) Index(deviceID protocol.DeviceID, folder string, fs []protocol.FileInfo) error {
  765. return m.handleIndex(deviceID, folder, fs, false)
  766. }
  767. // IndexUpdate is called for incremental updates to connected devices' indexes.
  768. // Implements the protocol.Model interface.
  769. func (m *model) IndexUpdate(deviceID protocol.DeviceID, folder string, fs []protocol.FileInfo) error {
  770. return m.handleIndex(deviceID, folder, fs, true)
  771. }
  772. func (m *model) handleIndex(deviceID protocol.DeviceID, folder string, fs []protocol.FileInfo, update bool) error {
  773. op := "Index"
  774. if update {
  775. op += " update"
  776. }
  777. l.Debugf("%v (in): %s / %q: %d files", op, deviceID, folder, len(fs))
  778. if cfg, ok := m.cfg.Folder(folder); !ok || !cfg.SharedWith(deviceID) {
  779. l.Infof("%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)
  780. return errors.Wrap(errFolderMissing, folder)
  781. } else if cfg.Paused {
  782. l.Debugf("%v for paused folder (ID %q) sent from device %q.", op, folder, deviceID)
  783. return errors.Wrap(ErrFolderPaused, folder)
  784. }
  785. m.fmut.RLock()
  786. files, existing := m.folderFiles[folder]
  787. runner, running := m.folderRunners[folder]
  788. m.fmut.RUnlock()
  789. if !existing {
  790. l.Infof("%v for nonexistent folder %q", op, folder)
  791. return errors.Wrap(errFolderMissing, folder)
  792. }
  793. if running {
  794. defer runner.SchedulePull()
  795. }
  796. m.pmut.RLock()
  797. downloads := m.deviceDownloads[deviceID]
  798. m.pmut.RUnlock()
  799. downloads.Update(folder, makeForgetUpdate(fs))
  800. if !update {
  801. files.Drop(deviceID)
  802. }
  803. for i := range fs {
  804. // The local attributes should never be transmitted over the wire.
  805. // Make sure they look like they weren't.
  806. fs[i].LocalFlags = 0
  807. }
  808. files.Update(deviceID, fs)
  809. m.evLogger.Log(events.RemoteIndexUpdated, map[string]interface{}{
  810. "device": deviceID.String(),
  811. "folder": folder,
  812. "items": len(fs),
  813. "version": files.Sequence(deviceID),
  814. })
  815. return nil
  816. }
  817. func (m *model) ClusterConfig(deviceID protocol.DeviceID, cm protocol.ClusterConfig) error {
  818. // Check the peer device's announced folders against our own. Emits events
  819. // for folders that we don't expect (unknown or not shared).
  820. // Also, collect a list of folders we do share, and if he's interested in
  821. // temporary indexes, subscribe the connection.
  822. tempIndexFolders := make([]string, 0, len(cm.Folders))
  823. m.pmut.RLock()
  824. conn, ok := m.conn[deviceID]
  825. closed := m.closed[deviceID]
  826. m.pmut.RUnlock()
  827. if !ok {
  828. panic("bug: ClusterConfig called on closed or nonexistent connection")
  829. }
  830. changed := false
  831. deviceCfg := m.cfg.Devices()[deviceID]
  832. // Needs to happen outside of the fmut, as can cause CommitConfiguration
  833. if deviceCfg.AutoAcceptFolders {
  834. for _, folder := range cm.Folders {
  835. changed = m.handleAutoAccepts(deviceCfg, folder) || changed
  836. }
  837. }
  838. m.fmut.RLock()
  839. var paused []string
  840. for _, folder := range cm.Folders {
  841. cfg, ok := m.cfg.Folder(folder.ID)
  842. if !ok || !cfg.SharedWith(deviceID) {
  843. if deviceCfg.IgnoredFolder(folder.ID) {
  844. l.Infof("Ignoring folder %s from device %s since we are configured to", folder.Description(), deviceID)
  845. continue
  846. }
  847. m.cfg.AddOrUpdatePendingFolder(folder.ID, folder.Label, deviceID)
  848. changed = true
  849. m.evLogger.Log(events.FolderRejected, map[string]string{
  850. "folder": folder.ID,
  851. "folderLabel": folder.Label,
  852. "device": deviceID.String(),
  853. })
  854. 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)
  855. continue
  856. }
  857. if folder.Paused {
  858. paused = append(paused, folder.ID)
  859. continue
  860. }
  861. if cfg.Paused {
  862. continue
  863. }
  864. fs, ok := m.folderFiles[folder.ID]
  865. if !ok {
  866. // Shouldn't happen because !cfg.Paused, but might happen
  867. // if the folder is about to be unpaused, but not yet.
  868. continue
  869. }
  870. if !folder.DisableTempIndexes {
  871. tempIndexFolders = append(tempIndexFolders, folder.ID)
  872. }
  873. myIndexID := fs.IndexID(protocol.LocalDeviceID)
  874. mySequence := fs.Sequence(protocol.LocalDeviceID)
  875. var startSequence int64
  876. for _, dev := range folder.Devices {
  877. if dev.ID == m.id {
  878. // This is the other side's description of what it knows
  879. // about us. Lets check to see if we can start sending index
  880. // updates directly or need to send the index from start...
  881. if dev.IndexID == myIndexID {
  882. // They say they've seen our index ID before, so we can
  883. // send a delta update only.
  884. if dev.MaxSequence > mySequence {
  885. // Safety check. They claim to have more or newer
  886. // index data than we have - either we have lost
  887. // index data, or reset the index without resetting
  888. // the IndexID, or something else weird has
  889. // happened. We send a full index to reset the
  890. // situation.
  891. l.Infof("Device %v folder %s is delta index compatible, but seems out of sync with reality", deviceID, folder.Description())
  892. startSequence = 0
  893. continue
  894. }
  895. l.Debugf("Device %v folder %s is delta index compatible (mlv=%d)", deviceID, folder.Description(), dev.MaxSequence)
  896. startSequence = dev.MaxSequence
  897. } else if dev.IndexID != 0 {
  898. // They say they've seen an index ID from us, but it's
  899. // not the right one. Either they are confused or we
  900. // must have reset our database since last talking to
  901. // them. We'll start with a full index transfer.
  902. l.Infof("Device %v folder %s has mismatching index ID for us (%v != %v)", deviceID, folder.Description(), dev.IndexID, myIndexID)
  903. startSequence = 0
  904. }
  905. } else if dev.ID == deviceID {
  906. // This is the other side's description of themselves. We
  907. // check to see that it matches the IndexID we have on file,
  908. // otherwise we drop our old index data and expect to get a
  909. // completely new set.
  910. theirIndexID := fs.IndexID(deviceID)
  911. if dev.IndexID == 0 {
  912. // They're not announcing an index ID. This means they
  913. // do not support delta indexes and we should clear any
  914. // information we have from them before accepting their
  915. // index, which will presumably be a full index.
  916. fs.Drop(deviceID)
  917. } else if dev.IndexID != theirIndexID {
  918. // The index ID we have on file is not what they're
  919. // announcing. They must have reset their database and
  920. // will probably send us a full index. We drop any
  921. // information we have and remember this new index ID
  922. // instead.
  923. l.Infof("Device %v folder %s has a new index ID (%v)", deviceID, folder.Description(), dev.IndexID)
  924. fs.Drop(deviceID)
  925. fs.SetIndexID(deviceID, dev.IndexID)
  926. } else {
  927. // They're sending a recognized index ID and will most
  928. // likely use delta indexes. We might already have files
  929. // that we need to pull so let the folder runner know
  930. // that it should recheck the index data.
  931. if runner := m.folderRunners[folder.ID]; runner != nil {
  932. defer runner.SchedulePull()
  933. }
  934. }
  935. }
  936. }
  937. is := &indexSender{
  938. conn: conn,
  939. connClosed: closed,
  940. folder: folder.ID,
  941. fset: fs,
  942. prevSequence: startSequence,
  943. evLogger: m.evLogger,
  944. }
  945. is.Service = util.AsService(is.serve, is.String())
  946. // The token isn't tracked as the service stops when the connection
  947. // terminates and is automatically removed from supervisor (by
  948. // implementing suture.IsCompletable).
  949. m.Add(is)
  950. }
  951. m.fmut.RUnlock()
  952. m.pmut.Lock()
  953. m.remotePausedFolders[deviceID] = paused
  954. m.pmut.Unlock()
  955. // This breaks if we send multiple CM messages during the same connection.
  956. if len(tempIndexFolders) > 0 {
  957. m.pmut.RLock()
  958. conn, ok := m.conn[deviceID]
  959. m.pmut.RUnlock()
  960. // In case we've got ClusterConfig, and the connection disappeared
  961. // from infront of our nose.
  962. if ok {
  963. m.progressEmitter.temporaryIndexSubscribe(conn, tempIndexFolders)
  964. }
  965. }
  966. if deviceCfg.Introducer {
  967. folders, devices, foldersDevices, introduced := m.handleIntroductions(deviceCfg, cm)
  968. folders, devices, deintroduced := m.handleDeintroductions(deviceCfg, foldersDevices, folders, devices)
  969. if introduced || deintroduced {
  970. changed = true
  971. cfg := m.cfg.RawCopy()
  972. cfg.Folders = make([]config.FolderConfiguration, 0, len(folders))
  973. for _, fcfg := range folders {
  974. cfg.Folders = append(cfg.Folders, fcfg)
  975. }
  976. cfg.Devices = make([]config.DeviceConfiguration, len(devices))
  977. for _, dcfg := range devices {
  978. cfg.Devices = append(cfg.Devices, dcfg)
  979. }
  980. m.cfg.Replace(cfg)
  981. }
  982. }
  983. if changed {
  984. if err := m.cfg.Save(); err != nil {
  985. l.Warnln("Failed to save config", err)
  986. }
  987. }
  988. return nil
  989. }
  990. // handleIntroductions handles adding devices/folders that are shared by an introducer device
  991. func (m *model) handleIntroductions(introducerCfg config.DeviceConfiguration, cm protocol.ClusterConfig) (map[string]config.FolderConfiguration, map[protocol.DeviceID]config.DeviceConfiguration, folderDeviceSet, bool) {
  992. changed := false
  993. folders := m.cfg.Folders()
  994. devices := m.cfg.Devices()
  995. foldersDevices := make(folderDeviceSet)
  996. for _, folder := range cm.Folders {
  997. // Adds devices which we do not have, but the introducer has
  998. // for the folders that we have in common. Also, shares folders
  999. // with devices that we have in common, yet are currently not sharing
  1000. // the folder.
  1001. fcfg, ok := folders[folder.ID]
  1002. if !ok {
  1003. // Don't have this folder, carry on.
  1004. continue
  1005. }
  1006. folderChanged := false
  1007. for _, device := range folder.Devices {
  1008. // No need to share with self.
  1009. if device.ID == m.id {
  1010. continue
  1011. }
  1012. foldersDevices.set(device.ID, folder.ID)
  1013. if _, ok := m.cfg.Devices()[device.ID]; !ok {
  1014. // The device is currently unknown. Add it to the config.
  1015. devices[device.ID] = m.introduceDevice(device, introducerCfg)
  1016. } else if fcfg.SharedWith(device.ID) {
  1017. // We already share the folder with this device, so
  1018. // nothing to do.
  1019. continue
  1020. }
  1021. // We don't yet share this folder with this device. Add the device
  1022. // to sharing list of the folder.
  1023. l.Infof("Sharing folder %s with %v (vouched for by introducer %v)", folder.Description(), device.ID, introducerCfg.DeviceID)
  1024. fcfg.Devices = append(fcfg.Devices, config.FolderDeviceConfiguration{
  1025. DeviceID: device.ID,
  1026. IntroducedBy: introducerCfg.DeviceID,
  1027. })
  1028. folderChanged = true
  1029. }
  1030. if folderChanged {
  1031. folders[fcfg.ID] = fcfg
  1032. changed = true
  1033. }
  1034. }
  1035. return folders, devices, foldersDevices, changed
  1036. }
  1037. // handleDeintroductions handles removals of devices/shares that are removed by an introducer device
  1038. func (m *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) {
  1039. if introducerCfg.SkipIntroductionRemovals {
  1040. return folders, devices, false
  1041. }
  1042. changed := false
  1043. devicesNotIntroduced := make(map[protocol.DeviceID]struct{})
  1044. // Check if we should unshare some folders, if the introducer has unshared them.
  1045. for folderID, folderCfg := range folders {
  1046. for k := 0; k < len(folderCfg.Devices); k++ {
  1047. if folderCfg.Devices[k].IntroducedBy != introducerCfg.DeviceID {
  1048. devicesNotIntroduced[folderCfg.Devices[k].DeviceID] = struct{}{}
  1049. continue
  1050. }
  1051. if !foldersDevices.has(folderCfg.Devices[k].DeviceID, folderCfg.ID) {
  1052. // We could not find that folder shared on the
  1053. // introducer with the device that was introduced to us.
  1054. // We should follow and unshare as well.
  1055. 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)
  1056. folderCfg.Devices = append(folderCfg.Devices[:k], folderCfg.Devices[k+1:]...)
  1057. folders[folderID] = folderCfg
  1058. k--
  1059. changed = true
  1060. }
  1061. }
  1062. }
  1063. // Check if we should remove some devices, if the introducer no longer
  1064. // shares any folder with them. Yet do not remove if we share other
  1065. // folders that haven't been introduced by the introducer.
  1066. for deviceID, device := range devices {
  1067. if device.IntroducedBy == introducerCfg.DeviceID {
  1068. if !foldersDevices.hasDevice(deviceID) {
  1069. if _, ok := devicesNotIntroduced[deviceID]; !ok {
  1070. // The introducer no longer shares any folder with the
  1071. // device, remove the device.
  1072. l.Infof("Removing device %v as introducer %v no longer shares any folders with that device", deviceID, device.IntroducedBy)
  1073. changed = true
  1074. delete(devices, deviceID)
  1075. continue
  1076. }
  1077. 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)
  1078. }
  1079. }
  1080. }
  1081. return folders, devices, changed
  1082. }
  1083. // handleAutoAccepts handles adding and sharing folders for devices that have
  1084. // AutoAcceptFolders set to true.
  1085. func (m *model) handleAutoAccepts(deviceCfg config.DeviceConfiguration, folder protocol.Folder) bool {
  1086. if cfg, ok := m.cfg.Folder(folder.ID); !ok {
  1087. defaultPath := m.cfg.Options().DefaultFolderPath
  1088. defaultPathFs := fs.NewFilesystem(fs.FilesystemTypeBasic, defaultPath)
  1089. pathAlternatives := []string{
  1090. sanitizePath(folder.Label),
  1091. sanitizePath(folder.ID),
  1092. }
  1093. for _, path := range pathAlternatives {
  1094. if _, err := defaultPathFs.Lstat(path); !fs.IsNotExist(err) {
  1095. continue
  1096. }
  1097. fcfg := config.NewFolderConfiguration(m.id, folder.ID, folder.Label, fs.FilesystemTypeBasic, filepath.Join(defaultPath, path))
  1098. fcfg.Devices = append(fcfg.Devices, config.FolderDeviceConfiguration{
  1099. DeviceID: deviceCfg.DeviceID,
  1100. })
  1101. // Need to wait for the waiter, as this calls CommitConfiguration,
  1102. // which sets up the folder and as we return from this call,
  1103. // ClusterConfig starts poking at m.folderFiles and other things
  1104. // that might not exist until the config is committed.
  1105. w, _ := m.cfg.SetFolder(fcfg)
  1106. w.Wait()
  1107. l.Infof("Auto-accepted %s folder %s at path %s", deviceCfg.DeviceID, folder.Description(), fcfg.Path)
  1108. return true
  1109. }
  1110. l.Infof("Failed to auto-accept folder %s from %s due to path conflict", folder.Description(), deviceCfg.DeviceID)
  1111. return false
  1112. } else {
  1113. for _, device := range cfg.DeviceIDs() {
  1114. if device == deviceCfg.DeviceID {
  1115. // Already shared nothing todo.
  1116. return false
  1117. }
  1118. }
  1119. cfg.Devices = append(cfg.Devices, config.FolderDeviceConfiguration{
  1120. DeviceID: deviceCfg.DeviceID,
  1121. })
  1122. w, _ := m.cfg.SetFolder(cfg)
  1123. w.Wait()
  1124. l.Infof("Shared %s with %s due to auto-accept", folder.ID, deviceCfg.DeviceID)
  1125. return true
  1126. }
  1127. }
  1128. func (m *model) introduceDevice(device protocol.Device, introducerCfg config.DeviceConfiguration) config.DeviceConfiguration {
  1129. addresses := []string{"dynamic"}
  1130. for _, addr := range device.Addresses {
  1131. if addr != "dynamic" {
  1132. addresses = append(addresses, addr)
  1133. }
  1134. }
  1135. l.Infof("Adding device %v to config (vouched for by introducer %v)", device.ID, introducerCfg.DeviceID)
  1136. newDeviceCfg := config.DeviceConfiguration{
  1137. DeviceID: device.ID,
  1138. Name: device.Name,
  1139. Compression: introducerCfg.Compression,
  1140. Addresses: addresses,
  1141. CertName: device.CertName,
  1142. IntroducedBy: introducerCfg.DeviceID,
  1143. }
  1144. // The introducers' introducers are also our introducers.
  1145. if device.Introducer {
  1146. l.Infof("Device %v is now also an introducer", device.ID)
  1147. newDeviceCfg.Introducer = true
  1148. newDeviceCfg.SkipIntroductionRemovals = device.SkipIntroductionRemovals
  1149. }
  1150. return newDeviceCfg
  1151. }
  1152. // Closed is called when a connection has been closed
  1153. func (m *model) Closed(conn protocol.Connection, err error) {
  1154. device := conn.ID()
  1155. m.pmut.Lock()
  1156. conn, ok := m.conn[device]
  1157. if !ok {
  1158. m.pmut.Unlock()
  1159. return
  1160. }
  1161. delete(m.conn, device)
  1162. delete(m.connRequestLimiters, device)
  1163. delete(m.helloMessages, device)
  1164. delete(m.deviceDownloads, device)
  1165. delete(m.remotePausedFolders, device)
  1166. closed := m.closed[device]
  1167. delete(m.closed, device)
  1168. m.pmut.Unlock()
  1169. m.progressEmitter.temporaryIndexUnsubscribe(conn)
  1170. l.Infof("Connection to %s at %s closed: %v", device, conn.Name(), err)
  1171. m.evLogger.Log(events.DeviceDisconnected, map[string]string{
  1172. "id": device.String(),
  1173. "error": err.Error(),
  1174. })
  1175. close(closed)
  1176. }
  1177. // closeConns will close the underlying connection for given devices and return
  1178. // a waiter that will return once all the connections are finished closing.
  1179. func (m *model) closeConns(devs []protocol.DeviceID, err error) config.Waiter {
  1180. conns := make([]connections.Connection, 0, len(devs))
  1181. closed := make([]chan struct{}, 0, len(devs))
  1182. m.pmut.RLock()
  1183. for _, dev := range devs {
  1184. if conn, ok := m.conn[dev]; ok {
  1185. conns = append(conns, conn)
  1186. closed = append(closed, m.closed[dev])
  1187. }
  1188. }
  1189. m.pmut.RUnlock()
  1190. for _, conn := range conns {
  1191. conn.Close(err)
  1192. }
  1193. return &channelWaiter{chans: closed}
  1194. }
  1195. // closeConn closes the underlying connection for the given device and returns
  1196. // a waiter that will return once the connection is finished closing.
  1197. func (m *model) closeConn(dev protocol.DeviceID, err error) config.Waiter {
  1198. return m.closeConns([]protocol.DeviceID{dev}, err)
  1199. }
  1200. type channelWaiter struct {
  1201. chans []chan struct{}
  1202. }
  1203. func (w *channelWaiter) Wait() {
  1204. for _, c := range w.chans {
  1205. <-c
  1206. }
  1207. }
  1208. // Implements protocol.RequestResponse
  1209. type requestResponse struct {
  1210. data []byte
  1211. closed chan struct{}
  1212. once stdsync.Once
  1213. }
  1214. func newRequestResponse(size int) *requestResponse {
  1215. return &requestResponse{
  1216. data: protocol.BufferPool.Get(size),
  1217. closed: make(chan struct{}),
  1218. }
  1219. }
  1220. func (r *requestResponse) Data() []byte {
  1221. return r.data
  1222. }
  1223. func (r *requestResponse) Close() {
  1224. r.once.Do(func() {
  1225. protocol.BufferPool.Put(r.data)
  1226. close(r.closed)
  1227. })
  1228. }
  1229. func (r *requestResponse) Wait() {
  1230. <-r.closed
  1231. }
  1232. // Request returns the specified data segment by reading it from local disk.
  1233. // Implements the protocol.Model interface.
  1234. func (m *model) Request(deviceID protocol.DeviceID, folder, name string, size int32, offset int64, hash []byte, weakHash uint32, fromTemporary bool) (out protocol.RequestResponse, err error) {
  1235. if size < 0 || offset < 0 {
  1236. return nil, protocol.ErrInvalid
  1237. }
  1238. m.fmut.RLock()
  1239. folderCfg, ok := m.folderCfgs[folder]
  1240. folderIgnores := m.folderIgnores[folder]
  1241. m.fmut.RUnlock()
  1242. if !ok {
  1243. // The folder might be already unpaused in the config, but not yet
  1244. // in the model.
  1245. l.Debugf("Request from %s for file %s in unstarted folder %q", deviceID, name, folder)
  1246. return nil, protocol.ErrGeneric
  1247. }
  1248. if !folderCfg.SharedWith(deviceID) {
  1249. l.Warnf("Request from %s for file %s in unshared folder %q", deviceID, name, folder)
  1250. return nil, protocol.ErrGeneric
  1251. }
  1252. if folderCfg.Paused {
  1253. l.Debugf("Request from %s for file %s in paused folder %q", deviceID, name, folder)
  1254. return nil, protocol.ErrGeneric
  1255. }
  1256. // Make sure the path is valid and in canonical form
  1257. if name, err = fs.Canonicalize(name); err != nil {
  1258. l.Debugf("Request from %s in folder %q for invalid filename %s", deviceID, folder, name)
  1259. return nil, protocol.ErrGeneric
  1260. }
  1261. if deviceID != protocol.LocalDeviceID {
  1262. l.Debugf("%v REQ(in): %s: %q / %q o=%d s=%d t=%v", m, deviceID, folder, name, offset, size, fromTemporary)
  1263. }
  1264. if fs.IsInternal(name) {
  1265. l.Debugf("%v REQ(in) for internal file: %s: %q / %q o=%d s=%d", m, deviceID, folder, name, offset, size)
  1266. return nil, protocol.ErrInvalid
  1267. }
  1268. if folderIgnores.Match(name).IsIgnored() {
  1269. l.Debugf("%v REQ(in) for ignored file: %s: %q / %q o=%d s=%d", m, deviceID, folder, name, offset, size)
  1270. return nil, protocol.ErrInvalid
  1271. }
  1272. folderFs := folderCfg.Filesystem()
  1273. if err := osutil.TraversesSymlink(folderFs, filepath.Dir(name)); err != nil {
  1274. l.Debugf("%v REQ(in) traversal check: %s - %s: %q / %q o=%d s=%d", m, err, deviceID, folder, name, offset, size)
  1275. return nil, protocol.ErrNoSuchFile
  1276. }
  1277. // Restrict parallel requests by connection/device
  1278. m.pmut.RLock()
  1279. limiter := m.connRequestLimiters[deviceID]
  1280. m.pmut.RUnlock()
  1281. // The requestResponse releases the bytes to the buffer pool and the
  1282. // limiters when its Close method is called.
  1283. res := newLimitedRequestResponse(int(size), limiter, m.globalRequestLimiter)
  1284. defer func() {
  1285. // Close it ourselves if it isn't returned due to an error
  1286. if err != nil {
  1287. res.Close()
  1288. }
  1289. }()
  1290. // Only check temp files if the flag is set, and if we are set to advertise
  1291. // the temp indexes.
  1292. if fromTemporary && !folderCfg.DisableTempIndexes {
  1293. tempFn := fs.TempName(name)
  1294. if info, err := folderFs.Lstat(tempFn); err != nil || !info.IsRegular() {
  1295. // Reject reads for anything that doesn't exist or is something
  1296. // other than a regular file.
  1297. l.Debugf("%v REQ(in) failed stating temp file (%v): %s: %q / %q o=%d s=%d", m, err, deviceID, folder, name, offset, size)
  1298. return nil, protocol.ErrNoSuchFile
  1299. }
  1300. err := readOffsetIntoBuf(folderFs, tempFn, offset, res.data)
  1301. if err == nil && scanner.Validate(res.data, hash, weakHash) {
  1302. return res, nil
  1303. }
  1304. // Fall through to reading from a non-temp file, just incase the temp
  1305. // file has finished downloading.
  1306. }
  1307. if info, err := folderFs.Lstat(name); err != nil || !info.IsRegular() {
  1308. // Reject reads for anything that doesn't exist or is something
  1309. // other than a regular file.
  1310. l.Debugf("%v REQ(in) failed stating file (%v): %s: %q / %q o=%d s=%d", m, err, deviceID, folder, name, offset, size)
  1311. return nil, protocol.ErrNoSuchFile
  1312. }
  1313. if err := readOffsetIntoBuf(folderFs, name, offset, res.data); fs.IsNotExist(err) {
  1314. l.Debugf("%v REQ(in) file doesn't exist: %s: %q / %q o=%d s=%d", m, deviceID, folder, name, offset, size)
  1315. return nil, protocol.ErrNoSuchFile
  1316. } else if err != nil {
  1317. l.Debugf("%v REQ(in) failed reading file (%v): %s: %q / %q o=%d s=%d", m, err, deviceID, folder, name, offset, size)
  1318. return nil, protocol.ErrGeneric
  1319. }
  1320. if !scanner.Validate(res.data, hash, weakHash) {
  1321. m.recheckFile(deviceID, folder, name, offset, hash)
  1322. l.Debugf("%v REQ(in) failed validating data (%v): %s: %q / %q o=%d s=%d", m, err, deviceID, folder, name, offset, size)
  1323. return nil, protocol.ErrNoSuchFile
  1324. }
  1325. return res, nil
  1326. }
  1327. // newLimitedRequestResponse takes size bytes from the limiters in order,
  1328. // skipping nil limiters, then returns a requestResponse of the given size.
  1329. // When the requestResponse is closed the limiters are given back the bytes,
  1330. // in reverse order.
  1331. func newLimitedRequestResponse(size int, limiters ...*byteSemaphore) *requestResponse {
  1332. for _, limiter := range limiters {
  1333. if limiter != nil {
  1334. limiter.take(size)
  1335. }
  1336. }
  1337. res := newRequestResponse(size)
  1338. go func() {
  1339. res.Wait()
  1340. for i := range limiters {
  1341. limiter := limiters[len(limiters)-1-i]
  1342. if limiter != nil {
  1343. limiter.give(size)
  1344. }
  1345. }
  1346. }()
  1347. return res
  1348. }
  1349. func (m *model) recheckFile(deviceID protocol.DeviceID, folder, name string, offset int64, hash []byte) {
  1350. cf, ok := m.CurrentFolderFile(folder, name)
  1351. if !ok {
  1352. l.Debugf("%v recheckFile: %s: %q / %q: no current file", m, deviceID, folder, name)
  1353. return
  1354. }
  1355. if cf.IsDeleted() || cf.IsInvalid() || cf.IsSymlink() || cf.IsDirectory() {
  1356. l.Debugf("%v recheckFile: %s: %q / %q: not a regular file", m, deviceID, folder, name)
  1357. return
  1358. }
  1359. blockIndex := int(offset / int64(cf.BlockSize()))
  1360. if blockIndex >= len(cf.Blocks) {
  1361. l.Debugf("%v recheckFile: %s: %q / %q i=%d: block index too far", m, deviceID, folder, name, blockIndex)
  1362. return
  1363. }
  1364. block := cf.Blocks[blockIndex]
  1365. // Seems to want a different version of the file, whatever.
  1366. if !bytes.Equal(block.Hash, hash) {
  1367. l.Debugf("%v recheckFile: %s: %q / %q i=%d: hash mismatch %x != %x", m, deviceID, folder, name, blockIndex, block.Hash, hash)
  1368. return
  1369. }
  1370. // The hashes provided part of the request match what we expect to find according
  1371. // to what we have in the database, yet the content we've read off the filesystem doesn't
  1372. // Something is fishy, invalidate the file and rescan it.
  1373. // The file will temporarily become invalid, which is ok as the content is messed up.
  1374. m.fmut.RLock()
  1375. runner, ok := m.folderRunners[folder]
  1376. m.fmut.RUnlock()
  1377. if !ok {
  1378. l.Debugf("%v recheckFile: %s: %q / %q: Folder stopped before rescan could be scheduled", m, deviceID, folder, name)
  1379. return
  1380. }
  1381. runner.ScheduleForceRescan(name)
  1382. l.Debugf("%v recheckFile: %s: %q / %q", m, deviceID, folder, name)
  1383. }
  1384. func (m *model) CurrentFolderFile(folder string, file string) (protocol.FileInfo, bool) {
  1385. m.fmut.RLock()
  1386. fs, ok := m.folderFiles[folder]
  1387. m.fmut.RUnlock()
  1388. if !ok {
  1389. return protocol.FileInfo{}, false
  1390. }
  1391. snap := fs.Snapshot()
  1392. defer snap.Release()
  1393. return snap.Get(protocol.LocalDeviceID, file)
  1394. }
  1395. func (m *model) CurrentGlobalFile(folder string, file string) (protocol.FileInfo, bool) {
  1396. m.fmut.RLock()
  1397. fs, ok := m.folderFiles[folder]
  1398. m.fmut.RUnlock()
  1399. if !ok {
  1400. return protocol.FileInfo{}, false
  1401. }
  1402. snap := fs.Snapshot()
  1403. defer snap.Release()
  1404. return snap.GetGlobal(file)
  1405. }
  1406. // Connection returns the current connection for device, and a boolean whether a connection was found.
  1407. func (m *model) Connection(deviceID protocol.DeviceID) (connections.Connection, bool) {
  1408. m.pmut.RLock()
  1409. cn, ok := m.conn[deviceID]
  1410. m.pmut.RUnlock()
  1411. if ok {
  1412. m.deviceWasSeen(deviceID)
  1413. }
  1414. return cn, ok
  1415. }
  1416. func (m *model) GetIgnores(folder string) ([]string, []string, error) {
  1417. m.fmut.RLock()
  1418. cfg, cfgOk := m.folderCfgs[folder]
  1419. ignores, ignoresOk := m.folderIgnores[folder]
  1420. m.fmut.RUnlock()
  1421. if !cfgOk {
  1422. cfg, cfgOk = m.cfg.Folders()[folder]
  1423. if !cfgOk {
  1424. return nil, nil, fmt.Errorf("folder %s does not exist", folder)
  1425. }
  1426. }
  1427. // On creation a new folder with ignore patterns validly has no marker yet.
  1428. if err := cfg.CheckPath(); err != nil && err != config.ErrMarkerMissing {
  1429. return nil, nil, err
  1430. }
  1431. if !ignoresOk {
  1432. ignores = ignore.New(fs.NewFilesystem(cfg.FilesystemType, cfg.Path))
  1433. }
  1434. if err := ignores.Load(".stignore"); err != nil && !fs.IsNotExist(err) {
  1435. return nil, nil, err
  1436. }
  1437. return ignores.Lines(), ignores.Patterns(), nil
  1438. }
  1439. func (m *model) SetIgnores(folder string, content []string) error {
  1440. cfg, ok := m.cfg.Folders()[folder]
  1441. if !ok {
  1442. return fmt.Errorf("folder %s does not exist", cfg.Description())
  1443. }
  1444. err := cfg.CheckPath()
  1445. if err == config.ErrPathMissing {
  1446. if err = cfg.CreateRoot(); err != nil {
  1447. return errors.Wrap(err, "failed to create folder root")
  1448. }
  1449. err = cfg.CheckPath()
  1450. }
  1451. if err != nil && err != config.ErrMarkerMissing {
  1452. return err
  1453. }
  1454. if err := ignore.WriteIgnores(cfg.Filesystem(), ".stignore", content); err != nil {
  1455. l.Warnln("Saving .stignore:", err)
  1456. return err
  1457. }
  1458. m.fmut.RLock()
  1459. runner, ok := m.folderRunners[folder]
  1460. m.fmut.RUnlock()
  1461. if ok {
  1462. return runner.Scan(nil)
  1463. }
  1464. return nil
  1465. }
  1466. // OnHello is called when an device connects to us.
  1467. // This allows us to extract some information from the Hello message
  1468. // and add it to a list of known devices ahead of any checks.
  1469. func (m *model) OnHello(remoteID protocol.DeviceID, addr net.Addr, hello protocol.HelloResult) error {
  1470. if m.cfg.IgnoredDevice(remoteID) {
  1471. return errDeviceIgnored
  1472. }
  1473. cfg, ok := m.cfg.Device(remoteID)
  1474. if !ok {
  1475. m.cfg.AddOrUpdatePendingDevice(remoteID, hello.DeviceName, addr.String())
  1476. _ = m.cfg.Save() // best effort
  1477. m.evLogger.Log(events.DeviceRejected, map[string]string{
  1478. "name": hello.DeviceName,
  1479. "device": remoteID.String(),
  1480. "address": addr.String(),
  1481. })
  1482. return errDeviceUnknown
  1483. }
  1484. if cfg.Paused {
  1485. return errDevicePaused
  1486. }
  1487. if len(cfg.AllowedNetworks) > 0 {
  1488. if !connections.IsAllowedNetwork(addr.String(), cfg.AllowedNetworks) {
  1489. return errNetworkNotAllowed
  1490. }
  1491. }
  1492. return nil
  1493. }
  1494. // GetHello is called when we are about to connect to some remote device.
  1495. func (m *model) GetHello(id protocol.DeviceID) protocol.HelloIntf {
  1496. name := ""
  1497. if _, ok := m.cfg.Device(id); ok {
  1498. name = m.cfg.MyName()
  1499. }
  1500. return &protocol.Hello{
  1501. DeviceName: name,
  1502. ClientName: m.clientName,
  1503. ClientVersion: m.clientVersion,
  1504. }
  1505. }
  1506. // AddConnection adds a new peer connection to the model. An initial index will
  1507. // be sent to the connected peer, thereafter index updates whenever the local
  1508. // folder changes.
  1509. func (m *model) AddConnection(conn connections.Connection, hello protocol.HelloResult) {
  1510. deviceID := conn.ID()
  1511. device, ok := m.cfg.Device(deviceID)
  1512. if !ok {
  1513. l.Infoln("Trying to add connection to unknown device")
  1514. return
  1515. }
  1516. m.pmut.Lock()
  1517. if oldConn, ok := m.conn[deviceID]; ok {
  1518. l.Infoln("Replacing old connection", oldConn, "with", conn, "for", deviceID)
  1519. // There is an existing connection to this device that we are
  1520. // replacing. We must close the existing connection and wait for the
  1521. // close to complete before adding the new connection. We do the
  1522. // actual close without holding pmut as the connection will call
  1523. // back into Closed() for the cleanup.
  1524. closed := m.closed[deviceID]
  1525. m.pmut.Unlock()
  1526. oldConn.Close(errReplacingConnection)
  1527. <-closed
  1528. m.pmut.Lock()
  1529. }
  1530. m.conn[deviceID] = conn
  1531. m.closed[deviceID] = make(chan struct{})
  1532. m.deviceDownloads[deviceID] = newDeviceDownloadState()
  1533. // 0: default, <0: no limiting
  1534. switch {
  1535. case device.MaxRequestKiB > 0:
  1536. m.connRequestLimiters[deviceID] = newByteSemaphore(1024 * device.MaxRequestKiB)
  1537. case device.MaxRequestKiB == 0:
  1538. m.connRequestLimiters[deviceID] = newByteSemaphore(1024 * defaultPullerPendingKiB)
  1539. }
  1540. m.helloMessages[deviceID] = hello
  1541. event := map[string]string{
  1542. "id": deviceID.String(),
  1543. "deviceName": hello.DeviceName,
  1544. "clientName": hello.ClientName,
  1545. "clientVersion": hello.ClientVersion,
  1546. "type": conn.Type(),
  1547. }
  1548. addr := conn.RemoteAddr()
  1549. if addr != nil {
  1550. event["addr"] = addr.String()
  1551. }
  1552. m.evLogger.Log(events.DeviceConnected, event)
  1553. l.Infof(`Device %s client is "%s %s" named "%s" at %s`, deviceID, hello.ClientName, hello.ClientVersion, hello.DeviceName, conn)
  1554. conn.Start()
  1555. m.pmut.Unlock()
  1556. // Acquires fmut, so has to be done outside of pmut.
  1557. cm := m.generateClusterConfig(deviceID)
  1558. conn.ClusterConfig(cm)
  1559. if (device.Name == "" || m.cfg.Options().OverwriteRemoteDevNames) && hello.DeviceName != "" {
  1560. device.Name = hello.DeviceName
  1561. m.cfg.SetDevice(device)
  1562. m.cfg.Save()
  1563. }
  1564. m.deviceWasSeen(deviceID)
  1565. }
  1566. func (m *model) DownloadProgress(device protocol.DeviceID, folder string, updates []protocol.FileDownloadProgressUpdate) error {
  1567. m.fmut.RLock()
  1568. cfg, ok := m.folderCfgs[folder]
  1569. m.fmut.RUnlock()
  1570. if !ok || cfg.DisableTempIndexes || !cfg.SharedWith(device) {
  1571. return nil
  1572. }
  1573. m.pmut.RLock()
  1574. downloads := m.deviceDownloads[device]
  1575. m.pmut.RUnlock()
  1576. downloads.Update(folder, updates)
  1577. state := downloads.GetBlockCounts(folder)
  1578. m.evLogger.Log(events.RemoteDownloadProgress, map[string]interface{}{
  1579. "device": device.String(),
  1580. "folder": folder,
  1581. "state": state,
  1582. })
  1583. return nil
  1584. }
  1585. func (m *model) deviceWasSeen(deviceID protocol.DeviceID) {
  1586. m.fmut.RLock()
  1587. sr, ok := m.deviceStatRefs[deviceID]
  1588. m.fmut.RUnlock()
  1589. if ok {
  1590. sr.WasSeen()
  1591. }
  1592. }
  1593. type indexSender struct {
  1594. suture.Service
  1595. conn protocol.Connection
  1596. folder string
  1597. dev string
  1598. fset *db.FileSet
  1599. prevSequence int64
  1600. evLogger events.Logger
  1601. connClosed chan struct{}
  1602. }
  1603. func (s *indexSender) serve(ctx context.Context) {
  1604. var err error
  1605. l.Debugf("Starting indexSender for %s to %s at %s (slv=%d)", s.folder, s.dev, s.conn, s.prevSequence)
  1606. defer l.Debugf("Exiting indexSender for %s to %s at %s: %v", s.folder, s.dev, s.conn, err)
  1607. // We need to send one index, regardless of whether there is something to send or not
  1608. err = s.sendIndexTo(ctx)
  1609. // Subscribe to LocalIndexUpdated (we have new information to send) and
  1610. // DeviceDisconnected (it might be us who disconnected, so we should
  1611. // exit).
  1612. sub := s.evLogger.Subscribe(events.LocalIndexUpdated | events.DeviceDisconnected)
  1613. defer sub.Unsubscribe()
  1614. evChan := sub.C()
  1615. ticker := time.NewTicker(time.Minute)
  1616. defer ticker.Stop()
  1617. for err == nil {
  1618. select {
  1619. case <-ctx.Done():
  1620. return
  1621. case <-s.connClosed:
  1622. return
  1623. default:
  1624. }
  1625. // While we have sent a sequence at least equal to the one
  1626. // currently in the database, wait for the local index to update. The
  1627. // local index may update for other folders than the one we are
  1628. // sending for.
  1629. if s.fset.Sequence(protocol.LocalDeviceID) <= s.prevSequence {
  1630. select {
  1631. case <-ctx.Done():
  1632. return
  1633. case <-s.connClosed:
  1634. return
  1635. case <-evChan:
  1636. case <-ticker.C:
  1637. }
  1638. continue
  1639. }
  1640. err = s.sendIndexTo(ctx)
  1641. // Wait a short amount of time before entering the next loop. If there
  1642. // are continuous changes happening to the local index, this gives us
  1643. // time to batch them up a little.
  1644. time.Sleep(250 * time.Millisecond)
  1645. }
  1646. }
  1647. // Complete implements the suture.IsCompletable interface. When Serve terminates
  1648. // before Stop is called, the supervisor will check for this method and if it
  1649. // returns true removes the service instead of restarting it. Here it always
  1650. // returns true, as indexSender only terminates when a connection is
  1651. // closed/has failed, in which case retrying doesn't help.
  1652. func (s *indexSender) Complete() bool { return true }
  1653. // sendIndexTo sends file infos with a sequence number higher than prevSequence and
  1654. // returns the highest sent sequence number.
  1655. func (s *indexSender) sendIndexTo(ctx context.Context) error {
  1656. initial := s.prevSequence == 0
  1657. batch := newFileInfoBatch(nil)
  1658. batch.flushFn = func(fs []protocol.FileInfo) error {
  1659. l.Debugf("%v: Sending %d files (<%d bytes)", s, len(batch.infos), batch.size)
  1660. if initial {
  1661. initial = false
  1662. return s.conn.Index(ctx, s.folder, fs)
  1663. }
  1664. return s.conn.IndexUpdate(ctx, s.folder, fs)
  1665. }
  1666. var err error
  1667. var f protocol.FileInfo
  1668. snap := s.fset.Snapshot()
  1669. defer snap.Release()
  1670. snap.WithHaveSequence(s.prevSequence+1, func(fi db.FileIntf) bool {
  1671. if err = batch.flushIfFull(); err != nil {
  1672. return false
  1673. }
  1674. if shouldDebug() {
  1675. if fi.SequenceNo() < s.prevSequence+1 {
  1676. panic(fmt.Sprintln("sequence lower than requested, got:", fi.SequenceNo(), ", asked to start at:", s.prevSequence+1))
  1677. }
  1678. }
  1679. if f.Sequence > 0 && fi.SequenceNo() <= f.Sequence {
  1680. l.Warnln("Non-increasing sequence detected: Checking and repairing the db...")
  1681. // Abort this round of index sending - the next one will pick
  1682. // up from the last successful one with the repeaired db.
  1683. defer func() {
  1684. if fixed, dbErr := s.fset.RepairSequence(); dbErr != nil {
  1685. l.Warnln("Failed repairing sequence entries:", dbErr)
  1686. panic("Failed repairing sequence entries")
  1687. } else {
  1688. l.Infof("Repaired %v sequence entries in database", fixed)
  1689. }
  1690. }()
  1691. return false
  1692. }
  1693. f = fi.(protocol.FileInfo)
  1694. // Mark the file as invalid if any of the local bad stuff flags are set.
  1695. f.RawInvalid = f.IsInvalid()
  1696. // If the file is marked LocalReceive (i.e., changed locally on a
  1697. // receive only folder) we do not want it to ever become the
  1698. // globally best version, invalid or not.
  1699. if f.IsReceiveOnlyChanged() {
  1700. f.Version = protocol.Vector{}
  1701. }
  1702. f.LocalFlags = 0 // never sent externally
  1703. batch.append(f)
  1704. return true
  1705. })
  1706. if err != nil {
  1707. return err
  1708. }
  1709. err = batch.flush()
  1710. // True if there was nothing to be sent
  1711. if f.Sequence == 0 {
  1712. return err
  1713. }
  1714. s.prevSequence = f.Sequence
  1715. return err
  1716. }
  1717. func (s *indexSender) String() string {
  1718. return fmt.Sprintf("indexSender@%p for %s to %s at %s", s, s.folder, s.dev, s.conn)
  1719. }
  1720. func (m *model) requestGlobal(ctx context.Context, deviceID protocol.DeviceID, folder, name string, offset int64, size int, hash []byte, weakHash uint32, fromTemporary bool) ([]byte, error) {
  1721. m.pmut.RLock()
  1722. nc, ok := m.conn[deviceID]
  1723. m.pmut.RUnlock()
  1724. if !ok {
  1725. return nil, fmt.Errorf("requestGlobal: no such device: %s", deviceID)
  1726. }
  1727. l.Debugf("%v REQ(out): %s: %q / %q o=%d s=%d h=%x wh=%x ft=%t", m, deviceID, folder, name, offset, size, hash, weakHash, fromTemporary)
  1728. return nc.Request(ctx, folder, name, offset, size, hash, weakHash, fromTemporary)
  1729. }
  1730. func (m *model) ScanFolders() map[string]error {
  1731. m.fmut.RLock()
  1732. folders := make([]string, 0, len(m.folderCfgs))
  1733. for folder := range m.folderCfgs {
  1734. folders = append(folders, folder)
  1735. }
  1736. m.fmut.RUnlock()
  1737. errors := make(map[string]error, len(m.folderCfgs))
  1738. errorsMut := sync.NewMutex()
  1739. wg := sync.NewWaitGroup()
  1740. wg.Add(len(folders))
  1741. for _, folder := range folders {
  1742. folder := folder
  1743. go func() {
  1744. err := m.ScanFolder(folder)
  1745. if err != nil {
  1746. errorsMut.Lock()
  1747. errors[folder] = err
  1748. errorsMut.Unlock()
  1749. }
  1750. wg.Done()
  1751. }()
  1752. }
  1753. wg.Wait()
  1754. return errors
  1755. }
  1756. func (m *model) ScanFolder(folder string) error {
  1757. return m.ScanFolderSubdirs(folder, nil)
  1758. }
  1759. func (m *model) ScanFolderSubdirs(folder string, subs []string) error {
  1760. m.fmut.RLock()
  1761. err := m.checkFolderRunningLocked(folder)
  1762. runner := m.folderRunners[folder]
  1763. m.fmut.RUnlock()
  1764. if err != nil {
  1765. return err
  1766. }
  1767. return runner.Scan(subs)
  1768. }
  1769. func (m *model) DelayScan(folder string, next time.Duration) {
  1770. m.fmut.RLock()
  1771. runner, ok := m.folderRunners[folder]
  1772. m.fmut.RUnlock()
  1773. if !ok {
  1774. return
  1775. }
  1776. runner.DelayScan(next)
  1777. }
  1778. // numHashers returns the number of hasher routines to use for a given folder,
  1779. // taking into account configuration and available CPU cores.
  1780. func (m *model) numHashers(folder string) int {
  1781. m.fmut.RLock()
  1782. folderCfg := m.folderCfgs[folder]
  1783. numFolders := len(m.folderCfgs)
  1784. m.fmut.RUnlock()
  1785. if folderCfg.Hashers > 0 {
  1786. // Specific value set in the config, use that.
  1787. return folderCfg.Hashers
  1788. }
  1789. if runtime.GOOS == "windows" || runtime.GOOS == "darwin" {
  1790. // Interactive operating systems; don't load the system too heavily by
  1791. // default.
  1792. return 1
  1793. }
  1794. // For other operating systems and architectures, lets try to get some
  1795. // work done... Divide the available CPU cores among the configured
  1796. // folders.
  1797. if perFolder := runtime.GOMAXPROCS(-1) / numFolders; perFolder > 0 {
  1798. return perFolder
  1799. }
  1800. return 1
  1801. }
  1802. // generateClusterConfig returns a ClusterConfigMessage that is correct for
  1803. // the given peer device
  1804. func (m *model) generateClusterConfig(device protocol.DeviceID) protocol.ClusterConfig {
  1805. var message protocol.ClusterConfig
  1806. m.fmut.RLock()
  1807. defer m.fmut.RUnlock()
  1808. for _, folderCfg := range m.cfg.FolderList() {
  1809. if !folderCfg.SharedWith(device) {
  1810. continue
  1811. }
  1812. protocolFolder := protocol.Folder{
  1813. ID: folderCfg.ID,
  1814. Label: folderCfg.Label,
  1815. ReadOnly: folderCfg.Type == config.FolderTypeSendOnly,
  1816. IgnorePermissions: folderCfg.IgnorePerms,
  1817. IgnoreDelete: folderCfg.IgnoreDelete,
  1818. DisableTempIndexes: folderCfg.DisableTempIndexes,
  1819. Paused: folderCfg.Paused,
  1820. }
  1821. var fs *db.FileSet
  1822. if !folderCfg.Paused {
  1823. fs = m.folderFiles[folderCfg.ID]
  1824. }
  1825. for _, device := range folderCfg.Devices {
  1826. deviceCfg, _ := m.cfg.Device(device.DeviceID)
  1827. protocolDevice := protocol.Device{
  1828. ID: deviceCfg.DeviceID,
  1829. Name: deviceCfg.Name,
  1830. Addresses: deviceCfg.Addresses,
  1831. Compression: deviceCfg.Compression,
  1832. CertName: deviceCfg.CertName,
  1833. Introducer: deviceCfg.Introducer,
  1834. }
  1835. if fs != nil {
  1836. if deviceCfg.DeviceID == m.id {
  1837. protocolDevice.IndexID = fs.IndexID(protocol.LocalDeviceID)
  1838. protocolDevice.MaxSequence = fs.Sequence(protocol.LocalDeviceID)
  1839. } else {
  1840. protocolDevice.IndexID = fs.IndexID(deviceCfg.DeviceID)
  1841. protocolDevice.MaxSequence = fs.Sequence(deviceCfg.DeviceID)
  1842. }
  1843. }
  1844. protocolFolder.Devices = append(protocolFolder.Devices, protocolDevice)
  1845. }
  1846. message.Folders = append(message.Folders, protocolFolder)
  1847. }
  1848. return message
  1849. }
  1850. func (m *model) State(folder string) (string, time.Time, error) {
  1851. m.fmut.RLock()
  1852. runner, ok := m.folderRunners[folder]
  1853. m.fmut.RUnlock()
  1854. if !ok {
  1855. // The returned error should be an actual folder error, so returning
  1856. // errors.New("does not exist") or similar here would be
  1857. // inappropriate.
  1858. return "", time.Time{}, nil
  1859. }
  1860. state, changed, err := runner.getState()
  1861. return state.String(), changed, err
  1862. }
  1863. func (m *model) FolderErrors(folder string) ([]FileError, error) {
  1864. m.fmut.RLock()
  1865. err := m.checkFolderRunningLocked(folder)
  1866. runner := m.folderRunners[folder]
  1867. m.fmut.RUnlock()
  1868. if err != nil {
  1869. return nil, err
  1870. }
  1871. return runner.Errors(), nil
  1872. }
  1873. func (m *model) WatchError(folder string) error {
  1874. m.fmut.RLock()
  1875. err := m.checkFolderRunningLocked(folder)
  1876. runner := m.folderRunners[folder]
  1877. m.fmut.RUnlock()
  1878. if err != nil {
  1879. return nil // If the folder isn't running, there's no error to report.
  1880. }
  1881. return runner.WatchError()
  1882. }
  1883. func (m *model) Override(folder string) {
  1884. // Grab the runner and the file set.
  1885. m.fmut.RLock()
  1886. runner, ok := m.folderRunners[folder]
  1887. m.fmut.RUnlock()
  1888. if !ok {
  1889. return
  1890. }
  1891. // Run the override, taking updates as if they came from scanning.
  1892. runner.Override()
  1893. }
  1894. func (m *model) Revert(folder string) {
  1895. // Grab the runner and the file set.
  1896. m.fmut.RLock()
  1897. runner, ok := m.folderRunners[folder]
  1898. m.fmut.RUnlock()
  1899. if !ok {
  1900. return
  1901. }
  1902. // Run the revert, taking updates as if they came from scanning.
  1903. runner.Revert()
  1904. }
  1905. func (m *model) GlobalDirectoryTree(folder, prefix string, levels int, dirsonly bool) map[string]interface{} {
  1906. m.fmut.RLock()
  1907. files, ok := m.folderFiles[folder]
  1908. m.fmut.RUnlock()
  1909. if !ok {
  1910. return nil
  1911. }
  1912. output := make(map[string]interface{})
  1913. sep := string(filepath.Separator)
  1914. prefix = osutil.NativeFilename(prefix)
  1915. if prefix != "" && !strings.HasSuffix(prefix, sep) {
  1916. prefix = prefix + sep
  1917. }
  1918. snap := files.Snapshot()
  1919. defer snap.Release()
  1920. snap.WithPrefixedGlobalTruncated(prefix, func(fi db.FileIntf) bool {
  1921. f := fi.(db.FileInfoTruncated)
  1922. // Don't include the prefix itself.
  1923. if f.IsInvalid() || f.IsDeleted() || strings.HasPrefix(prefix, f.Name) {
  1924. return true
  1925. }
  1926. f.Name = strings.Replace(f.Name, prefix, "", 1)
  1927. var dir, base string
  1928. if f.IsDirectory() && !f.IsSymlink() {
  1929. dir = f.Name
  1930. } else {
  1931. dir = filepath.Dir(f.Name)
  1932. base = filepath.Base(f.Name)
  1933. }
  1934. if levels > -1 && strings.Count(f.Name, sep) > levels {
  1935. return true
  1936. }
  1937. last := output
  1938. if dir != "." {
  1939. for _, path := range strings.Split(dir, sep) {
  1940. directory, ok := last[path]
  1941. if !ok {
  1942. newdir := make(map[string]interface{})
  1943. last[path] = newdir
  1944. last = newdir
  1945. } else {
  1946. last = directory.(map[string]interface{})
  1947. }
  1948. }
  1949. }
  1950. if !dirsonly && base != "" {
  1951. last[base] = []interface{}{
  1952. f.ModTime(), f.FileSize(),
  1953. }
  1954. }
  1955. return true
  1956. })
  1957. return output
  1958. }
  1959. func (m *model) GetFolderVersions(folder string) (map[string][]versioner.FileVersion, error) {
  1960. m.fmut.RLock()
  1961. err := m.checkFolderRunningLocked(folder)
  1962. ver := m.folderVersioners[folder]
  1963. m.fmut.RUnlock()
  1964. if err != nil {
  1965. return nil, err
  1966. }
  1967. if ver == nil {
  1968. return nil, errNoVersioner
  1969. }
  1970. return ver.GetVersions()
  1971. }
  1972. func (m *model) RestoreFolderVersions(folder string, versions map[string]time.Time) (map[string]string, error) {
  1973. m.fmut.RLock()
  1974. err := m.checkFolderRunningLocked(folder)
  1975. fcfg := m.folderCfgs[folder]
  1976. ver := m.folderVersioners[folder]
  1977. m.fmut.RUnlock()
  1978. if err != nil {
  1979. return nil, err
  1980. }
  1981. if ver == nil {
  1982. return nil, errNoVersioner
  1983. }
  1984. restoreErrors := make(map[string]string)
  1985. for file, version := range versions {
  1986. if err := ver.Restore(file, version); err != nil {
  1987. restoreErrors[file] = err.Error()
  1988. }
  1989. }
  1990. // Trigger scan
  1991. if !fcfg.FSWatcherEnabled {
  1992. go func() { _ = m.ScanFolder(folder) }()
  1993. }
  1994. return restoreErrors, nil
  1995. }
  1996. func (m *model) Availability(folder string, file protocol.FileInfo, block protocol.BlockInfo) []Availability {
  1997. // The slightly unusual locking sequence here is because we need to hold
  1998. // pmut for the duration (as the value returned from foldersFiles can
  1999. // get heavily modified on Close()), but also must acquire fmut before
  2000. // pmut. (The locks can be *released* in any order.)
  2001. m.fmut.RLock()
  2002. m.pmut.RLock()
  2003. defer m.pmut.RUnlock()
  2004. fs, ok := m.folderFiles[folder]
  2005. cfg := m.folderCfgs[folder]
  2006. m.fmut.RUnlock()
  2007. if !ok {
  2008. return nil
  2009. }
  2010. var availabilities []Availability
  2011. snap := fs.Snapshot()
  2012. defer snap.Release()
  2013. next:
  2014. for _, device := range snap.Availability(file.Name) {
  2015. for _, pausedFolder := range m.remotePausedFolders[device] {
  2016. if pausedFolder == folder {
  2017. continue next
  2018. }
  2019. }
  2020. _, ok := m.conn[device]
  2021. if ok {
  2022. availabilities = append(availabilities, Availability{ID: device, FromTemporary: false})
  2023. }
  2024. }
  2025. for _, device := range cfg.Devices {
  2026. if m.deviceDownloads[device.DeviceID].Has(folder, file.Name, file.Version, int32(block.Offset/int64(file.BlockSize()))) {
  2027. availabilities = append(availabilities, Availability{ID: device.DeviceID, FromTemporary: true})
  2028. }
  2029. }
  2030. return availabilities
  2031. }
  2032. // BringToFront bumps the given files priority in the job queue.
  2033. func (m *model) BringToFront(folder, file string) {
  2034. m.fmut.RLock()
  2035. runner, ok := m.folderRunners[folder]
  2036. m.fmut.RUnlock()
  2037. if ok {
  2038. runner.BringToFront(file)
  2039. }
  2040. }
  2041. func (m *model) ResetFolder(folder string) {
  2042. l.Infof("Cleaning data for folder %q", folder)
  2043. db.DropFolder(m.db, folder)
  2044. }
  2045. func (m *model) String() string {
  2046. return fmt.Sprintf("model@%p", m)
  2047. }
  2048. func (m *model) VerifyConfiguration(from, to config.Configuration) error {
  2049. return nil
  2050. }
  2051. func (m *model) CommitConfiguration(from, to config.Configuration) bool {
  2052. // TODO: This should not use reflect, and should take more care to try to handle stuff without restart.
  2053. // Go through the folder configs and figure out if we need to restart or not.
  2054. fromFolders := mapFolders(from.Folders)
  2055. toFolders := mapFolders(to.Folders)
  2056. for folderID, cfg := range toFolders {
  2057. if _, ok := fromFolders[folderID]; !ok {
  2058. // A folder was added.
  2059. if cfg.Paused {
  2060. l.Infoln("Paused folder", cfg.Description())
  2061. } else {
  2062. l.Infoln("Adding folder", cfg.Description())
  2063. m.newFolder(cfg)
  2064. }
  2065. }
  2066. }
  2067. for folderID, fromCfg := range fromFolders {
  2068. toCfg, ok := toFolders[folderID]
  2069. if !ok {
  2070. // The folder was removed.
  2071. m.removeFolder(fromCfg)
  2072. continue
  2073. }
  2074. if fromCfg.Paused && toCfg.Paused {
  2075. continue
  2076. }
  2077. // This folder exists on both sides. Settings might have changed.
  2078. // Check if anything differs that requires a restart.
  2079. if !reflect.DeepEqual(fromCfg.RequiresRestartOnly(), toCfg.RequiresRestartOnly()) {
  2080. m.restartFolder(fromCfg, toCfg)
  2081. }
  2082. // Emit the folder pause/resume event
  2083. if fromCfg.Paused != toCfg.Paused {
  2084. eventType := events.FolderResumed
  2085. if toCfg.Paused {
  2086. eventType = events.FolderPaused
  2087. }
  2088. m.evLogger.Log(eventType, map[string]string{"id": toCfg.ID, "label": toCfg.Label})
  2089. }
  2090. }
  2091. // Removing a device. We actually don't need to do anything.
  2092. // Because folder config has changed (since the device lists do not match)
  2093. // Folders for that had device got "restarted", which involves killing
  2094. // connections to all devices that we were sharing the folder with.
  2095. // At some point model.Close() will get called for that device which will
  2096. // clean residue device state that is not part of any folder.
  2097. // Pausing a device, unpausing is handled by the connection service.
  2098. fromDevices := from.DeviceMap()
  2099. toDevices := to.DeviceMap()
  2100. for deviceID, toCfg := range toDevices {
  2101. fromCfg, ok := fromDevices[deviceID]
  2102. if !ok {
  2103. sr := stats.NewDeviceStatisticsReference(m.db, deviceID.String())
  2104. m.fmut.Lock()
  2105. m.deviceStatRefs[deviceID] = sr
  2106. m.fmut.Unlock()
  2107. continue
  2108. }
  2109. delete(fromDevices, deviceID)
  2110. if fromCfg.Paused == toCfg.Paused {
  2111. continue
  2112. }
  2113. // Ignored folder was removed, reconnect to retrigger the prompt.
  2114. if len(fromCfg.IgnoredFolders) > len(toCfg.IgnoredFolders) {
  2115. m.closeConn(deviceID, errIgnoredFolderRemoved)
  2116. }
  2117. if toCfg.Paused {
  2118. l.Infoln("Pausing", deviceID)
  2119. m.closeConn(deviceID, errDevicePaused)
  2120. m.evLogger.Log(events.DevicePaused, map[string]string{"device": deviceID.String()})
  2121. } else {
  2122. m.evLogger.Log(events.DeviceResumed, map[string]string{"device": deviceID.String()})
  2123. }
  2124. }
  2125. m.fmut.Lock()
  2126. for deviceID := range fromDevices {
  2127. delete(m.deviceStatRefs, deviceID)
  2128. }
  2129. m.fmut.Unlock()
  2130. m.globalRequestLimiter.setCapacity(1024 * to.Options.MaxConcurrentIncomingRequestKiB())
  2131. m.folderIOLimiter.setCapacity(to.Options.MaxFolderConcurrency())
  2132. // Some options don't require restart as those components handle it fine
  2133. // by themselves. Compare the options structs containing only the
  2134. // attributes that require restart and act apprioriately.
  2135. if !reflect.DeepEqual(from.Options.RequiresRestartOnly(), to.Options.RequiresRestartOnly()) {
  2136. l.Debugln(m, "requires restart, options differ")
  2137. return false
  2138. }
  2139. return true
  2140. }
  2141. // checkFolderRunningLocked returns nil if the folder is up and running and a
  2142. // descriptive error if not.
  2143. // Need to hold (read) lock on m.fmut when calling this.
  2144. func (m *model) checkFolderRunningLocked(folder string) error {
  2145. _, ok := m.folderRunners[folder]
  2146. if ok {
  2147. return nil
  2148. }
  2149. if cfg, ok := m.cfg.Folder(folder); !ok {
  2150. return errFolderMissing
  2151. } else if cfg.Paused {
  2152. return ErrFolderPaused
  2153. }
  2154. return errFolderNotRunning
  2155. }
  2156. // mapFolders returns a map of folder ID to folder configuration for the given
  2157. // slice of folder configurations.
  2158. func mapFolders(folders []config.FolderConfiguration) map[string]config.FolderConfiguration {
  2159. m := make(map[string]config.FolderConfiguration, len(folders))
  2160. for _, cfg := range folders {
  2161. m[cfg.ID] = cfg
  2162. }
  2163. return m
  2164. }
  2165. // mapDevices returns a map of device ID to nothing for the given slice of
  2166. // device IDs.
  2167. func mapDevices(devices []protocol.DeviceID) map[protocol.DeviceID]struct{} {
  2168. m := make(map[protocol.DeviceID]struct{}, len(devices))
  2169. for _, dev := range devices {
  2170. m[dev] = struct{}{}
  2171. }
  2172. return m
  2173. }
  2174. func readOffsetIntoBuf(fs fs.Filesystem, file string, offset int64, buf []byte) error {
  2175. fd, err := fs.Open(file)
  2176. if err != nil {
  2177. l.Debugln("readOffsetIntoBuf.Open", file, err)
  2178. return err
  2179. }
  2180. defer fd.Close()
  2181. _, err = fd.ReadAt(buf, offset)
  2182. if err != nil {
  2183. l.Debugln("readOffsetIntoBuf.ReadAt", file, err)
  2184. }
  2185. return err
  2186. }
  2187. // makeForgetUpdate takes an index update and constructs a download progress update
  2188. // causing to forget any progress for files which we've just been sent.
  2189. func makeForgetUpdate(files []protocol.FileInfo) []protocol.FileDownloadProgressUpdate {
  2190. updates := make([]protocol.FileDownloadProgressUpdate, 0, len(files))
  2191. for _, file := range files {
  2192. if file.IsSymlink() || file.IsDirectory() || file.IsDeleted() {
  2193. continue
  2194. }
  2195. updates = append(updates, protocol.FileDownloadProgressUpdate{
  2196. Name: file.Name,
  2197. Version: file.Version,
  2198. UpdateType: protocol.UpdateTypeForget,
  2199. })
  2200. }
  2201. return updates
  2202. }
  2203. // folderDeviceSet is a set of (folder, deviceID) pairs
  2204. type folderDeviceSet map[string]map[protocol.DeviceID]struct{}
  2205. // set adds the (dev, folder) pair to the set
  2206. func (s folderDeviceSet) set(dev protocol.DeviceID, folder string) {
  2207. devs, ok := s[folder]
  2208. if !ok {
  2209. devs = make(map[protocol.DeviceID]struct{})
  2210. s[folder] = devs
  2211. }
  2212. devs[dev] = struct{}{}
  2213. }
  2214. // has returns true if the (dev, folder) pair is in the set
  2215. func (s folderDeviceSet) has(dev protocol.DeviceID, folder string) bool {
  2216. _, ok := s[folder][dev]
  2217. return ok
  2218. }
  2219. // hasDevice returns true if the device is set on any folder
  2220. func (s folderDeviceSet) hasDevice(dev protocol.DeviceID) bool {
  2221. for _, devices := range s {
  2222. if _, ok := devices[dev]; ok {
  2223. return true
  2224. }
  2225. }
  2226. return false
  2227. }
  2228. type fileInfoBatch struct {
  2229. infos []protocol.FileInfo
  2230. size int
  2231. flushFn func([]protocol.FileInfo) error
  2232. }
  2233. func newFileInfoBatch(fn func([]protocol.FileInfo) error) *fileInfoBatch {
  2234. return &fileInfoBatch{
  2235. infos: make([]protocol.FileInfo, 0, maxBatchSizeFiles),
  2236. flushFn: fn,
  2237. }
  2238. }
  2239. func (b *fileInfoBatch) append(f protocol.FileInfo) {
  2240. b.infos = append(b.infos, f)
  2241. b.size += f.ProtoSize()
  2242. }
  2243. func (b *fileInfoBatch) flushIfFull() error {
  2244. if len(b.infos) >= maxBatchSizeFiles || b.size >= maxBatchSizeBytes {
  2245. return b.flush()
  2246. }
  2247. return nil
  2248. }
  2249. func (b *fileInfoBatch) flush() error {
  2250. if len(b.infos) == 0 {
  2251. return nil
  2252. }
  2253. if err := b.flushFn(b.infos); err != nil {
  2254. return err
  2255. }
  2256. b.reset()
  2257. return nil
  2258. }
  2259. func (b *fileInfoBatch) reset() {
  2260. b.infos = b.infos[:0]
  2261. b.size = 0
  2262. }
  2263. // syncMutexMap is a type safe wrapper for a sync.Map that holds mutexes
  2264. type syncMutexMap struct {
  2265. inner stdsync.Map
  2266. }
  2267. func (m *syncMutexMap) Get(key string) sync.Mutex {
  2268. v, _ := m.inner.LoadOrStore(key, sync.NewMutex())
  2269. return v.(sync.Mutex)
  2270. }
  2271. // sanitizePath takes a string that might contain all kinds of special
  2272. // characters and makes a valid, similar, path name out of it.
  2273. //
  2274. // Spans of invalid characters, whitespace and/or non-UTF-8 sequences are
  2275. // replaced by a single space. The result is always UTF-8 and contains only
  2276. // printable characters, as determined by unicode.IsPrint.
  2277. //
  2278. // Invalid characters are non-printing runes, things not allowed in file names
  2279. // in Windows, and common shell metacharacters. Even if asterisks and pipes
  2280. // and stuff are allowed on Unixes in general they might not be allowed by
  2281. // the filesystem and may surprise the user and cause shell oddness. This
  2282. // function is intended for file names we generate on behalf of the user,
  2283. // and surprising them with odd shell characters in file names is unkind.
  2284. //
  2285. // We include whitespace in the invalid characters so that multiple
  2286. // whitespace is collapsed to a single space. Additionally, whitespace at
  2287. // either end is removed.
  2288. func sanitizePath(path string) string {
  2289. var b strings.Builder
  2290. prev := ' '
  2291. for _, c := range path {
  2292. if !unicode.IsPrint(c) || c == unicode.ReplacementChar ||
  2293. strings.ContainsRune(`<>:"'/\|?*[]{};:!@$%&^#`, c) {
  2294. c = ' '
  2295. }
  2296. if !(c == ' ' && prev == ' ') {
  2297. b.WriteRune(c)
  2298. }
  2299. prev = c
  2300. }
  2301. return strings.TrimSpace(b.String())
  2302. }