model.go 36 KB

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