model.go 83 KB

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