model.go 37 KB

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