model.go 84 KB

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