model.go 80 KB

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