model.go 80 KB

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