model.go 82 KB

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