model.go 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482
  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 http://mozilla.org/MPL/2.0/.
  6. package model
  7. import (
  8. "bufio"
  9. "bytes"
  10. "crypto/tls"
  11. "encoding/json"
  12. "errors"
  13. "fmt"
  14. "io"
  15. "net"
  16. "os"
  17. "path/filepath"
  18. "reflect"
  19. "runtime"
  20. "sort"
  21. "strings"
  22. stdsync "sync"
  23. "time"
  24. "github.com/syncthing/syncthing/lib/config"
  25. "github.com/syncthing/syncthing/lib/connections"
  26. "github.com/syncthing/syncthing/lib/db"
  27. "github.com/syncthing/syncthing/lib/events"
  28. "github.com/syncthing/syncthing/lib/fs"
  29. "github.com/syncthing/syncthing/lib/ignore"
  30. "github.com/syncthing/syncthing/lib/osutil"
  31. "github.com/syncthing/syncthing/lib/protocol"
  32. "github.com/syncthing/syncthing/lib/scanner"
  33. "github.com/syncthing/syncthing/lib/stats"
  34. "github.com/syncthing/syncthing/lib/symlinks"
  35. "github.com/syncthing/syncthing/lib/sync"
  36. "github.com/syncthing/syncthing/lib/versioner"
  37. "github.com/thejerf/suture"
  38. )
  39. // How many files to send in each Index/IndexUpdate message.
  40. const (
  41. indexTargetSize = 250 * 1024 // Aim for making index messages no larger than 250 KiB (uncompressed)
  42. indexBatchSize = 1000 // Either way, don't include more files than this
  43. )
  44. type service interface {
  45. BringToFront(string)
  46. DelayScan(d time.Duration)
  47. IndexUpdated() // Remote index was updated notification
  48. Jobs() ([]string, []string) // In progress, Queued
  49. Scan(subs []string) error
  50. Serve()
  51. Stop()
  52. getState() (folderState, time.Time, error)
  53. setState(state folderState)
  54. clearError()
  55. setError(err error)
  56. }
  57. type Availability struct {
  58. ID protocol.DeviceID `json:"id"`
  59. FromTemporary bool `json:"fromTemporary"`
  60. }
  61. type Model struct {
  62. *suture.Supervisor
  63. cfg *config.Wrapper
  64. db *db.Instance
  65. finder *db.BlockFinder
  66. progressEmitter *ProgressEmitter
  67. id protocol.DeviceID
  68. shortID protocol.ShortID
  69. cacheIgnoredFiles bool
  70. protectedFiles []string
  71. deviceName string
  72. clientName string
  73. clientVersion string
  74. folderCfgs map[string]config.FolderConfiguration // folder -> cfg
  75. folderFiles map[string]*db.FileSet // folder -> files
  76. folderDevices map[string][]protocol.DeviceID // folder -> deviceIDs
  77. deviceFolders map[protocol.DeviceID][]string // deviceID -> folders
  78. deviceStatRefs map[protocol.DeviceID]*stats.DeviceStatisticsReference // deviceID -> statsRef
  79. folderIgnores map[string]*ignore.Matcher // folder -> matcher object
  80. folderRunners map[string]service // folder -> puller or scanner
  81. folderRunnerTokens map[string][]suture.ServiceToken // folder -> tokens for puller or scanner
  82. folderStatRefs map[string]*stats.FolderStatisticsReference // folder -> statsRef
  83. fmut sync.RWMutex // protects the above
  84. conn map[protocol.DeviceID]connections.Connection
  85. closed map[protocol.DeviceID]chan struct{}
  86. helloMessages map[protocol.DeviceID]protocol.HelloResult
  87. devicePaused map[protocol.DeviceID]bool
  88. deviceDownloads map[protocol.DeviceID]*deviceDownloadState
  89. pmut sync.RWMutex // protects the above
  90. }
  91. type folderFactory func(*Model, config.FolderConfiguration, versioner.Versioner, *fs.MtimeFS) service
  92. var (
  93. symlinkWarning = stdsync.Once{}
  94. folderFactories = make(map[config.FolderType]folderFactory, 0)
  95. )
  96. // errors returned by the CheckFolderHealth method
  97. var (
  98. errFolderPathEmpty = errors.New("folder path empty")
  99. errFolderPathMissing = errors.New("folder path missing")
  100. errFolderMarkerMissing = errors.New("folder marker missing")
  101. errHomeDiskNoSpace = errors.New("home disk has insufficient free space")
  102. errFolderNoSpace = errors.New("folder has insufficient free space")
  103. errUnsupportedSymlink = errors.New("symlink not supported")
  104. errInvalidFilename = errors.New("filename is invalid")
  105. errDeviceUnknown = errors.New("unknown device")
  106. errDevicePaused = errors.New("device is paused")
  107. errDeviceIgnored = errors.New("device is ignored")
  108. )
  109. // NewModel creates and starts a new model. The model starts in read-only mode,
  110. // where it sends index information to connected peers and responds to requests
  111. // for file data without altering the local folder in any way.
  112. func NewModel(cfg *config.Wrapper, id protocol.DeviceID, deviceName, clientName, clientVersion string, ldb *db.Instance, protectedFiles []string) *Model {
  113. m := &Model{
  114. Supervisor: suture.New("model", suture.Spec{
  115. Log: func(line string) {
  116. l.Debugln(line)
  117. },
  118. }),
  119. cfg: cfg,
  120. db: ldb,
  121. finder: db.NewBlockFinder(ldb),
  122. progressEmitter: NewProgressEmitter(cfg),
  123. id: id,
  124. shortID: id.Short(),
  125. cacheIgnoredFiles: cfg.Options().CacheIgnoredFiles,
  126. protectedFiles: protectedFiles,
  127. deviceName: deviceName,
  128. clientName: clientName,
  129. clientVersion: clientVersion,
  130. folderCfgs: make(map[string]config.FolderConfiguration),
  131. folderFiles: make(map[string]*db.FileSet),
  132. folderDevices: make(map[string][]protocol.DeviceID),
  133. deviceFolders: make(map[protocol.DeviceID][]string),
  134. deviceStatRefs: make(map[protocol.DeviceID]*stats.DeviceStatisticsReference),
  135. folderIgnores: make(map[string]*ignore.Matcher),
  136. folderRunners: make(map[string]service),
  137. folderRunnerTokens: make(map[string][]suture.ServiceToken),
  138. folderStatRefs: make(map[string]*stats.FolderStatisticsReference),
  139. conn: make(map[protocol.DeviceID]connections.Connection),
  140. closed: make(map[protocol.DeviceID]chan struct{}),
  141. helloMessages: make(map[protocol.DeviceID]protocol.HelloResult),
  142. devicePaused: make(map[protocol.DeviceID]bool),
  143. deviceDownloads: make(map[protocol.DeviceID]*deviceDownloadState),
  144. fmut: sync.NewRWMutex(),
  145. pmut: sync.NewRWMutex(),
  146. }
  147. if cfg.Options().ProgressUpdateIntervalS > -1 {
  148. go m.progressEmitter.Serve()
  149. }
  150. cfg.Subscribe(m)
  151. return m
  152. }
  153. // StartDeadlockDetector starts a deadlock detector on the models locks which
  154. // causes panics in case the locks cannot be acquired in the given timeout
  155. // period.
  156. func (m *Model) StartDeadlockDetector(timeout time.Duration) {
  157. l.Infof("Starting deadlock detector with %v timeout", timeout)
  158. deadlockDetect(m.fmut, timeout, "fmut")
  159. deadlockDetect(m.pmut, timeout, "pmut")
  160. }
  161. // StartFolder constructs the folder service and starts it.
  162. func (m *Model) StartFolder(folder string) {
  163. m.fmut.Lock()
  164. folderType := m.startFolderLocked(folder)
  165. m.fmut.Unlock()
  166. l.Infoln("Ready to synchronize", folder, fmt.Sprintf("(%s)", folderType))
  167. }
  168. func (m *Model) startFolderLocked(folder string) config.FolderType {
  169. cfg, ok := m.folderCfgs[folder]
  170. if !ok {
  171. panic("cannot start nonexistent folder " + folder)
  172. }
  173. _, ok = m.folderRunners[folder]
  174. if ok {
  175. panic("cannot start already running folder " + folder)
  176. }
  177. folderFactory, ok := folderFactories[cfg.Type]
  178. if !ok {
  179. panic(fmt.Sprintf("unknown folder type 0x%x", cfg.Type))
  180. }
  181. fs := m.folderFiles[folder]
  182. // Find any devices for which we hold the index in the db, but the folder
  183. // is not shared, and drop it.
  184. expected := mapDevices(cfg.DeviceIDs())
  185. for _, available := range fs.ListDevices() {
  186. if _, ok := expected[available]; !ok {
  187. l.Debugln("dropping", folder, "state for", available)
  188. fs.Replace(available, nil)
  189. }
  190. }
  191. v, ok := fs.Sequence(protocol.LocalDeviceID), true
  192. indexHasFiles := ok && v > 0
  193. if !indexHasFiles {
  194. // It's a blank folder, so this may the first time we're looking at
  195. // it. Attempt to create and tag with our marker as appropriate. We
  196. // don't really do anything with errors at this point except warn -
  197. // if these things don't work, we still want to start the folder and
  198. // it'll show up as errored later.
  199. if _, err := os.Stat(cfg.Path()); os.IsNotExist(err) {
  200. if err := osutil.MkdirAll(cfg.Path(), 0700); err != nil {
  201. l.Warnln("Creating folder:", err)
  202. }
  203. }
  204. if err := cfg.CreateMarker(); err != nil {
  205. l.Warnln("Creating folder marker:", err)
  206. }
  207. }
  208. var ver versioner.Versioner
  209. if len(cfg.Versioning.Type) > 0 {
  210. versionerFactory, ok := versioner.Factories[cfg.Versioning.Type]
  211. if !ok {
  212. l.Fatalf("Requested versioning type %q that does not exist", cfg.Versioning.Type)
  213. }
  214. ver = versionerFactory(folder, cfg.Path(), cfg.Versioning.Params)
  215. if service, ok := ver.(suture.Service); ok {
  216. // The versioner implements the suture.Service interface, so
  217. // expects to be run in the background in addition to being called
  218. // when files are going to be archived.
  219. token := m.Add(service)
  220. m.folderRunnerTokens[folder] = append(m.folderRunnerTokens[folder], token)
  221. }
  222. }
  223. p := folderFactory(m, cfg, ver, fs.MtimeFS())
  224. m.folderRunners[folder] = p
  225. m.warnAboutOverwritingProtectedFiles(folder)
  226. token := m.Add(p)
  227. m.folderRunnerTokens[folder] = append(m.folderRunnerTokens[folder], token)
  228. return cfg.Type
  229. }
  230. func (m *Model) warnAboutOverwritingProtectedFiles(folder string) {
  231. if m.folderCfgs[folder].Type == config.FolderTypeReadOnly {
  232. return
  233. }
  234. folderLocation := m.folderCfgs[folder].Path()
  235. ignores := m.folderIgnores[folder]
  236. var filesAtRisk []string
  237. for _, protectedFilePath := range m.protectedFiles {
  238. // check if file is synced in this folder
  239. if !strings.HasPrefix(protectedFilePath, folderLocation) {
  240. continue
  241. }
  242. // check if file is ignored
  243. if ignores.Match(protectedFilePath).IsIgnored() {
  244. continue
  245. }
  246. filesAtRisk = append(filesAtRisk, protectedFilePath)
  247. }
  248. if len(filesAtRisk) > 0 {
  249. 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, ", "))
  250. }
  251. }
  252. func (m *Model) AddFolder(cfg config.FolderConfiguration) {
  253. if len(cfg.ID) == 0 {
  254. panic("cannot add empty folder id")
  255. }
  256. m.fmut.Lock()
  257. m.addFolderLocked(cfg)
  258. m.fmut.Unlock()
  259. }
  260. func (m *Model) addFolderLocked(cfg config.FolderConfiguration) {
  261. m.folderCfgs[cfg.ID] = cfg
  262. m.folderFiles[cfg.ID] = db.NewFileSet(cfg.ID, m.db)
  263. m.folderDevices[cfg.ID] = make([]protocol.DeviceID, len(cfg.Devices))
  264. for i, device := range cfg.Devices {
  265. m.folderDevices[cfg.ID][i] = device.DeviceID
  266. m.deviceFolders[device.DeviceID] = append(m.deviceFolders[device.DeviceID], cfg.ID)
  267. }
  268. ignores := ignore.New(m.cacheIgnoredFiles)
  269. if err := ignores.Load(filepath.Join(cfg.Path(), ".stignore")); err != nil && !os.IsNotExist(err) {
  270. l.Warnln("Loading ignores:", err)
  271. }
  272. m.folderIgnores[cfg.ID] = ignores
  273. }
  274. func (m *Model) RemoveFolder(folder string) {
  275. m.fmut.Lock()
  276. m.pmut.Lock()
  277. m.tearDownFolderLocked(folder)
  278. // Remove it from the database
  279. db.DropFolder(m.db, folder)
  280. m.pmut.Unlock()
  281. m.fmut.Unlock()
  282. }
  283. func (m *Model) tearDownFolderLocked(folder string) {
  284. // Stop the services running for this folder
  285. for _, id := range m.folderRunnerTokens[folder] {
  286. m.Remove(id)
  287. }
  288. // Close connections to affected devices
  289. for _, dev := range m.folderDevices[folder] {
  290. if conn, ok := m.conn[dev]; ok {
  291. closeRawConn(conn)
  292. }
  293. }
  294. // Clean up our config maps
  295. delete(m.folderCfgs, folder)
  296. delete(m.folderFiles, folder)
  297. delete(m.folderDevices, folder)
  298. delete(m.folderIgnores, folder)
  299. delete(m.folderRunners, folder)
  300. delete(m.folderRunnerTokens, folder)
  301. delete(m.folderStatRefs, folder)
  302. for dev, folders := range m.deviceFolders {
  303. m.deviceFolders[dev] = stringSliceWithout(folders, folder)
  304. }
  305. }
  306. func (m *Model) RestartFolder(cfg config.FolderConfiguration) {
  307. if len(cfg.ID) == 0 {
  308. panic("cannot add empty folder id")
  309. }
  310. m.fmut.Lock()
  311. m.pmut.Lock()
  312. m.tearDownFolderLocked(cfg.ID)
  313. m.addFolderLocked(cfg)
  314. folderType := m.startFolderLocked(cfg.ID)
  315. m.pmut.Unlock()
  316. m.fmut.Unlock()
  317. l.Infoln("Restarted folder", cfg.ID, fmt.Sprintf("(%s)", folderType))
  318. }
  319. type ConnectionInfo struct {
  320. protocol.Statistics
  321. Connected bool
  322. Paused bool
  323. Address string
  324. ClientVersion string
  325. Type string
  326. }
  327. func (info ConnectionInfo) MarshalJSON() ([]byte, error) {
  328. return json.Marshal(map[string]interface{}{
  329. "at": info.At,
  330. "inBytesTotal": info.InBytesTotal,
  331. "outBytesTotal": info.OutBytesTotal,
  332. "connected": info.Connected,
  333. "paused": info.Paused,
  334. "address": info.Address,
  335. "clientVersion": info.ClientVersion,
  336. "type": info.Type,
  337. })
  338. }
  339. // ConnectionStats returns a map with connection statistics for each device.
  340. func (m *Model) ConnectionStats() map[string]interface{} {
  341. m.fmut.RLock()
  342. m.pmut.RLock()
  343. res := make(map[string]interface{})
  344. devs := m.cfg.Devices()
  345. conns := make(map[string]ConnectionInfo, len(devs))
  346. for device := range devs {
  347. hello := m.helloMessages[device]
  348. versionString := hello.ClientVersion
  349. if hello.ClientName != "syncthing" {
  350. versionString = hello.ClientName + " " + hello.ClientVersion
  351. }
  352. ci := ConnectionInfo{
  353. ClientVersion: strings.TrimSpace(versionString),
  354. Paused: m.devicePaused[device],
  355. }
  356. if conn, ok := m.conn[device]; ok {
  357. ci.Type = conn.Type
  358. ci.Connected = ok
  359. ci.Statistics = conn.Statistics()
  360. if addr := conn.RemoteAddr(); addr != nil {
  361. ci.Address = addr.String()
  362. }
  363. }
  364. conns[device.String()] = ci
  365. }
  366. res["connections"] = conns
  367. m.pmut.RUnlock()
  368. m.fmut.RUnlock()
  369. in, out := protocol.TotalInOut()
  370. res["total"] = ConnectionInfo{
  371. Statistics: protocol.Statistics{
  372. At: time.Now(),
  373. InBytesTotal: in,
  374. OutBytesTotal: out,
  375. },
  376. }
  377. return res
  378. }
  379. // DeviceStatistics returns statistics about each device
  380. func (m *Model) DeviceStatistics() map[string]stats.DeviceStatistics {
  381. var res = make(map[string]stats.DeviceStatistics)
  382. for id := range m.cfg.Devices() {
  383. res[id.String()] = m.deviceStatRef(id).GetStatistics()
  384. }
  385. return res
  386. }
  387. // FolderStatistics returns statistics about each folder
  388. func (m *Model) FolderStatistics() map[string]stats.FolderStatistics {
  389. var res = make(map[string]stats.FolderStatistics)
  390. for id := range m.cfg.Folders() {
  391. res[id] = m.folderStatRef(id).GetStatistics()
  392. }
  393. return res
  394. }
  395. type FolderCompletion struct {
  396. CompletionPct float64
  397. NeedBytes int64
  398. GlobalBytes int64
  399. NeedDeletes int64
  400. }
  401. // Completion returns the completion status, in percent, for the given device
  402. // and folder.
  403. func (m *Model) Completion(device protocol.DeviceID, folder string) FolderCompletion {
  404. m.fmut.RLock()
  405. rf, ok := m.folderFiles[folder]
  406. m.fmut.RUnlock()
  407. if !ok {
  408. return FolderCompletion{} // Folder doesn't exist, so we hardly have any of it
  409. }
  410. tot := rf.GlobalSize().Bytes
  411. if tot == 0 {
  412. // Folder is empty, so we have all of it
  413. return FolderCompletion{
  414. CompletionPct: 100,
  415. }
  416. }
  417. m.pmut.RLock()
  418. counts := m.deviceDownloads[device].GetBlockCounts(folder)
  419. m.pmut.RUnlock()
  420. var need, fileNeed, downloaded, deletes int64
  421. rf.WithNeedTruncated(device, func(f db.FileIntf) bool {
  422. ft := f.(db.FileInfoTruncated)
  423. // If the file is deleted, we account it only in the deleted column.
  424. if ft.Deleted {
  425. deletes++
  426. return true
  427. }
  428. // This might might be more than it really is, because some blocks can be of a smaller size.
  429. downloaded = int64(counts[ft.Name] * protocol.BlockSize)
  430. fileNeed = ft.FileSize() - downloaded
  431. if fileNeed < 0 {
  432. fileNeed = 0
  433. }
  434. need += fileNeed
  435. return true
  436. })
  437. needRatio := float64(need) / float64(tot)
  438. completionPct := 100 * (1 - needRatio)
  439. // If the completion is 100% but there are deletes we need to handle,
  440. // drop it down a notch. Hack for consumers that look only at the
  441. // percentage (our own GUI does the same calculation as here on it's own
  442. // and needs the same fixup).
  443. if need == 0 && deletes > 0 {
  444. completionPct = 95 // chosen by fair dice roll
  445. }
  446. l.Debugf("%v Completion(%s, %q): %f (%d / %d = %f)", m, device, folder, completionPct, need, tot, needRatio)
  447. return FolderCompletion{
  448. CompletionPct: completionPct,
  449. NeedBytes: need,
  450. GlobalBytes: tot,
  451. NeedDeletes: deletes,
  452. }
  453. }
  454. func addSizeOfFile(s *db.Counts, f db.FileIntf) {
  455. switch {
  456. case f.IsDeleted():
  457. s.Deleted++
  458. case f.IsDirectory():
  459. s.Directories++
  460. case f.IsSymlink():
  461. s.Symlinks++
  462. default:
  463. s.Files++
  464. }
  465. s.Bytes += f.FileSize()
  466. return
  467. }
  468. // GlobalSize returns the number of files, deleted files and total bytes for all
  469. // files in the global model.
  470. func (m *Model) GlobalSize(folder string) db.Counts {
  471. m.fmut.RLock()
  472. defer m.fmut.RUnlock()
  473. if rf, ok := m.folderFiles[folder]; ok {
  474. return rf.GlobalSize()
  475. }
  476. return db.Counts{}
  477. }
  478. // LocalSize returns the number of files, deleted files and total bytes for all
  479. // files in the local folder.
  480. func (m *Model) LocalSize(folder string) db.Counts {
  481. m.fmut.RLock()
  482. defer m.fmut.RUnlock()
  483. if rf, ok := m.folderFiles[folder]; ok {
  484. return rf.LocalSize()
  485. }
  486. return db.Counts{}
  487. }
  488. // NeedSize returns the number and total size of currently needed files.
  489. func (m *Model) NeedSize(folder string) db.Counts {
  490. m.fmut.RLock()
  491. defer m.fmut.RUnlock()
  492. var result db.Counts
  493. if rf, ok := m.folderFiles[folder]; ok {
  494. ignores := m.folderIgnores[folder]
  495. cfg := m.folderCfgs[folder]
  496. rf.WithNeedTruncated(protocol.LocalDeviceID, func(f db.FileIntf) bool {
  497. if shouldIgnore(f, ignores, cfg.IgnoreDelete) {
  498. return true
  499. }
  500. addSizeOfFile(&result, f)
  501. return true
  502. })
  503. }
  504. result.Bytes -= m.progressEmitter.BytesCompleted(folder)
  505. l.Debugf("%v NeedSize(%q): %v", m, folder, result)
  506. return result
  507. }
  508. // NeedFolderFiles returns paginated list of currently needed files in
  509. // progress, queued, and to be queued on next puller iteration, as well as the
  510. // total number of files currently needed.
  511. func (m *Model) NeedFolderFiles(folder string, page, perpage int) ([]db.FileInfoTruncated, []db.FileInfoTruncated, []db.FileInfoTruncated, int) {
  512. m.fmut.RLock()
  513. defer m.fmut.RUnlock()
  514. total := 0
  515. rf, ok := m.folderFiles[folder]
  516. if !ok {
  517. return nil, nil, nil, 0
  518. }
  519. var progress, queued, rest []db.FileInfoTruncated
  520. var seen map[string]struct{}
  521. skip := (page - 1) * perpage
  522. get := perpage
  523. runner, ok := m.folderRunners[folder]
  524. if ok {
  525. allProgressNames, allQueuedNames := runner.Jobs()
  526. var progressNames, queuedNames []string
  527. progressNames, skip, get = getChunk(allProgressNames, skip, get)
  528. queuedNames, skip, get = getChunk(allQueuedNames, skip, get)
  529. progress = make([]db.FileInfoTruncated, len(progressNames))
  530. queued = make([]db.FileInfoTruncated, len(queuedNames))
  531. seen = make(map[string]struct{}, len(progressNames)+len(queuedNames))
  532. for i, name := range progressNames {
  533. if f, ok := rf.GetGlobalTruncated(name); ok {
  534. progress[i] = f
  535. seen[name] = struct{}{}
  536. }
  537. }
  538. for i, name := range queuedNames {
  539. if f, ok := rf.GetGlobalTruncated(name); ok {
  540. queued[i] = f
  541. seen[name] = struct{}{}
  542. }
  543. }
  544. }
  545. rest = make([]db.FileInfoTruncated, 0, perpage)
  546. ignores := m.folderIgnores[folder]
  547. cfg := m.folderCfgs[folder]
  548. rf.WithNeedTruncated(protocol.LocalDeviceID, func(f db.FileIntf) bool {
  549. if shouldIgnore(f, ignores, cfg.IgnoreDelete) {
  550. return true
  551. }
  552. total++
  553. if skip > 0 {
  554. skip--
  555. return true
  556. }
  557. if get > 0 {
  558. ft := f.(db.FileInfoTruncated)
  559. if _, ok := seen[ft.Name]; !ok {
  560. rest = append(rest, ft)
  561. get--
  562. }
  563. }
  564. return true
  565. })
  566. return progress, queued, rest, total
  567. }
  568. // Index is called when a new device is connected and we receive their full index.
  569. // Implements the protocol.Model interface.
  570. func (m *Model) Index(deviceID protocol.DeviceID, folder string, fs []protocol.FileInfo) {
  571. l.Debugf("IDX(in): %s %q: %d files", deviceID, folder, len(fs))
  572. if !m.folderSharedWith(folder, deviceID) {
  573. l.Debugf("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.", folder, deviceID)
  574. return
  575. }
  576. m.fmut.RLock()
  577. files, ok := m.folderFiles[folder]
  578. runner := m.folderRunners[folder]
  579. m.fmut.RUnlock()
  580. if runner != nil {
  581. // Runner may legitimately not be set if this is the "cleanup" Index
  582. // message at startup.
  583. defer runner.IndexUpdated()
  584. }
  585. if !ok {
  586. l.Fatalf("Index for nonexistent folder %q", folder)
  587. }
  588. m.pmut.RLock()
  589. m.deviceDownloads[deviceID].Update(folder, makeForgetUpdate(fs))
  590. m.pmut.RUnlock()
  591. files.Replace(deviceID, fs)
  592. events.Default.Log(events.RemoteIndexUpdated, map[string]interface{}{
  593. "device": deviceID.String(),
  594. "folder": folder,
  595. "items": len(fs),
  596. "version": files.Sequence(deviceID),
  597. })
  598. }
  599. // IndexUpdate is called for incremental updates to connected devices' indexes.
  600. // Implements the protocol.Model interface.
  601. func (m *Model) IndexUpdate(deviceID protocol.DeviceID, folder string, fs []protocol.FileInfo) {
  602. l.Debugf("%v IDXUP(in): %s / %q: %d files", m, deviceID, folder, len(fs))
  603. if !m.folderSharedWith(folder, deviceID) {
  604. l.Debugf("Update 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.", folder, deviceID)
  605. return
  606. }
  607. m.fmut.RLock()
  608. files := m.folderFiles[folder]
  609. runner, ok := m.folderRunners[folder]
  610. m.fmut.RUnlock()
  611. if !ok {
  612. l.Fatalf("IndexUpdate for nonexistent folder %q", folder)
  613. }
  614. m.pmut.RLock()
  615. m.deviceDownloads[deviceID].Update(folder, makeForgetUpdate(fs))
  616. m.pmut.RUnlock()
  617. files.Update(deviceID, fs)
  618. events.Default.Log(events.RemoteIndexUpdated, map[string]interface{}{
  619. "device": deviceID.String(),
  620. "folder": folder,
  621. "items": len(fs),
  622. "version": files.Sequence(deviceID),
  623. })
  624. runner.IndexUpdated()
  625. }
  626. func (m *Model) folderSharedWith(folder string, deviceID protocol.DeviceID) bool {
  627. m.fmut.RLock()
  628. defer m.fmut.RUnlock()
  629. return m.folderSharedWithLocked(folder, deviceID)
  630. }
  631. func (m *Model) folderSharedWithLocked(folder string, deviceID protocol.DeviceID) bool {
  632. for _, nfolder := range m.deviceFolders[deviceID] {
  633. if nfolder == folder {
  634. return true
  635. }
  636. }
  637. return false
  638. }
  639. func (m *Model) ClusterConfig(deviceID protocol.DeviceID, cm protocol.ClusterConfig) {
  640. // Check the peer device's announced folders against our own. Emits events
  641. // for folders that we don't expect (unknown or not shared).
  642. // Also, collect a list of folders we do share, and if he's interested in
  643. // temporary indexes, subscribe the connection.
  644. tempIndexFolders := make([]string, 0, len(cm.Folders))
  645. m.pmut.RLock()
  646. conn, ok := m.conn[deviceID]
  647. m.pmut.RUnlock()
  648. if !ok {
  649. panic("bug: ClusterConfig called on closed or nonexistent connection")
  650. }
  651. dbLocation := filepath.Dir(m.db.Location())
  652. m.fmut.Lock()
  653. for _, folder := range cm.Folders {
  654. if !m.folderSharedWithLocked(folder.ID, deviceID) {
  655. events.Default.Log(events.FolderRejected, map[string]string{
  656. "folder": folder.ID,
  657. "folderLabel": folder.Label,
  658. "device": deviceID.String(),
  659. })
  660. l.Infof("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.", folder.ID, deviceID)
  661. continue
  662. }
  663. if !folder.DisableTempIndexes {
  664. tempIndexFolders = append(tempIndexFolders, folder.ID)
  665. }
  666. fs := m.folderFiles[folder.ID]
  667. myIndexID := fs.IndexID(protocol.LocalDeviceID)
  668. mySequence := fs.Sequence(protocol.LocalDeviceID)
  669. var startSequence int64
  670. for _, dev := range folder.Devices {
  671. if bytes.Equal(dev.ID, m.id[:]) {
  672. // This is the other side's description of what it knows
  673. // about us. Lets check to see if we can start sending index
  674. // updates directly or need to send the index from start...
  675. if dev.IndexID == myIndexID {
  676. // They say they've seen our index ID before, so we can
  677. // send a delta update only.
  678. if dev.MaxSequence > mySequence {
  679. // Safety check. They claim to have more or newer
  680. // index data than we have - either we have lost
  681. // index data, or reset the index without resetting
  682. // the IndexID, or something else weird has
  683. // happened. We send a full index to reset the
  684. // situation.
  685. l.Infof("Device %v folder %q is delta index compatible, but seems out of sync with reality", deviceID, folder.ID)
  686. startSequence = 0
  687. continue
  688. }
  689. l.Debugf("Device %v folder %q is delta index compatible (mlv=%d)", deviceID, folder.ID, dev.MaxSequence)
  690. startSequence = dev.MaxSequence
  691. } else if dev.IndexID != 0 {
  692. // They say they've seen an index ID from us, but it's
  693. // not the right one. Either they are confused or we
  694. // must have reset our database since last talking to
  695. // them. We'll start with a full index transfer.
  696. l.Infof("Device %v folder %q has mismatching index ID for us (%v != %v)", deviceID, folder.ID, dev.IndexID, myIndexID)
  697. startSequence = 0
  698. }
  699. } else if bytes.Equal(dev.ID, deviceID[:]) && dev.IndexID != 0 {
  700. // This is the other side's description of themselves. We
  701. // check to see that it matches the IndexID we have on file,
  702. // otherwise we drop our old index data and expect to get a
  703. // completely new set.
  704. theirIndexID := fs.IndexID(deviceID)
  705. if dev.IndexID == 0 {
  706. // They're not announcing an index ID. This means they
  707. // do not support delta indexes and we should clear any
  708. // information we have from them before accepting their
  709. // index, which will presumably be a full index.
  710. fs.Replace(deviceID, nil)
  711. } else if dev.IndexID != theirIndexID {
  712. // The index ID we have on file is not what they're
  713. // announcing. They must have reset their database and
  714. // will probably send us a full index. We drop any
  715. // information we have and remember this new index ID
  716. // instead.
  717. l.Infof("Device %v folder %q has a new index ID (%v)", deviceID, folder.ID, dev.IndexID)
  718. fs.Replace(deviceID, nil)
  719. fs.SetIndexID(deviceID, dev.IndexID)
  720. } else {
  721. // They're sending a recognized index ID and will most
  722. // likely use delta indexes. We might already have files
  723. // that we need to pull so let the folder runner know
  724. // that it should recheck the index data.
  725. if runner := m.folderRunners[folder.ID]; runner != nil {
  726. defer runner.IndexUpdated()
  727. }
  728. }
  729. }
  730. }
  731. go sendIndexes(conn, folder.ID, fs, m.folderIgnores[folder.ID], startSequence, dbLocation)
  732. }
  733. m.fmut.Unlock()
  734. // This breaks if we send multiple CM messages during the same connection.
  735. if len(tempIndexFolders) > 0 {
  736. m.pmut.RLock()
  737. conn, ok := m.conn[deviceID]
  738. m.pmut.RUnlock()
  739. // In case we've got ClusterConfig, and the connection disappeared
  740. // from infront of our nose.
  741. if ok {
  742. m.progressEmitter.temporaryIndexSubscribe(conn, tempIndexFolders)
  743. }
  744. }
  745. var changed bool
  746. if m.cfg.Devices()[deviceID].Introducer {
  747. // This device is an introducer. Go through the announced lists of folders
  748. // and devices and add what we are missing.
  749. for _, folder := range cm.Folders {
  750. if _, ok := m.folderDevices[folder.ID]; !ok {
  751. continue
  752. }
  753. nextDevice:
  754. for _, device := range folder.Devices {
  755. var id protocol.DeviceID
  756. copy(id[:], device.ID)
  757. if _, ok := m.cfg.Devices()[id]; !ok {
  758. // The device is currently unknown. Add it to the config.
  759. addresses := []string{"dynamic"}
  760. for _, addr := range device.Addresses {
  761. if addr != "dynamic" {
  762. addresses = append(addresses, addr)
  763. }
  764. }
  765. l.Infof("Adding device %v to config (vouched for by introducer %v)", id, deviceID)
  766. newDeviceCfg := config.DeviceConfiguration{
  767. DeviceID: id,
  768. Name: device.Name,
  769. Compression: m.cfg.Devices()[deviceID].Compression,
  770. Addresses: addresses,
  771. CertName: device.CertName,
  772. }
  773. // The introducers' introducers are also our introducers.
  774. if device.Introducer {
  775. l.Infof("Device %v is now also an introducer", id)
  776. newDeviceCfg.Introducer = true
  777. }
  778. m.cfg.SetDevice(newDeviceCfg)
  779. changed = true
  780. }
  781. for _, er := range m.deviceFolders[id] {
  782. if er == folder.ID {
  783. // We already share the folder with this device, so
  784. // nothing to do.
  785. continue nextDevice
  786. }
  787. }
  788. // We don't yet share this folder with this device. Add the device
  789. // to sharing list of the folder.
  790. l.Infof("Adding device %v to share %q (vouched for by introducer %v)", id, folder.ID, deviceID)
  791. m.deviceFolders[id] = append(m.deviceFolders[id], folder.ID)
  792. m.folderDevices[folder.ID] = append(m.folderDevices[folder.ID], id)
  793. folderCfg := m.cfg.Folders()[folder.ID]
  794. folderCfg.Devices = append(folderCfg.Devices, config.FolderDeviceConfiguration{
  795. DeviceID: id,
  796. })
  797. m.cfg.SetFolder(folderCfg)
  798. changed = true
  799. }
  800. }
  801. }
  802. if changed {
  803. m.cfg.Save()
  804. }
  805. }
  806. // Closed is called when a connection has been closed
  807. func (m *Model) Closed(conn protocol.Connection, err error) {
  808. device := conn.ID()
  809. m.pmut.Lock()
  810. conn, ok := m.conn[device]
  811. if ok {
  812. m.progressEmitter.temporaryIndexUnsubscribe(conn)
  813. }
  814. delete(m.conn, device)
  815. delete(m.helloMessages, device)
  816. delete(m.deviceDownloads, device)
  817. closed := m.closed[device]
  818. delete(m.closed, device)
  819. m.pmut.Unlock()
  820. l.Infof("Connection to %s closed: %v", device, err)
  821. events.Default.Log(events.DeviceDisconnected, map[string]string{
  822. "id": device.String(),
  823. "error": err.Error(),
  824. })
  825. close(closed)
  826. }
  827. // close will close the underlying connection for a given device
  828. func (m *Model) close(device protocol.DeviceID) {
  829. m.pmut.Lock()
  830. conn, ok := m.conn[device]
  831. m.pmut.Unlock()
  832. if !ok {
  833. // There is no connection to close
  834. return
  835. }
  836. closeRawConn(conn)
  837. }
  838. // Request returns the specified data segment by reading it from local disk.
  839. // Implements the protocol.Model interface.
  840. func (m *Model) Request(deviceID protocol.DeviceID, folder, name string, offset int64, hash []byte, fromTemporary bool, buf []byte) error {
  841. if offset < 0 {
  842. return protocol.ErrInvalid
  843. }
  844. if !m.folderSharedWith(folder, deviceID) {
  845. l.Warnf("Request from %s for file %s in unshared folder %q", deviceID, name, folder)
  846. return protocol.ErrNoSuchFile
  847. }
  848. if deviceID != protocol.LocalDeviceID {
  849. l.Debugf("%v REQ(in): %s: %q / %q o=%d s=%d t=%v", m, deviceID, folder, name, offset, len(buf), fromTemporary)
  850. }
  851. m.fmut.RLock()
  852. folderCfg := m.folderCfgs[folder]
  853. folderPath := folderCfg.Path()
  854. folderIgnores := m.folderIgnores[folder]
  855. m.fmut.RUnlock()
  856. // filepath.Join() returns a filepath.Clean()ed path, which (quoting the
  857. // docs for clarity here):
  858. //
  859. // Clean returns the shortest path name equivalent to path by purely lexical
  860. // processing. It applies the following rules iteratively until no further
  861. // processing can be done:
  862. //
  863. // 1. Replace multiple Separator elements with a single one.
  864. // 2. Eliminate each . path name element (the current directory).
  865. // 3. Eliminate each inner .. path name element (the parent directory)
  866. // along with the non-.. element that precedes it.
  867. // 4. Eliminate .. elements that begin a rooted path:
  868. // that is, replace "/.." by "/" at the beginning of a path,
  869. // assuming Separator is '/'.
  870. fn := filepath.Join(folderPath, name)
  871. if !strings.HasPrefix(fn, folderPath) {
  872. // Request tries to escape!
  873. l.Debugf("%v Invalid REQ(in) tries to escape: %s: %q / %q o=%d s=%d", m, deviceID, folder, name, offset, len(buf))
  874. return protocol.ErrInvalid
  875. }
  876. if folderIgnores != nil {
  877. // "rn" becomes the relative name of the file within the folder. This is
  878. // different than the original "name" parameter in that it's been
  879. // cleaned from any possible funny business.
  880. if rn, err := filepath.Rel(folderPath, fn); err != nil {
  881. return err
  882. } else if folderIgnores.Match(rn).IsIgnored() {
  883. l.Debugf("%v REQ(in) for ignored file: %s: %q / %q o=%d s=%d", m, deviceID, folder, name, offset, len(buf))
  884. return protocol.ErrNoSuchFile
  885. }
  886. }
  887. if info, err := osutil.Lstat(fn); err == nil && info.Mode()&os.ModeSymlink != 0 {
  888. target, _, err := symlinks.Read(fn)
  889. if err != nil {
  890. l.Debugln("symlinks.Read:", err)
  891. if os.IsNotExist(err) {
  892. return protocol.ErrNoSuchFile
  893. }
  894. return protocol.ErrGeneric
  895. }
  896. if _, err := strings.NewReader(target).ReadAt(buf, offset); err != nil {
  897. l.Debugln("symlink.Reader.ReadAt", err)
  898. return protocol.ErrGeneric
  899. }
  900. return nil
  901. }
  902. // Only check temp files if the flag is set, and if we are set to advertise
  903. // the temp indexes.
  904. if fromTemporary && !folderCfg.DisableTempIndexes {
  905. tempFn := filepath.Join(folderPath, defTempNamer.TempName(name))
  906. if err := readOffsetIntoBuf(tempFn, offset, buf); err == nil {
  907. return nil
  908. }
  909. // Fall through to reading from a non-temp file, just incase the temp
  910. // file has finished downloading.
  911. }
  912. err := readOffsetIntoBuf(fn, offset, buf)
  913. if os.IsNotExist(err) {
  914. return protocol.ErrNoSuchFile
  915. } else if err != nil {
  916. return protocol.ErrGeneric
  917. }
  918. return nil
  919. }
  920. func (m *Model) CurrentFolderFile(folder string, file string) (protocol.FileInfo, bool) {
  921. m.fmut.RLock()
  922. fs, ok := m.folderFiles[folder]
  923. m.fmut.RUnlock()
  924. if !ok {
  925. return protocol.FileInfo{}, false
  926. }
  927. f, ok := fs.Get(protocol.LocalDeviceID, file)
  928. return f, ok
  929. }
  930. func (m *Model) CurrentGlobalFile(folder string, file string) (protocol.FileInfo, bool) {
  931. m.fmut.RLock()
  932. fs, ok := m.folderFiles[folder]
  933. m.fmut.RUnlock()
  934. if !ok {
  935. return protocol.FileInfo{}, false
  936. }
  937. f, ok := fs.GetGlobal(file)
  938. return f, ok
  939. }
  940. type cFiler struct {
  941. m *Model
  942. r string
  943. }
  944. // Implements scanner.CurrentFiler
  945. func (cf cFiler) CurrentFile(file string) (protocol.FileInfo, bool) {
  946. return cf.m.CurrentFolderFile(cf.r, file)
  947. }
  948. // ConnectedTo returns true if we are connected to the named device.
  949. func (m *Model) ConnectedTo(deviceID protocol.DeviceID) bool {
  950. m.pmut.RLock()
  951. _, ok := m.conn[deviceID]
  952. m.pmut.RUnlock()
  953. if ok {
  954. m.deviceWasSeen(deviceID)
  955. }
  956. return ok
  957. }
  958. func (m *Model) GetIgnores(folder string) ([]string, []string, error) {
  959. var lines []string
  960. m.fmut.RLock()
  961. cfg, ok := m.folderCfgs[folder]
  962. m.fmut.RUnlock()
  963. if !ok {
  964. return lines, nil, fmt.Errorf("Folder %s does not exist", folder)
  965. }
  966. if !cfg.HasMarker() {
  967. return lines, nil, fmt.Errorf("Folder %s stopped", folder)
  968. }
  969. fd, err := os.Open(filepath.Join(cfg.Path(), ".stignore"))
  970. if err != nil {
  971. if os.IsNotExist(err) {
  972. return lines, nil, nil
  973. }
  974. l.Warnln("Loading .stignore:", err)
  975. return lines, nil, err
  976. }
  977. defer fd.Close()
  978. scanner := bufio.NewScanner(fd)
  979. for scanner.Scan() {
  980. lines = append(lines, strings.TrimSpace(scanner.Text()))
  981. }
  982. m.fmut.RLock()
  983. patterns := m.folderIgnores[folder].Patterns()
  984. m.fmut.RUnlock()
  985. return lines, patterns, nil
  986. }
  987. func (m *Model) SetIgnores(folder string, content []string) error {
  988. cfg, ok := m.folderCfgs[folder]
  989. if !ok {
  990. return fmt.Errorf("Folder %s does not exist", folder)
  991. }
  992. path := filepath.Join(cfg.Path(), ".stignore")
  993. fd, err := osutil.CreateAtomic(path, 0644)
  994. if err != nil {
  995. l.Warnln("Saving .stignore:", err)
  996. return err
  997. }
  998. for _, line := range content {
  999. fmt.Fprintln(fd, line)
  1000. }
  1001. if err := fd.Close(); err != nil {
  1002. l.Warnln("Saving .stignore:", err)
  1003. return err
  1004. }
  1005. osutil.HideFile(path)
  1006. return m.ScanFolder(folder)
  1007. }
  1008. // OnHello is called when an device connects to us.
  1009. // This allows us to extract some information from the Hello message
  1010. // and add it to a list of known devices ahead of any checks.
  1011. func (m *Model) OnHello(remoteID protocol.DeviceID, addr net.Addr, hello protocol.HelloResult) error {
  1012. if m.IsPaused(remoteID) {
  1013. return errDevicePaused
  1014. }
  1015. if m.cfg.IgnoredDevice(remoteID) {
  1016. return errDeviceIgnored
  1017. }
  1018. if _, ok := m.cfg.Device(remoteID); ok {
  1019. // The device exists
  1020. return nil
  1021. }
  1022. events.Default.Log(events.DeviceRejected, map[string]string{
  1023. "name": hello.DeviceName,
  1024. "device": remoteID.String(),
  1025. "address": addr.String(),
  1026. })
  1027. return errDeviceUnknown
  1028. }
  1029. // GetHello is called when we are about to connect to some remote device.
  1030. func (m *Model) GetHello(protocol.DeviceID) protocol.HelloIntf {
  1031. return &protocol.Hello{
  1032. DeviceName: m.deviceName,
  1033. ClientName: m.clientName,
  1034. ClientVersion: m.clientVersion,
  1035. }
  1036. }
  1037. // AddConnection adds a new peer connection to the model. An initial index will
  1038. // be sent to the connected peer, thereafter index updates whenever the local
  1039. // folder changes.
  1040. func (m *Model) AddConnection(conn connections.Connection, hello protocol.HelloResult) {
  1041. deviceID := conn.ID()
  1042. m.pmut.Lock()
  1043. if oldConn, ok := m.conn[deviceID]; ok {
  1044. l.Infoln("Replacing old connection", oldConn, "with", conn, "for", deviceID)
  1045. // There is an existing connection to this device that we are
  1046. // replacing. We must close the existing connection and wait for the
  1047. // close to complete before adding the new connection. We do the
  1048. // actual close without holding pmut as the connection will call
  1049. // back into Closed() for the cleanup.
  1050. closed := m.closed[deviceID]
  1051. m.pmut.Unlock()
  1052. closeRawConn(oldConn)
  1053. <-closed
  1054. m.pmut.Lock()
  1055. }
  1056. m.conn[deviceID] = conn
  1057. m.closed[deviceID] = make(chan struct{})
  1058. m.deviceDownloads[deviceID] = newDeviceDownloadState()
  1059. m.helloMessages[deviceID] = hello
  1060. event := map[string]string{
  1061. "id": deviceID.String(),
  1062. "deviceName": hello.DeviceName,
  1063. "clientName": hello.ClientName,
  1064. "clientVersion": hello.ClientVersion,
  1065. "type": conn.Type,
  1066. }
  1067. addr := conn.RemoteAddr()
  1068. if addr != nil {
  1069. event["addr"] = addr.String()
  1070. }
  1071. events.Default.Log(events.DeviceConnected, event)
  1072. l.Infof(`Device %s client is "%s %s" named "%s"`, deviceID, hello.ClientName, hello.ClientVersion, hello.DeviceName)
  1073. conn.Start()
  1074. cm := m.generateClusterConfig(deviceID)
  1075. conn.ClusterConfig(cm)
  1076. m.pmut.Unlock()
  1077. device, ok := m.cfg.Devices()[deviceID]
  1078. if ok && (device.Name == "" || m.cfg.Options().OverwriteRemoteDevNames) {
  1079. device.Name = hello.DeviceName
  1080. m.cfg.SetDevice(device)
  1081. m.cfg.Save()
  1082. }
  1083. m.deviceWasSeen(deviceID)
  1084. }
  1085. func (m *Model) PauseDevice(device protocol.DeviceID) {
  1086. m.pmut.Lock()
  1087. m.devicePaused[device] = true
  1088. conn, ok := m.conn[device]
  1089. m.pmut.Unlock()
  1090. if ok {
  1091. closeRawConn(conn)
  1092. }
  1093. events.Default.Log(events.DevicePaused, map[string]string{"device": device.String()})
  1094. }
  1095. func (m *Model) DownloadProgress(device protocol.DeviceID, folder string, updates []protocol.FileDownloadProgressUpdate) {
  1096. if !m.folderSharedWith(folder, device) {
  1097. return
  1098. }
  1099. m.fmut.RLock()
  1100. cfg, ok := m.folderCfgs[folder]
  1101. m.fmut.RUnlock()
  1102. if !ok || cfg.Type == config.FolderTypeReadOnly || cfg.DisableTempIndexes {
  1103. return
  1104. }
  1105. m.pmut.RLock()
  1106. m.deviceDownloads[device].Update(folder, updates)
  1107. state := m.deviceDownloads[device].GetBlockCounts(folder)
  1108. m.pmut.RUnlock()
  1109. events.Default.Log(events.RemoteDownloadProgress, map[string]interface{}{
  1110. "device": device.String(),
  1111. "folder": folder,
  1112. "state": state,
  1113. })
  1114. }
  1115. func (m *Model) ResumeDevice(device protocol.DeviceID) {
  1116. m.pmut.Lock()
  1117. m.devicePaused[device] = false
  1118. m.pmut.Unlock()
  1119. events.Default.Log(events.DeviceResumed, map[string]string{"device": device.String()})
  1120. }
  1121. func (m *Model) IsPaused(device protocol.DeviceID) bool {
  1122. m.pmut.Lock()
  1123. paused := m.devicePaused[device]
  1124. m.pmut.Unlock()
  1125. return paused
  1126. }
  1127. func (m *Model) deviceStatRef(deviceID protocol.DeviceID) *stats.DeviceStatisticsReference {
  1128. m.fmut.Lock()
  1129. defer m.fmut.Unlock()
  1130. if sr, ok := m.deviceStatRefs[deviceID]; ok {
  1131. return sr
  1132. }
  1133. sr := stats.NewDeviceStatisticsReference(m.db, deviceID.String())
  1134. m.deviceStatRefs[deviceID] = sr
  1135. return sr
  1136. }
  1137. func (m *Model) deviceWasSeen(deviceID protocol.DeviceID) {
  1138. m.deviceStatRef(deviceID).WasSeen()
  1139. }
  1140. func (m *Model) folderStatRef(folder string) *stats.FolderStatisticsReference {
  1141. m.fmut.Lock()
  1142. defer m.fmut.Unlock()
  1143. sr, ok := m.folderStatRefs[folder]
  1144. if !ok {
  1145. sr = stats.NewFolderStatisticsReference(m.db, folder)
  1146. m.folderStatRefs[folder] = sr
  1147. }
  1148. return sr
  1149. }
  1150. func (m *Model) receivedFile(folder string, file protocol.FileInfo) {
  1151. m.folderStatRef(folder).ReceivedFile(file.Name, file.IsDeleted())
  1152. }
  1153. func sendIndexes(conn protocol.Connection, folder string, fs *db.FileSet, ignores *ignore.Matcher, startSequence int64, dbLocation string) {
  1154. deviceID := conn.ID()
  1155. name := conn.Name()
  1156. var err error
  1157. l.Debugf("sendIndexes for %s-%s/%q starting (slv=%d)", deviceID, name, folder, startSequence)
  1158. defer l.Debugf("sendIndexes for %s-%s/%q exiting: %v", deviceID, name, folder, err)
  1159. minSequence, err := sendIndexTo(startSequence, conn, folder, fs, ignores, dbLocation)
  1160. // Subscribe to LocalIndexUpdated (we have new information to send) and
  1161. // DeviceDisconnected (it might be us who disconnected, so we should
  1162. // exit).
  1163. sub := events.Default.Subscribe(events.LocalIndexUpdated | events.DeviceDisconnected)
  1164. defer events.Default.Unsubscribe(sub)
  1165. for err == nil {
  1166. if conn.Closed() {
  1167. // Our work is done.
  1168. return
  1169. }
  1170. // While we have sent a sequence at least equal to the one
  1171. // currently in the database, wait for the local index to update. The
  1172. // local index may update for other folders than the one we are
  1173. // sending for.
  1174. if fs.Sequence(protocol.LocalDeviceID) <= minSequence {
  1175. sub.Poll(time.Minute)
  1176. continue
  1177. }
  1178. minSequence, err = sendIndexTo(minSequence, conn, folder, fs, ignores, dbLocation)
  1179. // Wait a short amount of time before entering the next loop. If there
  1180. // are continuous changes happening to the local index, this gives us
  1181. // time to batch them up a little.
  1182. time.Sleep(250 * time.Millisecond)
  1183. }
  1184. }
  1185. func sendIndexTo(minSequence int64, conn protocol.Connection, folder string, fs *db.FileSet, ignores *ignore.Matcher, dbLocation string) (int64, error) {
  1186. deviceID := conn.ID()
  1187. name := conn.Name()
  1188. batch := make([]protocol.FileInfo, 0, indexBatchSize)
  1189. currentBatchSize := 0
  1190. initial := minSequence == 0
  1191. maxSequence := minSequence
  1192. var err error
  1193. sorter := NewIndexSorter(dbLocation)
  1194. defer sorter.Close()
  1195. fs.WithHave(protocol.LocalDeviceID, func(fi db.FileIntf) bool {
  1196. f := fi.(protocol.FileInfo)
  1197. if f.Sequence <= minSequence {
  1198. return true
  1199. }
  1200. if f.Sequence > maxSequence {
  1201. maxSequence = f.Sequence
  1202. }
  1203. sorter.Append(f)
  1204. return true
  1205. })
  1206. sorter.Sorted(func(f protocol.FileInfo) bool {
  1207. if len(batch) == indexBatchSize || currentBatchSize > indexTargetSize {
  1208. if initial {
  1209. if err = conn.Index(folder, batch); err != nil {
  1210. return false
  1211. }
  1212. l.Debugf("sendIndexes for %s-%s/%q: %d files (<%d bytes) (initial index)", deviceID, name, folder, len(batch), currentBatchSize)
  1213. initial = false
  1214. } else {
  1215. if err = conn.IndexUpdate(folder, batch); err != nil {
  1216. return false
  1217. }
  1218. l.Debugf("sendIndexes for %s-%s/%q: %d files (<%d bytes) (batched update)", deviceID, name, folder, len(batch), currentBatchSize)
  1219. }
  1220. batch = make([]protocol.FileInfo, 0, indexBatchSize)
  1221. currentBatchSize = 0
  1222. }
  1223. batch = append(batch, f)
  1224. currentBatchSize += f.ProtoSize()
  1225. return true
  1226. })
  1227. if initial && err == nil {
  1228. err = conn.Index(folder, batch)
  1229. if err == nil {
  1230. l.Debugf("sendIndexes for %s-%s/%q: %d files (small initial index)", deviceID, name, folder, len(batch))
  1231. }
  1232. } else if len(batch) > 0 && err == nil {
  1233. err = conn.IndexUpdate(folder, batch)
  1234. if err == nil {
  1235. l.Debugf("sendIndexes for %s-%s/%q: %d files (last batch)", deviceID, name, folder, len(batch))
  1236. }
  1237. }
  1238. return maxSequence, err
  1239. }
  1240. func (m *Model) updateLocalsFromScanning(folder string, fs []protocol.FileInfo) {
  1241. m.updateLocals(folder, fs)
  1242. m.fmut.RLock()
  1243. folderCfg := m.folderCfgs[folder]
  1244. m.fmut.RUnlock()
  1245. // Fire the LocalChangeDetected event to notify listeners about local updates.
  1246. m.localChangeDetected(folderCfg, fs)
  1247. }
  1248. func (m *Model) updateLocalsFromPulling(folder string, fs []protocol.FileInfo) {
  1249. m.updateLocals(folder, fs)
  1250. }
  1251. func (m *Model) updateLocals(folder string, fs []protocol.FileInfo) {
  1252. m.fmut.RLock()
  1253. files := m.folderFiles[folder]
  1254. m.fmut.RUnlock()
  1255. if files == nil {
  1256. // The folder doesn't exist.
  1257. return
  1258. }
  1259. files.Update(protocol.LocalDeviceID, fs)
  1260. filenames := make([]string, len(fs))
  1261. for i, file := range fs {
  1262. filenames[i] = file.Name
  1263. }
  1264. events.Default.Log(events.LocalIndexUpdated, map[string]interface{}{
  1265. "folder": folder,
  1266. "items": len(fs),
  1267. "filenames": filenames,
  1268. "version": files.Sequence(protocol.LocalDeviceID),
  1269. })
  1270. }
  1271. func (m *Model) localChangeDetected(folderCfg config.FolderConfiguration, files []protocol.FileInfo) {
  1272. path := strings.Replace(folderCfg.Path(), `\\?\`, "", 1)
  1273. for _, file := range files {
  1274. objType := "file"
  1275. action := "modified"
  1276. // If our local vector is version 1 AND it is the only version
  1277. // vector so far seen for this file then it is a new file. Else if
  1278. // it is > 1 it's not new, and if it is 1 but another shortId
  1279. // version vector exists then it is new for us but created elsewhere
  1280. // so the file is still not new but modified by us. Only if it is
  1281. // truly new do we change this to 'added', else we leave it as
  1282. // 'modified'.
  1283. if len(file.Version.Counters) == 1 && file.Version.Counters[0].Value == 1 {
  1284. action = "added"
  1285. }
  1286. if file.IsDirectory() {
  1287. objType = "dir"
  1288. }
  1289. if file.IsDeleted() {
  1290. action = "deleted"
  1291. }
  1292. // The full file path, adjusted to the local path separator character. Also
  1293. // for windows paths, strip unwanted chars from the front.
  1294. path := filepath.Join(path, filepath.FromSlash(file.Name))
  1295. events.Default.Log(events.LocalChangeDetected, map[string]string{
  1296. "folderID": folderCfg.ID,
  1297. "label": folderCfg.Label,
  1298. "action": action,
  1299. "type": objType,
  1300. "path": path,
  1301. })
  1302. }
  1303. }
  1304. func (m *Model) requestGlobal(deviceID protocol.DeviceID, folder, name string, offset int64, size int, hash []byte, fromTemporary bool) ([]byte, error) {
  1305. m.pmut.RLock()
  1306. nc, ok := m.conn[deviceID]
  1307. m.pmut.RUnlock()
  1308. if !ok {
  1309. return nil, fmt.Errorf("requestGlobal: no such device: %s", deviceID)
  1310. }
  1311. l.Debugf("%v REQ(out): %s: %q / %q o=%d s=%d h=%x ft=%t", m, deviceID, folder, name, offset, size, hash, fromTemporary)
  1312. return nc.Request(folder, name, offset, size, hash, fromTemporary)
  1313. }
  1314. func (m *Model) ScanFolders() map[string]error {
  1315. m.fmut.RLock()
  1316. folders := make([]string, 0, len(m.folderCfgs))
  1317. for folder := range m.folderCfgs {
  1318. folders = append(folders, folder)
  1319. }
  1320. m.fmut.RUnlock()
  1321. errors := make(map[string]error, len(m.folderCfgs))
  1322. errorsMut := sync.NewMutex()
  1323. wg := sync.NewWaitGroup()
  1324. wg.Add(len(folders))
  1325. for _, folder := range folders {
  1326. folder := folder
  1327. go func() {
  1328. err := m.ScanFolder(folder)
  1329. if err != nil {
  1330. errorsMut.Lock()
  1331. errors[folder] = err
  1332. errorsMut.Unlock()
  1333. // Potentially sets the error twice, once in the scanner just
  1334. // by doing a check, and once here, if the error returned is
  1335. // the same one as returned by CheckFolderHealth, though
  1336. // duplicate set is handled by setError.
  1337. m.fmut.RLock()
  1338. srv := m.folderRunners[folder]
  1339. m.fmut.RUnlock()
  1340. srv.setError(err)
  1341. }
  1342. wg.Done()
  1343. }()
  1344. }
  1345. wg.Wait()
  1346. return errors
  1347. }
  1348. func (m *Model) ScanFolder(folder string) error {
  1349. return m.ScanFolderSubdirs(folder, nil)
  1350. }
  1351. func (m *Model) ScanFolderSubdirs(folder string, subs []string) error {
  1352. m.fmut.Lock()
  1353. runner, ok := m.folderRunners[folder]
  1354. m.fmut.Unlock()
  1355. // Folders are added to folderRunners only when they are started. We can't
  1356. // scan them before they have started, so that's what we need to check for
  1357. // here.
  1358. if !ok {
  1359. return errors.New("no such folder")
  1360. }
  1361. return runner.Scan(subs)
  1362. }
  1363. func (m *Model) internalScanFolderSubdirs(folder string, subDirs []string) error {
  1364. for i, sub := range subDirs {
  1365. sub = osutil.NativeFilename(sub)
  1366. if p := filepath.Clean(filepath.Join(folder, sub)); !strings.HasPrefix(p, folder) {
  1367. return errors.New("invalid subpath")
  1368. }
  1369. subDirs[i] = sub
  1370. }
  1371. m.fmut.Lock()
  1372. fs := m.folderFiles[folder]
  1373. folderCfg := m.folderCfgs[folder]
  1374. ignores := m.folderIgnores[folder]
  1375. runner, ok := m.folderRunners[folder]
  1376. m.fmut.Unlock()
  1377. mtimefs := fs.MtimeFS()
  1378. // Check if the ignore patterns changed as part of scanning this folder.
  1379. // If they did we should schedule a pull of the folder so that we
  1380. // request things we might have suddenly become unignored and so on.
  1381. oldHash := ignores.Hash()
  1382. defer func() {
  1383. if ignores.Hash() != oldHash {
  1384. l.Debugln("Folder", folder, "ignore patterns changed; triggering puller")
  1385. runner.IndexUpdated()
  1386. }
  1387. }()
  1388. // Folders are added to folderRunners only when they are started. We can't
  1389. // scan them before they have started, so that's what we need to check for
  1390. // here.
  1391. if !ok {
  1392. return errors.New("no such folder")
  1393. }
  1394. if err := m.CheckFolderHealth(folder); err != nil {
  1395. runner.setError(err)
  1396. l.Infof("Stopping folder %s due to error: %s", folder, err)
  1397. return err
  1398. }
  1399. if err := ignores.Load(filepath.Join(folderCfg.Path(), ".stignore")); err != nil && !os.IsNotExist(err) {
  1400. err = fmt.Errorf("loading ignores: %v", err)
  1401. runner.setError(err)
  1402. l.Infof("Stopping folder %s due to error: %s", folder, err)
  1403. return err
  1404. }
  1405. // Clean the list of subitems to ensure that we start at a known
  1406. // directory, and don't scan subdirectories of things we've already
  1407. // scanned.
  1408. subDirs = unifySubs(subDirs, func(f string) bool {
  1409. _, ok := fs.Get(protocol.LocalDeviceID, f)
  1410. return ok
  1411. })
  1412. // The cancel channel is closed whenever we return (such as from an error),
  1413. // to signal the potentially still running walker to stop.
  1414. cancel := make(chan struct{})
  1415. defer close(cancel)
  1416. runner.setState(FolderScanning)
  1417. fchan, err := scanner.Walk(scanner.Config{
  1418. Folder: folderCfg.ID,
  1419. Dir: folderCfg.Path(),
  1420. Subs: subDirs,
  1421. Matcher: ignores,
  1422. BlockSize: protocol.BlockSize,
  1423. TempNamer: defTempNamer,
  1424. TempLifetime: time.Duration(m.cfg.Options().KeepTemporariesH) * time.Hour,
  1425. CurrentFiler: cFiler{m, folder},
  1426. Lstater: mtimefs,
  1427. IgnorePerms: folderCfg.IgnorePerms,
  1428. AutoNormalize: folderCfg.AutoNormalize,
  1429. Hashers: m.numHashers(folder),
  1430. ShortID: m.shortID,
  1431. ProgressTickIntervalS: folderCfg.ScanProgressIntervalS,
  1432. Cancel: cancel,
  1433. })
  1434. if err != nil {
  1435. // The error we get here is likely an OS level error, which might not be
  1436. // as readable as our health check errors. Check if we can get a health
  1437. // check error first, and use that if it's available.
  1438. if ferr := m.CheckFolderHealth(folder); ferr != nil {
  1439. err = ferr
  1440. }
  1441. runner.setError(err)
  1442. return err
  1443. }
  1444. batchSizeFiles := 100
  1445. batchSizeBlocks := 2048 // about 256 MB
  1446. batch := make([]protocol.FileInfo, 0, batchSizeFiles)
  1447. blocksHandled := 0
  1448. for f := range fchan {
  1449. if len(batch) == batchSizeFiles || blocksHandled > batchSizeBlocks {
  1450. if err := m.CheckFolderHealth(folder); err != nil {
  1451. l.Infof("Stopping folder %s mid-scan due to folder error: %s", folder, err)
  1452. return err
  1453. }
  1454. m.updateLocalsFromScanning(folder, batch)
  1455. batch = batch[:0]
  1456. blocksHandled = 0
  1457. }
  1458. batch = append(batch, f)
  1459. blocksHandled += len(f.Blocks)
  1460. }
  1461. if err := m.CheckFolderHealth(folder); err != nil {
  1462. l.Infof("Stopping folder %s mid-scan due to folder error: %s", folder, err)
  1463. return err
  1464. } else if len(batch) > 0 {
  1465. m.updateLocalsFromScanning(folder, batch)
  1466. }
  1467. if len(subDirs) == 0 {
  1468. // If we have no specific subdirectories to traverse, set it to one
  1469. // empty prefix so we traverse the entire folder contents once.
  1470. subDirs = []string{""}
  1471. }
  1472. // Do a scan of the database for each prefix, to check for deleted and
  1473. // ignored files.
  1474. batch = batch[:0]
  1475. for _, sub := range subDirs {
  1476. var iterError error
  1477. fs.WithPrefixedHaveTruncated(protocol.LocalDeviceID, sub, func(fi db.FileIntf) bool {
  1478. f := fi.(db.FileInfoTruncated)
  1479. if len(batch) == batchSizeFiles {
  1480. if err := m.CheckFolderHealth(folder); err != nil {
  1481. iterError = err
  1482. return false
  1483. }
  1484. m.updateLocalsFromScanning(folder, batch)
  1485. batch = batch[:0]
  1486. }
  1487. switch {
  1488. case !f.IsInvalid() && (ignores.Match(f.Name).IsIgnored() || symlinkInvalid(folder, f)):
  1489. // File was valid at last pass but has been ignored or is an
  1490. // unsupported symlink. Set invalid bit.
  1491. l.Debugln("setting invalid bit on ignored", f)
  1492. nf := protocol.FileInfo{
  1493. Name: f.Name,
  1494. Type: f.Type,
  1495. Size: f.Size,
  1496. ModifiedS: f.ModifiedS,
  1497. ModifiedNs: f.ModifiedNs,
  1498. Permissions: f.Permissions,
  1499. NoPermissions: f.NoPermissions,
  1500. Invalid: true,
  1501. Version: f.Version, // The file is still the same, so don't bump version
  1502. }
  1503. batch = append(batch, nf)
  1504. case !f.IsInvalid() && !f.IsDeleted():
  1505. // The file is valid and not deleted. Lets check if it's
  1506. // still here.
  1507. if _, err := mtimefs.Lstat(filepath.Join(folderCfg.Path(), f.Name)); err != nil {
  1508. // We don't specifically verify that the error is
  1509. // os.IsNotExist because there is a corner case when a
  1510. // directory is suddenly transformed into a file. When that
  1511. // happens, files that were in the directory (that is now a
  1512. // file) are deleted but will return a confusing error ("not a
  1513. // directory") when we try to Lstat() them.
  1514. nf := protocol.FileInfo{
  1515. Name: f.Name,
  1516. Type: f.Type,
  1517. Size: 0,
  1518. ModifiedS: f.ModifiedS,
  1519. ModifiedNs: f.ModifiedNs,
  1520. Deleted: true,
  1521. Version: f.Version.Update(m.shortID),
  1522. }
  1523. batch = append(batch, nf)
  1524. }
  1525. }
  1526. return true
  1527. })
  1528. if iterError != nil {
  1529. l.Infof("Stopping folder %s mid-scan due to folder error: %s", folder, iterError)
  1530. return iterError
  1531. }
  1532. }
  1533. if err := m.CheckFolderHealth(folder); err != nil {
  1534. l.Infof("Stopping folder %s mid-scan due to folder error: %s", folder, err)
  1535. return err
  1536. } else if len(batch) > 0 {
  1537. m.updateLocalsFromScanning(folder, batch)
  1538. }
  1539. m.folderStatRef(folder).ScanCompleted()
  1540. runner.setState(FolderIdle)
  1541. return nil
  1542. }
  1543. func (m *Model) DelayScan(folder string, next time.Duration) {
  1544. m.fmut.Lock()
  1545. runner, ok := m.folderRunners[folder]
  1546. m.fmut.Unlock()
  1547. if !ok {
  1548. return
  1549. }
  1550. runner.DelayScan(next)
  1551. }
  1552. // numHashers returns the number of hasher routines to use for a given folder,
  1553. // taking into account configuration and available CPU cores.
  1554. func (m *Model) numHashers(folder string) int {
  1555. m.fmut.Lock()
  1556. folderCfg := m.folderCfgs[folder]
  1557. numFolders := len(m.folderCfgs)
  1558. m.fmut.Unlock()
  1559. if folderCfg.Hashers > 0 {
  1560. // Specific value set in the config, use that.
  1561. return folderCfg.Hashers
  1562. }
  1563. if runtime.GOOS == "windows" || runtime.GOOS == "darwin" {
  1564. // Interactive operating systems; don't load the system too heavily by
  1565. // default.
  1566. return 1
  1567. }
  1568. // For other operating systems and architectures, lets try to get some
  1569. // work done... Divide the available CPU cores among the configured
  1570. // folders.
  1571. if perFolder := runtime.GOMAXPROCS(-1) / numFolders; perFolder > 0 {
  1572. return perFolder
  1573. }
  1574. return 1
  1575. }
  1576. // generateClusterConfig returns a ClusterConfigMessage that is correct for
  1577. // the given peer device
  1578. func (m *Model) generateClusterConfig(device protocol.DeviceID) protocol.ClusterConfig {
  1579. var message protocol.ClusterConfig
  1580. m.fmut.RLock()
  1581. for _, folder := range m.deviceFolders[device] {
  1582. folderCfg := m.cfg.Folders()[folder]
  1583. fs := m.folderFiles[folder]
  1584. protocolFolder := protocol.Folder{
  1585. ID: folder,
  1586. Label: folderCfg.Label,
  1587. ReadOnly: folderCfg.Type == config.FolderTypeReadOnly,
  1588. IgnorePermissions: folderCfg.IgnorePerms,
  1589. IgnoreDelete: folderCfg.IgnoreDelete,
  1590. DisableTempIndexes: folderCfg.DisableTempIndexes,
  1591. }
  1592. for _, device := range m.folderDevices[folder] {
  1593. // DeviceID is a value type, but with an underlying array. Copy it
  1594. // so we don't grab aliases to the same array later on in device[:]
  1595. device := device
  1596. // TODO: Set read only bit when relevant, and when we have per device
  1597. // access controls.
  1598. deviceCfg := m.cfg.Devices()[device]
  1599. var indexID protocol.IndexID
  1600. var maxSequence int64
  1601. if device == m.id {
  1602. indexID = fs.IndexID(protocol.LocalDeviceID)
  1603. maxSequence = fs.Sequence(protocol.LocalDeviceID)
  1604. } else {
  1605. indexID = fs.IndexID(device)
  1606. maxSequence = fs.Sequence(device)
  1607. }
  1608. protocolDevice := protocol.Device{
  1609. ID: device[:],
  1610. Name: deviceCfg.Name,
  1611. Addresses: deviceCfg.Addresses,
  1612. Compression: deviceCfg.Compression,
  1613. CertName: deviceCfg.CertName,
  1614. Introducer: deviceCfg.Introducer,
  1615. IndexID: indexID,
  1616. MaxSequence: maxSequence,
  1617. }
  1618. protocolFolder.Devices = append(protocolFolder.Devices, protocolDevice)
  1619. }
  1620. message.Folders = append(message.Folders, protocolFolder)
  1621. }
  1622. m.fmut.RUnlock()
  1623. return message
  1624. }
  1625. func (m *Model) State(folder string) (string, time.Time, error) {
  1626. m.fmut.RLock()
  1627. runner, ok := m.folderRunners[folder]
  1628. m.fmut.RUnlock()
  1629. if !ok {
  1630. // The returned error should be an actual folder error, so returning
  1631. // errors.New("does not exist") or similar here would be
  1632. // inappropriate.
  1633. return "", time.Time{}, nil
  1634. }
  1635. state, changed, err := runner.getState()
  1636. return state.String(), changed, err
  1637. }
  1638. func (m *Model) Override(folder string) {
  1639. m.fmut.RLock()
  1640. fs, ok := m.folderFiles[folder]
  1641. runner := m.folderRunners[folder]
  1642. m.fmut.RUnlock()
  1643. if !ok {
  1644. return
  1645. }
  1646. runner.setState(FolderScanning)
  1647. batch := make([]protocol.FileInfo, 0, indexBatchSize)
  1648. fs.WithNeed(protocol.LocalDeviceID, func(fi db.FileIntf) bool {
  1649. need := fi.(protocol.FileInfo)
  1650. if len(batch) == indexBatchSize {
  1651. m.updateLocalsFromScanning(folder, batch)
  1652. batch = batch[:0]
  1653. }
  1654. have, ok := fs.Get(protocol.LocalDeviceID, need.Name)
  1655. if !ok || have.Name != need.Name {
  1656. // We are missing the file
  1657. need.Deleted = true
  1658. need.Blocks = nil
  1659. need.Version = need.Version.Update(m.shortID)
  1660. need.Size = 0
  1661. } else {
  1662. // We have the file, replace with our version
  1663. have.Version = have.Version.Merge(need.Version).Update(m.shortID)
  1664. need = have
  1665. }
  1666. need.Sequence = 0
  1667. batch = append(batch, need)
  1668. return true
  1669. })
  1670. if len(batch) > 0 {
  1671. m.updateLocalsFromScanning(folder, batch)
  1672. }
  1673. runner.setState(FolderIdle)
  1674. }
  1675. // CurrentSequence returns the change version for the given folder.
  1676. // This is guaranteed to increment if the contents of the local folder has
  1677. // changed.
  1678. func (m *Model) CurrentSequence(folder string) (int64, bool) {
  1679. m.fmut.RLock()
  1680. fs, ok := m.folderFiles[folder]
  1681. m.fmut.RUnlock()
  1682. if !ok {
  1683. // The folder might not exist, since this can be called with a user
  1684. // specified folder name from the REST interface.
  1685. return 0, false
  1686. }
  1687. return fs.Sequence(protocol.LocalDeviceID), true
  1688. }
  1689. // RemoteSequence returns the change version for the given folder, as
  1690. // sent by remote peers. This is guaranteed to increment if the contents of
  1691. // the remote or global folder has changed.
  1692. func (m *Model) RemoteSequence(folder string) (int64, bool) {
  1693. m.fmut.RLock()
  1694. defer m.fmut.RUnlock()
  1695. fs, ok := m.folderFiles[folder]
  1696. if !ok {
  1697. // The folder might not exist, since this can be called with a user
  1698. // specified folder name from the REST interface.
  1699. return 0, false
  1700. }
  1701. var ver int64
  1702. for _, n := range m.folderDevices[folder] {
  1703. ver += fs.Sequence(n)
  1704. }
  1705. return ver, true
  1706. }
  1707. func (m *Model) GlobalDirectoryTree(folder, prefix string, levels int, dirsonly bool) map[string]interface{} {
  1708. m.fmut.RLock()
  1709. files, ok := m.folderFiles[folder]
  1710. m.fmut.RUnlock()
  1711. if !ok {
  1712. return nil
  1713. }
  1714. output := make(map[string]interface{})
  1715. sep := string(filepath.Separator)
  1716. prefix = osutil.NativeFilename(prefix)
  1717. if prefix != "" && !strings.HasSuffix(prefix, sep) {
  1718. prefix = prefix + sep
  1719. }
  1720. files.WithPrefixedGlobalTruncated(prefix, func(fi db.FileIntf) bool {
  1721. f := fi.(db.FileInfoTruncated)
  1722. if f.IsInvalid() || f.IsDeleted() || f.Name == prefix {
  1723. return true
  1724. }
  1725. f.Name = strings.Replace(f.Name, prefix, "", 1)
  1726. var dir, base string
  1727. if f.IsDirectory() && !f.IsSymlink() {
  1728. dir = f.Name
  1729. } else {
  1730. dir = filepath.Dir(f.Name)
  1731. base = filepath.Base(f.Name)
  1732. }
  1733. if levels > -1 && strings.Count(f.Name, sep) > levels {
  1734. return true
  1735. }
  1736. last := output
  1737. if dir != "." {
  1738. for _, path := range strings.Split(dir, sep) {
  1739. directory, ok := last[path]
  1740. if !ok {
  1741. newdir := make(map[string]interface{})
  1742. last[path] = newdir
  1743. last = newdir
  1744. } else {
  1745. last = directory.(map[string]interface{})
  1746. }
  1747. }
  1748. }
  1749. if !dirsonly && base != "" {
  1750. last[base] = []interface{}{
  1751. f.ModTime(), f.FileSize(),
  1752. }
  1753. }
  1754. return true
  1755. })
  1756. return output
  1757. }
  1758. func (m *Model) Availability(folder, file string, version protocol.Vector, block protocol.BlockInfo) []Availability {
  1759. // Acquire this lock first, as the value returned from foldersFiles can
  1760. // get heavily modified on Close()
  1761. m.pmut.RLock()
  1762. defer m.pmut.RUnlock()
  1763. m.fmut.RLock()
  1764. fs, ok := m.folderFiles[folder]
  1765. devices := m.folderDevices[folder]
  1766. m.fmut.RUnlock()
  1767. if !ok {
  1768. return nil
  1769. }
  1770. var availabilities []Availability
  1771. for _, device := range fs.Availability(file) {
  1772. _, ok := m.conn[device]
  1773. if ok {
  1774. availabilities = append(availabilities, Availability{ID: device, FromTemporary: false})
  1775. }
  1776. }
  1777. for _, device := range devices {
  1778. if m.deviceDownloads[device].Has(folder, file, version, int32(block.Offset/protocol.BlockSize)) {
  1779. availabilities = append(availabilities, Availability{ID: device, FromTemporary: true})
  1780. }
  1781. }
  1782. return availabilities
  1783. }
  1784. // BringToFront bumps the given files priority in the job queue.
  1785. func (m *Model) BringToFront(folder, file string) {
  1786. m.pmut.RLock()
  1787. defer m.pmut.RUnlock()
  1788. runner, ok := m.folderRunners[folder]
  1789. if ok {
  1790. runner.BringToFront(file)
  1791. }
  1792. }
  1793. // CheckFolderHealth checks the folder for common errors and returns the
  1794. // current folder error, or nil if the folder is healthy.
  1795. func (m *Model) CheckFolderHealth(id string) error {
  1796. folder, ok := m.cfg.Folders()[id]
  1797. if !ok {
  1798. return errors.New("folder does not exist")
  1799. }
  1800. // Check for folder errors, with the most serious and specific first and
  1801. // generic ones like out of space on the home disk later. Note the
  1802. // inverted error flow (err==nil checks) here.
  1803. err := m.checkFolderPath(folder)
  1804. if err == nil {
  1805. err = m.checkFolderFreeSpace(folder)
  1806. }
  1807. if err == nil {
  1808. err = m.checkHomeDiskFree()
  1809. }
  1810. // Set or clear the error on the runner, which also does logging and
  1811. // generates events and stuff.
  1812. m.runnerExchangeError(folder, err)
  1813. return err
  1814. }
  1815. // checkFolderPath returns nil if the folder path exists and has the marker file.
  1816. func (m *Model) checkFolderPath(folder config.FolderConfiguration) error {
  1817. if folder.Path() == "" {
  1818. return errFolderPathEmpty
  1819. }
  1820. if fi, err := os.Stat(folder.Path()); err != nil || !fi.IsDir() {
  1821. return errFolderPathMissing
  1822. }
  1823. if !folder.HasMarker() {
  1824. return errFolderMarkerMissing
  1825. }
  1826. return nil
  1827. }
  1828. // checkFolderFreeSpace returns nil if the folder has the required amount of
  1829. // free space, or if folder free space checking is disabled.
  1830. func (m *Model) checkFolderFreeSpace(folder config.FolderConfiguration) error {
  1831. if folder.MinDiskFreePct <= 0 {
  1832. return nil
  1833. }
  1834. free, err := osutil.DiskFreePercentage(folder.Path())
  1835. if err == nil && free < folder.MinDiskFreePct {
  1836. return errFolderNoSpace
  1837. }
  1838. return nil
  1839. }
  1840. // checkHomeDiskFree returns nil if the home disk has the required amount of
  1841. // free space, or if home disk free space checking is disabled.
  1842. func (m *Model) checkHomeDiskFree() error {
  1843. minFree := m.cfg.Options().MinHomeDiskFreePct
  1844. if minFree <= 0 {
  1845. return nil
  1846. }
  1847. free, err := osutil.DiskFreePercentage(m.cfg.ConfigPath())
  1848. if err == nil && free < minFree {
  1849. return errHomeDiskNoSpace
  1850. }
  1851. return nil
  1852. }
  1853. // runnerExchangeError sets the given error (which way be nil) on the folder
  1854. // runner. If the error differs from any previous error, logging and events
  1855. // happen.
  1856. func (m *Model) runnerExchangeError(folder config.FolderConfiguration, err error) {
  1857. m.fmut.RLock()
  1858. runner, runnerExists := m.folderRunners[folder.ID]
  1859. m.fmut.RUnlock()
  1860. var oldErr error
  1861. if runnerExists {
  1862. _, _, oldErr = runner.getState()
  1863. }
  1864. if err != nil {
  1865. if oldErr != nil && oldErr.Error() != err.Error() {
  1866. l.Infof("Folder %q error changed: %q -> %q", folder.ID, oldErr, err)
  1867. } else if oldErr == nil {
  1868. l.Warnf("Stopping folder %q - %v", folder.ID, err)
  1869. }
  1870. if runnerExists {
  1871. runner.setError(err)
  1872. }
  1873. } else if oldErr != nil {
  1874. l.Infof("Folder %q error is cleared, restarting", folder.ID)
  1875. if runnerExists {
  1876. runner.clearError()
  1877. }
  1878. }
  1879. }
  1880. func (m *Model) ResetFolder(folder string) {
  1881. l.Infof("Cleaning data for folder %q", folder)
  1882. db.DropFolder(m.db, folder)
  1883. }
  1884. func (m *Model) String() string {
  1885. return fmt.Sprintf("model@%p", m)
  1886. }
  1887. func (m *Model) VerifyConfiguration(from, to config.Configuration) error {
  1888. return nil
  1889. }
  1890. func (m *Model) CommitConfiguration(from, to config.Configuration) bool {
  1891. // TODO: This should not use reflect, and should take more care to try to handle stuff without restart.
  1892. // Go through the folder configs and figure out if we need to restart or not.
  1893. fromFolders := mapFolders(from.Folders)
  1894. toFolders := mapFolders(to.Folders)
  1895. for folderID, cfg := range toFolders {
  1896. if _, ok := fromFolders[folderID]; !ok {
  1897. // A folder was added.
  1898. l.Debugln(m, "adding folder", folderID)
  1899. m.AddFolder(cfg)
  1900. m.StartFolder(folderID)
  1901. // Drop connections to all devices that can now share the new
  1902. // folder.
  1903. m.pmut.Lock()
  1904. for _, dev := range cfg.DeviceIDs() {
  1905. if conn, ok := m.conn[dev]; ok {
  1906. closeRawConn(conn)
  1907. }
  1908. }
  1909. m.pmut.Unlock()
  1910. }
  1911. }
  1912. for folderID, fromCfg := range fromFolders {
  1913. toCfg, ok := toFolders[folderID]
  1914. if !ok {
  1915. // The folder was removed.
  1916. m.RemoveFolder(folderID)
  1917. continue
  1918. }
  1919. // This folder exists on both sides. Settings might have changed.
  1920. // Check if anything differs, apart from the label.
  1921. toCfgCopy := toCfg
  1922. fromCfgCopy := fromCfg
  1923. fromCfgCopy.Label = ""
  1924. toCfgCopy.Label = ""
  1925. if !reflect.DeepEqual(fromCfgCopy, toCfgCopy) {
  1926. m.RestartFolder(toCfg)
  1927. }
  1928. }
  1929. // Removing a device. We actually don't need to do anything.
  1930. // Because folder config has changed (since the device lists do not match)
  1931. // Folders for that had device got "restarted", which involves killing
  1932. // connections to all devices that we were sharing the folder with.
  1933. // At some point model.Close() will get called for that device which will
  1934. // clean residue device state that is not part of any folder.
  1935. // Some options don't require restart as those components handle it fine
  1936. // by themselves.
  1937. from.Options.URAccepted = to.Options.URAccepted
  1938. from.Options.URUniqueID = to.Options.URUniqueID
  1939. from.Options.ListenAddresses = to.Options.ListenAddresses
  1940. from.Options.RelaysEnabled = to.Options.RelaysEnabled
  1941. from.Options.UnackedNotificationIDs = to.Options.UnackedNotificationIDs
  1942. // All of the other generic options require restart. Or at least they may;
  1943. // removing this check requires going through those options carefully and
  1944. // making sure there are individual services that handle them correctly.
  1945. // This code is the "original" requires-restart check and protects other
  1946. // components that haven't yet been converted to VerifyConfig/CommitConfig
  1947. // handling.
  1948. if !reflect.DeepEqual(from.Options, to.Options) {
  1949. l.Debugln(m, "requires restart, options differ")
  1950. return false
  1951. }
  1952. return true
  1953. }
  1954. // mapFolders returns a map of folder ID to folder configuration for the given
  1955. // slice of folder configurations.
  1956. func mapFolders(folders []config.FolderConfiguration) map[string]config.FolderConfiguration {
  1957. m := make(map[string]config.FolderConfiguration, len(folders))
  1958. for _, cfg := range folders {
  1959. m[cfg.ID] = cfg
  1960. }
  1961. return m
  1962. }
  1963. // mapDevices returns a map of device ID to nothing for the given slice of
  1964. // device IDs.
  1965. func mapDevices(devices []protocol.DeviceID) map[protocol.DeviceID]struct{} {
  1966. m := make(map[protocol.DeviceID]struct{}, len(devices))
  1967. for _, dev := range devices {
  1968. m[dev] = struct{}{}
  1969. }
  1970. return m
  1971. }
  1972. func symlinkInvalid(folder string, fi db.FileIntf) bool {
  1973. if !symlinks.Supported && fi.IsSymlink() && !fi.IsInvalid() && !fi.IsDeleted() {
  1974. symlinkWarning.Do(func() {
  1975. l.Warnln("Symlinks are disabled, unsupported or require Administrator privileges. This might cause your folder to appear out of sync.")
  1976. })
  1977. // Need to type switch for the concrete type to be able to access fields...
  1978. var name string
  1979. switch fi := fi.(type) {
  1980. case protocol.FileInfo:
  1981. name = fi.Name
  1982. case db.FileInfoTruncated:
  1983. name = fi.Name
  1984. }
  1985. l.Infoln("Unsupported symlink", name, "in folder", folder)
  1986. return true
  1987. }
  1988. return false
  1989. }
  1990. // Skips `skip` elements and retrieves up to `get` elements from a given slice.
  1991. // Returns the resulting slice, plus how much elements are left to skip or
  1992. // copy to satisfy the values which were provided, given the slice is not
  1993. // big enough.
  1994. func getChunk(data []string, skip, get int) ([]string, int, int) {
  1995. l := len(data)
  1996. if l <= skip {
  1997. return []string{}, skip - l, get
  1998. } else if l < skip+get {
  1999. return data[skip:l], 0, get - (l - skip)
  2000. }
  2001. return data[skip : skip+get], 0, 0
  2002. }
  2003. func closeRawConn(conn io.Closer) error {
  2004. if conn, ok := conn.(*tls.Conn); ok {
  2005. // If the underlying connection is a *tls.Conn, Close() does more
  2006. // than it says on the tin. Specifically, it sends a TLS alert
  2007. // message, which might block forever if the connection is dead
  2008. // and we don't have a deadline set.
  2009. conn.SetWriteDeadline(time.Now().Add(250 * time.Millisecond))
  2010. }
  2011. return conn.Close()
  2012. }
  2013. func stringSliceWithout(ss []string, s string) []string {
  2014. for i := range ss {
  2015. if ss[i] == s {
  2016. copy(ss[i:], ss[i+1:])
  2017. ss = ss[:len(ss)-1]
  2018. return ss
  2019. }
  2020. }
  2021. return ss
  2022. }
  2023. func readOffsetIntoBuf(file string, offset int64, buf []byte) error {
  2024. fd, err := os.Open(file)
  2025. if err != nil {
  2026. l.Debugln("readOffsetIntoBuf.Open", file, err)
  2027. return err
  2028. }
  2029. defer fd.Close()
  2030. _, err = fd.ReadAt(buf, offset)
  2031. if err != nil {
  2032. l.Debugln("readOffsetIntoBuf.ReadAt", file, err)
  2033. }
  2034. return err
  2035. }
  2036. // The exists function is expected to return true for all known paths
  2037. // (excluding "" and ".")
  2038. func unifySubs(dirs []string, exists func(dir string) bool) []string {
  2039. subs := trimUntilParentKnown(dirs, exists)
  2040. sort.Strings(subs)
  2041. return simplifySortedPaths(subs)
  2042. }
  2043. func trimUntilParentKnown(dirs []string, exists func(dir string) bool) []string {
  2044. var subs []string
  2045. for _, sub := range dirs {
  2046. for sub != "" && sub != ".stfolder" && sub != ".stignore" {
  2047. sub = filepath.Clean(sub)
  2048. parent := filepath.Dir(sub)
  2049. if parent == "." || exists(parent) {
  2050. break
  2051. }
  2052. sub = parent
  2053. if sub == "." || sub == string(filepath.Separator) {
  2054. // Shortcut. We are going to scan the full folder, so we can
  2055. // just return an empty list of subs at this point.
  2056. return nil
  2057. }
  2058. }
  2059. if sub == "" {
  2060. return nil
  2061. }
  2062. subs = append(subs, sub)
  2063. }
  2064. return subs
  2065. }
  2066. func simplifySortedPaths(subs []string) []string {
  2067. var cleaned []string
  2068. next:
  2069. for _, sub := range subs {
  2070. for _, existing := range cleaned {
  2071. if sub == existing || strings.HasPrefix(sub, existing+string(os.PathSeparator)) {
  2072. continue next
  2073. }
  2074. }
  2075. cleaned = append(cleaned, sub)
  2076. }
  2077. return cleaned
  2078. }
  2079. // makeForgetUpdate takes an index update and constructs a download progress update
  2080. // causing to forget any progress for files which we've just been sent.
  2081. func makeForgetUpdate(files []protocol.FileInfo) []protocol.FileDownloadProgressUpdate {
  2082. updates := make([]protocol.FileDownloadProgressUpdate, 0, len(files))
  2083. for _, file := range files {
  2084. if file.IsSymlink() || file.IsDirectory() || file.IsDeleted() {
  2085. continue
  2086. }
  2087. updates = append(updates, protocol.FileDownloadProgressUpdate{
  2088. Name: file.Name,
  2089. Version: file.Version,
  2090. UpdateType: protocol.UpdateTypeForget,
  2091. })
  2092. }
  2093. return updates
  2094. }
  2095. // shouldIgnore returns true when a file should be excluded from processing
  2096. func shouldIgnore(file db.FileIntf, matcher *ignore.Matcher, ignoreDelete bool) bool {
  2097. // We check things in a certain order here...
  2098. switch {
  2099. case ignoreDelete && file.IsDeleted():
  2100. // ignoreDelete first because it's a very cheap test so a win if it
  2101. // succeeds, and we might in the long run accumulate quite a few
  2102. // deleted files.
  2103. return true
  2104. case matcher.Match(file.FileName()).IsIgnored():
  2105. // ignore patterns second because ignoring them is a valid way to
  2106. // silence warnings about them being invalid and so on.
  2107. return true
  2108. }
  2109. return false
  2110. }