model.go 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306
  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. indexBatchSize = 1000 // Either way, don't include more files than this
  41. )
  42. type service interface {
  43. BringToFront(string)
  44. DelayScan(d time.Duration)
  45. IndexUpdated() // Remote index was updated notification
  46. Jobs() ([]string, []string) // In progress, Queued
  47. Scan(subs []string) error
  48. Serve()
  49. Stop()
  50. getState() (folderState, time.Time, error)
  51. setState(state folderState)
  52. clearError()
  53. setError(err error)
  54. }
  55. type Availability struct {
  56. ID protocol.DeviceID `json:"id"`
  57. FromTemporary bool `json:"fromTemporary"`
  58. }
  59. type Model struct {
  60. *suture.Supervisor
  61. cfg *config.Wrapper
  62. db *db.Instance
  63. finder *db.BlockFinder
  64. progressEmitter *ProgressEmitter
  65. id protocol.DeviceID
  66. shortID protocol.ShortID
  67. cacheIgnoredFiles bool
  68. protectedFiles []string
  69. deviceName string
  70. clientName string
  71. clientVersion string
  72. folderCfgs map[string]config.FolderConfiguration // folder -> cfg
  73. folderFiles map[string]*db.FileSet // folder -> files
  74. folderDevices map[string][]protocol.DeviceID // folder -> deviceIDs
  75. deviceFolders map[protocol.DeviceID][]string // deviceID -> folders
  76. deviceStatRefs map[protocol.DeviceID]*stats.DeviceStatisticsReference // deviceID -> statsRef
  77. folderIgnores map[string]*ignore.Matcher // folder -> matcher object
  78. folderRunners map[string]service // folder -> puller or scanner
  79. folderRunnerTokens map[string][]suture.ServiceToken // folder -> tokens for puller or scanner
  80. folderStatRefs map[string]*stats.FolderStatisticsReference // folder -> statsRef
  81. fmut sync.RWMutex // protects the above
  82. conn map[protocol.DeviceID]connections.Connection
  83. helloMessages map[protocol.DeviceID]protocol.HelloResult
  84. deviceClusterConf map[protocol.DeviceID]protocol.ClusterConfig
  85. devicePaused map[protocol.DeviceID]bool
  86. deviceDownloads map[protocol.DeviceID]*deviceDownloadState
  87. pmut sync.RWMutex // protects the above
  88. }
  89. type folderFactory func(*Model, config.FolderConfiguration, versioner.Versioner) service
  90. var (
  91. symlinkWarning = stdsync.Once{}
  92. folderFactories = make(map[config.FolderType]folderFactory, 0)
  93. )
  94. // errors returned by the CheckFolderHealth method
  95. var (
  96. errFolderPathEmpty = errors.New("folder path empty")
  97. errFolderPathMissing = errors.New("folder path missing")
  98. errFolderMarkerMissing = errors.New("folder marker missing")
  99. errHomeDiskNoSpace = errors.New("home disk has insufficient free space")
  100. errFolderNoSpace = errors.New("folder has insufficient free space")
  101. )
  102. // NewModel creates and starts a new model. The model starts in read-only mode,
  103. // where it sends index information to connected peers and responds to requests
  104. // for file data without altering the local folder in any way.
  105. func NewModel(cfg *config.Wrapper, id protocol.DeviceID, deviceName, clientName, clientVersion string, ldb *db.Instance, protectedFiles []string) *Model {
  106. m := &Model{
  107. Supervisor: suture.New("model", suture.Spec{
  108. Log: func(line string) {
  109. l.Debugln(line)
  110. },
  111. }),
  112. cfg: cfg,
  113. db: ldb,
  114. finder: db.NewBlockFinder(ldb),
  115. progressEmitter: NewProgressEmitter(cfg),
  116. id: id,
  117. shortID: id.Short(),
  118. cacheIgnoredFiles: cfg.Options().CacheIgnoredFiles,
  119. protectedFiles: protectedFiles,
  120. deviceName: deviceName,
  121. clientName: clientName,
  122. clientVersion: clientVersion,
  123. folderCfgs: make(map[string]config.FolderConfiguration),
  124. folderFiles: make(map[string]*db.FileSet),
  125. folderDevices: make(map[string][]protocol.DeviceID),
  126. deviceFolders: make(map[protocol.DeviceID][]string),
  127. deviceStatRefs: make(map[protocol.DeviceID]*stats.DeviceStatisticsReference),
  128. folderIgnores: make(map[string]*ignore.Matcher),
  129. folderRunners: make(map[string]service),
  130. folderRunnerTokens: make(map[string][]suture.ServiceToken),
  131. folderStatRefs: make(map[string]*stats.FolderStatisticsReference),
  132. conn: make(map[protocol.DeviceID]connections.Connection),
  133. helloMessages: make(map[protocol.DeviceID]protocol.HelloResult),
  134. deviceClusterConf: make(map[protocol.DeviceID]protocol.ClusterConfig),
  135. devicePaused: make(map[protocol.DeviceID]bool),
  136. deviceDownloads: make(map[protocol.DeviceID]*deviceDownloadState),
  137. fmut: sync.NewRWMutex(),
  138. pmut: sync.NewRWMutex(),
  139. }
  140. if cfg.Options().ProgressUpdateIntervalS > -1 {
  141. go m.progressEmitter.Serve()
  142. }
  143. return m
  144. }
  145. // StartDeadlockDetector starts a deadlock detector on the models locks which
  146. // causes panics in case the locks cannot be acquired in the given timeout
  147. // period.
  148. func (m *Model) StartDeadlockDetector(timeout time.Duration) {
  149. l.Infof("Starting deadlock detector with %v timeout", timeout)
  150. deadlockDetect(m.fmut, timeout)
  151. deadlockDetect(m.pmut, timeout)
  152. }
  153. // StartFolder constructs the folder service and starts it.
  154. func (m *Model) StartFolder(folder string) {
  155. m.fmut.Lock()
  156. cfg, ok := m.folderCfgs[folder]
  157. if !ok {
  158. panic("cannot start nonexistent folder " + folder)
  159. }
  160. _, ok = m.folderRunners[folder]
  161. if ok {
  162. panic("cannot start already running folder " + folder)
  163. }
  164. folderFactory, ok := folderFactories[cfg.Type]
  165. if !ok {
  166. panic(fmt.Sprintf("unknown folder type 0x%x", cfg.Type))
  167. }
  168. fs := m.folderFiles[folder]
  169. v, ok := fs.LocalVersion(protocol.LocalDeviceID), true
  170. indexHasFiles := ok && v > 0
  171. if !indexHasFiles {
  172. // It's a blank folder, so this may the first time we're looking at
  173. // it. Attempt to create and tag with our marker as appropriate. We
  174. // don't really do anything with errors at this point except warn -
  175. // if these things don't work, we still want to start the folder and
  176. // it'll show up as errored later.
  177. if _, err := os.Stat(cfg.Path()); os.IsNotExist(err) {
  178. if err := osutil.MkdirAll(cfg.Path(), 0700); err != nil {
  179. l.Warnln("Creating folder:", err)
  180. }
  181. }
  182. if err := cfg.CreateMarker(); err != nil {
  183. l.Warnln("Creating folder marker:", err)
  184. }
  185. }
  186. var ver versioner.Versioner
  187. if len(cfg.Versioning.Type) > 0 {
  188. versionerFactory, ok := versioner.Factories[cfg.Versioning.Type]
  189. if !ok {
  190. l.Fatalf("Requested versioning type %q that does not exist", cfg.Versioning.Type)
  191. }
  192. ver = versionerFactory(folder, cfg.Path(), cfg.Versioning.Params)
  193. if service, ok := ver.(suture.Service); ok {
  194. // The versioner implements the suture.Service interface, so
  195. // expects to be run in the background in addition to being called
  196. // when files are going to be archived.
  197. token := m.Add(service)
  198. m.folderRunnerTokens[folder] = append(m.folderRunnerTokens[folder], token)
  199. }
  200. }
  201. p := folderFactory(m, cfg, ver)
  202. m.folderRunners[folder] = p
  203. m.warnAboutOverwritingProtectedFiles(folder)
  204. token := m.Add(p)
  205. m.folderRunnerTokens[folder] = append(m.folderRunnerTokens[folder], token)
  206. m.fmut.Unlock()
  207. l.Infoln("Ready to synchronize", folder, fmt.Sprintf("(%s)", cfg.Type))
  208. }
  209. func (m *Model) warnAboutOverwritingProtectedFiles(folder string) {
  210. if m.folderCfgs[folder].Type == config.FolderTypeReadOnly {
  211. return
  212. }
  213. folderLocation := m.folderCfgs[folder].Path()
  214. ignores := m.folderIgnores[folder]
  215. var filesAtRisk []string
  216. for _, protectedFilePath := range m.protectedFiles {
  217. // check if file is synced in this folder
  218. if !strings.HasPrefix(protectedFilePath, folderLocation) {
  219. continue
  220. }
  221. // check if file is ignored
  222. if ignores.Match(protectedFilePath).IsIgnored() {
  223. continue
  224. }
  225. filesAtRisk = append(filesAtRisk, protectedFilePath)
  226. }
  227. if len(filesAtRisk) > 0 {
  228. 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, ", "))
  229. }
  230. }
  231. func (m *Model) RemoveFolder(folder string) {
  232. m.fmut.Lock()
  233. m.pmut.Lock()
  234. // Stop the services running for this folder
  235. for _, id := range m.folderRunnerTokens[folder] {
  236. m.Remove(id)
  237. }
  238. // Close connections to affected devices
  239. for _, dev := range m.folderDevices[folder] {
  240. if conn, ok := m.conn[dev]; ok {
  241. closeRawConn(conn)
  242. }
  243. }
  244. // Clean up our config maps
  245. delete(m.folderCfgs, folder)
  246. delete(m.folderFiles, folder)
  247. delete(m.folderDevices, folder)
  248. delete(m.folderIgnores, folder)
  249. delete(m.folderRunners, folder)
  250. delete(m.folderRunnerTokens, folder)
  251. delete(m.folderStatRefs, folder)
  252. for dev, folders := range m.deviceFolders {
  253. m.deviceFolders[dev] = stringSliceWithout(folders, folder)
  254. }
  255. // Remove it from the database
  256. db.DropFolder(m.db, folder)
  257. m.pmut.Unlock()
  258. m.fmut.Unlock()
  259. }
  260. type ConnectionInfo struct {
  261. protocol.Statistics
  262. Connected bool
  263. Paused bool
  264. Address string
  265. ClientVersion string
  266. Type string
  267. }
  268. func (info ConnectionInfo) MarshalJSON() ([]byte, error) {
  269. return json.Marshal(map[string]interface{}{
  270. "at": info.At,
  271. "inBytesTotal": info.InBytesTotal,
  272. "outBytesTotal": info.OutBytesTotal,
  273. "connected": info.Connected,
  274. "paused": info.Paused,
  275. "address": info.Address,
  276. "clientVersion": info.ClientVersion,
  277. "type": info.Type,
  278. })
  279. }
  280. // ConnectionStats returns a map with connection statistics for each device.
  281. func (m *Model) ConnectionStats() map[string]interface{} {
  282. m.pmut.RLock()
  283. m.fmut.RLock()
  284. res := make(map[string]interface{})
  285. devs := m.cfg.Devices()
  286. conns := make(map[string]ConnectionInfo, len(devs))
  287. for device := range devs {
  288. hello := m.helloMessages[device]
  289. versionString := hello.ClientVersion
  290. if hello.ClientName != "syncthing" {
  291. versionString = hello.ClientName + " " + hello.ClientVersion
  292. }
  293. ci := ConnectionInfo{
  294. ClientVersion: strings.TrimSpace(versionString),
  295. Paused: m.devicePaused[device],
  296. }
  297. if conn, ok := m.conn[device]; ok {
  298. ci.Type = conn.Type
  299. ci.Connected = ok
  300. ci.Statistics = conn.Statistics()
  301. if addr := conn.RemoteAddr(); addr != nil {
  302. ci.Address = addr.String()
  303. }
  304. }
  305. conns[device.String()] = ci
  306. }
  307. res["connections"] = conns
  308. m.fmut.RUnlock()
  309. m.pmut.RUnlock()
  310. in, out := protocol.TotalInOut()
  311. res["total"] = ConnectionInfo{
  312. Statistics: protocol.Statistics{
  313. At: time.Now(),
  314. InBytesTotal: in,
  315. OutBytesTotal: out,
  316. },
  317. }
  318. return res
  319. }
  320. // DeviceStatistics returns statistics about each device
  321. func (m *Model) DeviceStatistics() map[string]stats.DeviceStatistics {
  322. var res = make(map[string]stats.DeviceStatistics)
  323. for id := range m.cfg.Devices() {
  324. res[id.String()] = m.deviceStatRef(id).GetStatistics()
  325. }
  326. return res
  327. }
  328. // FolderStatistics returns statistics about each folder
  329. func (m *Model) FolderStatistics() map[string]stats.FolderStatistics {
  330. var res = make(map[string]stats.FolderStatistics)
  331. for id := range m.cfg.Folders() {
  332. res[id] = m.folderStatRef(id).GetStatistics()
  333. }
  334. return res
  335. }
  336. // Completion returns the completion status, in percent, for the given device
  337. // and folder.
  338. func (m *Model) Completion(device protocol.DeviceID, folder string) float64 {
  339. m.fmut.RLock()
  340. rf, ok := m.folderFiles[folder]
  341. m.fmut.RUnlock()
  342. if !ok {
  343. return 0 // Folder doesn't exist, so we hardly have any of it
  344. }
  345. _, _, tot := rf.GlobalSize()
  346. if tot == 0 {
  347. return 100 // Folder is empty, so we have all of it
  348. }
  349. m.pmut.RLock()
  350. counts := m.deviceDownloads[device].GetBlockCounts(folder)
  351. m.pmut.RUnlock()
  352. var need, fileNeed, downloaded int64
  353. rf.WithNeedTruncated(device, func(f db.FileIntf) bool {
  354. ft := f.(db.FileInfoTruncated)
  355. // This might might be more than it really is, because some blocks can be of a smaller size.
  356. downloaded = int64(counts[ft.Name] * protocol.BlockSize)
  357. fileNeed = ft.Size - downloaded
  358. if fileNeed < 0 {
  359. fileNeed = 0
  360. }
  361. need += fileNeed
  362. return true
  363. })
  364. needRatio := float64(need) / float64(tot)
  365. completionPct := 100 * (1 - needRatio)
  366. l.Debugf("%v Completion(%s, %q): %f (%d / %d = %f)", m, device, folder, completionPct, need, tot, needRatio)
  367. return completionPct
  368. }
  369. func sizeOfFile(f db.FileIntf) (files, deleted int, bytes int64) {
  370. if !f.IsDeleted() {
  371. files++
  372. } else {
  373. deleted++
  374. }
  375. bytes += f.FileSize()
  376. return
  377. }
  378. // GlobalSize returns the number of files, deleted files and total bytes for all
  379. // files in the global model.
  380. func (m *Model) GlobalSize(folder string) (nfiles, deleted int, bytes int64) {
  381. m.fmut.RLock()
  382. defer m.fmut.RUnlock()
  383. if rf, ok := m.folderFiles[folder]; ok {
  384. nfiles, deleted, bytes = rf.GlobalSize()
  385. }
  386. return
  387. }
  388. // LocalSize returns the number of files, deleted files and total bytes for all
  389. // files in the local folder.
  390. func (m *Model) LocalSize(folder string) (nfiles, deleted int, bytes int64) {
  391. m.fmut.RLock()
  392. defer m.fmut.RUnlock()
  393. if rf, ok := m.folderFiles[folder]; ok {
  394. nfiles, deleted, bytes = rf.LocalSize()
  395. }
  396. return
  397. }
  398. // NeedSize returns the number and total size of currently needed files.
  399. func (m *Model) NeedSize(folder string) (nfiles int, bytes int64) {
  400. m.fmut.RLock()
  401. defer m.fmut.RUnlock()
  402. if rf, ok := m.folderFiles[folder]; ok {
  403. rf.WithNeedTruncated(protocol.LocalDeviceID, func(f db.FileIntf) bool {
  404. fs, de, by := sizeOfFile(f)
  405. nfiles += fs + de
  406. bytes += by
  407. return true
  408. })
  409. }
  410. bytes -= m.progressEmitter.BytesCompleted(folder)
  411. l.Debugf("%v NeedSize(%q): %d %d", m, folder, nfiles, bytes)
  412. return
  413. }
  414. // NeedFolderFiles returns paginated list of currently needed files in
  415. // progress, queued, and to be queued on next puller iteration, as well as the
  416. // total number of files currently needed.
  417. func (m *Model) NeedFolderFiles(folder string, page, perpage int) ([]db.FileInfoTruncated, []db.FileInfoTruncated, []db.FileInfoTruncated, int) {
  418. m.fmut.RLock()
  419. defer m.fmut.RUnlock()
  420. total := 0
  421. rf, ok := m.folderFiles[folder]
  422. if !ok {
  423. return nil, nil, nil, 0
  424. }
  425. var progress, queued, rest []db.FileInfoTruncated
  426. var seen map[string]struct{}
  427. skip := (page - 1) * perpage
  428. get := perpage
  429. runner, ok := m.folderRunners[folder]
  430. if ok {
  431. allProgressNames, allQueuedNames := runner.Jobs()
  432. var progressNames, queuedNames []string
  433. progressNames, skip, get = getChunk(allProgressNames, skip, get)
  434. queuedNames, skip, get = getChunk(allQueuedNames, skip, get)
  435. progress = make([]db.FileInfoTruncated, len(progressNames))
  436. queued = make([]db.FileInfoTruncated, len(queuedNames))
  437. seen = make(map[string]struct{}, len(progressNames)+len(queuedNames))
  438. for i, name := range progressNames {
  439. if f, ok := rf.GetGlobalTruncated(name); ok {
  440. progress[i] = f
  441. seen[name] = struct{}{}
  442. }
  443. }
  444. for i, name := range queuedNames {
  445. if f, ok := rf.GetGlobalTruncated(name); ok {
  446. queued[i] = f
  447. seen[name] = struct{}{}
  448. }
  449. }
  450. }
  451. rest = make([]db.FileInfoTruncated, 0, perpage)
  452. rf.WithNeedTruncated(protocol.LocalDeviceID, func(f db.FileIntf) bool {
  453. total++
  454. if skip > 0 {
  455. skip--
  456. return true
  457. }
  458. if get > 0 {
  459. ft := f.(db.FileInfoTruncated)
  460. if _, ok := seen[ft.Name]; !ok {
  461. rest = append(rest, ft)
  462. get--
  463. }
  464. }
  465. return true
  466. })
  467. return progress, queued, rest, total
  468. }
  469. // Index is called when a new device is connected and we receive their full index.
  470. // Implements the protocol.Model interface.
  471. func (m *Model) Index(deviceID protocol.DeviceID, folder string, fs []protocol.FileInfo) {
  472. l.Debugf("IDX(in): %s %q: %d files", deviceID, folder, len(fs))
  473. if !m.folderSharedWith(folder, deviceID) {
  474. 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)
  475. return
  476. }
  477. m.fmut.RLock()
  478. cfg := m.folderCfgs[folder]
  479. files, ok := m.folderFiles[folder]
  480. runner := m.folderRunners[folder]
  481. ignores := m.folderIgnores[folder]
  482. m.fmut.RUnlock()
  483. if runner != nil {
  484. // Runner may legitimately not be set if this is the "cleanup" Index
  485. // message at startup.
  486. defer runner.IndexUpdated()
  487. }
  488. if !ok {
  489. l.Fatalf("Index for nonexistent folder %q", folder)
  490. }
  491. m.pmut.RLock()
  492. m.deviceDownloads[deviceID].Update(folder, makeForgetUpdate(fs))
  493. m.pmut.RUnlock()
  494. fs = filterIndex(folder, fs, cfg.IgnoreDelete, ignores)
  495. files.Replace(deviceID, fs)
  496. events.Default.Log(events.RemoteIndexUpdated, map[string]interface{}{
  497. "device": deviceID.String(),
  498. "folder": folder,
  499. "items": len(fs),
  500. "version": files.LocalVersion(deviceID),
  501. })
  502. }
  503. // IndexUpdate is called for incremental updates to connected devices' indexes.
  504. // Implements the protocol.Model interface.
  505. func (m *Model) IndexUpdate(deviceID protocol.DeviceID, folder string, fs []protocol.FileInfo) {
  506. l.Debugf("%v IDXUP(in): %s / %q: %d files", m, deviceID, folder, len(fs))
  507. if !m.folderSharedWith(folder, deviceID) {
  508. 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)
  509. return
  510. }
  511. m.fmut.RLock()
  512. files := m.folderFiles[folder]
  513. cfg := m.folderCfgs[folder]
  514. runner, ok := m.folderRunners[folder]
  515. ignores := m.folderIgnores[folder]
  516. m.fmut.RUnlock()
  517. if !ok {
  518. l.Fatalf("IndexUpdate for nonexistent folder %q", folder)
  519. }
  520. m.pmut.RLock()
  521. m.deviceDownloads[deviceID].Update(folder, makeForgetUpdate(fs))
  522. m.pmut.RUnlock()
  523. fs = filterIndex(folder, fs, cfg.IgnoreDelete, ignores)
  524. files.Update(deviceID, fs)
  525. events.Default.Log(events.RemoteIndexUpdated, map[string]interface{}{
  526. "device": deviceID.String(),
  527. "folder": folder,
  528. "items": len(fs),
  529. "version": files.LocalVersion(deviceID),
  530. })
  531. runner.IndexUpdated()
  532. }
  533. func (m *Model) folderSharedWith(folder string, deviceID protocol.DeviceID) bool {
  534. m.fmut.RLock()
  535. defer m.fmut.RUnlock()
  536. return m.folderSharedWithUnlocked(folder, deviceID)
  537. }
  538. func (m *Model) folderSharedWithUnlocked(folder string, deviceID protocol.DeviceID) bool {
  539. for _, nfolder := range m.deviceFolders[deviceID] {
  540. if nfolder == folder {
  541. return true
  542. }
  543. }
  544. return false
  545. }
  546. func (m *Model) ClusterConfig(deviceID protocol.DeviceID, cm protocol.ClusterConfig) {
  547. // Check the peer device's announced folders against our own. Emits events
  548. // for folders that we don't expect (unknown or not shared).
  549. // Also, collect a list of folders we do share, and if he's interested in
  550. // temporary indexes, subscribe the connection.
  551. tempIndexFolders := make([]string, 0, len(cm.Folders))
  552. m.fmut.Lock()
  553. for _, folder := range cm.Folders {
  554. if !m.folderSharedWithUnlocked(folder.ID, deviceID) {
  555. events.Default.Log(events.FolderRejected, map[string]string{
  556. "folder": folder.ID,
  557. "folderLabel": folder.Label,
  558. "device": deviceID.String(),
  559. })
  560. 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)
  561. continue
  562. }
  563. if !folder.DisableTempIndexes {
  564. tempIndexFolders = append(tempIndexFolders, folder.ID)
  565. }
  566. }
  567. m.fmut.Unlock()
  568. // This breaks if we send multiple CM messages during the same connection.
  569. if len(tempIndexFolders) > 0 {
  570. m.pmut.RLock()
  571. conn, ok := m.conn[deviceID]
  572. m.pmut.RUnlock()
  573. // In case we've got ClusterConfig, and the connection disappeared
  574. // from infront of our nose.
  575. if ok {
  576. m.progressEmitter.temporaryIndexSubscribe(conn, tempIndexFolders)
  577. }
  578. }
  579. var changed bool
  580. if m.cfg.Devices()[deviceID].Introducer {
  581. // This device is an introducer. Go through the announced lists of folders
  582. // and devices and add what we are missing.
  583. for _, folder := range cm.Folders {
  584. if _, ok := m.folderDevices[folder.ID]; !ok {
  585. continue
  586. }
  587. nextDevice:
  588. for _, device := range folder.Devices {
  589. var id protocol.DeviceID
  590. copy(id[:], device.ID)
  591. if _, ok := m.cfg.Devices()[id]; !ok {
  592. // The device is currently unknown. Add it to the config.
  593. addresses := []string{"dynamic"}
  594. for _, addr := range device.Addresses {
  595. if addr != "dynamic" {
  596. addresses = append(addresses, addr)
  597. }
  598. }
  599. l.Infof("Adding device %v to config (vouched for by introducer %v)", id, deviceID)
  600. newDeviceCfg := config.DeviceConfiguration{
  601. DeviceID: id,
  602. Name: device.Name,
  603. Compression: m.cfg.Devices()[deviceID].Compression,
  604. Addresses: addresses,
  605. CertName: device.CertName,
  606. }
  607. // The introducers' introducers are also our introducers.
  608. if device.Introducer {
  609. l.Infof("Device %v is now also an introducer", id)
  610. newDeviceCfg.Introducer = true
  611. }
  612. m.cfg.SetDevice(newDeviceCfg)
  613. changed = true
  614. }
  615. for _, er := range m.deviceFolders[id] {
  616. if er == folder.ID {
  617. // We already share the folder with this device, so
  618. // nothing to do.
  619. continue nextDevice
  620. }
  621. }
  622. // We don't yet share this folder with this device. Add the device
  623. // to sharing list of the folder.
  624. l.Infof("Adding device %v to share %q (vouched for by introducer %v)", id, folder.ID, deviceID)
  625. m.deviceFolders[id] = append(m.deviceFolders[id], folder.ID)
  626. m.folderDevices[folder.ID] = append(m.folderDevices[folder.ID], id)
  627. folderCfg := m.cfg.Folders()[folder.ID]
  628. folderCfg.Devices = append(folderCfg.Devices, config.FolderDeviceConfiguration{
  629. DeviceID: id,
  630. })
  631. m.cfg.SetFolder(folderCfg)
  632. changed = true
  633. }
  634. }
  635. }
  636. if changed {
  637. m.cfg.Save()
  638. }
  639. }
  640. // Close removes the peer from the model and closes the underlying connection if possible.
  641. // Implements the protocol.Model interface.
  642. func (m *Model) Close(device protocol.DeviceID, err error) {
  643. l.Infof("Connection to %s closed: %v", device, err)
  644. events.Default.Log(events.DeviceDisconnected, map[string]string{
  645. "id": device.String(),
  646. "error": err.Error(),
  647. })
  648. m.pmut.Lock()
  649. m.fmut.RLock()
  650. for _, folder := range m.deviceFolders[device] {
  651. m.folderFiles[folder].Replace(device, nil)
  652. }
  653. m.fmut.RUnlock()
  654. conn, ok := m.conn[device]
  655. if ok {
  656. m.progressEmitter.temporaryIndexUnsubscribe(conn)
  657. closeRawConn(conn)
  658. }
  659. delete(m.conn, device)
  660. delete(m.helloMessages, device)
  661. delete(m.deviceClusterConf, device)
  662. delete(m.deviceDownloads, device)
  663. m.pmut.Unlock()
  664. }
  665. // Request returns the specified data segment by reading it from local disk.
  666. // Implements the protocol.Model interface.
  667. func (m *Model) Request(deviceID protocol.DeviceID, folder, name string, offset int64, hash []byte, fromTemporary bool, buf []byte) error {
  668. if offset < 0 {
  669. return protocol.ErrInvalid
  670. }
  671. if !m.folderSharedWith(folder, deviceID) {
  672. l.Warnf("Request from %s for file %s in unshared folder %q", deviceID, name, folder)
  673. return protocol.ErrNoSuchFile
  674. }
  675. if deviceID != protocol.LocalDeviceID {
  676. l.Debugf("%v REQ(in): %s: %q / %q o=%d s=%d t=%v", m, deviceID, folder, name, offset, len(buf), fromTemporary)
  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 fromTemporary && !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.HelloIntf {
  857. return &protocol.Hello{
  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) {
  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. sorter := NewIndexSorter()
  1014. defer sorter.Close()
  1015. fs.WithHave(protocol.LocalDeviceID, func(fi db.FileIntf) bool {
  1016. f := fi.(protocol.FileInfo)
  1017. if f.LocalVersion <= minLocalVer {
  1018. return true
  1019. }
  1020. if f.LocalVersion > maxLocalVer {
  1021. maxLocalVer = f.LocalVersion
  1022. }
  1023. if ignores.Match(f.Name).IsIgnored() || symlinkInvalid(folder, f) {
  1024. l.Debugln("not sending update for ignored/unsupported symlink", f)
  1025. return true
  1026. }
  1027. sorter.Append(f)
  1028. return true
  1029. })
  1030. sorter.Sorted(func(f protocol.FileInfo) bool {
  1031. if len(batch) == indexBatchSize || currentBatchSize > indexTargetSize {
  1032. if initial {
  1033. if err = conn.Index(folder, batch); err != nil {
  1034. return false
  1035. }
  1036. l.Debugf("sendIndexes for %s-%s/%q: %d files (<%d bytes) (initial index)", deviceID, name, folder, len(batch), currentBatchSize)
  1037. initial = false
  1038. } else {
  1039. if err = conn.IndexUpdate(folder, batch); err != nil {
  1040. return false
  1041. }
  1042. l.Debugf("sendIndexes for %s-%s/%q: %d files (<%d bytes) (batched update)", deviceID, name, folder, len(batch), currentBatchSize)
  1043. }
  1044. batch = make([]protocol.FileInfo, 0, indexBatchSize)
  1045. currentBatchSize = 0
  1046. }
  1047. batch = append(batch, f)
  1048. currentBatchSize += f.ProtoSize()
  1049. return true
  1050. })
  1051. if initial && err == nil {
  1052. err = conn.Index(folder, batch)
  1053. if err == nil {
  1054. l.Debugf("sendIndexes for %s-%s/%q: %d files (small initial index)", deviceID, name, folder, len(batch))
  1055. }
  1056. } else if len(batch) > 0 && err == nil {
  1057. err = conn.IndexUpdate(folder, batch)
  1058. if err == nil {
  1059. l.Debugf("sendIndexes for %s-%s/%q: %d files (last batch)", deviceID, name, folder, len(batch))
  1060. }
  1061. }
  1062. return maxLocalVer, err
  1063. }
  1064. func (m *Model) updateLocalsFromScanning(folder string, fs []protocol.FileInfo) {
  1065. m.updateLocals(folder, fs)
  1066. // Fire the LocalChangeDetected event to notify listeners about local
  1067. // updates.
  1068. m.fmut.RLock()
  1069. path := m.folderCfgs[folder].Path()
  1070. m.fmut.RUnlock()
  1071. m.localChangeDetected(folder, path, fs)
  1072. }
  1073. func (m *Model) updateLocalsFromPulling(folder string, fs []protocol.FileInfo) {
  1074. m.updateLocals(folder, fs)
  1075. }
  1076. func (m *Model) updateLocals(folder string, fs []protocol.FileInfo) {
  1077. m.fmut.RLock()
  1078. files := m.folderFiles[folder]
  1079. m.fmut.RUnlock()
  1080. if files == nil {
  1081. // The folder doesn't exist.
  1082. return
  1083. }
  1084. files.Update(protocol.LocalDeviceID, fs)
  1085. filenames := make([]string, len(fs))
  1086. for i, file := range fs {
  1087. filenames[i] = file.Name
  1088. }
  1089. events.Default.Log(events.LocalIndexUpdated, map[string]interface{}{
  1090. "folder": folder,
  1091. "items": len(fs),
  1092. "filenames": filenames,
  1093. "version": files.LocalVersion(protocol.LocalDeviceID),
  1094. })
  1095. }
  1096. func (m *Model) localChangeDetected(folder, path string, files []protocol.FileInfo) {
  1097. // For windows paths, strip unwanted chars from the front
  1098. path = strings.Replace(path, `\\?\`, "", 1)
  1099. for _, file := range files {
  1100. objType := "file"
  1101. action := "modified"
  1102. // If our local vector is version 1 AND it is the only version
  1103. // vector so far seen for this file then it is a new file. Else if
  1104. // it is > 1 it's not new, and if it is 1 but another shortId
  1105. // version vector exists then it is new for us but created elsewhere
  1106. // so the file is still not new but modified by us. Only if it is
  1107. // truly new do we change this to 'added', else we leave it as
  1108. // 'modified'.
  1109. if len(file.Version.Counters) == 1 && file.Version.Counters[0].Value == 1 {
  1110. action = "added"
  1111. }
  1112. if file.IsDirectory() {
  1113. objType = "dir"
  1114. }
  1115. if file.IsDeleted() {
  1116. action = "deleted"
  1117. }
  1118. // The full file path, adjusted to the local path separator character.
  1119. path := filepath.Join(path, filepath.FromSlash(file.Name))
  1120. events.Default.Log(events.LocalChangeDetected, map[string]string{
  1121. "folder": folder,
  1122. "action": action,
  1123. "type": objType,
  1124. "path": path,
  1125. })
  1126. }
  1127. }
  1128. func (m *Model) requestGlobal(deviceID protocol.DeviceID, folder, name string, offset int64, size int, hash []byte, fromTemporary bool) ([]byte, error) {
  1129. m.pmut.RLock()
  1130. nc, ok := m.conn[deviceID]
  1131. m.pmut.RUnlock()
  1132. if !ok {
  1133. return nil, fmt.Errorf("requestGlobal: no such device: %s", deviceID)
  1134. }
  1135. 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)
  1136. return nc.Request(folder, name, offset, size, hash, fromTemporary)
  1137. }
  1138. func (m *Model) AddFolder(cfg config.FolderConfiguration) {
  1139. if len(cfg.ID) == 0 {
  1140. panic("cannot add empty folder id")
  1141. }
  1142. m.fmut.Lock()
  1143. m.folderCfgs[cfg.ID] = cfg
  1144. m.folderFiles[cfg.ID] = db.NewFileSet(cfg.ID, m.db)
  1145. m.folderDevices[cfg.ID] = make([]protocol.DeviceID, len(cfg.Devices))
  1146. for i, device := range cfg.Devices {
  1147. m.folderDevices[cfg.ID][i] = device.DeviceID
  1148. m.deviceFolders[device.DeviceID] = append(m.deviceFolders[device.DeviceID], cfg.ID)
  1149. }
  1150. ignores := ignore.New(m.cacheIgnoredFiles)
  1151. if err := ignores.Load(filepath.Join(cfg.Path(), ".stignore")); err != nil && !os.IsNotExist(err) {
  1152. l.Warnln("Loading ignores:", err)
  1153. }
  1154. m.folderIgnores[cfg.ID] = ignores
  1155. m.fmut.Unlock()
  1156. }
  1157. func (m *Model) ScanFolders() map[string]error {
  1158. m.fmut.RLock()
  1159. folders := make([]string, 0, len(m.folderCfgs))
  1160. for folder := range m.folderCfgs {
  1161. folders = append(folders, folder)
  1162. }
  1163. m.fmut.RUnlock()
  1164. errors := make(map[string]error, len(m.folderCfgs))
  1165. errorsMut := sync.NewMutex()
  1166. wg := sync.NewWaitGroup()
  1167. wg.Add(len(folders))
  1168. for _, folder := range folders {
  1169. folder := folder
  1170. go func() {
  1171. err := m.ScanFolder(folder)
  1172. if err != nil {
  1173. errorsMut.Lock()
  1174. errors[folder] = err
  1175. errorsMut.Unlock()
  1176. // Potentially sets the error twice, once in the scanner just
  1177. // by doing a check, and once here, if the error returned is
  1178. // the same one as returned by CheckFolderHealth, though
  1179. // duplicate set is handled by setError.
  1180. m.fmut.RLock()
  1181. srv := m.folderRunners[folder]
  1182. m.fmut.RUnlock()
  1183. srv.setError(err)
  1184. }
  1185. wg.Done()
  1186. }()
  1187. }
  1188. wg.Wait()
  1189. return errors
  1190. }
  1191. func (m *Model) ScanFolder(folder string) error {
  1192. return m.ScanFolderSubdirs(folder, nil)
  1193. }
  1194. func (m *Model) ScanFolderSubdirs(folder string, subs []string) error {
  1195. m.fmut.Lock()
  1196. runner, ok := m.folderRunners[folder]
  1197. m.fmut.Unlock()
  1198. // Folders are added to folderRunners only when they are started. We can't
  1199. // scan them before they have started, so that's what we need to check for
  1200. // here.
  1201. if !ok {
  1202. return errors.New("no such folder")
  1203. }
  1204. return runner.Scan(subs)
  1205. }
  1206. func (m *Model) internalScanFolderSubdirs(folder string, subDirs []string) error {
  1207. for i, sub := range subDirs {
  1208. sub = osutil.NativeFilename(sub)
  1209. if p := filepath.Clean(filepath.Join(folder, sub)); !strings.HasPrefix(p, folder) {
  1210. return errors.New("invalid subpath")
  1211. }
  1212. subDirs[i] = sub
  1213. }
  1214. m.fmut.Lock()
  1215. fs := m.folderFiles[folder]
  1216. folderCfg := m.folderCfgs[folder]
  1217. ignores := m.folderIgnores[folder]
  1218. runner, ok := m.folderRunners[folder]
  1219. m.fmut.Unlock()
  1220. // Folders are added to folderRunners only when they are started. We can't
  1221. // scan them before they have started, so that's what we need to check for
  1222. // here.
  1223. if !ok {
  1224. return errors.New("no such folder")
  1225. }
  1226. if err := m.CheckFolderHealth(folder); err != nil {
  1227. runner.setError(err)
  1228. l.Infof("Stopping folder %s due to error: %s", folder, err)
  1229. return err
  1230. }
  1231. if err := ignores.Load(filepath.Join(folderCfg.Path(), ".stignore")); err != nil && !os.IsNotExist(err) {
  1232. err = fmt.Errorf("loading ignores: %v", err)
  1233. runner.setError(err)
  1234. l.Infof("Stopping folder %s due to error: %s", folder, err)
  1235. return err
  1236. }
  1237. // Clean the list of subitems to ensure that we start at a known
  1238. // directory, and don't scan subdirectories of things we've already
  1239. // scanned.
  1240. subDirs = unifySubs(subDirs, func(f string) bool {
  1241. _, ok := fs.Get(protocol.LocalDeviceID, f)
  1242. return ok
  1243. })
  1244. // The cancel channel is closed whenever we return (such as from an error),
  1245. // to signal the potentially still running walker to stop.
  1246. cancel := make(chan struct{})
  1247. defer close(cancel)
  1248. runner.setState(FolderScanning)
  1249. fchan, err := scanner.Walk(scanner.Config{
  1250. Folder: folderCfg.ID,
  1251. Dir: folderCfg.Path(),
  1252. Subs: subDirs,
  1253. Matcher: ignores,
  1254. BlockSize: protocol.BlockSize,
  1255. TempNamer: defTempNamer,
  1256. TempLifetime: time.Duration(m.cfg.Options().KeepTemporariesH) * time.Hour,
  1257. CurrentFiler: cFiler{m, folder},
  1258. MtimeRepo: db.NewVirtualMtimeRepo(m.db, folderCfg.ID),
  1259. IgnorePerms: folderCfg.IgnorePerms,
  1260. AutoNormalize: folderCfg.AutoNormalize,
  1261. Hashers: m.numHashers(folder),
  1262. ShortID: m.shortID,
  1263. ProgressTickIntervalS: folderCfg.ScanProgressIntervalS,
  1264. Cancel: cancel,
  1265. })
  1266. if err != nil {
  1267. // The error we get here is likely an OS level error, which might not be
  1268. // as readable as our health check errors. Check if we can get a health
  1269. // check error first, and use that if it's available.
  1270. if ferr := m.CheckFolderHealth(folder); ferr != nil {
  1271. err = ferr
  1272. }
  1273. runner.setError(err)
  1274. return err
  1275. }
  1276. batchSizeFiles := 100
  1277. batchSizeBlocks := 2048 // about 256 MB
  1278. batch := make([]protocol.FileInfo, 0, batchSizeFiles)
  1279. blocksHandled := 0
  1280. for f := range fchan {
  1281. if len(batch) == batchSizeFiles || blocksHandled > batchSizeBlocks {
  1282. if err := m.CheckFolderHealth(folder); err != nil {
  1283. l.Infof("Stopping folder %s mid-scan due to folder error: %s", folder, err)
  1284. return err
  1285. }
  1286. m.updateLocalsFromScanning(folder, batch)
  1287. batch = batch[:0]
  1288. blocksHandled = 0
  1289. }
  1290. batch = append(batch, f)
  1291. blocksHandled += len(f.Blocks)
  1292. }
  1293. if err := m.CheckFolderHealth(folder); err != nil {
  1294. l.Infof("Stopping folder %s mid-scan due to folder error: %s", folder, err)
  1295. return err
  1296. } else if len(batch) > 0 {
  1297. m.updateLocalsFromScanning(folder, batch)
  1298. }
  1299. if len(subDirs) == 0 {
  1300. // If we have no specific subdirectories to traverse, set it to one
  1301. // empty prefix so we traverse the entire folder contents once.
  1302. subDirs = []string{""}
  1303. }
  1304. // Do a scan of the database for each prefix, to check for deleted files.
  1305. batch = batch[:0]
  1306. for _, sub := range subDirs {
  1307. var iterError error
  1308. fs.WithPrefixedHaveTruncated(protocol.LocalDeviceID, sub, func(fi db.FileIntf) bool {
  1309. f := fi.(db.FileInfoTruncated)
  1310. if !f.IsDeleted() {
  1311. if len(batch) == batchSizeFiles {
  1312. if err := m.CheckFolderHealth(folder); err != nil {
  1313. iterError = err
  1314. return false
  1315. }
  1316. m.updateLocalsFromScanning(folder, batch)
  1317. batch = batch[:0]
  1318. }
  1319. if !f.IsInvalid() && (ignores.Match(f.Name).IsIgnored() || symlinkInvalid(folder, f)) {
  1320. // File has been ignored or an unsupported symlink. Set invalid bit.
  1321. l.Debugln("setting invalid bit on ignored", f)
  1322. nf := protocol.FileInfo{
  1323. Name: f.Name,
  1324. Type: f.Type,
  1325. Size: f.Size,
  1326. Modified: f.Modified,
  1327. Permissions: f.Permissions,
  1328. NoPermissions: f.NoPermissions,
  1329. Invalid: true,
  1330. Version: f.Version, // The file is still the same, so don't bump version
  1331. }
  1332. batch = append(batch, nf)
  1333. } else if _, err := osutil.Lstat(filepath.Join(folderCfg.Path(), f.Name)); err != nil {
  1334. // File has been deleted.
  1335. // We don't specifically verify that the error is
  1336. // os.IsNotExist because there is a corner case when a
  1337. // directory is suddenly transformed into a file. When that
  1338. // happens, files that were in the directory (that is now a
  1339. // file) are deleted but will return a confusing error ("not a
  1340. // directory") when we try to Lstat() them.
  1341. nf := protocol.FileInfo{
  1342. Name: f.Name,
  1343. Type: f.Type,
  1344. Size: f.Size,
  1345. Modified: f.Modified,
  1346. Deleted: true,
  1347. Version: f.Version.Update(m.shortID),
  1348. }
  1349. batch = append(batch, nf)
  1350. }
  1351. }
  1352. return true
  1353. })
  1354. if iterError != nil {
  1355. l.Infof("Stopping folder %s mid-scan due to folder error: %s", folder, iterError)
  1356. return iterError
  1357. }
  1358. }
  1359. if err := m.CheckFolderHealth(folder); err != nil {
  1360. l.Infof("Stopping folder %s mid-scan due to folder error: %s", folder, err)
  1361. return err
  1362. } else if len(batch) > 0 {
  1363. m.updateLocalsFromScanning(folder, batch)
  1364. }
  1365. m.folderStatRef(folder).ScanCompleted()
  1366. runner.setState(FolderIdle)
  1367. return nil
  1368. }
  1369. func (m *Model) DelayScan(folder string, next time.Duration) {
  1370. m.fmut.Lock()
  1371. runner, ok := m.folderRunners[folder]
  1372. m.fmut.Unlock()
  1373. if !ok {
  1374. return
  1375. }
  1376. runner.DelayScan(next)
  1377. }
  1378. // numHashers returns the number of hasher routines to use for a given folder,
  1379. // taking into account configuration and available CPU cores.
  1380. func (m *Model) numHashers(folder string) int {
  1381. m.fmut.Lock()
  1382. folderCfg := m.folderCfgs[folder]
  1383. numFolders := len(m.folderCfgs)
  1384. m.fmut.Unlock()
  1385. if folderCfg.Hashers > 0 {
  1386. // Specific value set in the config, use that.
  1387. return folderCfg.Hashers
  1388. }
  1389. if runtime.GOOS == "windows" || runtime.GOOS == "darwin" {
  1390. // Interactive operating systems; don't load the system too heavily by
  1391. // default.
  1392. return 1
  1393. }
  1394. // For other operating systems and architectures, lets try to get some
  1395. // work done... Divide the available CPU cores among the configured
  1396. // folders.
  1397. if perFolder := runtime.GOMAXPROCS(-1) / numFolders; perFolder > 0 {
  1398. return perFolder
  1399. }
  1400. return 1
  1401. }
  1402. // generateClusterConfig returns a ClusterConfigMessage that is correct for
  1403. // the given peer device
  1404. func (m *Model) generateClusterConfig(device protocol.DeviceID) protocol.ClusterConfig {
  1405. var message protocol.ClusterConfig
  1406. m.fmut.RLock()
  1407. for _, folder := range m.deviceFolders[device] {
  1408. folderCfg := m.cfg.Folders()[folder]
  1409. protocolFolder := protocol.Folder{
  1410. ID: folder,
  1411. Label: folderCfg.Label,
  1412. ReadOnly: folderCfg.Type == config.FolderTypeReadOnly,
  1413. IgnorePermissions: folderCfg.IgnorePerms,
  1414. IgnoreDelete: folderCfg.IgnoreDelete,
  1415. DisableTempIndexes: folderCfg.DisableTempIndexes,
  1416. }
  1417. for _, device := range m.folderDevices[folder] {
  1418. // DeviceID is a value type, but with an underlying array. Copy it
  1419. // so we don't grab aliases to the same array later on in device[:]
  1420. device := device
  1421. // TODO: Set read only bit when relevant, and when we have per device
  1422. // access controls.
  1423. deviceCfg := m.cfg.Devices()[device]
  1424. protocolDevice := protocol.Device{
  1425. ID: device[:],
  1426. Name: deviceCfg.Name,
  1427. Addresses: deviceCfg.Addresses,
  1428. Compression: deviceCfg.Compression,
  1429. CertName: deviceCfg.CertName,
  1430. Introducer: deviceCfg.Introducer,
  1431. }
  1432. protocolFolder.Devices = append(protocolFolder.Devices, protocolDevice)
  1433. }
  1434. message.Folders = append(message.Folders, protocolFolder)
  1435. }
  1436. m.fmut.RUnlock()
  1437. return message
  1438. }
  1439. func (m *Model) State(folder string) (string, time.Time, error) {
  1440. m.fmut.RLock()
  1441. runner, ok := m.folderRunners[folder]
  1442. m.fmut.RUnlock()
  1443. if !ok {
  1444. // The returned error should be an actual folder error, so returning
  1445. // errors.New("does not exist") or similar here would be
  1446. // inappropriate.
  1447. return "", time.Time{}, nil
  1448. }
  1449. state, changed, err := runner.getState()
  1450. return state.String(), changed, err
  1451. }
  1452. func (m *Model) Override(folder string) {
  1453. m.fmut.RLock()
  1454. fs, ok := m.folderFiles[folder]
  1455. runner := m.folderRunners[folder]
  1456. m.fmut.RUnlock()
  1457. if !ok {
  1458. return
  1459. }
  1460. runner.setState(FolderScanning)
  1461. batch := make([]protocol.FileInfo, 0, indexBatchSize)
  1462. fs.WithNeed(protocol.LocalDeviceID, func(fi db.FileIntf) bool {
  1463. need := fi.(protocol.FileInfo)
  1464. if len(batch) == indexBatchSize {
  1465. m.updateLocalsFromScanning(folder, batch)
  1466. batch = batch[:0]
  1467. }
  1468. have, ok := fs.Get(protocol.LocalDeviceID, need.Name)
  1469. if !ok || have.Name != need.Name {
  1470. // We are missing the file
  1471. need.Deleted = true
  1472. need.Blocks = nil
  1473. need.Version = need.Version.Update(m.shortID)
  1474. } else {
  1475. // We have the file, replace with our version
  1476. have.Version = have.Version.Merge(need.Version).Update(m.shortID)
  1477. need = have
  1478. }
  1479. need.LocalVersion = 0
  1480. batch = append(batch, need)
  1481. return true
  1482. })
  1483. if len(batch) > 0 {
  1484. m.updateLocalsFromScanning(folder, batch)
  1485. }
  1486. runner.setState(FolderIdle)
  1487. }
  1488. // CurrentLocalVersion returns the change version for the given folder.
  1489. // This is guaranteed to increment if the contents of the local folder has
  1490. // changed.
  1491. func (m *Model) CurrentLocalVersion(folder string) (int64, bool) {
  1492. m.fmut.RLock()
  1493. fs, ok := m.folderFiles[folder]
  1494. m.fmut.RUnlock()
  1495. if !ok {
  1496. // The folder might not exist, since this can be called with a user
  1497. // specified folder name from the REST interface.
  1498. return 0, false
  1499. }
  1500. return fs.LocalVersion(protocol.LocalDeviceID), true
  1501. }
  1502. // RemoteLocalVersion returns the change version for the given folder, as
  1503. // sent by remote peers. This is guaranteed to increment if the contents of
  1504. // the remote or global folder has changed.
  1505. func (m *Model) RemoteLocalVersion(folder string) (int64, bool) {
  1506. m.fmut.RLock()
  1507. defer m.fmut.RUnlock()
  1508. fs, ok := m.folderFiles[folder]
  1509. if !ok {
  1510. // The folder might not exist, since this can be called with a user
  1511. // specified folder name from the REST interface.
  1512. return 0, false
  1513. }
  1514. var ver int64
  1515. for _, n := range m.folderDevices[folder] {
  1516. ver += fs.LocalVersion(n)
  1517. }
  1518. return ver, true
  1519. }
  1520. func (m *Model) GlobalDirectoryTree(folder, prefix string, levels int, dirsonly bool) map[string]interface{} {
  1521. m.fmut.RLock()
  1522. files, ok := m.folderFiles[folder]
  1523. m.fmut.RUnlock()
  1524. if !ok {
  1525. return nil
  1526. }
  1527. output := make(map[string]interface{})
  1528. sep := string(filepath.Separator)
  1529. prefix = osutil.NativeFilename(prefix)
  1530. if prefix != "" && !strings.HasSuffix(prefix, sep) {
  1531. prefix = prefix + sep
  1532. }
  1533. files.WithPrefixedGlobalTruncated(prefix, func(fi db.FileIntf) bool {
  1534. f := fi.(db.FileInfoTruncated)
  1535. if f.IsInvalid() || f.IsDeleted() || f.Name == prefix {
  1536. return true
  1537. }
  1538. f.Name = strings.Replace(f.Name, prefix, "", 1)
  1539. var dir, base string
  1540. if f.IsDirectory() && !f.IsSymlink() {
  1541. dir = f.Name
  1542. } else {
  1543. dir = filepath.Dir(f.Name)
  1544. base = filepath.Base(f.Name)
  1545. }
  1546. if levels > -1 && strings.Count(f.Name, sep) > levels {
  1547. return true
  1548. }
  1549. last := output
  1550. if dir != "." {
  1551. for _, path := range strings.Split(dir, sep) {
  1552. directory, ok := last[path]
  1553. if !ok {
  1554. newdir := make(map[string]interface{})
  1555. last[path] = newdir
  1556. last = newdir
  1557. } else {
  1558. last = directory.(map[string]interface{})
  1559. }
  1560. }
  1561. }
  1562. if !dirsonly && base != "" {
  1563. last[base] = []interface{}{
  1564. time.Unix(f.Modified, 0), f.FileSize(),
  1565. }
  1566. }
  1567. return true
  1568. })
  1569. return output
  1570. }
  1571. func (m *Model) Availability(folder, file string, version protocol.Vector, block protocol.BlockInfo) []Availability {
  1572. // Acquire this lock first, as the value returned from foldersFiles can
  1573. // get heavily modified on Close()
  1574. m.pmut.RLock()
  1575. defer m.pmut.RUnlock()
  1576. m.fmut.RLock()
  1577. fs, ok := m.folderFiles[folder]
  1578. devices := m.folderDevices[folder]
  1579. m.fmut.RUnlock()
  1580. if !ok {
  1581. return nil
  1582. }
  1583. var availabilities []Availability
  1584. for _, device := range fs.Availability(file) {
  1585. _, ok := m.conn[device]
  1586. if ok {
  1587. availabilities = append(availabilities, Availability{ID: device, FromTemporary: false})
  1588. }
  1589. }
  1590. for _, device := range devices {
  1591. if m.deviceDownloads[device].Has(folder, file, version, int32(block.Offset/protocol.BlockSize)) {
  1592. availabilities = append(availabilities, Availability{ID: device, FromTemporary: true})
  1593. }
  1594. }
  1595. return availabilities
  1596. }
  1597. // BringToFront bumps the given files priority in the job queue.
  1598. func (m *Model) BringToFront(folder, file string) {
  1599. m.pmut.RLock()
  1600. defer m.pmut.RUnlock()
  1601. runner, ok := m.folderRunners[folder]
  1602. if ok {
  1603. runner.BringToFront(file)
  1604. }
  1605. }
  1606. // CheckFolderHealth checks the folder for common errors and returns the
  1607. // current folder error, or nil if the folder is healthy.
  1608. func (m *Model) CheckFolderHealth(id string) error {
  1609. folder, ok := m.cfg.Folders()[id]
  1610. if !ok {
  1611. return errors.New("folder does not exist")
  1612. }
  1613. // Check for folder errors, with the most serious and specific first and
  1614. // generic ones like out of space on the home disk later. Note the
  1615. // inverted error flow (err==nil checks) here.
  1616. err := m.checkFolderPath(folder)
  1617. if err == nil {
  1618. err = m.checkFolderFreeSpace(folder)
  1619. }
  1620. if err == nil {
  1621. err = m.checkHomeDiskFree()
  1622. }
  1623. // Set or clear the error on the runner, which also does logging and
  1624. // generates events and stuff.
  1625. m.runnerExchangeError(folder, err)
  1626. return err
  1627. }
  1628. // checkFolderPath returns nil if the folder path exists and has the marker file.
  1629. func (m *Model) checkFolderPath(folder config.FolderConfiguration) error {
  1630. if folder.Path() == "" {
  1631. return errFolderPathEmpty
  1632. }
  1633. if fi, err := os.Stat(folder.Path()); err != nil || !fi.IsDir() {
  1634. return errFolderPathMissing
  1635. }
  1636. if !folder.HasMarker() {
  1637. return errFolderMarkerMissing
  1638. }
  1639. return nil
  1640. }
  1641. // checkFolderFreeSpace returns nil if the folder has the required amount of
  1642. // free space, or if folder free space checking is disabled.
  1643. func (m *Model) checkFolderFreeSpace(folder config.FolderConfiguration) error {
  1644. if folder.MinDiskFreePct <= 0 {
  1645. return nil
  1646. }
  1647. free, err := osutil.DiskFreePercentage(folder.Path())
  1648. if err == nil && free < folder.MinDiskFreePct {
  1649. return errFolderNoSpace
  1650. }
  1651. return nil
  1652. }
  1653. // checkHomeDiskFree returns nil if the home disk has the required amount of
  1654. // free space, or if home disk free space checking is disabled.
  1655. func (m *Model) checkHomeDiskFree() error {
  1656. minFree := m.cfg.Options().MinHomeDiskFreePct
  1657. if minFree <= 0 {
  1658. return nil
  1659. }
  1660. free, err := osutil.DiskFreePercentage(m.cfg.ConfigPath())
  1661. if err == nil && free < minFree {
  1662. return errHomeDiskNoSpace
  1663. }
  1664. return nil
  1665. }
  1666. // runnerExchangeError sets the given error (which way be nil) on the folder
  1667. // runner. If the error differs from any previous error, logging and events
  1668. // happen.
  1669. func (m *Model) runnerExchangeError(folder config.FolderConfiguration, err error) {
  1670. m.fmut.RLock()
  1671. runner, runnerExists := m.folderRunners[folder.ID]
  1672. m.fmut.RUnlock()
  1673. var oldErr error
  1674. if runnerExists {
  1675. _, _, oldErr = runner.getState()
  1676. }
  1677. if err != nil {
  1678. if oldErr != nil && oldErr.Error() != err.Error() {
  1679. l.Infof("Folder %q error changed: %q -> %q", folder.ID, oldErr, err)
  1680. } else if oldErr == nil {
  1681. l.Warnf("Stopping folder %q - %v", folder.ID, err)
  1682. }
  1683. if runnerExists {
  1684. runner.setError(err)
  1685. }
  1686. } else if oldErr != nil {
  1687. l.Infof("Folder %q error is cleared, restarting", folder.ID)
  1688. if runnerExists {
  1689. runner.clearError()
  1690. }
  1691. }
  1692. }
  1693. func (m *Model) ResetFolder(folder string) {
  1694. l.Infof("Cleaning data for folder %q", folder)
  1695. db.DropFolder(m.db, folder)
  1696. }
  1697. func (m *Model) String() string {
  1698. return fmt.Sprintf("model@%p", m)
  1699. }
  1700. func (m *Model) VerifyConfiguration(from, to config.Configuration) error {
  1701. return nil
  1702. }
  1703. func (m *Model) CommitConfiguration(from, to config.Configuration) bool {
  1704. // TODO: This should not use reflect, and should take more care to try to handle stuff without restart.
  1705. // Go through the folder configs and figure out if we need to restart or not.
  1706. fromFolders := mapFolders(from.Folders)
  1707. toFolders := mapFolders(to.Folders)
  1708. for folderID, cfg := range toFolders {
  1709. if _, ok := fromFolders[folderID]; !ok {
  1710. // A folder was added.
  1711. l.Debugln(m, "adding folder", folderID)
  1712. m.AddFolder(cfg)
  1713. m.StartFolder(folderID)
  1714. // Drop connections to all devices that can now share the new
  1715. // folder.
  1716. m.pmut.Lock()
  1717. for _, dev := range cfg.DeviceIDs() {
  1718. if conn, ok := m.conn[dev]; ok {
  1719. closeRawConn(conn)
  1720. }
  1721. }
  1722. m.pmut.Unlock()
  1723. }
  1724. }
  1725. for folderID, fromCfg := range fromFolders {
  1726. toCfg, ok := toFolders[folderID]
  1727. if !ok {
  1728. // The folder was removed.
  1729. m.RemoveFolder(folderID)
  1730. continue
  1731. }
  1732. // This folder exists on both sides. Compare the device lists, as we
  1733. // can handle adding a device (but not currently removing one).
  1734. fromDevs := mapDevices(fromCfg.DeviceIDs())
  1735. toDevs := mapDevices(toCfg.DeviceIDs())
  1736. for dev := range fromDevs {
  1737. if _, ok := toDevs[dev]; !ok {
  1738. // A device was removed. Requires restart.
  1739. l.Debugln(m, "requires restart, removing device", dev, "from folder", folderID)
  1740. return false
  1741. }
  1742. }
  1743. for dev := range toDevs {
  1744. if _, ok := fromDevs[dev]; !ok {
  1745. // A device was added. Handle it!
  1746. m.fmut.Lock()
  1747. m.pmut.Lock()
  1748. m.folderCfgs[folderID] = toCfg
  1749. m.folderDevices[folderID] = append(m.folderDevices[folderID], dev)
  1750. m.deviceFolders[dev] = append(m.deviceFolders[dev], folderID)
  1751. // If we already have a connection to this device, we should
  1752. // disconnect it so that we start sharing the folder with it.
  1753. // We close the underlying connection and let the normal error
  1754. // handling kick in to clean up and reconnect.
  1755. if conn, ok := m.conn[dev]; ok {
  1756. closeRawConn(conn)
  1757. }
  1758. m.pmut.Unlock()
  1759. m.fmut.Unlock()
  1760. }
  1761. }
  1762. // Check if anything else differs, apart from the device list and label.
  1763. fromCfg.Devices = nil
  1764. toCfg.Devices = nil
  1765. fromCfg.Label = ""
  1766. toCfg.Label = ""
  1767. if !reflect.DeepEqual(fromCfg, toCfg) {
  1768. l.Debugln(m, "requires restart, folder", folderID, "configuration differs")
  1769. return false
  1770. }
  1771. }
  1772. // Removing a device requires restart
  1773. toDevs := mapDeviceCfgs(from.Devices)
  1774. for _, dev := range from.Devices {
  1775. if _, ok := toDevs[dev.DeviceID]; !ok {
  1776. l.Debugln(m, "requires restart, device", dev.DeviceID, "was removed")
  1777. return false
  1778. }
  1779. }
  1780. // Some options don't require restart as those components handle it fine
  1781. // by themselves.
  1782. from.Options.URAccepted = to.Options.URAccepted
  1783. from.Options.URUniqueID = to.Options.URUniqueID
  1784. from.Options.ListenAddresses = to.Options.ListenAddresses
  1785. from.Options.RelaysEnabled = to.Options.RelaysEnabled
  1786. // All of the other generic options require restart. Or at least they may;
  1787. // removing this check requires going through those options carefully and
  1788. // making sure there are individual services that handle them correctly.
  1789. // This code is the "original" requires-restart check and protects other
  1790. // components that haven't yet been converted to VerifyConfig/CommitConfig
  1791. // handling.
  1792. if !reflect.DeepEqual(from.Options, to.Options) {
  1793. l.Debugln(m, "requires restart, options differ")
  1794. return false
  1795. }
  1796. return true
  1797. }
  1798. // mapFolders returns a map of folder ID to folder configuration for the given
  1799. // slice of folder configurations.
  1800. func mapFolders(folders []config.FolderConfiguration) map[string]config.FolderConfiguration {
  1801. m := make(map[string]config.FolderConfiguration, len(folders))
  1802. for _, cfg := range folders {
  1803. m[cfg.ID] = cfg
  1804. }
  1805. return m
  1806. }
  1807. // mapDevices returns a map of device ID to nothing for the given slice of
  1808. // device IDs.
  1809. func mapDevices(devices []protocol.DeviceID) map[protocol.DeviceID]struct{} {
  1810. m := make(map[protocol.DeviceID]struct{}, len(devices))
  1811. for _, dev := range devices {
  1812. m[dev] = struct{}{}
  1813. }
  1814. return m
  1815. }
  1816. // mapDeviceCfgs returns a map of device ID to nothing for the given slice of
  1817. // device configurations.
  1818. func mapDeviceCfgs(devices []config.DeviceConfiguration) map[protocol.DeviceID]struct{} {
  1819. m := make(map[protocol.DeviceID]struct{}, len(devices))
  1820. for _, dev := range devices {
  1821. m[dev.DeviceID] = struct{}{}
  1822. }
  1823. return m
  1824. }
  1825. func filterIndex(folder string, fs []protocol.FileInfo, dropDeletes bool, ignores *ignore.Matcher) []protocol.FileInfo {
  1826. for i := 0; i < len(fs); {
  1827. if fs[i].IsDeleted() && dropDeletes {
  1828. l.Debugln("dropping update for undesired delete", fs[i])
  1829. fs[i] = fs[len(fs)-1]
  1830. fs = fs[:len(fs)-1]
  1831. } else if symlinkInvalid(folder, fs[i]) {
  1832. l.Debugln("dropping update for unsupported symlink", fs[i])
  1833. fs[i] = fs[len(fs)-1]
  1834. fs = fs[:len(fs)-1]
  1835. } else if ignores != nil && ignores.Match(fs[i].Name).IsIgnored() {
  1836. l.Debugln("dropping update for ignored item", fs[i])
  1837. fs[i] = fs[len(fs)-1]
  1838. fs = fs[:len(fs)-1]
  1839. } else {
  1840. i++
  1841. }
  1842. }
  1843. return fs
  1844. }
  1845. func symlinkInvalid(folder string, fi db.FileIntf) bool {
  1846. if !symlinks.Supported && fi.IsSymlink() && !fi.IsInvalid() && !fi.IsDeleted() {
  1847. symlinkWarning.Do(func() {
  1848. l.Warnln("Symlinks are disabled, unsupported or require Administrator privileges. This might cause your folder to appear out of sync.")
  1849. })
  1850. // Need to type switch for the concrete type to be able to access fields...
  1851. var name string
  1852. switch fi := fi.(type) {
  1853. case protocol.FileInfo:
  1854. name = fi.Name
  1855. case db.FileInfoTruncated:
  1856. name = fi.Name
  1857. }
  1858. l.Infoln("Unsupported symlink", name, "in folder", folder)
  1859. return true
  1860. }
  1861. return false
  1862. }
  1863. // Skips `skip` elements and retrieves up to `get` elements from a given slice.
  1864. // Returns the resulting slice, plus how much elements are left to skip or
  1865. // copy to satisfy the values which were provided, given the slice is not
  1866. // big enough.
  1867. func getChunk(data []string, skip, get int) ([]string, int, int) {
  1868. l := len(data)
  1869. if l <= skip {
  1870. return []string{}, skip - l, get
  1871. } else if l < skip+get {
  1872. return data[skip:l], 0, get - (l - skip)
  1873. }
  1874. return data[skip : skip+get], 0, 0
  1875. }
  1876. func closeRawConn(conn io.Closer) error {
  1877. if conn, ok := conn.(*tls.Conn); ok {
  1878. // If the underlying connection is a *tls.Conn, Close() does more
  1879. // than it says on the tin. Specifically, it sends a TLS alert
  1880. // message, which might block forever if the connection is dead
  1881. // and we don't have a deadline set.
  1882. conn.SetWriteDeadline(time.Now().Add(250 * time.Millisecond))
  1883. }
  1884. return conn.Close()
  1885. }
  1886. func stringSliceWithout(ss []string, s string) []string {
  1887. for i := range ss {
  1888. if ss[i] == s {
  1889. copy(ss[i:], ss[i+1:])
  1890. ss = ss[:len(ss)-1]
  1891. return ss
  1892. }
  1893. }
  1894. return ss
  1895. }
  1896. func readOffsetIntoBuf(file string, offset int64, buf []byte) error {
  1897. fd, err := os.Open(file)
  1898. if err != nil {
  1899. l.Debugln("readOffsetIntoBuf.Open", file, err)
  1900. return err
  1901. }
  1902. defer fd.Close()
  1903. _, err = fd.ReadAt(buf, offset)
  1904. if err != nil {
  1905. l.Debugln("readOffsetIntoBuf.ReadAt", file, err)
  1906. }
  1907. return err
  1908. }
  1909. // The exists function is expected to return true for all known paths
  1910. // (excluding "" and ".")
  1911. func unifySubs(dirs []string, exists func(dir string) bool) []string {
  1912. subs := trimUntilParentKnown(dirs, exists)
  1913. sort.Strings(subs)
  1914. return simplifySortedPaths(subs)
  1915. }
  1916. func trimUntilParentKnown(dirs []string, exists func(dir string) bool) []string {
  1917. var subs []string
  1918. for _, sub := range dirs {
  1919. for sub != "" && sub != ".stfolder" && sub != ".stignore" {
  1920. sub = filepath.Clean(sub)
  1921. parent := filepath.Dir(sub)
  1922. if parent == "." || exists(parent) {
  1923. break
  1924. }
  1925. sub = parent
  1926. if sub == "." || sub == string(filepath.Separator) {
  1927. // Shortcut. We are going to scan the full folder, so we can
  1928. // just return an empty list of subs at this point.
  1929. return nil
  1930. }
  1931. }
  1932. if sub == "" {
  1933. return nil
  1934. }
  1935. subs = append(subs, sub)
  1936. }
  1937. return subs
  1938. }
  1939. func simplifySortedPaths(subs []string) []string {
  1940. var cleaned []string
  1941. next:
  1942. for _, sub := range subs {
  1943. for _, existing := range cleaned {
  1944. if sub == existing || strings.HasPrefix(sub, existing+string(os.PathSeparator)) {
  1945. continue next
  1946. }
  1947. }
  1948. cleaned = append(cleaned, sub)
  1949. }
  1950. return cleaned
  1951. }
  1952. // makeForgetUpdate takes an index update and constructs a download progress update
  1953. // causing to forget any progress for files which we've just been sent.
  1954. func makeForgetUpdate(files []protocol.FileInfo) []protocol.FileDownloadProgressUpdate {
  1955. updates := make([]protocol.FileDownloadProgressUpdate, 0, len(files))
  1956. for _, file := range files {
  1957. if file.IsSymlink() || file.IsDirectory() || file.IsDeleted() {
  1958. continue
  1959. }
  1960. updates = append(updates, protocol.FileDownloadProgressUpdate{
  1961. Name: file.Name,
  1962. Version: file.Version,
  1963. UpdateType: protocol.UpdateTypeForget,
  1964. })
  1965. }
  1966. return updates
  1967. }