model.go 80 KB

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