model.go 83 KB

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