model.go 81 KB

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