model.go 80 KB

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