model.go 78 KB

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