model.go 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129
  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 http://mozilla.org/MPL/2.0/.
  6. package model
  7. import (
  8. "bufio"
  9. "crypto/tls"
  10. "encoding/json"
  11. "errors"
  12. "fmt"
  13. "io"
  14. "net"
  15. "os"
  16. "path/filepath"
  17. "reflect"
  18. "runtime"
  19. "sort"
  20. "strings"
  21. stdsync "sync"
  22. "time"
  23. "github.com/syncthing/syncthing/lib/config"
  24. "github.com/syncthing/syncthing/lib/db"
  25. "github.com/syncthing/syncthing/lib/events"
  26. "github.com/syncthing/syncthing/lib/ignore"
  27. "github.com/syncthing/syncthing/lib/osutil"
  28. "github.com/syncthing/syncthing/lib/protocol"
  29. "github.com/syncthing/syncthing/lib/scanner"
  30. "github.com/syncthing/syncthing/lib/stats"
  31. "github.com/syncthing/syncthing/lib/symlinks"
  32. "github.com/syncthing/syncthing/lib/sync"
  33. "github.com/syncthing/syncthing/lib/versioner"
  34. "github.com/thejerf/suture"
  35. )
  36. // How many files to send in each Index/IndexUpdate message.
  37. const (
  38. indexTargetSize = 250 * 1024 // Aim for making index messages no larger than 250 KiB (uncompressed)
  39. indexPerFileSize = 250 // Each FileInfo is approximately this big, in bytes, excluding BlockInfos
  40. indexPerBlockSize = 40 // Each BlockInfo is approximately this big
  41. indexBatchSize = 1000 // Either way, don't include more files than this
  42. )
  43. type service interface {
  44. Serve()
  45. Stop()
  46. Jobs() ([]string, []string) // In progress, Queued
  47. BringToFront(string)
  48. DelayScan(d time.Duration)
  49. IndexUpdated() // Remote index was updated notification
  50. Scan(subs []string) error
  51. setState(state folderState)
  52. setError(err error)
  53. clearError()
  54. getState() (folderState, time.Time, error)
  55. }
  56. type Model struct {
  57. *suture.Supervisor
  58. cfg *config.Wrapper
  59. db *db.Instance
  60. finder *db.BlockFinder
  61. progressEmitter *ProgressEmitter
  62. id protocol.DeviceID
  63. shortID protocol.ShortID
  64. cacheIgnoredFiles bool
  65. protectedFiles []string
  66. deviceName string
  67. clientName string
  68. clientVersion string
  69. folderCfgs map[string]config.FolderConfiguration // folder -> cfg
  70. folderFiles map[string]*db.FileSet // folder -> files
  71. folderDevices map[string][]protocol.DeviceID // folder -> deviceIDs
  72. deviceFolders map[protocol.DeviceID][]string // deviceID -> folders
  73. deviceStatRefs map[protocol.DeviceID]*stats.DeviceStatisticsReference // deviceID -> statsRef
  74. folderIgnores map[string]*ignore.Matcher // folder -> matcher object
  75. folderRunners map[string]service // folder -> puller or scanner
  76. folderRunnerTokens map[string][]suture.ServiceToken // folder -> tokens for puller or scanner
  77. folderStatRefs map[string]*stats.FolderStatisticsReference // folder -> statsRef
  78. fmut sync.RWMutex // protects the above
  79. conn map[protocol.DeviceID]Connection
  80. helloMessages map[protocol.DeviceID]protocol.HelloMessage
  81. devicePaused map[protocol.DeviceID]bool
  82. pmut sync.RWMutex // protects the above
  83. }
  84. var (
  85. symlinkWarning = stdsync.Once{}
  86. )
  87. // NewModel creates and starts a new model. The model starts in read-only mode,
  88. // where it sends index information to connected peers and responds to requests
  89. // for file data without altering the local folder in any way.
  90. func NewModel(cfg *config.Wrapper, id protocol.DeviceID, deviceName, clientName, clientVersion string, ldb *db.Instance, protectedFiles []string) *Model {
  91. m := &Model{
  92. Supervisor: suture.New("model", suture.Spec{
  93. Log: func(line string) {
  94. l.Debugln(line)
  95. },
  96. }),
  97. cfg: cfg,
  98. db: ldb,
  99. finder: db.NewBlockFinder(ldb),
  100. progressEmitter: NewProgressEmitter(cfg),
  101. id: id,
  102. shortID: id.Short(),
  103. cacheIgnoredFiles: cfg.Options().CacheIgnoredFiles,
  104. protectedFiles: protectedFiles,
  105. deviceName: deviceName,
  106. clientName: clientName,
  107. clientVersion: clientVersion,
  108. folderCfgs: make(map[string]config.FolderConfiguration),
  109. folderFiles: make(map[string]*db.FileSet),
  110. folderDevices: make(map[string][]protocol.DeviceID),
  111. deviceFolders: make(map[protocol.DeviceID][]string),
  112. deviceStatRefs: make(map[protocol.DeviceID]*stats.DeviceStatisticsReference),
  113. folderIgnores: make(map[string]*ignore.Matcher),
  114. folderRunners: make(map[string]service),
  115. folderRunnerTokens: make(map[string][]suture.ServiceToken),
  116. folderStatRefs: make(map[string]*stats.FolderStatisticsReference),
  117. conn: make(map[protocol.DeviceID]Connection),
  118. helloMessages: make(map[protocol.DeviceID]protocol.HelloMessage),
  119. devicePaused: make(map[protocol.DeviceID]bool),
  120. fmut: sync.NewRWMutex(),
  121. pmut: sync.NewRWMutex(),
  122. }
  123. if cfg.Options().ProgressUpdateIntervalS > -1 {
  124. go m.progressEmitter.Serve()
  125. }
  126. return m
  127. }
  128. // StartDeadlockDetector starts a deadlock detector on the models locks which
  129. // causes panics in case the locks cannot be acquired in the given timeout
  130. // period.
  131. func (m *Model) StartDeadlockDetector(timeout time.Duration) {
  132. l.Infof("Starting deadlock detector with %v timeout", timeout)
  133. deadlockDetect(m.fmut, timeout)
  134. deadlockDetect(m.pmut, timeout)
  135. }
  136. // StartFolderRW starts read/write processing on the current model. When in
  137. // read/write mode the model will attempt to keep in sync with the cluster by
  138. // pulling needed files from peer devices.
  139. func (m *Model) StartFolderRW(folder string) {
  140. m.fmut.Lock()
  141. cfg, ok := m.folderCfgs[folder]
  142. if !ok {
  143. panic("cannot start nonexistent folder " + folder)
  144. }
  145. _, ok = m.folderRunners[folder]
  146. if ok {
  147. panic("cannot start already running folder " + folder)
  148. }
  149. p := newRWFolder(m, m.shortID, cfg)
  150. m.folderRunners[folder] = p
  151. if len(cfg.Versioning.Type) > 0 {
  152. factory, ok := versioner.Factories[cfg.Versioning.Type]
  153. if !ok {
  154. l.Fatalf("Requested versioning type %q that does not exist", cfg.Versioning.Type)
  155. }
  156. versioner := factory(folder, cfg.Path(), cfg.Versioning.Params)
  157. if service, ok := versioner.(suture.Service); ok {
  158. // The versioner implements the suture.Service interface, so
  159. // expects to be run in the background in addition to being called
  160. // when files are going to be archived.
  161. token := m.Add(service)
  162. m.folderRunnerTokens[folder] = append(m.folderRunnerTokens[folder], token)
  163. }
  164. p.versioner = versioner
  165. }
  166. m.warnAboutOverwritingProtectedFiles(folder)
  167. token := m.Add(p)
  168. m.folderRunnerTokens[folder] = append(m.folderRunnerTokens[folder], token)
  169. m.fmut.Unlock()
  170. l.Infoln("Ready to synchronize", folder, "(read-write)")
  171. }
  172. func (m *Model) warnAboutOverwritingProtectedFiles(folder string) {
  173. if m.folderCfgs[folder].ReadOnly {
  174. return
  175. }
  176. folderLocation := m.folderCfgs[folder].Path()
  177. ignores := m.folderIgnores[folder]
  178. var filesAtRisk []string
  179. for _, protectedFilePath := range m.protectedFiles {
  180. // check if file is synced in this folder
  181. if !strings.HasPrefix(protectedFilePath, folderLocation) {
  182. continue
  183. }
  184. // check if file is ignored
  185. if ignores.Match(protectedFilePath) {
  186. continue
  187. }
  188. filesAtRisk = append(filesAtRisk, protectedFilePath)
  189. }
  190. if len(filesAtRisk) > 0 {
  191. l.Warnln("Some protected files may be overwritten and cause issues. See http://docs.syncthing.net/users/config.html#syncing-configuration-files for more information. The at risk files are:", strings.Join(filesAtRisk, ", "))
  192. }
  193. }
  194. // StartFolderRO starts read only processing on the current model. When in
  195. // read only mode the model will announce files to the cluster but not pull in
  196. // any external changes.
  197. func (m *Model) StartFolderRO(folder string) {
  198. m.fmut.Lock()
  199. cfg, ok := m.folderCfgs[folder]
  200. if !ok {
  201. panic("cannot start nonexistent folder " + folder)
  202. }
  203. _, ok = m.folderRunners[folder]
  204. if ok {
  205. panic("cannot start already running folder " + folder)
  206. }
  207. s := newROFolder(m, folder, time.Duration(cfg.RescanIntervalS)*time.Second)
  208. m.folderRunners[folder] = s
  209. token := m.Add(s)
  210. m.folderRunnerTokens[folder] = append(m.folderRunnerTokens[folder], token)
  211. m.fmut.Unlock()
  212. l.Infoln("Ready to synchronize", folder, "(read only; no external updates accepted)")
  213. }
  214. func (m *Model) RemoveFolder(folder string) {
  215. m.fmut.Lock()
  216. m.pmut.Lock()
  217. // Stop the services running for this folder
  218. for _, id := range m.folderRunnerTokens[folder] {
  219. m.Remove(id)
  220. }
  221. // Close connections to affected devices
  222. for _, dev := range m.folderDevices[folder] {
  223. if conn, ok := m.conn[dev]; ok {
  224. closeRawConn(conn)
  225. }
  226. }
  227. // Clean up our config maps
  228. delete(m.folderCfgs, folder)
  229. delete(m.folderFiles, folder)
  230. delete(m.folderDevices, folder)
  231. delete(m.folderIgnores, folder)
  232. delete(m.folderRunners, folder)
  233. delete(m.folderRunnerTokens, folder)
  234. delete(m.folderStatRefs, folder)
  235. for dev, folders := range m.deviceFolders {
  236. m.deviceFolders[dev] = stringSliceWithout(folders, folder)
  237. }
  238. // Remove it from the database
  239. db.DropFolder(m.db, folder)
  240. m.pmut.Unlock()
  241. m.fmut.Unlock()
  242. }
  243. type ConnectionInfo struct {
  244. protocol.Statistics
  245. Connected bool
  246. Paused bool
  247. Address string
  248. ClientVersion string
  249. Type ConnectionType
  250. }
  251. func (info ConnectionInfo) MarshalJSON() ([]byte, error) {
  252. return json.Marshal(map[string]interface{}{
  253. "at": info.At,
  254. "inBytesTotal": info.InBytesTotal,
  255. "outBytesTotal": info.OutBytesTotal,
  256. "connected": info.Connected,
  257. "paused": info.Paused,
  258. "address": info.Address,
  259. "clientVersion": info.ClientVersion,
  260. "type": info.Type.String(),
  261. })
  262. }
  263. // ConnectionStats returns a map with connection statistics for each device.
  264. func (m *Model) ConnectionStats() map[string]interface{} {
  265. type remoteAddrer interface {
  266. RemoteAddr() net.Addr
  267. }
  268. m.pmut.RLock()
  269. m.fmut.RLock()
  270. res := make(map[string]interface{})
  271. devs := m.cfg.Devices()
  272. conns := make(map[string]ConnectionInfo, len(devs))
  273. for device := range devs {
  274. hello := m.helloMessages[device]
  275. versionString := hello.ClientVersion
  276. if hello.ClientName != "syncthing" {
  277. versionString = hello.ClientName + " " + hello.ClientVersion
  278. }
  279. ci := ConnectionInfo{
  280. ClientVersion: versionString,
  281. Paused: m.devicePaused[device],
  282. }
  283. if conn, ok := m.conn[device]; ok {
  284. ci.Type = conn.Type
  285. ci.Connected = ok
  286. ci.Statistics = conn.Statistics()
  287. if addr := conn.RemoteAddr(); addr != nil {
  288. ci.Address = addr.String()
  289. }
  290. }
  291. conns[device.String()] = ci
  292. }
  293. res["connections"] = conns
  294. m.fmut.RUnlock()
  295. m.pmut.RUnlock()
  296. in, out := protocol.TotalInOut()
  297. res["total"] = ConnectionInfo{
  298. Statistics: protocol.Statistics{
  299. At: time.Now(),
  300. InBytesTotal: in,
  301. OutBytesTotal: out,
  302. },
  303. }
  304. return res
  305. }
  306. // DeviceStatistics returns statistics about each device
  307. func (m *Model) DeviceStatistics() map[string]stats.DeviceStatistics {
  308. var res = make(map[string]stats.DeviceStatistics)
  309. for id := range m.cfg.Devices() {
  310. res[id.String()] = m.deviceStatRef(id).GetStatistics()
  311. }
  312. return res
  313. }
  314. // FolderStatistics returns statistics about each folder
  315. func (m *Model) FolderStatistics() map[string]stats.FolderStatistics {
  316. var res = make(map[string]stats.FolderStatistics)
  317. for id := range m.cfg.Folders() {
  318. res[id] = m.folderStatRef(id).GetStatistics()
  319. }
  320. return res
  321. }
  322. // Completion returns the completion status, in percent, for the given device
  323. // and folder.
  324. func (m *Model) Completion(device protocol.DeviceID, folder string) float64 {
  325. m.fmut.RLock()
  326. rf, ok := m.folderFiles[folder]
  327. m.fmut.RUnlock()
  328. if !ok {
  329. return 0 // Folder doesn't exist, so we hardly have any of it
  330. }
  331. _, _, tot := rf.GlobalSize()
  332. if tot == 0 {
  333. return 100 // Folder is empty, so we have all of it
  334. }
  335. var need int64
  336. rf.WithNeedTruncated(device, func(f db.FileIntf) bool {
  337. need += f.Size()
  338. return true
  339. })
  340. needRatio := float64(need) / float64(tot)
  341. completionPct := 100 * (1 - needRatio)
  342. l.Debugf("%v Completion(%s, %q): %f (%d / %d = %f)", m, device, folder, completionPct, need, tot, needRatio)
  343. return completionPct
  344. }
  345. func sizeOfFile(f db.FileIntf) (files, deleted int, bytes int64) {
  346. if !f.IsDeleted() {
  347. files++
  348. } else {
  349. deleted++
  350. }
  351. bytes += f.Size()
  352. return
  353. }
  354. // GlobalSize returns the number of files, deleted files and total bytes for all
  355. // files in the global model.
  356. func (m *Model) GlobalSize(folder string) (nfiles, deleted int, bytes int64) {
  357. m.fmut.RLock()
  358. defer m.fmut.RUnlock()
  359. if rf, ok := m.folderFiles[folder]; ok {
  360. nfiles, deleted, bytes = rf.GlobalSize()
  361. }
  362. return
  363. }
  364. // LocalSize returns the number of files, deleted files and total bytes for all
  365. // files in the local folder.
  366. func (m *Model) LocalSize(folder string) (nfiles, deleted int, bytes int64) {
  367. m.fmut.RLock()
  368. defer m.fmut.RUnlock()
  369. if rf, ok := m.folderFiles[folder]; ok {
  370. nfiles, deleted, bytes = rf.LocalSize()
  371. }
  372. return
  373. }
  374. // NeedSize returns the number and total size of currently needed files.
  375. func (m *Model) NeedSize(folder string) (nfiles int, bytes int64) {
  376. m.fmut.RLock()
  377. defer m.fmut.RUnlock()
  378. if rf, ok := m.folderFiles[folder]; ok {
  379. rf.WithNeedTruncated(protocol.LocalDeviceID, func(f db.FileIntf) bool {
  380. fs, de, by := sizeOfFile(f)
  381. nfiles += fs + de
  382. bytes += by
  383. return true
  384. })
  385. }
  386. bytes -= m.progressEmitter.BytesCompleted(folder)
  387. l.Debugf("%v NeedSize(%q): %d %d", m, folder, nfiles, bytes)
  388. return
  389. }
  390. // NeedFolderFiles returns paginated list of currently needed files in
  391. // progress, queued, and to be queued on next puller iteration, as well as the
  392. // total number of files currently needed.
  393. func (m *Model) NeedFolderFiles(folder string, page, perpage int) ([]db.FileInfoTruncated, []db.FileInfoTruncated, []db.FileInfoTruncated, int) {
  394. m.fmut.RLock()
  395. defer m.fmut.RUnlock()
  396. total := 0
  397. rf, ok := m.folderFiles[folder]
  398. if !ok {
  399. return nil, nil, nil, 0
  400. }
  401. var progress, queued, rest []db.FileInfoTruncated
  402. var seen map[string]struct{}
  403. skip := (page - 1) * perpage
  404. get := perpage
  405. runner, ok := m.folderRunners[folder]
  406. if ok {
  407. allProgressNames, allQueuedNames := runner.Jobs()
  408. var progressNames, queuedNames []string
  409. progressNames, skip, get = getChunk(allProgressNames, skip, get)
  410. queuedNames, skip, get = getChunk(allQueuedNames, skip, get)
  411. progress = make([]db.FileInfoTruncated, len(progressNames))
  412. queued = make([]db.FileInfoTruncated, len(queuedNames))
  413. seen = make(map[string]struct{}, len(progressNames)+len(queuedNames))
  414. for i, name := range progressNames {
  415. if f, ok := rf.GetGlobalTruncated(name); ok {
  416. progress[i] = f
  417. seen[name] = struct{}{}
  418. }
  419. }
  420. for i, name := range queuedNames {
  421. if f, ok := rf.GetGlobalTruncated(name); ok {
  422. queued[i] = f
  423. seen[name] = struct{}{}
  424. }
  425. }
  426. }
  427. rest = make([]db.FileInfoTruncated, 0, perpage)
  428. rf.WithNeedTruncated(protocol.LocalDeviceID, func(f db.FileIntf) bool {
  429. total++
  430. if skip > 0 {
  431. skip--
  432. return true
  433. }
  434. if get > 0 {
  435. ft := f.(db.FileInfoTruncated)
  436. if _, ok := seen[ft.Name]; !ok {
  437. rest = append(rest, ft)
  438. get--
  439. }
  440. }
  441. return true
  442. })
  443. return progress, queued, rest, total
  444. }
  445. // Index is called when a new device is connected and we receive their full index.
  446. // Implements the protocol.Model interface.
  447. func (m *Model) Index(deviceID protocol.DeviceID, folder string, fs []protocol.FileInfo, flags uint32, options []protocol.Option) {
  448. if flags != 0 {
  449. l.Warnln("protocol error: unknown flags 0x%x in Index message", flags)
  450. return
  451. }
  452. l.Debugf("IDX(in): %s %q: %d files", deviceID, folder, len(fs))
  453. if !m.folderSharedWith(folder, deviceID) {
  454. 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)
  455. return
  456. }
  457. m.fmut.RLock()
  458. cfg := m.folderCfgs[folder]
  459. files, ok := m.folderFiles[folder]
  460. runner := m.folderRunners[folder]
  461. m.fmut.RUnlock()
  462. if runner != nil {
  463. // Runner may legitimately not be set if this is the "cleanup" Index
  464. // message at startup.
  465. defer runner.IndexUpdated()
  466. }
  467. if !ok {
  468. l.Fatalf("Index for nonexistant folder %q", folder)
  469. }
  470. fs = filterIndex(folder, fs, cfg.IgnoreDelete)
  471. files.Replace(deviceID, fs)
  472. events.Default.Log(events.RemoteIndexUpdated, map[string]interface{}{
  473. "device": deviceID.String(),
  474. "folder": folder,
  475. "items": len(fs),
  476. "version": files.LocalVersion(deviceID),
  477. })
  478. }
  479. // IndexUpdate is called for incremental updates to connected devices' indexes.
  480. // Implements the protocol.Model interface.
  481. func (m *Model) IndexUpdate(deviceID protocol.DeviceID, folder string, fs []protocol.FileInfo, flags uint32, options []protocol.Option) {
  482. if flags != 0 {
  483. l.Warnln("protocol error: unknown flags 0x%x in IndexUpdate message", flags)
  484. return
  485. }
  486. l.Debugf("%v IDXUP(in): %s / %q: %d files", m, deviceID, folder, len(fs))
  487. if !m.folderSharedWith(folder, deviceID) {
  488. 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)
  489. return
  490. }
  491. m.fmut.RLock()
  492. files := m.folderFiles[folder]
  493. cfg := m.folderCfgs[folder]
  494. runner, ok := m.folderRunners[folder]
  495. m.fmut.RUnlock()
  496. if !ok {
  497. l.Fatalf("IndexUpdate for nonexistant folder %q", folder)
  498. }
  499. fs = filterIndex(folder, fs, cfg.IgnoreDelete)
  500. files.Update(deviceID, fs)
  501. events.Default.Log(events.RemoteIndexUpdated, map[string]interface{}{
  502. "device": deviceID.String(),
  503. "folder": folder,
  504. "items": len(fs),
  505. "version": files.LocalVersion(deviceID),
  506. })
  507. runner.IndexUpdated()
  508. }
  509. func (m *Model) folderSharedWith(folder string, deviceID protocol.DeviceID) bool {
  510. m.fmut.RLock()
  511. defer m.fmut.RUnlock()
  512. return m.folderSharedWithUnlocked(folder, deviceID)
  513. }
  514. func (m *Model) folderSharedWithUnlocked(folder string, deviceID protocol.DeviceID) bool {
  515. for _, nfolder := range m.deviceFolders[deviceID] {
  516. if nfolder == folder {
  517. return true
  518. }
  519. }
  520. return false
  521. }
  522. func (m *Model) ClusterConfig(deviceID protocol.DeviceID, cm protocol.ClusterConfigMessage) {
  523. // Check the peer device's announced folders against our own. Emits events
  524. // for folders that we don't expect (unknown or not shared).
  525. m.fmut.Lock()
  526. nextFolder:
  527. for _, folder := range cm.Folders {
  528. cfg := m.folderCfgs[folder.ID]
  529. if folder.Flags&^protocol.FlagFolderAll != 0 {
  530. // There are flags set that we don't know what they mean. Scary!
  531. l.Warnf("Device %v: unknown flags for folder %s", deviceID, folder.ID)
  532. cfg.Invalid = fmt.Sprintf("Unknown flags from device %v", deviceID)
  533. m.cfg.SetFolder(cfg)
  534. if srv := m.folderRunners[folder.ID]; srv != nil {
  535. srv.setError(fmt.Errorf(cfg.Invalid))
  536. }
  537. continue nextFolder
  538. }
  539. if !m.folderSharedWithUnlocked(folder.ID, deviceID) {
  540. events.Default.Log(events.FolderRejected, map[string]string{
  541. "folder": folder.ID,
  542. "folderLabel": folder.Label,
  543. "device": deviceID.String(),
  544. })
  545. l.Infof("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.ID, deviceID)
  546. continue
  547. }
  548. }
  549. m.fmut.Unlock()
  550. var changed bool
  551. if m.cfg.Devices()[deviceID].Introducer {
  552. // This device is an introducer. Go through the announced lists of folders
  553. // and devices and add what we are missing.
  554. for _, folder := range cm.Folders {
  555. // If we don't have this folder yet, skip it. Ideally, we'd
  556. // offer up something in the GUI to create the folder, but for the
  557. // moment we only handle folders that we already have.
  558. if _, ok := m.folderDevices[folder.ID]; !ok {
  559. continue
  560. }
  561. nextDevice:
  562. for _, device := range folder.Devices {
  563. var id protocol.DeviceID
  564. copy(id[:], device.ID)
  565. if _, ok := m.cfg.Devices()[id]; !ok {
  566. // The device is currently unknown. Add it to the config.
  567. addresses := []string{"dynamic"}
  568. for _, addr := range device.Addresses {
  569. if addr != "dynamic" {
  570. addresses = append(addresses, addr)
  571. }
  572. }
  573. l.Infof("Adding device %v to config (vouched for by introducer %v)", id, deviceID)
  574. newDeviceCfg := config.DeviceConfiguration{
  575. DeviceID: id,
  576. Name: device.Name,
  577. Compression: m.cfg.Devices()[deviceID].Compression,
  578. Addresses: addresses,
  579. CertName: device.CertName,
  580. }
  581. // The introducers' introducers are also our introducers.
  582. if device.Flags&protocol.FlagIntroducer != 0 {
  583. l.Infof("Device %v is now also an introducer", id)
  584. newDeviceCfg.Introducer = true
  585. }
  586. m.cfg.SetDevice(newDeviceCfg)
  587. changed = true
  588. }
  589. for _, er := range m.deviceFolders[id] {
  590. if er == folder.ID {
  591. // We already share the folder with this device, so
  592. // nothing to do.
  593. continue nextDevice
  594. }
  595. }
  596. // We don't yet share this folder with this device. Add the device
  597. // to sharing list of the folder.
  598. l.Infof("Adding device %v to share %q (vouched for by introducer %v)", id, folder.ID, deviceID)
  599. m.deviceFolders[id] = append(m.deviceFolders[id], folder.ID)
  600. m.folderDevices[folder.ID] = append(m.folderDevices[folder.ID], id)
  601. folderCfg := m.cfg.Folders()[folder.ID]
  602. folderCfg.Devices = append(folderCfg.Devices, config.FolderDeviceConfiguration{
  603. DeviceID: id,
  604. })
  605. m.cfg.SetFolder(folderCfg)
  606. changed = true
  607. }
  608. }
  609. }
  610. if changed {
  611. m.cfg.Save()
  612. }
  613. }
  614. // Close removes the peer from the model and closes the underlying connection if possible.
  615. // Implements the protocol.Model interface.
  616. func (m *Model) Close(device protocol.DeviceID, err error) {
  617. l.Infof("Connection to %s closed: %v", device, err)
  618. events.Default.Log(events.DeviceDisconnected, map[string]string{
  619. "id": device.String(),
  620. "error": err.Error(),
  621. })
  622. m.pmut.Lock()
  623. m.fmut.RLock()
  624. for _, folder := range m.deviceFolders[device] {
  625. m.folderFiles[folder].Replace(device, nil)
  626. }
  627. m.fmut.RUnlock()
  628. conn, ok := m.conn[device]
  629. if ok {
  630. closeRawConn(conn)
  631. }
  632. delete(m.conn, device)
  633. delete(m.helloMessages, device)
  634. m.pmut.Unlock()
  635. }
  636. // Request returns the specified data segment by reading it from local disk.
  637. // Implements the protocol.Model interface.
  638. func (m *Model) Request(deviceID protocol.DeviceID, folder, name string, offset int64, hash []byte, flags uint32, options []protocol.Option, buf []byte) error {
  639. if offset < 0 {
  640. return protocol.ErrInvalid
  641. }
  642. if !m.folderSharedWith(folder, deviceID) {
  643. l.Warnf("Request from %s for file %s in unshared folder %q", deviceID, name, folder)
  644. return protocol.ErrInvalid
  645. }
  646. if flags != 0 {
  647. // We don't currently support or expect any flags.
  648. return protocol.ErrInvalid
  649. }
  650. if deviceID != protocol.LocalDeviceID {
  651. l.Debugf("%v REQ(in): %s: %q / %q o=%d s=%d", m, deviceID, folder, name, offset, len(buf))
  652. }
  653. m.fmut.RLock()
  654. folderPath := m.folderCfgs[folder].Path()
  655. folderIgnores := m.folderIgnores[folder]
  656. m.fmut.RUnlock()
  657. // filepath.Join() returns a filepath.Clean()ed path, which (quoting the
  658. // docs for clarity here):
  659. //
  660. // Clean returns the shortest path name equivalent to path by purely lexical
  661. // processing. It applies the following rules iteratively until no further
  662. // processing can be done:
  663. //
  664. // 1. Replace multiple Separator elements with a single one.
  665. // 2. Eliminate each . path name element (the current directory).
  666. // 3. Eliminate each inner .. path name element (the parent directory)
  667. // along with the non-.. element that precedes it.
  668. // 4. Eliminate .. elements that begin a rooted path:
  669. // that is, replace "/.." by "/" at the beginning of a path,
  670. // assuming Separator is '/'.
  671. fn := filepath.Join(folderPath, name)
  672. if !strings.HasPrefix(fn, folderPath) {
  673. // Request tries to escape!
  674. l.Debugf("%v Invalid REQ(in) tries to escape: %s: %q / %q o=%d s=%d", m, deviceID, folder, name, offset, len(buf))
  675. return protocol.ErrInvalid
  676. }
  677. if folderIgnores != nil {
  678. // "rn" becomes the relative name of the file within the folder. This is
  679. // different than the original "name" parameter in that it's been
  680. // cleaned from any possible funny business.
  681. if rn, err := filepath.Rel(folderPath, fn); err != nil {
  682. return err
  683. } else if folderIgnores.Match(rn) {
  684. l.Debugf("%v REQ(in) for ignored file: %s: %q / %q o=%d s=%d", m, deviceID, folder, name, offset, len(buf))
  685. return protocol.ErrNoSuchFile
  686. }
  687. }
  688. var reader io.ReaderAt
  689. var err error
  690. if info, err := os.Lstat(fn); err == nil && info.Mode()&os.ModeSymlink != 0 {
  691. target, _, err := symlinks.Read(fn)
  692. if err != nil {
  693. l.Debugln("symlinks.Read:", err)
  694. if os.IsNotExist(err) {
  695. return protocol.ErrNoSuchFile
  696. }
  697. return protocol.ErrGeneric
  698. }
  699. reader = strings.NewReader(target)
  700. } else {
  701. // Cannot easily cache fd's because we might need to delete the file
  702. // at any moment.
  703. reader, err = os.Open(fn)
  704. if err != nil {
  705. l.Debugln("os.Open:", err)
  706. if os.IsNotExist(err) {
  707. return protocol.ErrNoSuchFile
  708. }
  709. return protocol.ErrGeneric
  710. }
  711. defer reader.(*os.File).Close()
  712. }
  713. _, err = reader.ReadAt(buf, offset)
  714. if err != nil {
  715. l.Debugln("reader.ReadAt:", err)
  716. return protocol.ErrGeneric
  717. }
  718. return nil
  719. }
  720. func (m *Model) CurrentFolderFile(folder string, file string) (protocol.FileInfo, bool) {
  721. m.fmut.RLock()
  722. fs, ok := m.folderFiles[folder]
  723. m.fmut.RUnlock()
  724. if !ok {
  725. return protocol.FileInfo{}, false
  726. }
  727. f, ok := fs.Get(protocol.LocalDeviceID, file)
  728. return f, ok
  729. }
  730. func (m *Model) CurrentGlobalFile(folder string, file string) (protocol.FileInfo, bool) {
  731. m.fmut.RLock()
  732. fs, ok := m.folderFiles[folder]
  733. m.fmut.RUnlock()
  734. if !ok {
  735. return protocol.FileInfo{}, false
  736. }
  737. f, ok := fs.GetGlobal(file)
  738. return f, ok
  739. }
  740. type cFiler struct {
  741. m *Model
  742. r string
  743. }
  744. // Implements scanner.CurrentFiler
  745. func (cf cFiler) CurrentFile(file string) (protocol.FileInfo, bool) {
  746. return cf.m.CurrentFolderFile(cf.r, file)
  747. }
  748. // ConnectedTo returns true if we are connected to the named device.
  749. func (m *Model) ConnectedTo(deviceID protocol.DeviceID) bool {
  750. m.pmut.RLock()
  751. _, ok := m.conn[deviceID]
  752. m.pmut.RUnlock()
  753. if ok {
  754. m.deviceWasSeen(deviceID)
  755. }
  756. return ok
  757. }
  758. func (m *Model) GetIgnores(folder string) ([]string, []string, error) {
  759. var lines []string
  760. m.fmut.RLock()
  761. cfg, ok := m.folderCfgs[folder]
  762. m.fmut.RUnlock()
  763. if !ok {
  764. return lines, nil, fmt.Errorf("Folder %s does not exist", folder)
  765. }
  766. if !cfg.HasMarker() {
  767. return lines, nil, fmt.Errorf("Folder %s stopped", folder)
  768. }
  769. fd, err := os.Open(filepath.Join(cfg.Path(), ".stignore"))
  770. if err != nil {
  771. if os.IsNotExist(err) {
  772. return lines, nil, nil
  773. }
  774. l.Warnln("Loading .stignore:", err)
  775. return lines, nil, err
  776. }
  777. defer fd.Close()
  778. scanner := bufio.NewScanner(fd)
  779. for scanner.Scan() {
  780. lines = append(lines, strings.TrimSpace(scanner.Text()))
  781. }
  782. m.fmut.RLock()
  783. patterns := m.folderIgnores[folder].Patterns()
  784. m.fmut.RUnlock()
  785. return lines, patterns, nil
  786. }
  787. func (m *Model) SetIgnores(folder string, content []string) error {
  788. cfg, ok := m.folderCfgs[folder]
  789. if !ok {
  790. return fmt.Errorf("Folder %s does not exist", folder)
  791. }
  792. path := filepath.Join(cfg.Path(), ".stignore")
  793. fd, err := osutil.CreateAtomic(path, 0644)
  794. if err != nil {
  795. l.Warnln("Saving .stignore:", err)
  796. return err
  797. }
  798. for _, line := range content {
  799. fmt.Fprintln(fd, line)
  800. }
  801. if err := fd.Close(); err != nil {
  802. l.Warnln("Saving .stignore:", err)
  803. return err
  804. }
  805. osutil.HideFile(path)
  806. return m.ScanFolder(folder)
  807. }
  808. // OnHello is called when an device connects to us.
  809. // This allows us to extract some information from the Hello message
  810. // and add it to a list of known devices ahead of any checks.
  811. func (m *Model) OnHello(remoteID protocol.DeviceID, addr net.Addr, hello protocol.HelloMessage) {
  812. for deviceID := range m.cfg.Devices() {
  813. if deviceID == remoteID {
  814. // Existing device, we will get the hello message in AddConnection
  815. // hence do not persist any state here, as the connection might
  816. // get killed before AddConnection
  817. return
  818. }
  819. }
  820. if !m.cfg.IgnoredDevice(remoteID) {
  821. events.Default.Log(events.DeviceRejected, map[string]string{
  822. "name": hello.DeviceName,
  823. "device": remoteID.String(),
  824. "address": addr.String(),
  825. })
  826. }
  827. }
  828. // GetHello is called when we are about to connect to some remote device.
  829. func (m *Model) GetHello(protocol.DeviceID) protocol.HelloMessage {
  830. return protocol.HelloMessage{
  831. DeviceName: m.deviceName,
  832. ClientName: m.clientName,
  833. ClientVersion: m.clientVersion,
  834. }
  835. }
  836. // AddConnection adds a new peer connection to the model. An initial index will
  837. // be sent to the connected peer, thereafter index updates whenever the local
  838. // folder changes.
  839. func (m *Model) AddConnection(conn Connection, hello protocol.HelloMessage) {
  840. deviceID := conn.ID()
  841. m.pmut.Lock()
  842. if _, ok := m.conn[deviceID]; ok {
  843. panic("add existing device")
  844. }
  845. m.conn[deviceID] = conn
  846. m.helloMessages[deviceID] = hello
  847. event := map[string]string{
  848. "id": deviceID.String(),
  849. "deviceName": hello.DeviceName,
  850. "clientName": hello.ClientName,
  851. "clientVersion": hello.ClientVersion,
  852. "type": conn.Type.String(),
  853. }
  854. addr := conn.RemoteAddr()
  855. if addr != nil {
  856. event["addr"] = addr.String()
  857. }
  858. events.Default.Log(events.DeviceConnected, event)
  859. l.Infof(`Device %s client is "%s %s" named "%s"`, deviceID, hello.ClientName, hello.ClientVersion, hello.DeviceName)
  860. device, ok := m.cfg.Devices()[deviceID]
  861. if ok && device.Name == "" {
  862. device.Name = hello.DeviceName
  863. m.cfg.SetDevice(device)
  864. m.cfg.Save()
  865. }
  866. conn.Start()
  867. cm := m.generateClusterConfig(deviceID)
  868. conn.ClusterConfig(cm)
  869. m.fmut.RLock()
  870. for _, folder := range m.deviceFolders[deviceID] {
  871. fs := m.folderFiles[folder]
  872. go sendIndexes(conn, folder, fs, m.folderIgnores[folder])
  873. }
  874. m.fmut.RUnlock()
  875. m.pmut.Unlock()
  876. m.deviceWasSeen(deviceID)
  877. }
  878. func (m *Model) PauseDevice(device protocol.DeviceID) {
  879. m.pmut.Lock()
  880. m.devicePaused[device] = true
  881. _, ok := m.conn[device]
  882. m.pmut.Unlock()
  883. if ok {
  884. m.Close(device, errors.New("device paused"))
  885. }
  886. events.Default.Log(events.DevicePaused, map[string]string{"device": device.String()})
  887. }
  888. func (m *Model) ResumeDevice(device protocol.DeviceID) {
  889. m.pmut.Lock()
  890. m.devicePaused[device] = false
  891. m.pmut.Unlock()
  892. events.Default.Log(events.DeviceResumed, map[string]string{"device": device.String()})
  893. }
  894. func (m *Model) IsPaused(device protocol.DeviceID) bool {
  895. m.pmut.Lock()
  896. paused := m.devicePaused[device]
  897. m.pmut.Unlock()
  898. return paused
  899. }
  900. func (m *Model) deviceStatRef(deviceID protocol.DeviceID) *stats.DeviceStatisticsReference {
  901. m.fmut.Lock()
  902. defer m.fmut.Unlock()
  903. if sr, ok := m.deviceStatRefs[deviceID]; ok {
  904. return sr
  905. }
  906. sr := stats.NewDeviceStatisticsReference(m.db, deviceID.String())
  907. m.deviceStatRefs[deviceID] = sr
  908. return sr
  909. }
  910. func (m *Model) deviceWasSeen(deviceID protocol.DeviceID) {
  911. m.deviceStatRef(deviceID).WasSeen()
  912. }
  913. func (m *Model) folderStatRef(folder string) *stats.FolderStatisticsReference {
  914. m.fmut.Lock()
  915. defer m.fmut.Unlock()
  916. sr, ok := m.folderStatRefs[folder]
  917. if !ok {
  918. sr = stats.NewFolderStatisticsReference(m.db, folder)
  919. m.folderStatRefs[folder] = sr
  920. }
  921. return sr
  922. }
  923. func (m *Model) receivedFile(folder string, file protocol.FileInfo) {
  924. m.folderStatRef(folder).ReceivedFile(file.Name, file.IsDeleted())
  925. }
  926. func sendIndexes(conn protocol.Connection, folder string, fs *db.FileSet, ignores *ignore.Matcher) {
  927. deviceID := conn.ID()
  928. name := conn.Name()
  929. var err error
  930. l.Debugf("sendIndexes for %s-%s/%q starting", deviceID, name, folder)
  931. defer l.Debugf("sendIndexes for %s-%s/%q exiting: %v", deviceID, name, folder, err)
  932. minLocalVer, err := sendIndexTo(true, 0, conn, folder, fs, ignores)
  933. // Subscribe to LocalIndexUpdated (we have new information to send) and
  934. // DeviceDisconnected (it might be us who disconnected, so we should
  935. // exit).
  936. sub := events.Default.Subscribe(events.LocalIndexUpdated | events.DeviceDisconnected)
  937. defer events.Default.Unsubscribe(sub)
  938. for err == nil {
  939. if conn.Closed() {
  940. // Our work is done.
  941. return
  942. }
  943. // While we have sent a localVersion at least equal to the one
  944. // currently in the database, wait for the local index to update. The
  945. // local index may update for other folders than the one we are
  946. // sending for.
  947. if fs.LocalVersion(protocol.LocalDeviceID) <= minLocalVer {
  948. sub.Poll(time.Minute)
  949. continue
  950. }
  951. minLocalVer, err = sendIndexTo(false, minLocalVer, conn, folder, fs, ignores)
  952. // Wait a short amount of time before entering the next loop. If there
  953. // are continuous changes happening to the local index, this gives us
  954. // time to batch them up a little.
  955. time.Sleep(250 * time.Millisecond)
  956. }
  957. }
  958. func sendIndexTo(initial bool, minLocalVer int64, conn protocol.Connection, folder string, fs *db.FileSet, ignores *ignore.Matcher) (int64, error) {
  959. deviceID := conn.ID()
  960. name := conn.Name()
  961. batch := make([]protocol.FileInfo, 0, indexBatchSize)
  962. currentBatchSize := 0
  963. maxLocalVer := int64(0)
  964. var err error
  965. fs.WithHave(protocol.LocalDeviceID, func(fi db.FileIntf) bool {
  966. f := fi.(protocol.FileInfo)
  967. if f.LocalVersion <= minLocalVer {
  968. return true
  969. }
  970. if f.LocalVersion > maxLocalVer {
  971. maxLocalVer = f.LocalVersion
  972. }
  973. if ignores.Match(f.Name) || symlinkInvalid(folder, f) {
  974. l.Debugln("not sending update for ignored/unsupported symlink", f)
  975. return true
  976. }
  977. if len(batch) == indexBatchSize || currentBatchSize > indexTargetSize {
  978. if initial {
  979. if err = conn.Index(folder, batch, 0, nil); err != nil {
  980. return false
  981. }
  982. l.Debugf("sendIndexes for %s-%s/%q: %d files (<%d bytes) (initial index)", deviceID, name, folder, len(batch), currentBatchSize)
  983. initial = false
  984. } else {
  985. if err = conn.IndexUpdate(folder, batch, 0, nil); err != nil {
  986. return false
  987. }
  988. l.Debugf("sendIndexes for %s-%s/%q: %d files (<%d bytes) (batched update)", deviceID, name, folder, len(batch), currentBatchSize)
  989. }
  990. batch = make([]protocol.FileInfo, 0, indexBatchSize)
  991. currentBatchSize = 0
  992. }
  993. batch = append(batch, f)
  994. currentBatchSize += indexPerFileSize + len(f.Blocks)*indexPerBlockSize
  995. return true
  996. })
  997. if initial && err == nil {
  998. err = conn.Index(folder, batch, 0, nil)
  999. if err == nil {
  1000. l.Debugf("sendIndexes for %s-%s/%q: %d files (small initial index)", deviceID, name, folder, len(batch))
  1001. }
  1002. } else if len(batch) > 0 && err == nil {
  1003. err = conn.IndexUpdate(folder, batch, 0, nil)
  1004. if err == nil {
  1005. l.Debugf("sendIndexes for %s-%s/%q: %d files (last batch)", deviceID, name, folder, len(batch))
  1006. }
  1007. }
  1008. return maxLocalVer, err
  1009. }
  1010. func (m *Model) updateLocals(folder string, fs []protocol.FileInfo) {
  1011. m.fmut.RLock()
  1012. files := m.folderFiles[folder]
  1013. m.fmut.RUnlock()
  1014. if files == nil {
  1015. // The folder doesn't exist.
  1016. return
  1017. }
  1018. files.Update(protocol.LocalDeviceID, fs)
  1019. filenames := make([]string, len(fs))
  1020. for i, file := range fs {
  1021. filenames[i] = file.Name
  1022. }
  1023. events.Default.Log(events.LocalIndexUpdated, map[string]interface{}{
  1024. "folder": folder,
  1025. "items": len(fs),
  1026. "filenames": filenames,
  1027. "version": files.LocalVersion(protocol.LocalDeviceID),
  1028. })
  1029. }
  1030. func (m *Model) requestGlobal(deviceID protocol.DeviceID, folder, name string, offset int64, size int, hash []byte, flags uint32, options []protocol.Option) ([]byte, error) {
  1031. m.pmut.RLock()
  1032. nc, ok := m.conn[deviceID]
  1033. m.pmut.RUnlock()
  1034. if !ok {
  1035. return nil, fmt.Errorf("requestGlobal: no such device: %s", deviceID)
  1036. }
  1037. l.Debugf("%v REQ(out): %s: %q / %q o=%d s=%d h=%x f=%x op=%s", m, deviceID, folder, name, offset, size, hash, flags, options)
  1038. return nc.Request(folder, name, offset, size, hash, flags, options)
  1039. }
  1040. func (m *Model) AddFolder(cfg config.FolderConfiguration) {
  1041. if len(cfg.ID) == 0 {
  1042. panic("cannot add empty folder id")
  1043. }
  1044. m.fmut.Lock()
  1045. m.folderCfgs[cfg.ID] = cfg
  1046. m.folderFiles[cfg.ID] = db.NewFileSet(cfg.ID, m.db)
  1047. m.folderDevices[cfg.ID] = make([]protocol.DeviceID, len(cfg.Devices))
  1048. for i, device := range cfg.Devices {
  1049. m.folderDevices[cfg.ID][i] = device.DeviceID
  1050. m.deviceFolders[device.DeviceID] = append(m.deviceFolders[device.DeviceID], cfg.ID)
  1051. }
  1052. ignores := ignore.New(m.cacheIgnoredFiles)
  1053. if err := ignores.Load(filepath.Join(cfg.Path(), ".stignore")); err != nil && !os.IsNotExist(err) {
  1054. l.Warnln("Loading ignores:", err)
  1055. }
  1056. m.folderIgnores[cfg.ID] = ignores
  1057. m.fmut.Unlock()
  1058. }
  1059. func (m *Model) ScanFolders() map[string]error {
  1060. m.fmut.RLock()
  1061. folders := make([]string, 0, len(m.folderCfgs))
  1062. for folder := range m.folderCfgs {
  1063. folders = append(folders, folder)
  1064. }
  1065. m.fmut.RUnlock()
  1066. errors := make(map[string]error, len(m.folderCfgs))
  1067. errorsMut := sync.NewMutex()
  1068. wg := sync.NewWaitGroup()
  1069. wg.Add(len(folders))
  1070. for _, folder := range folders {
  1071. folder := folder
  1072. go func() {
  1073. err := m.ScanFolder(folder)
  1074. if err != nil {
  1075. errorsMut.Lock()
  1076. errors[folder] = err
  1077. errorsMut.Unlock()
  1078. // Potentially sets the error twice, once in the scanner just
  1079. // by doing a check, and once here, if the error returned is
  1080. // the same one as returned by CheckFolderHealth, though
  1081. // duplicate set is handled by setError.
  1082. m.fmut.RLock()
  1083. srv := m.folderRunners[folder]
  1084. m.fmut.RUnlock()
  1085. srv.setError(err)
  1086. }
  1087. wg.Done()
  1088. }()
  1089. }
  1090. wg.Wait()
  1091. return errors
  1092. }
  1093. func (m *Model) ScanFolder(folder string) error {
  1094. return m.ScanFolderSubs(folder, nil)
  1095. }
  1096. func (m *Model) ScanFolderSubs(folder string, subs []string) error {
  1097. m.fmut.Lock()
  1098. runner, ok := m.folderRunners[folder]
  1099. m.fmut.Unlock()
  1100. // Folders are added to folderRunners only when they are started. We can't
  1101. // scan them before they have started, so that's what we need to check for
  1102. // here.
  1103. if !ok {
  1104. return errors.New("no such folder")
  1105. }
  1106. return runner.Scan(subs)
  1107. }
  1108. func (m *Model) internalScanFolderSubs(folder string, subs []string) error {
  1109. for i, sub := range subs {
  1110. sub = osutil.NativeFilename(sub)
  1111. if p := filepath.Clean(filepath.Join(folder, sub)); !strings.HasPrefix(p, folder) {
  1112. return errors.New("invalid subpath")
  1113. }
  1114. subs[i] = sub
  1115. }
  1116. m.fmut.Lock()
  1117. fs := m.folderFiles[folder]
  1118. folderCfg := m.folderCfgs[folder]
  1119. ignores := m.folderIgnores[folder]
  1120. runner, ok := m.folderRunners[folder]
  1121. m.fmut.Unlock()
  1122. // Folders are added to folderRunners only when they are started. We can't
  1123. // scan them before they have started, so that's what we need to check for
  1124. // here.
  1125. if !ok {
  1126. return errors.New("no such folder")
  1127. }
  1128. if err := m.CheckFolderHealth(folder); err != nil {
  1129. runner.setError(err)
  1130. l.Infof("Stopping folder %s due to error: %s", folder, err)
  1131. return err
  1132. }
  1133. if err := ignores.Load(filepath.Join(folderCfg.Path(), ".stignore")); err != nil && !os.IsNotExist(err) {
  1134. err = fmt.Errorf("loading ignores: %v", err)
  1135. runner.setError(err)
  1136. l.Infof("Stopping folder %s due to error: %s", folder, err)
  1137. return err
  1138. }
  1139. // Clean the list of subitems to ensure that we start at a known
  1140. // directory, and don't scan subdirectories of things we've already
  1141. // scanned.
  1142. subs = unifySubs(subs, func(f string) bool {
  1143. _, ok := fs.Get(protocol.LocalDeviceID, f)
  1144. return ok
  1145. })
  1146. // The cancel channel is closed whenever we return (such as from an error),
  1147. // to signal the potentially still running walker to stop.
  1148. cancel := make(chan struct{})
  1149. defer close(cancel)
  1150. w := &scanner.Walker{
  1151. Folder: folderCfg.ID,
  1152. Dir: folderCfg.Path(),
  1153. Subs: subs,
  1154. Matcher: ignores,
  1155. BlockSize: protocol.BlockSize,
  1156. TempNamer: defTempNamer,
  1157. TempLifetime: time.Duration(m.cfg.Options().KeepTemporariesH) * time.Hour,
  1158. CurrentFiler: cFiler{m, folder},
  1159. MtimeRepo: db.NewVirtualMtimeRepo(m.db, folderCfg.ID),
  1160. IgnorePerms: folderCfg.IgnorePerms,
  1161. AutoNormalize: folderCfg.AutoNormalize,
  1162. Hashers: m.numHashers(folder),
  1163. ShortID: m.shortID,
  1164. ProgressTickIntervalS: folderCfg.ScanProgressIntervalS,
  1165. Cancel: cancel,
  1166. }
  1167. runner.setState(FolderScanning)
  1168. fchan, err := w.Walk()
  1169. if err != nil {
  1170. // The error we get here is likely an OS level error, which might not be
  1171. // as readable as our health check errors. Check if we can get a health
  1172. // check error first, and use that if it's available.
  1173. if ferr := m.CheckFolderHealth(folder); ferr != nil {
  1174. err = ferr
  1175. }
  1176. runner.setError(err)
  1177. return err
  1178. }
  1179. batchSizeFiles := 100
  1180. batchSizeBlocks := 2048 // about 256 MB
  1181. batch := make([]protocol.FileInfo, 0, batchSizeFiles)
  1182. blocksHandled := 0
  1183. for f := range fchan {
  1184. if len(batch) == batchSizeFiles || blocksHandled > batchSizeBlocks {
  1185. if err := m.CheckFolderHealth(folder); err != nil {
  1186. l.Infof("Stopping folder %s mid-scan due to folder error: %s", folder, err)
  1187. return err
  1188. }
  1189. m.updateLocals(folder, batch)
  1190. batch = batch[:0]
  1191. blocksHandled = 0
  1192. }
  1193. batch = append(batch, f)
  1194. blocksHandled += len(f.Blocks)
  1195. }
  1196. if err := m.CheckFolderHealth(folder); err != nil {
  1197. l.Infof("Stopping folder %s mid-scan due to folder error: %s", folder, err)
  1198. return err
  1199. } else if len(batch) > 0 {
  1200. m.updateLocals(folder, batch)
  1201. }
  1202. if len(subs) == 0 {
  1203. // If we have no specific subdirectories to traverse, set it to one
  1204. // empty prefix so we traverse the entire folder contents once.
  1205. subs = []string{""}
  1206. }
  1207. // Do a scan of the database for each prefix, to check for deleted files.
  1208. batch = batch[:0]
  1209. for _, sub := range subs {
  1210. var iterError error
  1211. fs.WithPrefixedHaveTruncated(protocol.LocalDeviceID, sub, func(fi db.FileIntf) bool {
  1212. f := fi.(db.FileInfoTruncated)
  1213. if !f.IsDeleted() {
  1214. if f.IsInvalid() {
  1215. return true
  1216. }
  1217. if len(batch) == batchSizeFiles {
  1218. if err := m.CheckFolderHealth(folder); err != nil {
  1219. iterError = err
  1220. return false
  1221. }
  1222. m.updateLocals(folder, batch)
  1223. batch = batch[:0]
  1224. }
  1225. if ignores.Match(f.Name) || symlinkInvalid(folder, f) {
  1226. // File has been ignored or an unsupported symlink. Set invalid bit.
  1227. l.Debugln("setting invalid bit on ignored", f)
  1228. nf := protocol.FileInfo{
  1229. Name: f.Name,
  1230. Flags: f.Flags | protocol.FlagInvalid,
  1231. Modified: f.Modified,
  1232. Version: f.Version, // The file is still the same, so don't bump version
  1233. }
  1234. batch = append(batch, nf)
  1235. } else if _, err := osutil.Lstat(filepath.Join(folderCfg.Path(), f.Name)); err != nil {
  1236. // File has been deleted.
  1237. // We don't specifically verify that the error is
  1238. // os.IsNotExist because there is a corner case when a
  1239. // directory is suddenly transformed into a file. When that
  1240. // happens, files that were in the directory (that is now a
  1241. // file) are deleted but will return a confusing error ("not a
  1242. // directory") when we try to Lstat() them.
  1243. nf := protocol.FileInfo{
  1244. Name: f.Name,
  1245. Flags: f.Flags | protocol.FlagDeleted,
  1246. Modified: f.Modified,
  1247. Version: f.Version.Update(m.shortID),
  1248. }
  1249. batch = append(batch, nf)
  1250. }
  1251. }
  1252. return true
  1253. })
  1254. if iterError != nil {
  1255. l.Infof("Stopping folder %s mid-scan due to folder error: %s", folder, iterError)
  1256. return iterError
  1257. }
  1258. }
  1259. if err := m.CheckFolderHealth(folder); err != nil {
  1260. l.Infof("Stopping folder %s mid-scan due to folder error: %s", folder, err)
  1261. return err
  1262. } else if len(batch) > 0 {
  1263. m.updateLocals(folder, batch)
  1264. }
  1265. runner.setState(FolderIdle)
  1266. return nil
  1267. }
  1268. func (m *Model) DelayScan(folder string, next time.Duration) {
  1269. m.fmut.Lock()
  1270. runner, ok := m.folderRunners[folder]
  1271. m.fmut.Unlock()
  1272. if !ok {
  1273. return
  1274. }
  1275. runner.DelayScan(next)
  1276. }
  1277. // numHashers returns the number of hasher routines to use for a given folder,
  1278. // taking into account configuration and available CPU cores.
  1279. func (m *Model) numHashers(folder string) int {
  1280. m.fmut.Lock()
  1281. folderCfg := m.folderCfgs[folder]
  1282. numFolders := len(m.folderCfgs)
  1283. m.fmut.Unlock()
  1284. if folderCfg.Hashers > 0 {
  1285. // Specific value set in the config, use that.
  1286. return folderCfg.Hashers
  1287. }
  1288. if runtime.GOOS == "windows" || runtime.GOOS == "darwin" {
  1289. // Interactive operating systems; don't load the system too heavily by
  1290. // default.
  1291. return 1
  1292. }
  1293. // For other operating systems and architectures, lets try to get some
  1294. // work done... Divide the available CPU cores among the configured
  1295. // folders.
  1296. if perFolder := runtime.GOMAXPROCS(-1) / numFolders; perFolder > 0 {
  1297. return perFolder
  1298. }
  1299. return 1
  1300. }
  1301. // generateClusterConfig returns a ClusterConfigMessage that is correct for
  1302. // the given peer device
  1303. func (m *Model) generateClusterConfig(device protocol.DeviceID) protocol.ClusterConfigMessage {
  1304. var message protocol.ClusterConfigMessage
  1305. m.fmut.RLock()
  1306. for _, folder := range m.deviceFolders[device] {
  1307. folderCfg := m.cfg.Folders()[folder]
  1308. protocolFolder := protocol.Folder{
  1309. ID: folder,
  1310. Label: folderCfg.Label,
  1311. }
  1312. var flags uint32
  1313. if folderCfg.ReadOnly {
  1314. flags |= protocol.FlagFolderReadOnly
  1315. }
  1316. if folderCfg.IgnorePerms {
  1317. flags |= protocol.FlagFolderIgnorePerms
  1318. }
  1319. if folderCfg.IgnoreDelete {
  1320. flags |= protocol.FlagFolderIgnoreDelete
  1321. }
  1322. protocolFolder.Flags = flags
  1323. for _, device := range m.folderDevices[folder] {
  1324. // DeviceID is a value type, but with an underlying array. Copy it
  1325. // so we don't grab aliases to the same array later on in device[:]
  1326. device := device
  1327. // TODO: Set read only bit when relevant, and when we have per device
  1328. // access controls.
  1329. deviceCfg := m.cfg.Devices()[device]
  1330. protocolDevice := protocol.Device{
  1331. ID: device[:],
  1332. Name: deviceCfg.Name,
  1333. Addresses: deviceCfg.Addresses,
  1334. Compression: uint32(deviceCfg.Compression),
  1335. CertName: deviceCfg.CertName,
  1336. Flags: protocol.FlagShareTrusted,
  1337. }
  1338. if deviceCfg.Introducer {
  1339. protocolDevice.Flags |= protocol.FlagIntroducer
  1340. }
  1341. protocolFolder.Devices = append(protocolFolder.Devices, protocolDevice)
  1342. }
  1343. message.Folders = append(message.Folders, protocolFolder)
  1344. }
  1345. m.fmut.RUnlock()
  1346. return message
  1347. }
  1348. func (m *Model) State(folder string) (string, time.Time, error) {
  1349. m.fmut.RLock()
  1350. runner, ok := m.folderRunners[folder]
  1351. m.fmut.RUnlock()
  1352. if !ok {
  1353. // The returned error should be an actual folder error, so returning
  1354. // errors.New("does not exist") or similar here would be
  1355. // inappropriate.
  1356. return "", time.Time{}, nil
  1357. }
  1358. state, changed, err := runner.getState()
  1359. return state.String(), changed, err
  1360. }
  1361. func (m *Model) Override(folder string) {
  1362. m.fmut.RLock()
  1363. fs, ok := m.folderFiles[folder]
  1364. runner := m.folderRunners[folder]
  1365. m.fmut.RUnlock()
  1366. if !ok {
  1367. return
  1368. }
  1369. runner.setState(FolderScanning)
  1370. batch := make([]protocol.FileInfo, 0, indexBatchSize)
  1371. fs.WithNeed(protocol.LocalDeviceID, func(fi db.FileIntf) bool {
  1372. need := fi.(protocol.FileInfo)
  1373. if len(batch) == indexBatchSize {
  1374. m.updateLocals(folder, batch)
  1375. batch = batch[:0]
  1376. }
  1377. have, ok := fs.Get(protocol.LocalDeviceID, need.Name)
  1378. if !ok || have.Name != need.Name {
  1379. // We are missing the file
  1380. need.Flags |= protocol.FlagDeleted
  1381. need.Blocks = nil
  1382. need.Version = need.Version.Update(m.shortID)
  1383. } else {
  1384. // We have the file, replace with our version
  1385. have.Version = have.Version.Merge(need.Version).Update(m.shortID)
  1386. need = have
  1387. }
  1388. need.LocalVersion = 0
  1389. batch = append(batch, need)
  1390. return true
  1391. })
  1392. if len(batch) > 0 {
  1393. m.updateLocals(folder, batch)
  1394. }
  1395. runner.setState(FolderIdle)
  1396. }
  1397. // CurrentLocalVersion returns the change version for the given folder.
  1398. // This is guaranteed to increment if the contents of the local folder has
  1399. // changed.
  1400. func (m *Model) CurrentLocalVersion(folder string) (int64, bool) {
  1401. m.fmut.RLock()
  1402. fs, ok := m.folderFiles[folder]
  1403. m.fmut.RUnlock()
  1404. if !ok {
  1405. // The folder might not exist, since this can be called with a user
  1406. // specified folder name from the REST interface.
  1407. return 0, false
  1408. }
  1409. return fs.LocalVersion(protocol.LocalDeviceID), true
  1410. }
  1411. // RemoteLocalVersion returns the change version for the given folder, as
  1412. // sent by remote peers. This is guaranteed to increment if the contents of
  1413. // the remote or global folder has changed.
  1414. func (m *Model) RemoteLocalVersion(folder string) (int64, bool) {
  1415. m.fmut.RLock()
  1416. defer m.fmut.RUnlock()
  1417. fs, ok := m.folderFiles[folder]
  1418. if !ok {
  1419. // The folder might not exist, since this can be called with a user
  1420. // specified folder name from the REST interface.
  1421. return 0, false
  1422. }
  1423. var ver int64
  1424. for _, n := range m.folderDevices[folder] {
  1425. ver += fs.LocalVersion(n)
  1426. }
  1427. return ver, true
  1428. }
  1429. func (m *Model) GlobalDirectoryTree(folder, prefix string, levels int, dirsonly bool) map[string]interface{} {
  1430. m.fmut.RLock()
  1431. files, ok := m.folderFiles[folder]
  1432. m.fmut.RUnlock()
  1433. if !ok {
  1434. return nil
  1435. }
  1436. output := make(map[string]interface{})
  1437. sep := string(filepath.Separator)
  1438. prefix = osutil.NativeFilename(prefix)
  1439. if prefix != "" && !strings.HasSuffix(prefix, sep) {
  1440. prefix = prefix + sep
  1441. }
  1442. files.WithPrefixedGlobalTruncated(prefix, func(fi db.FileIntf) bool {
  1443. f := fi.(db.FileInfoTruncated)
  1444. if f.IsInvalid() || f.IsDeleted() || f.Name == prefix {
  1445. return true
  1446. }
  1447. f.Name = strings.Replace(f.Name, prefix, "", 1)
  1448. var dir, base string
  1449. if f.IsDirectory() && !f.IsSymlink() {
  1450. dir = f.Name
  1451. } else {
  1452. dir = filepath.Dir(f.Name)
  1453. base = filepath.Base(f.Name)
  1454. }
  1455. if levels > -1 && strings.Count(f.Name, sep) > levels {
  1456. return true
  1457. }
  1458. last := output
  1459. if dir != "." {
  1460. for _, path := range strings.Split(dir, sep) {
  1461. directory, ok := last[path]
  1462. if !ok {
  1463. newdir := make(map[string]interface{})
  1464. last[path] = newdir
  1465. last = newdir
  1466. } else {
  1467. last = directory.(map[string]interface{})
  1468. }
  1469. }
  1470. }
  1471. if !dirsonly && base != "" {
  1472. last[base] = []interface{}{
  1473. time.Unix(f.Modified, 0), f.Size(),
  1474. }
  1475. }
  1476. return true
  1477. })
  1478. return output
  1479. }
  1480. func (m *Model) Availability(folder, file string) []protocol.DeviceID {
  1481. // Acquire this lock first, as the value returned from foldersFiles can
  1482. // get heavily modified on Close()
  1483. m.pmut.RLock()
  1484. defer m.pmut.RUnlock()
  1485. m.fmut.RLock()
  1486. fs, ok := m.folderFiles[folder]
  1487. m.fmut.RUnlock()
  1488. if !ok {
  1489. return nil
  1490. }
  1491. availableDevices := []protocol.DeviceID{}
  1492. for _, device := range fs.Availability(file) {
  1493. _, ok := m.conn[device]
  1494. if ok {
  1495. availableDevices = append(availableDevices, device)
  1496. }
  1497. }
  1498. return availableDevices
  1499. }
  1500. // BringToFront bumps the given files priority in the job queue.
  1501. func (m *Model) BringToFront(folder, file string) {
  1502. m.pmut.RLock()
  1503. defer m.pmut.RUnlock()
  1504. runner, ok := m.folderRunners[folder]
  1505. if ok {
  1506. runner.BringToFront(file)
  1507. }
  1508. }
  1509. // CheckFolderHealth checks the folder for common errors and returns the
  1510. // current folder error, or nil if the folder is healthy.
  1511. func (m *Model) CheckFolderHealth(id string) error {
  1512. folder, ok := m.cfg.Folders()[id]
  1513. if !ok {
  1514. return errors.New("folder does not exist")
  1515. }
  1516. if minFree := m.cfg.Options().MinHomeDiskFreePct; minFree > 0 {
  1517. if free, err := osutil.DiskFreePercentage(m.cfg.ConfigPath()); err == nil && free < minFree {
  1518. return errors.New("home disk has insufficient free space")
  1519. }
  1520. }
  1521. fi, err := os.Stat(folder.Path())
  1522. v, ok := m.CurrentLocalVersion(id)
  1523. indexHasFiles := ok && v > 0
  1524. if indexHasFiles {
  1525. // There are files in the folder according to the index, so it must
  1526. // have existed and had a correct marker at some point. Verify that
  1527. // this is still the case.
  1528. switch {
  1529. case err != nil || !fi.IsDir():
  1530. err = errors.New("folder path missing")
  1531. case !folder.HasMarker():
  1532. err = errors.New("folder marker missing")
  1533. case !folder.ReadOnly:
  1534. // Check for free space, if it isn't a master folder. We aren't
  1535. // going to change the contents of master folders, so we don't
  1536. // care about the amount of free space there.
  1537. diskFreeP, errDfp := osutil.DiskFreePercentage(folder.Path())
  1538. if errDfp == nil && diskFreeP < folder.MinDiskFreePct {
  1539. diskFreeBytes, _ := osutil.DiskFreeBytes(folder.Path())
  1540. str := fmt.Sprintf("insufficient free space (%d MiB, %.2f%%)", diskFreeBytes/1024/1024, diskFreeP)
  1541. err = errors.New(str)
  1542. }
  1543. }
  1544. } else {
  1545. // It's a blank folder, so this may the first time we're looking at
  1546. // it. Attempt to create and tag with our marker as appropriate.
  1547. if os.IsNotExist(err) {
  1548. err = osutil.MkdirAll(folder.Path(), 0700)
  1549. }
  1550. if err == nil && !folder.HasMarker() {
  1551. err = folder.CreateMarker()
  1552. }
  1553. }
  1554. m.fmut.RLock()
  1555. runner, runnerExists := m.folderRunners[folder.ID]
  1556. m.fmut.RUnlock()
  1557. var oldErr error
  1558. if runnerExists {
  1559. _, _, oldErr = runner.getState()
  1560. }
  1561. if err != nil {
  1562. if oldErr != nil && oldErr.Error() != err.Error() {
  1563. l.Infof("Folder %q error changed: %q -> %q", folder.ID, oldErr, err)
  1564. } else if oldErr == nil {
  1565. l.Warnf("Stopping folder %q - %v", folder.ID, err)
  1566. }
  1567. if runnerExists {
  1568. runner.setError(err)
  1569. }
  1570. } else if oldErr != nil {
  1571. l.Infof("Folder %q error is cleared, restarting", folder.ID)
  1572. if runnerExists {
  1573. runner.clearError()
  1574. }
  1575. }
  1576. return err
  1577. }
  1578. func (m *Model) ResetFolder(folder string) {
  1579. l.Infof("Cleaning data for folder %q", folder)
  1580. db.DropFolder(m.db, folder)
  1581. }
  1582. func (m *Model) String() string {
  1583. return fmt.Sprintf("model@%p", m)
  1584. }
  1585. func (m *Model) VerifyConfiguration(from, to config.Configuration) error {
  1586. return nil
  1587. }
  1588. func (m *Model) CommitConfiguration(from, to config.Configuration) bool {
  1589. // TODO: This should not use reflect, and should take more care to try to handle stuff without restart.
  1590. // Go through the folder configs and figure out if we need to restart or not.
  1591. fromFolders := mapFolders(from.Folders)
  1592. toFolders := mapFolders(to.Folders)
  1593. for folderID, cfg := range toFolders {
  1594. if _, ok := fromFolders[folderID]; !ok {
  1595. // A folder was added.
  1596. l.Debugln(m, "adding folder", folderID)
  1597. m.AddFolder(cfg)
  1598. if cfg.ReadOnly {
  1599. m.StartFolderRO(folderID)
  1600. } else {
  1601. m.StartFolderRW(folderID)
  1602. }
  1603. // Drop connections to all devices that can now share the new
  1604. // folder.
  1605. m.pmut.Lock()
  1606. for _, dev := range cfg.DeviceIDs() {
  1607. if conn, ok := m.conn[dev]; ok {
  1608. closeRawConn(conn)
  1609. }
  1610. }
  1611. m.pmut.Unlock()
  1612. }
  1613. }
  1614. for folderID, fromCfg := range fromFolders {
  1615. toCfg, ok := toFolders[folderID]
  1616. if !ok {
  1617. // The folder was removed.
  1618. m.RemoveFolder(folderID)
  1619. continue
  1620. }
  1621. // This folder exists on both sides. Compare the device lists, as we
  1622. // can handle adding a device (but not currently removing one).
  1623. fromDevs := mapDevices(fromCfg.DeviceIDs())
  1624. toDevs := mapDevices(toCfg.DeviceIDs())
  1625. for dev := range fromDevs {
  1626. if _, ok := toDevs[dev]; !ok {
  1627. // A device was removed. Requires restart.
  1628. l.Debugln(m, "requires restart, removing device", dev, "from folder", folderID)
  1629. return false
  1630. }
  1631. }
  1632. for dev := range toDevs {
  1633. if _, ok := fromDevs[dev]; !ok {
  1634. // A device was added. Handle it!
  1635. m.fmut.Lock()
  1636. m.pmut.Lock()
  1637. m.folderCfgs[folderID] = toCfg
  1638. m.folderDevices[folderID] = append(m.folderDevices[folderID], dev)
  1639. m.deviceFolders[dev] = append(m.deviceFolders[dev], folderID)
  1640. // If we already have a connection to this device, we should
  1641. // disconnect it so that we start sharing the folder with it.
  1642. // We close the underlying connection and let the normal error
  1643. // handling kick in to clean up and reconnect.
  1644. if conn, ok := m.conn[dev]; ok {
  1645. closeRawConn(conn)
  1646. }
  1647. m.pmut.Unlock()
  1648. m.fmut.Unlock()
  1649. }
  1650. }
  1651. // Check if anything else differs, apart from the device list and label.
  1652. fromCfg.Devices = nil
  1653. toCfg.Devices = nil
  1654. fromCfg.Label = ""
  1655. toCfg.Label = ""
  1656. if !reflect.DeepEqual(fromCfg, toCfg) {
  1657. l.Debugln(m, "requires restart, folder", folderID, "configuration differs")
  1658. return false
  1659. }
  1660. }
  1661. // Removing a device requires restart
  1662. toDevs := mapDeviceCfgs(from.Devices)
  1663. for _, dev := range from.Devices {
  1664. if _, ok := toDevs[dev.DeviceID]; !ok {
  1665. l.Debugln(m, "requires restart, device", dev.DeviceID, "was removed")
  1666. return false
  1667. }
  1668. }
  1669. // Some options don't require restart as those components handle it fine
  1670. // by themselves.
  1671. from.Options.URAccepted = to.Options.URAccepted
  1672. from.Options.URUniqueID = to.Options.URUniqueID
  1673. // All of the other generic options require restart. Or at least they may;
  1674. // removing this check requires going through those options carefully and
  1675. // making sure there are individual services that handle them correctly.
  1676. // This code is the "original" requires-restart check and protects other
  1677. // components that haven't yet been converted to VerifyConfig/CommitConfig
  1678. // handling.
  1679. if !reflect.DeepEqual(from.Options, to.Options) {
  1680. l.Debugln(m, "requires restart, options differ")
  1681. return false
  1682. }
  1683. return true
  1684. }
  1685. // mapFolders returns a map of folder ID to folder configuration for the given
  1686. // slice of folder configurations.
  1687. func mapFolders(folders []config.FolderConfiguration) map[string]config.FolderConfiguration {
  1688. m := make(map[string]config.FolderConfiguration, len(folders))
  1689. for _, cfg := range folders {
  1690. m[cfg.ID] = cfg
  1691. }
  1692. return m
  1693. }
  1694. // mapDevices returns a map of device ID to nothing for the given slice of
  1695. // device IDs.
  1696. func mapDevices(devices []protocol.DeviceID) map[protocol.DeviceID]struct{} {
  1697. m := make(map[protocol.DeviceID]struct{}, len(devices))
  1698. for _, dev := range devices {
  1699. m[dev] = struct{}{}
  1700. }
  1701. return m
  1702. }
  1703. // mapDeviceCfgs returns a map of device ID to nothing for the given slice of
  1704. // device configurations.
  1705. func mapDeviceCfgs(devices []config.DeviceConfiguration) map[protocol.DeviceID]struct{} {
  1706. m := make(map[protocol.DeviceID]struct{}, len(devices))
  1707. for _, dev := range devices {
  1708. m[dev.DeviceID] = struct{}{}
  1709. }
  1710. return m
  1711. }
  1712. func filterIndex(folder string, fs []protocol.FileInfo, dropDeletes bool) []protocol.FileInfo {
  1713. for i := 0; i < len(fs); {
  1714. if fs[i].Flags&^protocol.FlagsAll != 0 {
  1715. l.Debugln("dropping update for file with unknown bits set", fs[i])
  1716. fs[i] = fs[len(fs)-1]
  1717. fs = fs[:len(fs)-1]
  1718. } else if fs[i].IsDeleted() && dropDeletes {
  1719. l.Debugln("dropping update for undesired delete", fs[i])
  1720. fs[i] = fs[len(fs)-1]
  1721. fs = fs[:len(fs)-1]
  1722. } else if symlinkInvalid(folder, fs[i]) {
  1723. l.Debugln("dropping update for unsupported symlink", fs[i])
  1724. fs[i] = fs[len(fs)-1]
  1725. fs = fs[:len(fs)-1]
  1726. } else {
  1727. i++
  1728. }
  1729. }
  1730. return fs
  1731. }
  1732. func symlinkInvalid(folder string, fi db.FileIntf) bool {
  1733. if !symlinks.Supported && fi.IsSymlink() && !fi.IsInvalid() && !fi.IsDeleted() {
  1734. symlinkWarning.Do(func() {
  1735. l.Warnln("Symlinks are disabled, unsupported or require Administrator privileges. This might cause your folder to appear out of sync.")
  1736. })
  1737. // Need to type switch for the concrete type to be able to access fields...
  1738. var name string
  1739. switch fi := fi.(type) {
  1740. case protocol.FileInfo:
  1741. name = fi.Name
  1742. case db.FileInfoTruncated:
  1743. name = fi.Name
  1744. }
  1745. l.Infoln("Unsupported symlink", name, "in folder", folder)
  1746. return true
  1747. }
  1748. return false
  1749. }
  1750. // Skips `skip` elements and retrieves up to `get` elements from a given slice.
  1751. // Returns the resulting slice, plus how much elements are left to skip or
  1752. // copy to satisfy the values which were provided, given the slice is not
  1753. // big enough.
  1754. func getChunk(data []string, skip, get int) ([]string, int, int) {
  1755. l := len(data)
  1756. if l <= skip {
  1757. return []string{}, skip - l, get
  1758. } else if l < skip+get {
  1759. return data[skip:l], 0, get - (l - skip)
  1760. }
  1761. return data[skip : skip+get], 0, 0
  1762. }
  1763. func closeRawConn(conn io.Closer) error {
  1764. if conn, ok := conn.(*tls.Conn); ok {
  1765. // If the underlying connection is a *tls.Conn, Close() does more
  1766. // than it says on the tin. Specifically, it sends a TLS alert
  1767. // message, which might block forever if the connection is dead
  1768. // and we don't have a deadline set.
  1769. conn.SetWriteDeadline(time.Now().Add(250 * time.Millisecond))
  1770. }
  1771. return conn.Close()
  1772. }
  1773. func stringSliceWithout(ss []string, s string) []string {
  1774. for i := range ss {
  1775. if ss[i] == s {
  1776. copy(ss[i:], ss[i+1:])
  1777. ss = ss[:len(ss)-1]
  1778. return ss
  1779. }
  1780. }
  1781. return ss
  1782. }
  1783. // unifySubs takes a list of files or directories and trims them down to
  1784. // themselves or the closest parent that exists() returns true for, while
  1785. // removing duplicates and subdirectories. That is, if we have foo/ in the
  1786. // list, we don't also need foo/bar/ because that's already covered.
  1787. func unifySubs(dirs []string, exists func(dir string) bool) []string {
  1788. var subs []string
  1789. // Trim each item to itself or its closest known parent
  1790. for _, sub := range dirs {
  1791. for sub != "" && sub != ".stfolder" && sub != ".stignore" {
  1792. if exists(sub) {
  1793. break
  1794. }
  1795. sub = filepath.Dir(sub)
  1796. if sub == "." || sub == string(filepath.Separator) {
  1797. // Shortcut. We are going to scan the full folder, so we can
  1798. // just return an empty list of subs at this point.
  1799. return nil
  1800. }
  1801. }
  1802. subs = append(subs, sub)
  1803. }
  1804. // Remove any paths that are already covered by their parent
  1805. sort.Strings(subs)
  1806. var cleaned []string
  1807. next:
  1808. for _, sub := range subs {
  1809. for _, existing := range cleaned {
  1810. if sub == existing || strings.HasPrefix(sub, existing+string(os.PathSeparator)) {
  1811. continue next
  1812. }
  1813. }
  1814. cleaned = append(cleaned, sub)
  1815. }
  1816. return cleaned
  1817. }