model.go 83 KB

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