model.go 81 KB

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