model.go 82 KB

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