model.go 80 KB

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