model.go 80 KB

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