model.go 80 KB

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