model.go 82 KB

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