model.go 77 KB

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