model.go 79 KB

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