model.go 83 KB

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