model.go 82 KB

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