model.go 76 KB

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