model.go 80 KB

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