model.go 37 KB

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