model.go 78 KB

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