model.go 36 KB

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