model.go 36 KB

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