model.go 81 KB

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