1
0

model.go 86 KB

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