model.go 37 KB

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