model.go 37 KB

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