model.go 80 KB

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