model.go 77 KB

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