model.go 80 KB

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