model.go 81 KB

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