model.go 79 KB

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