model.go 66 KB

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