model.go 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490
  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. "io/ioutil"
  15. "net"
  16. "os"
  17. "path/filepath"
  18. "strconv"
  19. "strings"
  20. "sync"
  21. "time"
  22. "github.com/syncthing/protocol"
  23. "github.com/syncthing/syncthing/internal/config"
  24. "github.com/syncthing/syncthing/internal/db"
  25. "github.com/syncthing/syncthing/internal/events"
  26. "github.com/syncthing/syncthing/internal/ignore"
  27. "github.com/syncthing/syncthing/internal/lamport"
  28. "github.com/syncthing/syncthing/internal/osutil"
  29. "github.com/syncthing/syncthing/internal/scanner"
  30. "github.com/syncthing/syncthing/internal/stats"
  31. "github.com/syncthing/syncthing/internal/symlinks"
  32. "github.com/syncthing/syncthing/internal/versioner"
  33. "github.com/syndtr/goleveldb/leveldb"
  34. )
  35. // How many files to send in each Index/IndexUpdate message.
  36. const (
  37. indexTargetSize = 250 * 1024 // Aim for making index messages no larger than 250 KiB (uncompressed)
  38. indexPerFileSize = 250 // Each FileInfo is approximately this big, in bytes, excluding BlockInfos
  39. IndexPerBlockSize = 40 // Each BlockInfo is approximately this big
  40. indexBatchSize = 1000 // Either way, don't include more files than this
  41. )
  42. type service interface {
  43. Serve()
  44. Stop()
  45. Jobs() ([]string, []string) // In progress, Queued
  46. BringToFront(string)
  47. setState(folderState)
  48. getState() (folderState, time.Time)
  49. }
  50. type Model struct {
  51. cfg *config.Wrapper
  52. db *leveldb.DB
  53. finder *db.BlockFinder
  54. progressEmitter *ProgressEmitter
  55. deviceName string
  56. clientName string
  57. clientVersion string
  58. folderCfgs map[string]config.FolderConfiguration // folder -> cfg
  59. folderFiles map[string]*db.FileSet // folder -> files
  60. folderDevices map[string][]protocol.DeviceID // folder -> deviceIDs
  61. deviceFolders map[protocol.DeviceID][]string // deviceID -> folders
  62. deviceStatRefs map[protocol.DeviceID]*stats.DeviceStatisticsReference // deviceID -> statsRef
  63. folderIgnores map[string]*ignore.Matcher // folder -> matcher object
  64. folderRunners map[string]service // folder -> puller or scanner
  65. folderStatRefs map[string]*stats.FolderStatisticsReference // folder -> statsRef
  66. fmut sync.RWMutex // protects the above
  67. protoConn map[protocol.DeviceID]protocol.Connection
  68. rawConn map[protocol.DeviceID]io.Closer
  69. deviceVer map[protocol.DeviceID]string
  70. pmut sync.RWMutex // protects protoConn and rawConn
  71. addedFolder bool
  72. started bool
  73. }
  74. var (
  75. ErrNoSuchFile = errors.New("no such file")
  76. ErrInvalid = errors.New("file is invalid")
  77. SymlinkWarning = sync.Once{}
  78. )
  79. // NewModel creates and starts a new model. The model starts in read-only mode,
  80. // where it sends index information to connected peers and responds to requests
  81. // for file data without altering the local folder in any way.
  82. func NewModel(cfg *config.Wrapper, deviceName, clientName, clientVersion string, ldb *leveldb.DB) *Model {
  83. m := &Model{
  84. cfg: cfg,
  85. db: ldb,
  86. deviceName: deviceName,
  87. clientName: clientName,
  88. clientVersion: clientVersion,
  89. folderCfgs: make(map[string]config.FolderConfiguration),
  90. folderFiles: make(map[string]*db.FileSet),
  91. folderDevices: make(map[string][]protocol.DeviceID),
  92. deviceFolders: make(map[protocol.DeviceID][]string),
  93. deviceStatRefs: make(map[protocol.DeviceID]*stats.DeviceStatisticsReference),
  94. folderIgnores: make(map[string]*ignore.Matcher),
  95. folderRunners: make(map[string]service),
  96. folderStatRefs: make(map[string]*stats.FolderStatisticsReference),
  97. protoConn: make(map[protocol.DeviceID]protocol.Connection),
  98. rawConn: make(map[protocol.DeviceID]io.Closer),
  99. deviceVer: make(map[protocol.DeviceID]string),
  100. finder: db.NewBlockFinder(ldb, cfg),
  101. progressEmitter: NewProgressEmitter(cfg),
  102. }
  103. if cfg.Options().ProgressUpdateIntervalS > -1 {
  104. go m.progressEmitter.Serve()
  105. }
  106. var timeout = 20 * 60 // seconds
  107. if t := os.Getenv("STDEADLOCKTIMEOUT"); len(t) > 0 {
  108. it, err := strconv.Atoi(t)
  109. if err == nil {
  110. timeout = it
  111. }
  112. }
  113. deadlockDetect(&m.fmut, time.Duration(timeout)*time.Second)
  114. deadlockDetect(&m.pmut, time.Duration(timeout)*time.Second)
  115. return m
  116. }
  117. // StartRW starts read/write processing on the current model. When in
  118. // read/write mode the model will attempt to keep in sync with the cluster by
  119. // pulling needed files from peer devices.
  120. func (m *Model) StartFolderRW(folder string) {
  121. m.fmut.Lock()
  122. cfg, ok := m.folderCfgs[folder]
  123. if !ok {
  124. panic("cannot start nonexistent folder " + folder)
  125. }
  126. _, ok = m.folderRunners[folder]
  127. if ok {
  128. panic("cannot start already running folder " + folder)
  129. }
  130. p := newRWFolder(m, cfg)
  131. m.folderRunners[folder] = p
  132. m.fmut.Unlock()
  133. if len(cfg.Versioning.Type) > 0 {
  134. factory, ok := versioner.Factories[cfg.Versioning.Type]
  135. if !ok {
  136. l.Fatalf("Requested versioning type %q that does not exist", cfg.Versioning.Type)
  137. }
  138. p.versioner = factory(folder, cfg.Path, cfg.Versioning.Params)
  139. }
  140. if cfg.LenientMtimes {
  141. l.Infof("Folder %q is running with LenientMtimes workaround. Syncing may not work properly.", folder)
  142. }
  143. go p.Serve()
  144. }
  145. // StartRO starts read only processing on the current model. When in
  146. // read only mode the model will announce files to the cluster but not
  147. // pull in any external changes.
  148. func (m *Model) StartFolderRO(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. s := newROFolder(m, folder, time.Duration(cfg.RescanIntervalS)*time.Second)
  159. m.folderRunners[folder] = s
  160. m.fmut.Unlock()
  161. go s.Serve()
  162. }
  163. type ConnectionInfo struct {
  164. protocol.Statistics
  165. Address string
  166. ClientVersion string
  167. }
  168. func (info ConnectionInfo) MarshalJSON() ([]byte, error) {
  169. return json.Marshal(map[string]interface{}{
  170. "at": info.At,
  171. "inBytesTotal": info.InBytesTotal,
  172. "outBytesTotal": info.OutBytesTotal,
  173. "address": info.Address,
  174. "clientVersion": info.ClientVersion,
  175. })
  176. }
  177. // ConnectionStats returns a map with connection statistics for each connected device.
  178. func (m *Model) ConnectionStats() map[string]ConnectionInfo {
  179. type remoteAddrer interface {
  180. RemoteAddr() net.Addr
  181. }
  182. m.pmut.RLock()
  183. m.fmut.RLock()
  184. var res = make(map[string]ConnectionInfo)
  185. for device, conn := range m.protoConn {
  186. ci := ConnectionInfo{
  187. Statistics: conn.Statistics(),
  188. ClientVersion: m.deviceVer[device],
  189. }
  190. if nc, ok := m.rawConn[device].(remoteAddrer); ok {
  191. ci.Address = nc.RemoteAddr().String()
  192. }
  193. res[device.String()] = ci
  194. }
  195. m.fmut.RUnlock()
  196. m.pmut.RUnlock()
  197. in, out := protocol.TotalInOut()
  198. res["total"] = ConnectionInfo{
  199. Statistics: protocol.Statistics{
  200. At: time.Now(),
  201. InBytesTotal: in,
  202. OutBytesTotal: out,
  203. },
  204. }
  205. return res
  206. }
  207. // Returns statistics about each device
  208. func (m *Model) DeviceStatistics() map[string]stats.DeviceStatistics {
  209. var res = make(map[string]stats.DeviceStatistics)
  210. for id := range m.cfg.Devices() {
  211. res[id.String()] = m.deviceStatRef(id).GetStatistics()
  212. }
  213. return res
  214. }
  215. // Returns statistics about each folder
  216. func (m *Model) FolderStatistics() map[string]stats.FolderStatistics {
  217. var res = make(map[string]stats.FolderStatistics)
  218. for id := range m.cfg.Folders() {
  219. res[id] = m.folderStatRef(id).GetStatistics()
  220. }
  221. return res
  222. }
  223. // Returns the completion status, in percent, for the given device and folder.
  224. func (m *Model) Completion(device protocol.DeviceID, folder string) float64 {
  225. var tot int64
  226. m.fmut.RLock()
  227. rf, ok := m.folderFiles[folder]
  228. m.fmut.RUnlock()
  229. if !ok {
  230. return 0 // Folder doesn't exist, so we hardly have any of it
  231. }
  232. rf.WithGlobalTruncated(func(f db.FileIntf) bool {
  233. if !f.IsDeleted() {
  234. tot += f.Size()
  235. }
  236. return true
  237. })
  238. if tot == 0 {
  239. return 100 // Folder is empty, so we have all of it
  240. }
  241. var need int64
  242. rf.WithNeedTruncated(device, func(f db.FileIntf) bool {
  243. if !f.IsDeleted() {
  244. need += f.Size()
  245. }
  246. return true
  247. })
  248. res := 100 * (1 - float64(need)/float64(tot))
  249. if debug {
  250. l.Debugf("%v Completion(%s, %q): %f (%d / %d)", m, device, folder, res, need, tot)
  251. }
  252. return res
  253. }
  254. func sizeOf(fs []protocol.FileInfo) (files, deleted int, bytes int64) {
  255. for _, f := range fs {
  256. fs, de, by := sizeOfFile(f)
  257. files += fs
  258. deleted += de
  259. bytes += by
  260. }
  261. return
  262. }
  263. func sizeOfFile(f db.FileIntf) (files, deleted int, bytes int64) {
  264. if !f.IsDeleted() {
  265. files++
  266. } else {
  267. deleted++
  268. }
  269. bytes += f.Size()
  270. return
  271. }
  272. // GlobalSize returns the number of files, deleted files and total bytes for all
  273. // files in the global model.
  274. func (m *Model) GlobalSize(folder string) (nfiles, deleted int, bytes int64) {
  275. m.fmut.RLock()
  276. defer m.fmut.RUnlock()
  277. if rf, ok := m.folderFiles[folder]; ok {
  278. rf.WithGlobalTruncated(func(f db.FileIntf) bool {
  279. fs, de, by := sizeOfFile(f)
  280. nfiles += fs
  281. deleted += de
  282. bytes += by
  283. return true
  284. })
  285. }
  286. return
  287. }
  288. // LocalSize returns the number of files, deleted files and total bytes for all
  289. // files in the local folder.
  290. func (m *Model) LocalSize(folder string) (nfiles, deleted int, bytes int64) {
  291. m.fmut.RLock()
  292. defer m.fmut.RUnlock()
  293. if rf, ok := m.folderFiles[folder]; ok {
  294. rf.WithHaveTruncated(protocol.LocalDeviceID, func(f db.FileIntf) bool {
  295. if f.IsInvalid() {
  296. return true
  297. }
  298. fs, de, by := sizeOfFile(f)
  299. nfiles += fs
  300. deleted += de
  301. bytes += by
  302. return true
  303. })
  304. }
  305. return
  306. }
  307. // NeedSize returns the number and total size of currently needed files.
  308. func (m *Model) NeedSize(folder string) (nfiles int, bytes int64) {
  309. m.fmut.RLock()
  310. defer m.fmut.RUnlock()
  311. if rf, ok := m.folderFiles[folder]; ok {
  312. rf.WithNeedTruncated(protocol.LocalDeviceID, func(f db.FileIntf) bool {
  313. fs, de, by := sizeOfFile(f)
  314. nfiles += fs + de
  315. bytes += by
  316. return true
  317. })
  318. }
  319. bytes -= m.progressEmitter.BytesCompleted(folder)
  320. if debug {
  321. l.Debugf("%v NeedSize(%q): %d %d", m, folder, nfiles, bytes)
  322. }
  323. return
  324. }
  325. // NeedFiles returns the list of currently needed files in progress, queued,
  326. // and to be queued on next puller iteration. Also takes a soft cap which is
  327. // only respected when adding files from the model rather than the runner queue.
  328. func (m *Model) NeedFolderFiles(folder string, max int) ([]db.FileInfoTruncated, []db.FileInfoTruncated, []db.FileInfoTruncated) {
  329. m.fmut.RLock()
  330. defer m.fmut.RUnlock()
  331. if rf, ok := m.folderFiles[folder]; ok {
  332. var progress, queued, rest []db.FileInfoTruncated
  333. var seen map[string]bool
  334. runner, ok := m.folderRunners[folder]
  335. if ok {
  336. progressNames, queuedNames := runner.Jobs()
  337. progress = make([]db.FileInfoTruncated, len(progressNames))
  338. queued = make([]db.FileInfoTruncated, len(queuedNames))
  339. seen = make(map[string]bool, len(progressNames)+len(queuedNames))
  340. for i, name := range progressNames {
  341. if f, ok := rf.GetGlobalTruncated(name); ok {
  342. progress[i] = f
  343. seen[name] = true
  344. }
  345. }
  346. for i, name := range queuedNames {
  347. if f, ok := rf.GetGlobalTruncated(name); ok {
  348. queued[i] = f
  349. seen[name] = true
  350. }
  351. }
  352. }
  353. left := max - len(progress) - len(queued)
  354. if max < 1 || left > 0 {
  355. rf.WithNeedTruncated(protocol.LocalDeviceID, func(f db.FileIntf) bool {
  356. left--
  357. ft := f.(db.FileInfoTruncated)
  358. if !seen[ft.Name] {
  359. rest = append(rest, ft)
  360. }
  361. return max < 1 || left > 0
  362. })
  363. }
  364. return progress, queued, rest
  365. }
  366. return nil, nil, nil
  367. }
  368. // Index is called when a new device is connected and we receive their full index.
  369. // Implements the protocol.Model interface.
  370. func (m *Model) Index(deviceID protocol.DeviceID, folder string, fs []protocol.FileInfo) {
  371. if debug {
  372. l.Debugf("IDX(in): %s %q: %d files", deviceID, folder, len(fs))
  373. }
  374. if !m.folderSharedWith(folder, deviceID) {
  375. events.Default.Log(events.FolderRejected, map[string]string{
  376. "folder": folder,
  377. "device": deviceID.String(),
  378. })
  379. 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, deviceID)
  380. return
  381. }
  382. m.fmut.RLock()
  383. files, ok := m.folderFiles[folder]
  384. m.fmut.RUnlock()
  385. if !ok {
  386. l.Fatalf("Index for nonexistant folder %q", folder)
  387. }
  388. for i := 0; i < len(fs); {
  389. lamport.Default.Tick(fs[i].Version)
  390. if fs[i].Flags&^protocol.FlagsAll != 0 {
  391. if debug {
  392. l.Debugln("dropping update for file with unknown bits set", fs[i])
  393. }
  394. fs[i] = fs[len(fs)-1]
  395. fs = fs[:len(fs)-1]
  396. } else if symlinkInvalid(fs[i].IsSymlink()) {
  397. if debug {
  398. l.Debugln("dropping update for unsupported symlink", fs[i])
  399. }
  400. fs[i] = fs[len(fs)-1]
  401. fs = fs[:len(fs)-1]
  402. } else {
  403. i++
  404. }
  405. }
  406. files.Replace(deviceID, fs)
  407. events.Default.Log(events.RemoteIndexUpdated, map[string]interface{}{
  408. "device": deviceID.String(),
  409. "folder": folder,
  410. "items": len(fs),
  411. "version": files.LocalVersion(deviceID),
  412. })
  413. }
  414. // IndexUpdate is called for incremental updates to connected devices' indexes.
  415. // Implements the protocol.Model interface.
  416. func (m *Model) IndexUpdate(deviceID protocol.DeviceID, folder string, fs []protocol.FileInfo) {
  417. if debug {
  418. l.Debugf("%v IDXUP(in): %s / %q: %d files", m, deviceID, folder, len(fs))
  419. }
  420. if !m.folderSharedWith(folder, deviceID) {
  421. l.Infof("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)
  422. return
  423. }
  424. m.fmut.RLock()
  425. files, ok := m.folderFiles[folder]
  426. m.fmut.RUnlock()
  427. if !ok {
  428. l.Fatalf("IndexUpdate for nonexistant folder %q", folder)
  429. }
  430. for i := 0; i < len(fs); {
  431. lamport.Default.Tick(fs[i].Version)
  432. if fs[i].Flags&^protocol.FlagsAll != 0 {
  433. if debug {
  434. l.Debugln("dropping update for file with unknown bits set", fs[i])
  435. }
  436. fs[i] = fs[len(fs)-1]
  437. fs = fs[:len(fs)-1]
  438. } else if symlinkInvalid(fs[i].IsSymlink()) {
  439. if debug {
  440. l.Debugln("dropping update for unsupported symlink", fs[i])
  441. }
  442. fs[i] = fs[len(fs)-1]
  443. fs = fs[:len(fs)-1]
  444. } else {
  445. i++
  446. }
  447. }
  448. files.Update(deviceID, fs)
  449. events.Default.Log(events.RemoteIndexUpdated, map[string]interface{}{
  450. "device": deviceID.String(),
  451. "folder": folder,
  452. "items": len(fs),
  453. "version": files.LocalVersion(deviceID),
  454. })
  455. }
  456. func (m *Model) folderSharedWith(folder string, deviceID protocol.DeviceID) bool {
  457. m.fmut.RLock()
  458. defer m.fmut.RUnlock()
  459. for _, nfolder := range m.deviceFolders[deviceID] {
  460. if nfolder == folder {
  461. return true
  462. }
  463. }
  464. return false
  465. }
  466. func (m *Model) ClusterConfig(deviceID protocol.DeviceID, cm protocol.ClusterConfigMessage) {
  467. m.pmut.Lock()
  468. if cm.ClientName == "syncthing" {
  469. m.deviceVer[deviceID] = cm.ClientVersion
  470. } else {
  471. m.deviceVer[deviceID] = cm.ClientName + " " + cm.ClientVersion
  472. }
  473. event := map[string]string{
  474. "id": deviceID.String(),
  475. "clientName": cm.ClientName,
  476. "clientVersion": cm.ClientVersion,
  477. }
  478. if conn, ok := m.rawConn[deviceID].(*tls.Conn); ok {
  479. event["addr"] = conn.RemoteAddr().String()
  480. }
  481. m.pmut.Unlock()
  482. events.Default.Log(events.DeviceConnected, event)
  483. l.Infof(`Device %s client is "%s %s"`, deviceID, cm.ClientName, cm.ClientVersion)
  484. var changed bool
  485. if name := cm.GetOption("name"); name != "" {
  486. l.Infof("Device %s name is %q", deviceID, name)
  487. device, ok := m.cfg.Devices()[deviceID]
  488. if ok && device.Name == "" {
  489. device.Name = name
  490. m.cfg.SetDevice(device)
  491. changed = true
  492. }
  493. }
  494. if m.cfg.Devices()[deviceID].Introducer {
  495. // This device is an introducer. Go through the announced lists of folders
  496. // and devices and add what we are missing.
  497. for _, folder := range cm.Folders {
  498. // If we don't have this folder yet, skip it. Ideally, we'd
  499. // offer up something in the GUI to create the folder, but for the
  500. // moment we only handle folders that we already have.
  501. if _, ok := m.folderDevices[folder.ID]; !ok {
  502. continue
  503. }
  504. nextDevice:
  505. for _, device := range folder.Devices {
  506. var id protocol.DeviceID
  507. copy(id[:], device.ID)
  508. if _, ok := m.cfg.Devices()[id]; !ok {
  509. // The device is currently unknown. Add it to the config.
  510. l.Infof("Adding device %v to config (vouched for by introducer %v)", id, deviceID)
  511. newDeviceCfg := config.DeviceConfiguration{
  512. DeviceID: id,
  513. Compression: m.cfg.Devices()[deviceID].Compression,
  514. Addresses: []string{"dynamic"},
  515. }
  516. // The introducers' introducers are also our introducers.
  517. if device.Flags&protocol.FlagIntroducer != 0 {
  518. l.Infof("Device %v is now also an introducer", id)
  519. newDeviceCfg.Introducer = true
  520. }
  521. m.cfg.SetDevice(newDeviceCfg)
  522. changed = true
  523. }
  524. for _, er := range m.deviceFolders[id] {
  525. if er == folder.ID {
  526. // We already share the folder with this device, so
  527. // nothing to do.
  528. continue nextDevice
  529. }
  530. }
  531. // We don't yet share this folder with this device. Add the device
  532. // to sharing list of the folder.
  533. l.Infof("Adding device %v to share %q (vouched for by introducer %v)", id, folder.ID, deviceID)
  534. m.deviceFolders[id] = append(m.deviceFolders[id], folder.ID)
  535. m.folderDevices[folder.ID] = append(m.folderDevices[folder.ID], id)
  536. folderCfg := m.cfg.Folders()[folder.ID]
  537. folderCfg.Devices = append(folderCfg.Devices, config.FolderDeviceConfiguration{
  538. DeviceID: id,
  539. })
  540. m.cfg.SetFolder(folderCfg)
  541. changed = true
  542. }
  543. }
  544. }
  545. if changed {
  546. m.cfg.Save()
  547. }
  548. }
  549. // Close removes the peer from the model and closes the underlying connection if possible.
  550. // Implements the protocol.Model interface.
  551. func (m *Model) Close(device protocol.DeviceID, err error) {
  552. l.Infof("Connection to %s closed: %v", device, err)
  553. events.Default.Log(events.DeviceDisconnected, map[string]string{
  554. "id": device.String(),
  555. "error": err.Error(),
  556. })
  557. m.pmut.Lock()
  558. m.fmut.RLock()
  559. for _, folder := range m.deviceFolders[device] {
  560. m.folderFiles[folder].Replace(device, nil)
  561. }
  562. m.fmut.RUnlock()
  563. conn, ok := m.rawConn[device]
  564. if ok {
  565. if conn, ok := conn.(*tls.Conn); ok {
  566. // If the underlying connection is a *tls.Conn, Close() does more
  567. // than it says on the tin. Specifically, it sends a TLS alert
  568. // message, which might block forever if the connection is dead
  569. // and we don't have a deadline site.
  570. conn.SetWriteDeadline(time.Now().Add(250 * time.Millisecond))
  571. }
  572. conn.Close()
  573. }
  574. delete(m.protoConn, device)
  575. delete(m.rawConn, device)
  576. delete(m.deviceVer, device)
  577. m.pmut.Unlock()
  578. }
  579. // Request returns the specified data segment by reading it from local disk.
  580. // Implements the protocol.Model interface.
  581. func (m *Model) Request(deviceID protocol.DeviceID, folder, name string, offset int64, size int) ([]byte, error) {
  582. if offset < 0 || size < 0 {
  583. return nil, ErrNoSuchFile
  584. }
  585. if !m.folderSharedWith(folder, deviceID) {
  586. l.Warnf("Request from %s for file %s in unshared folder %q", deviceID, name, folder)
  587. return nil, ErrNoSuchFile
  588. }
  589. // Verify that the requested file exists in the local model.
  590. m.fmut.RLock()
  591. folderFiles, ok := m.folderFiles[folder]
  592. m.fmut.RUnlock()
  593. if !ok {
  594. l.Warnf("Request from %s for file %s in nonexistent folder %q", deviceID, name, folder)
  595. return nil, ErrNoSuchFile
  596. }
  597. lf, ok := folderFiles.Get(protocol.LocalDeviceID, name)
  598. if !ok {
  599. return nil, ErrNoSuchFile
  600. }
  601. if lf.IsInvalid() || lf.IsDeleted() {
  602. if debug {
  603. l.Debugf("%v REQ(in): %s: %q / %q o=%d s=%d; invalid: %v", m, deviceID, folder, name, offset, size, lf)
  604. }
  605. return nil, ErrInvalid
  606. }
  607. if offset > lf.Size() {
  608. if debug {
  609. l.Debugf("%v REQ(in; nonexistent): %s: %q o=%d s=%d", m, deviceID, name, offset, size)
  610. }
  611. return nil, ErrNoSuchFile
  612. }
  613. if debug && deviceID != protocol.LocalDeviceID {
  614. l.Debugf("%v REQ(in): %s: %q / %q o=%d s=%d", m, deviceID, folder, name, offset, size)
  615. }
  616. m.fmut.RLock()
  617. fn := filepath.Join(m.folderCfgs[folder].Path, name)
  618. m.fmut.RUnlock()
  619. var reader io.ReaderAt
  620. var err error
  621. if lf.IsSymlink() {
  622. target, _, err := symlinks.Read(fn)
  623. if err != nil {
  624. return nil, err
  625. }
  626. reader = strings.NewReader(target)
  627. } else {
  628. // Cannot easily cache fd's because we might need to delete the file
  629. // at any moment.
  630. reader, err = os.Open(fn)
  631. if err != nil {
  632. return nil, err
  633. }
  634. defer reader.(*os.File).Close()
  635. }
  636. buf := make([]byte, size)
  637. _, err = reader.ReadAt(buf, offset)
  638. if err != nil {
  639. return nil, err
  640. }
  641. return buf, nil
  642. }
  643. // ReplaceLocal replaces the local folder index with the given list of files.
  644. func (m *Model) ReplaceLocal(folder string, fs []protocol.FileInfo) {
  645. m.fmut.RLock()
  646. m.folderFiles[folder].ReplaceWithDelete(protocol.LocalDeviceID, fs)
  647. m.fmut.RUnlock()
  648. }
  649. func (m *Model) CurrentFolderFile(folder string, file string) (protocol.FileInfo, bool) {
  650. m.fmut.RLock()
  651. f, ok := m.folderFiles[folder].Get(protocol.LocalDeviceID, file)
  652. m.fmut.RUnlock()
  653. return f, ok
  654. }
  655. func (m *Model) CurrentGlobalFile(folder string, file string) (protocol.FileInfo, bool) {
  656. m.fmut.RLock()
  657. f, ok := m.folderFiles[folder].GetGlobal(file)
  658. m.fmut.RUnlock()
  659. return f, ok
  660. }
  661. type cFiler struct {
  662. m *Model
  663. r string
  664. }
  665. // Implements scanner.CurrentFiler
  666. func (cf cFiler) CurrentFile(file string) (protocol.FileInfo, bool) {
  667. return cf.m.CurrentFolderFile(cf.r, file)
  668. }
  669. // ConnectedTo returns true if we are connected to the named device.
  670. func (m *Model) ConnectedTo(deviceID protocol.DeviceID) bool {
  671. m.pmut.RLock()
  672. _, ok := m.protoConn[deviceID]
  673. m.pmut.RUnlock()
  674. if ok {
  675. m.deviceWasSeen(deviceID)
  676. }
  677. return ok
  678. }
  679. func (m *Model) GetIgnores(folder string) ([]string, []string, error) {
  680. var lines []string
  681. m.fmut.RLock()
  682. cfg, ok := m.folderCfgs[folder]
  683. m.fmut.RUnlock()
  684. if !ok {
  685. return lines, nil, fmt.Errorf("Folder %s does not exist", folder)
  686. }
  687. fd, err := os.Open(filepath.Join(cfg.Path, ".stignore"))
  688. if err != nil {
  689. if os.IsNotExist(err) {
  690. return lines, nil, nil
  691. }
  692. l.Warnln("Loading .stignore:", err)
  693. return lines, nil, err
  694. }
  695. defer fd.Close()
  696. scanner := bufio.NewScanner(fd)
  697. for scanner.Scan() {
  698. lines = append(lines, strings.TrimSpace(scanner.Text()))
  699. }
  700. m.fmut.RLock()
  701. var patterns []string
  702. if matcher := m.folderIgnores[folder]; matcher != nil {
  703. patterns = matcher.Patterns()
  704. }
  705. m.fmut.RUnlock()
  706. return lines, patterns, nil
  707. }
  708. func (m *Model) SetIgnores(folder string, content []string) error {
  709. cfg, ok := m.folderCfgs[folder]
  710. if !ok {
  711. return fmt.Errorf("Folder %s does not exist", folder)
  712. }
  713. fd, err := ioutil.TempFile(cfg.Path, ".syncthing.stignore-"+folder)
  714. if err != nil {
  715. l.Warnln("Saving .stignore:", err)
  716. return err
  717. }
  718. defer os.Remove(fd.Name())
  719. for _, line := range content {
  720. _, err = fmt.Fprintln(fd, line)
  721. if err != nil {
  722. l.Warnln("Saving .stignore:", err)
  723. return err
  724. }
  725. }
  726. err = fd.Close()
  727. if err != nil {
  728. l.Warnln("Saving .stignore:", err)
  729. return err
  730. }
  731. file := filepath.Join(cfg.Path, ".stignore")
  732. err = osutil.Rename(fd.Name(), file)
  733. if err != nil {
  734. l.Warnln("Saving .stignore:", err)
  735. return err
  736. }
  737. return m.ScanFolder(folder)
  738. }
  739. // AddConnection adds a new peer connection to the model. An initial index will
  740. // be sent to the connected peer, thereafter index updates whenever the local
  741. // folder changes.
  742. func (m *Model) AddConnection(rawConn io.Closer, protoConn protocol.Connection) {
  743. deviceID := protoConn.ID()
  744. m.pmut.Lock()
  745. if _, ok := m.protoConn[deviceID]; ok {
  746. panic("add existing device")
  747. }
  748. m.protoConn[deviceID] = protoConn
  749. if _, ok := m.rawConn[deviceID]; ok {
  750. panic("add existing device")
  751. }
  752. m.rawConn[deviceID] = rawConn
  753. cm := m.clusterConfig(deviceID)
  754. protoConn.ClusterConfig(cm)
  755. m.fmut.RLock()
  756. for _, folder := range m.deviceFolders[deviceID] {
  757. fs := m.folderFiles[folder]
  758. go sendIndexes(protoConn, folder, fs, m.folderIgnores[folder])
  759. }
  760. m.fmut.RUnlock()
  761. m.pmut.Unlock()
  762. m.deviceWasSeen(deviceID)
  763. }
  764. func (m *Model) deviceStatRef(deviceID protocol.DeviceID) *stats.DeviceStatisticsReference {
  765. m.fmut.Lock()
  766. defer m.fmut.Unlock()
  767. if sr, ok := m.deviceStatRefs[deviceID]; ok {
  768. return sr
  769. }
  770. sr := stats.NewDeviceStatisticsReference(m.db, deviceID)
  771. m.deviceStatRefs[deviceID] = sr
  772. return sr
  773. }
  774. func (m *Model) deviceWasSeen(deviceID protocol.DeviceID) {
  775. m.deviceStatRef(deviceID).WasSeen()
  776. }
  777. func (m *Model) folderStatRef(folder string) *stats.FolderStatisticsReference {
  778. m.fmut.Lock()
  779. defer m.fmut.Unlock()
  780. sr, ok := m.folderStatRefs[folder]
  781. if !ok {
  782. sr = stats.NewFolderStatisticsReference(m.db, folder)
  783. m.folderStatRefs[folder] = sr
  784. }
  785. return sr
  786. }
  787. func (m *Model) receivedFile(folder, filename string) {
  788. m.folderStatRef(folder).ReceivedFile(filename)
  789. }
  790. func sendIndexes(conn protocol.Connection, folder string, fs *db.FileSet, ignores *ignore.Matcher) {
  791. deviceID := conn.ID()
  792. name := conn.Name()
  793. var err error
  794. if debug {
  795. l.Debugf("sendIndexes for %s-%s/%q starting", deviceID, name, folder)
  796. }
  797. minLocalVer, err := sendIndexTo(true, 0, conn, folder, fs, ignores)
  798. for err == nil {
  799. time.Sleep(5 * time.Second)
  800. if fs.LocalVersion(protocol.LocalDeviceID) <= minLocalVer {
  801. continue
  802. }
  803. minLocalVer, err = sendIndexTo(false, minLocalVer, conn, folder, fs, ignores)
  804. }
  805. if debug {
  806. l.Debugf("sendIndexes for %s-%s/%q exiting: %v", deviceID, name, folder, err)
  807. }
  808. }
  809. func sendIndexTo(initial bool, minLocalVer int64, conn protocol.Connection, folder string, fs *db.FileSet, ignores *ignore.Matcher) (int64, error) {
  810. deviceID := conn.ID()
  811. name := conn.Name()
  812. batch := make([]protocol.FileInfo, 0, indexBatchSize)
  813. currentBatchSize := 0
  814. maxLocalVer := int64(0)
  815. var err error
  816. fs.WithHave(protocol.LocalDeviceID, func(fi db.FileIntf) bool {
  817. f := fi.(protocol.FileInfo)
  818. if f.LocalVersion <= minLocalVer {
  819. return true
  820. }
  821. if f.LocalVersion > maxLocalVer {
  822. maxLocalVer = f.LocalVersion
  823. }
  824. if (ignores != nil && ignores.Match(f.Name)) || symlinkInvalid(f.IsSymlink()) {
  825. if debug {
  826. l.Debugln("not sending update for ignored/unsupported symlink", f)
  827. }
  828. return true
  829. }
  830. if len(batch) == indexBatchSize || currentBatchSize > indexTargetSize {
  831. if initial {
  832. if err = conn.Index(folder, batch); err != nil {
  833. return false
  834. }
  835. if debug {
  836. l.Debugf("sendIndexes for %s-%s/%q: %d files (<%d bytes) (initial index)", deviceID, name, folder, len(batch), currentBatchSize)
  837. }
  838. initial = false
  839. } else {
  840. if err = conn.IndexUpdate(folder, batch); err != nil {
  841. return false
  842. }
  843. if debug {
  844. l.Debugf("sendIndexes for %s-%s/%q: %d files (<%d bytes) (batched update)", deviceID, name, folder, len(batch), currentBatchSize)
  845. }
  846. }
  847. batch = make([]protocol.FileInfo, 0, indexBatchSize)
  848. currentBatchSize = 0
  849. }
  850. batch = append(batch, f)
  851. currentBatchSize += indexPerFileSize + len(f.Blocks)*IndexPerBlockSize
  852. return true
  853. })
  854. if initial && err == nil {
  855. err = conn.Index(folder, batch)
  856. if debug && err == nil {
  857. l.Debugf("sendIndexes for %s-%s/%q: %d files (small initial index)", deviceID, name, folder, len(batch))
  858. }
  859. } else if len(batch) > 0 && err == nil {
  860. err = conn.IndexUpdate(folder, batch)
  861. if debug && err == nil {
  862. l.Debugf("sendIndexes for %s-%s/%q: %d files (last batch)", deviceID, name, folder, len(batch))
  863. }
  864. }
  865. return maxLocalVer, err
  866. }
  867. func (m *Model) updateLocal(folder string, f protocol.FileInfo) {
  868. f.LocalVersion = 0
  869. m.fmut.RLock()
  870. m.folderFiles[folder].Update(protocol.LocalDeviceID, []protocol.FileInfo{f})
  871. m.fmut.RUnlock()
  872. events.Default.Log(events.LocalIndexUpdated, map[string]interface{}{
  873. "folder": folder,
  874. "name": f.Name,
  875. "modified": time.Unix(f.Modified, 0),
  876. "flags": fmt.Sprintf("0%o", f.Flags),
  877. "size": f.Size(),
  878. })
  879. }
  880. func (m *Model) requestGlobal(deviceID protocol.DeviceID, folder, name string, offset int64, size int, hash []byte) ([]byte, error) {
  881. m.pmut.RLock()
  882. nc, ok := m.protoConn[deviceID]
  883. m.pmut.RUnlock()
  884. if !ok {
  885. return nil, fmt.Errorf("requestGlobal: no such device: %s", deviceID)
  886. }
  887. if debug {
  888. l.Debugf("%v REQ(out): %s: %q / %q o=%d s=%d h=%x", m, deviceID, folder, name, offset, size, hash)
  889. }
  890. return nc.Request(folder, name, offset, size)
  891. }
  892. func (m *Model) AddFolder(cfg config.FolderConfiguration) {
  893. if m.started {
  894. panic("cannot add folder to started model")
  895. }
  896. if len(cfg.ID) == 0 {
  897. panic("cannot add empty folder id")
  898. }
  899. m.fmut.Lock()
  900. m.folderCfgs[cfg.ID] = cfg
  901. m.folderFiles[cfg.ID] = db.NewFileSet(cfg.ID, m.db)
  902. m.folderDevices[cfg.ID] = make([]protocol.DeviceID, len(cfg.Devices))
  903. for i, device := range cfg.Devices {
  904. m.folderDevices[cfg.ID][i] = device.DeviceID
  905. m.deviceFolders[device.DeviceID] = append(m.deviceFolders[device.DeviceID], cfg.ID)
  906. }
  907. ignores := ignore.New(m.cfg.Options().CacheIgnoredFiles)
  908. _ = ignores.Load(filepath.Join(cfg.Path, ".stignore")) // Ignore error, there might not be an .stignore
  909. m.folderIgnores[cfg.ID] = ignores
  910. m.addedFolder = true
  911. m.fmut.Unlock()
  912. }
  913. func (m *Model) ScanFolders() map[string]error {
  914. m.fmut.RLock()
  915. var folders = make([]string, 0, len(m.folderCfgs))
  916. for folder := range m.folderCfgs {
  917. folders = append(folders, folder)
  918. }
  919. m.fmut.RUnlock()
  920. var errors = make(map[string]error, len(m.folderCfgs))
  921. var errorsMut sync.Mutex
  922. var wg sync.WaitGroup
  923. wg.Add(len(folders))
  924. for _, folder := range folders {
  925. folder := folder
  926. go func() {
  927. err := m.ScanFolder(folder)
  928. if err != nil {
  929. errorsMut.Lock()
  930. errors[folder] = err
  931. errorsMut.Unlock()
  932. m.cfg.InvalidateFolder(folder, err.Error())
  933. }
  934. wg.Done()
  935. }()
  936. }
  937. wg.Wait()
  938. return errors
  939. }
  940. func (m *Model) ScanFolder(folder string) error {
  941. return m.ScanFolderSub(folder, "")
  942. }
  943. func (m *Model) ScanFolderSub(folder, sub string) error {
  944. sub = osutil.NativeFilename(sub)
  945. if p := filepath.Clean(filepath.Join(folder, sub)); !strings.HasPrefix(p, folder) {
  946. return errors.New("invalid subpath")
  947. }
  948. m.fmut.Lock()
  949. fs := m.folderFiles[folder]
  950. folderCfg := m.folderCfgs[folder]
  951. ignores := m.folderIgnores[folder]
  952. runner, ok := m.folderRunners[folder]
  953. m.fmut.Unlock()
  954. // Folders are added to folderRunners only when they are started. We can't
  955. // scan them before they have started, so that's what we need to check for
  956. // here.
  957. if !ok {
  958. return errors.New("no such folder")
  959. }
  960. _ = ignores.Load(filepath.Join(folderCfg.Path, ".stignore")) // Ignore error, there might not be an .stignore
  961. // Required to make sure that we start indexing at a directory we're already
  962. // aware off.
  963. for sub != "" {
  964. if _, ok = fs.Get(protocol.LocalDeviceID, sub); ok {
  965. break
  966. }
  967. sub = filepath.Dir(sub)
  968. if sub == "." || sub == string(filepath.Separator) {
  969. sub = ""
  970. }
  971. }
  972. w := &scanner.Walker{
  973. Dir: folderCfg.Path,
  974. Sub: sub,
  975. Matcher: ignores,
  976. BlockSize: protocol.BlockSize,
  977. TempNamer: defTempNamer,
  978. TempLifetime: time.Duration(m.cfg.Options().KeepTemporariesH) * time.Hour,
  979. CurrentFiler: cFiler{m, folder},
  980. IgnorePerms: folderCfg.IgnorePerms,
  981. AutoNormalize: folderCfg.AutoNormalize,
  982. Hashers: folderCfg.Hashers,
  983. }
  984. runner.setState(FolderScanning)
  985. fchan, err := w.Walk()
  986. if err != nil {
  987. return err
  988. }
  989. batchSize := 100
  990. batch := make([]protocol.FileInfo, 0, batchSize)
  991. for f := range fchan {
  992. events.Default.Log(events.LocalIndexUpdated, map[string]interface{}{
  993. "folder": folder,
  994. "name": f.Name,
  995. "modified": time.Unix(f.Modified, 0),
  996. "flags": fmt.Sprintf("0%o", f.Flags),
  997. "size": f.Size(),
  998. })
  999. if len(batch) == batchSize {
  1000. fs.Update(protocol.LocalDeviceID, batch)
  1001. batch = batch[:0]
  1002. }
  1003. batch = append(batch, f)
  1004. }
  1005. if len(batch) > 0 {
  1006. fs.Update(protocol.LocalDeviceID, batch)
  1007. }
  1008. batch = batch[:0]
  1009. // TODO: We should limit the Have scanning to start at sub
  1010. seenPrefix := false
  1011. fs.WithHaveTruncated(protocol.LocalDeviceID, func(fi db.FileIntf) bool {
  1012. f := fi.(db.FileInfoTruncated)
  1013. if !strings.HasPrefix(f.Name, sub) {
  1014. // Return true so that we keep iterating, until we get to the part
  1015. // of the tree we are interested in. Then return false so we stop
  1016. // iterating when we've passed the end of the subtree.
  1017. return !seenPrefix
  1018. }
  1019. seenPrefix = true
  1020. if !f.IsDeleted() {
  1021. if f.IsInvalid() {
  1022. return true
  1023. }
  1024. if len(batch) == batchSize {
  1025. fs.Update(protocol.LocalDeviceID, batch)
  1026. batch = batch[:0]
  1027. }
  1028. if (ignores != nil && ignores.Match(f.Name)) || symlinkInvalid(f.IsSymlink()) {
  1029. // File has been ignored or an unsupported symlink. Set invalid bit.
  1030. if debug {
  1031. l.Debugln("setting invalid bit on ignored", f)
  1032. }
  1033. nf := protocol.FileInfo{
  1034. Name: f.Name,
  1035. Flags: f.Flags | protocol.FlagInvalid,
  1036. Modified: f.Modified,
  1037. Version: f.Version, // The file is still the same, so don't bump version
  1038. }
  1039. events.Default.Log(events.LocalIndexUpdated, map[string]interface{}{
  1040. "folder": folder,
  1041. "name": f.Name,
  1042. "modified": time.Unix(f.Modified, 0),
  1043. "flags": fmt.Sprintf("0%o", f.Flags),
  1044. "size": f.Size(),
  1045. })
  1046. batch = append(batch, nf)
  1047. } else if _, err := os.Lstat(filepath.Join(folderCfg.Path, f.Name)); err != nil {
  1048. // File has been deleted.
  1049. // We don't specifically verify that the error is
  1050. // os.IsNotExist because there is a corner case when a
  1051. // directory is suddenly transformed into a file. When that
  1052. // happens, files that were in the directory (that is now a
  1053. // file) are deleted but will return a confusing error ("not a
  1054. // directory") when we try to Lstat() them.
  1055. nf := protocol.FileInfo{
  1056. Name: f.Name,
  1057. Flags: f.Flags | protocol.FlagDeleted,
  1058. Modified: f.Modified,
  1059. Version: lamport.Default.Tick(f.Version),
  1060. }
  1061. events.Default.Log(events.LocalIndexUpdated, map[string]interface{}{
  1062. "folder": folder,
  1063. "name": f.Name,
  1064. "modified": time.Unix(f.Modified, 0),
  1065. "flags": fmt.Sprintf("0%o", f.Flags),
  1066. "size": f.Size(),
  1067. })
  1068. batch = append(batch, nf)
  1069. }
  1070. }
  1071. return true
  1072. })
  1073. if len(batch) > 0 {
  1074. fs.Update(protocol.LocalDeviceID, batch)
  1075. }
  1076. runner.setState(FolderIdle)
  1077. return nil
  1078. }
  1079. // clusterConfig returns a ClusterConfigMessage that is correct for the given peer device
  1080. func (m *Model) clusterConfig(device protocol.DeviceID) protocol.ClusterConfigMessage {
  1081. cm := protocol.ClusterConfigMessage{
  1082. ClientName: m.clientName,
  1083. ClientVersion: m.clientVersion,
  1084. Options: []protocol.Option{
  1085. {
  1086. Key: "name",
  1087. Value: m.deviceName,
  1088. },
  1089. },
  1090. }
  1091. m.fmut.RLock()
  1092. for _, folder := range m.deviceFolders[device] {
  1093. cr := protocol.Folder{
  1094. ID: folder,
  1095. }
  1096. for _, device := range m.folderDevices[folder] {
  1097. // DeviceID is a value type, but with an underlying array. Copy it
  1098. // so we don't grab aliases to the same array later on in device[:]
  1099. device := device
  1100. // TODO: Set read only bit when relevant
  1101. cn := protocol.Device{
  1102. ID: device[:],
  1103. Flags: protocol.FlagShareTrusted,
  1104. }
  1105. if deviceCfg := m.cfg.Devices()[device]; deviceCfg.Introducer {
  1106. cn.Flags |= protocol.FlagIntroducer
  1107. }
  1108. cr.Devices = append(cr.Devices, cn)
  1109. }
  1110. cm.Folders = append(cm.Folders, cr)
  1111. }
  1112. m.fmut.RUnlock()
  1113. return cm
  1114. }
  1115. func (m *Model) State(folder string) (string, time.Time) {
  1116. m.fmut.RLock()
  1117. runner, ok := m.folderRunners[folder]
  1118. m.fmut.RUnlock()
  1119. if !ok {
  1120. return "", time.Time{}
  1121. }
  1122. state, changed := runner.getState()
  1123. return state.String(), changed
  1124. }
  1125. func (m *Model) Override(folder string) {
  1126. m.fmut.RLock()
  1127. fs := m.folderFiles[folder]
  1128. runner := m.folderRunners[folder]
  1129. m.fmut.RUnlock()
  1130. runner.setState(FolderScanning)
  1131. batch := make([]protocol.FileInfo, 0, indexBatchSize)
  1132. fs.WithNeed(protocol.LocalDeviceID, func(fi db.FileIntf) bool {
  1133. need := fi.(protocol.FileInfo)
  1134. if len(batch) == indexBatchSize {
  1135. fs.Update(protocol.LocalDeviceID, batch)
  1136. batch = batch[:0]
  1137. }
  1138. have, ok := fs.Get(protocol.LocalDeviceID, need.Name)
  1139. if !ok || have.Name != need.Name {
  1140. // We are missing the file
  1141. need.Flags |= protocol.FlagDeleted
  1142. need.Blocks = nil
  1143. } else {
  1144. // We have the file, replace with our version
  1145. need = have
  1146. }
  1147. need.Version = lamport.Default.Tick(need.Version)
  1148. need.LocalVersion = 0
  1149. batch = append(batch, need)
  1150. return true
  1151. })
  1152. if len(batch) > 0 {
  1153. fs.Update(protocol.LocalDeviceID, batch)
  1154. }
  1155. runner.setState(FolderIdle)
  1156. }
  1157. // CurrentLocalVersion returns the change version for the given folder.
  1158. // This is guaranteed to increment if the contents of the local folder has
  1159. // changed.
  1160. func (m *Model) CurrentLocalVersion(folder string) int64 {
  1161. m.fmut.RLock()
  1162. fs, ok := m.folderFiles[folder]
  1163. m.fmut.RUnlock()
  1164. if !ok {
  1165. // The folder might not exist, since this can be called with a user
  1166. // specified folder name from the REST interface.
  1167. return 0
  1168. }
  1169. return fs.LocalVersion(protocol.LocalDeviceID)
  1170. }
  1171. // RemoteLocalVersion returns the change version for the given folder, as
  1172. // sent by remote peers. This is guaranteed to increment if the contents of
  1173. // the remote or global folder has changed.
  1174. func (m *Model) RemoteLocalVersion(folder string) int64 {
  1175. m.fmut.RLock()
  1176. defer m.fmut.RUnlock()
  1177. fs, ok := m.folderFiles[folder]
  1178. if !ok {
  1179. // The folder might not exist, since this can be called with a user
  1180. // specified folder name from the REST interface.
  1181. return 0
  1182. }
  1183. var ver int64
  1184. for _, n := range m.folderDevices[folder] {
  1185. ver += fs.LocalVersion(n)
  1186. }
  1187. return ver
  1188. }
  1189. func (m *Model) GlobalDirectoryTree(folder, prefix string, levels int, dirsonly bool) map[string]interface{} {
  1190. m.fmut.RLock()
  1191. files, ok := m.folderFiles[folder]
  1192. m.fmut.RUnlock()
  1193. if !ok {
  1194. return nil
  1195. }
  1196. output := make(map[string]interface{})
  1197. sep := string(filepath.Separator)
  1198. prefix = osutil.NativeFilename(prefix)
  1199. if prefix != "" && !strings.HasSuffix(prefix, sep) {
  1200. prefix = prefix + sep
  1201. }
  1202. files.WithPrefixedGlobalTruncated(prefix, func(fi db.FileIntf) bool {
  1203. f := fi.(db.FileInfoTruncated)
  1204. if f.IsInvalid() || f.IsDeleted() || f.Name == prefix {
  1205. return true
  1206. }
  1207. f.Name = strings.Replace(f.Name, prefix, "", 1)
  1208. var dir, base string
  1209. if f.IsDirectory() && !f.IsSymlink() {
  1210. dir = f.Name
  1211. } else {
  1212. dir = filepath.Dir(f.Name)
  1213. base = filepath.Base(f.Name)
  1214. }
  1215. if levels > -1 && strings.Count(f.Name, sep) > levels {
  1216. return true
  1217. }
  1218. last := output
  1219. if dir != "." {
  1220. for _, path := range strings.Split(dir, sep) {
  1221. directory, ok := last[path]
  1222. if !ok {
  1223. newdir := make(map[string]interface{})
  1224. last[path] = newdir
  1225. last = newdir
  1226. } else {
  1227. last = directory.(map[string]interface{})
  1228. }
  1229. }
  1230. }
  1231. if !dirsonly && base != "" {
  1232. last[base] = []int64{
  1233. f.Modified, f.Size(),
  1234. }
  1235. }
  1236. return true
  1237. })
  1238. return output
  1239. }
  1240. func (m *Model) Availability(folder, file string) []protocol.DeviceID {
  1241. // Acquire this lock first, as the value returned from foldersFiles can
  1242. // get heavily modified on Close()
  1243. m.pmut.RLock()
  1244. defer m.pmut.RUnlock()
  1245. m.fmut.RLock()
  1246. fs, ok := m.folderFiles[folder]
  1247. m.fmut.RUnlock()
  1248. if !ok {
  1249. return nil
  1250. }
  1251. availableDevices := []protocol.DeviceID{}
  1252. for _, device := range fs.Availability(file) {
  1253. _, ok := m.protoConn[device]
  1254. if ok {
  1255. availableDevices = append(availableDevices, device)
  1256. }
  1257. }
  1258. return availableDevices
  1259. }
  1260. // Bump the given files priority in the job queue
  1261. func (m *Model) BringToFront(folder, file string) {
  1262. m.pmut.RLock()
  1263. defer m.pmut.RUnlock()
  1264. runner, ok := m.folderRunners[folder]
  1265. if ok {
  1266. runner.BringToFront(file)
  1267. }
  1268. }
  1269. func (m *Model) String() string {
  1270. return fmt.Sprintf("model@%p", m)
  1271. }
  1272. func symlinkInvalid(isLink bool) bool {
  1273. if !symlinks.Supported && isLink {
  1274. SymlinkWarning.Do(func() {
  1275. l.Warnln("Symlinks are disabled, unsupported or require Administrator priviledges. This might cause your folder to appear out of sync.")
  1276. })
  1277. return true
  1278. }
  1279. return false
  1280. }