model.go 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396
  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. ignores, _ := m.folderIgnores[folder]
  399. m.fmut.RUnlock()
  400. if !ok {
  401. l.Fatalf("Index for nonexistant folder %q", folder)
  402. }
  403. for i := 0; i < len(fs); {
  404. lamport.Default.Tick(fs[i].Version)
  405. if (ignores != nil && ignores.Match(fs[i].Name)) || symlinkInvalid(fs[i].IsSymlink()) {
  406. if debug {
  407. l.Debugln("dropping update for ignored/unsupported symlink", fs[i])
  408. }
  409. fs[i] = fs[len(fs)-1]
  410. fs = fs[:len(fs)-1]
  411. } else {
  412. i++
  413. }
  414. }
  415. files.Replace(deviceID, fs)
  416. events.Default.Log(events.RemoteIndexUpdated, map[string]interface{}{
  417. "device": deviceID.String(),
  418. "folder": folder,
  419. "items": len(fs),
  420. "version": files.LocalVersion(deviceID),
  421. })
  422. }
  423. // IndexUpdate is called for incremental updates to connected devices' indexes.
  424. // Implements the protocol.Model interface.
  425. func (m *Model) IndexUpdate(deviceID protocol.DeviceID, folder string, fs []protocol.FileInfo) {
  426. if debug {
  427. l.Debugf("%v IDXUP(in): %s / %q: %d files", m, deviceID, folder, len(fs))
  428. }
  429. if !m.folderSharedWith(folder, deviceID) {
  430. 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)
  431. return
  432. }
  433. m.fmut.RLock()
  434. files, ok := m.folderFiles[folder]
  435. ignores, _ := m.folderIgnores[folder]
  436. m.fmut.RUnlock()
  437. if !ok {
  438. l.Fatalf("IndexUpdate for nonexistant folder %q", folder)
  439. }
  440. for i := 0; i < len(fs); {
  441. lamport.Default.Tick(fs[i].Version)
  442. if (ignores != nil && ignores.Match(fs[i].Name)) || symlinkInvalid(fs[i].IsSymlink()) {
  443. if debug {
  444. l.Debugln("dropping update for ignored/unsupported symlink", fs[i])
  445. }
  446. fs[i] = fs[len(fs)-1]
  447. fs = fs[:len(fs)-1]
  448. } else {
  449. i++
  450. }
  451. }
  452. files.Update(deviceID, fs)
  453. events.Default.Log(events.RemoteIndexUpdated, map[string]interface{}{
  454. "device": deviceID.String(),
  455. "folder": folder,
  456. "items": len(fs),
  457. "version": files.LocalVersion(deviceID),
  458. })
  459. }
  460. func (m *Model) folderSharedWith(folder string, deviceID protocol.DeviceID) bool {
  461. m.fmut.RLock()
  462. defer m.fmut.RUnlock()
  463. for _, nfolder := range m.deviceFolders[deviceID] {
  464. if nfolder == folder {
  465. return true
  466. }
  467. }
  468. return false
  469. }
  470. func (m *Model) ClusterConfig(deviceID protocol.DeviceID, cm protocol.ClusterConfigMessage) {
  471. m.pmut.Lock()
  472. if cm.ClientName == "syncthing" {
  473. m.deviceVer[deviceID] = cm.ClientVersion
  474. } else {
  475. m.deviceVer[deviceID] = cm.ClientName + " " + cm.ClientVersion
  476. }
  477. m.pmut.Unlock()
  478. l.Infof(`Device %s client is "%s %s"`, deviceID, cm.ClientName, cm.ClientVersion)
  479. var changed bool
  480. if name := cm.GetOption("name"); name != "" {
  481. l.Infof("Device %s name is %q", deviceID, name)
  482. device, ok := m.cfg.Devices()[deviceID]
  483. if ok && device.Name == "" {
  484. device.Name = name
  485. m.cfg.SetDevice(device)
  486. changed = true
  487. }
  488. }
  489. if m.cfg.Devices()[deviceID].Introducer {
  490. // This device is an introducer. Go through the announced lists of folders
  491. // and devices and add what we are missing.
  492. for _, folder := range cm.Folders {
  493. // If we don't have this folder yet, skip it. Ideally, we'd
  494. // offer up something in the GUI to create the folder, but for the
  495. // moment we only handle folders that we already have.
  496. if _, ok := m.folderDevices[folder.ID]; !ok {
  497. continue
  498. }
  499. nextDevice:
  500. for _, device := range folder.Devices {
  501. var id protocol.DeviceID
  502. copy(id[:], device.ID)
  503. if _, ok := m.cfg.Devices()[id]; !ok {
  504. // The device is currently unknown. Add it to the config.
  505. l.Infof("Adding device %v to config (vouched for by introducer %v)", id, deviceID)
  506. newDeviceCfg := config.DeviceConfiguration{
  507. DeviceID: id,
  508. Compression: m.cfg.Devices()[deviceID].Compression,
  509. Addresses: []string{"dynamic"},
  510. }
  511. // The introducers' introducers are also our introducers.
  512. if device.Flags&protocol.FlagIntroducer != 0 {
  513. l.Infof("Device %v is now also an introducer", id)
  514. newDeviceCfg.Introducer = true
  515. }
  516. m.cfg.SetDevice(newDeviceCfg)
  517. changed = true
  518. }
  519. for _, er := range m.deviceFolders[id] {
  520. if er == folder.ID {
  521. // We already share the folder with this device, so
  522. // nothing to do.
  523. continue nextDevice
  524. }
  525. }
  526. // We don't yet share this folder with this device. Add the device
  527. // to sharing list of the folder.
  528. l.Infof("Adding device %v to share %q (vouched for by introducer %v)", id, folder.ID, deviceID)
  529. m.deviceFolders[id] = append(m.deviceFolders[id], folder.ID)
  530. m.folderDevices[folder.ID] = append(m.folderDevices[folder.ID], id)
  531. folderCfg := m.cfg.Folders()[folder.ID]
  532. folderCfg.Devices = append(folderCfg.Devices, config.FolderDeviceConfiguration{
  533. DeviceID: id,
  534. })
  535. m.cfg.SetFolder(folderCfg)
  536. changed = true
  537. }
  538. }
  539. }
  540. if changed {
  541. m.cfg.Save()
  542. }
  543. }
  544. // Close removes the peer from the model and closes the underlying connection if possible.
  545. // Implements the protocol.Model interface.
  546. func (m *Model) Close(device protocol.DeviceID, err error) {
  547. l.Infof("Connection to %s closed: %v", device, err)
  548. events.Default.Log(events.DeviceDisconnected, map[string]string{
  549. "id": device.String(),
  550. "error": err.Error(),
  551. })
  552. m.pmut.Lock()
  553. m.fmut.RLock()
  554. for _, folder := range m.deviceFolders[device] {
  555. m.folderFiles[folder].Replace(device, nil)
  556. }
  557. m.fmut.RUnlock()
  558. conn, ok := m.rawConn[device]
  559. if ok {
  560. if conn, ok := conn.(*tls.Conn); ok {
  561. // If the underlying connection is a *tls.Conn, Close() does more
  562. // than it says on the tin. Specifically, it sends a TLS alert
  563. // message, which might block forever if the connection is dead
  564. // and we don't have a deadline site.
  565. conn.SetWriteDeadline(time.Now().Add(250 * time.Millisecond))
  566. }
  567. conn.Close()
  568. }
  569. delete(m.protoConn, device)
  570. delete(m.rawConn, device)
  571. delete(m.deviceVer, device)
  572. m.pmut.Unlock()
  573. }
  574. // Request returns the specified data segment by reading it from local disk.
  575. // Implements the protocol.Model interface.
  576. func (m *Model) Request(deviceID protocol.DeviceID, folder, name string, offset int64, size int) ([]byte, error) {
  577. // Verify that the requested file exists in the local model.
  578. m.fmut.RLock()
  579. r, ok := m.folderFiles[folder]
  580. m.fmut.RUnlock()
  581. if !ok {
  582. l.Warnf("Request from %s for file %s in nonexistent folder %q", deviceID, name, folder)
  583. return nil, ErrNoSuchFile
  584. }
  585. lf := r.Get(protocol.LocalDeviceID, name)
  586. if lf.IsInvalid() || lf.IsDeleted() {
  587. if debug {
  588. l.Debugf("%v REQ(in): %s: %q / %q o=%d s=%d; invalid: %v", m, deviceID, folder, name, offset, size, lf)
  589. }
  590. return nil, ErrInvalid
  591. }
  592. if offset > lf.Size() {
  593. if debug {
  594. l.Debugf("%v REQ(in; nonexistent): %s: %q o=%d s=%d", m, deviceID, name, offset, size)
  595. }
  596. return nil, ErrNoSuchFile
  597. }
  598. if debug && deviceID != protocol.LocalDeviceID {
  599. l.Debugf("%v REQ(in): %s: %q / %q o=%d s=%d", m, deviceID, folder, name, offset, size)
  600. }
  601. m.fmut.RLock()
  602. fn := filepath.Join(m.folderCfgs[folder].Path, name)
  603. m.fmut.RUnlock()
  604. var reader io.ReaderAt
  605. var err error
  606. if lf.IsSymlink() {
  607. target, _, err := symlinks.Read(fn)
  608. if err != nil {
  609. return nil, err
  610. }
  611. reader = strings.NewReader(target)
  612. } else {
  613. reader, err = os.Open(fn) // XXX: Inefficient, should cache fd?
  614. if err != nil {
  615. return nil, err
  616. }
  617. defer reader.(*os.File).Close()
  618. }
  619. buf := make([]byte, size)
  620. _, err = reader.ReadAt(buf, offset)
  621. if err != nil {
  622. return nil, err
  623. }
  624. return buf, nil
  625. }
  626. // ReplaceLocal replaces the local folder index with the given list of files.
  627. func (m *Model) ReplaceLocal(folder string, fs []protocol.FileInfo) {
  628. m.fmut.RLock()
  629. m.folderFiles[folder].ReplaceWithDelete(protocol.LocalDeviceID, fs)
  630. m.fmut.RUnlock()
  631. }
  632. func (m *Model) CurrentFolderFile(folder string, file string) protocol.FileInfo {
  633. m.fmut.RLock()
  634. f := m.folderFiles[folder].Get(protocol.LocalDeviceID, file)
  635. m.fmut.RUnlock()
  636. return f
  637. }
  638. func (m *Model) CurrentGlobalFile(folder string, file string) protocol.FileInfo {
  639. m.fmut.RLock()
  640. f := m.folderFiles[folder].GetGlobal(file)
  641. m.fmut.RUnlock()
  642. return f
  643. }
  644. type cFiler struct {
  645. m *Model
  646. r string
  647. }
  648. // Implements scanner.CurrentFiler
  649. func (cf cFiler) CurrentFile(file string) protocol.FileInfo {
  650. return cf.m.CurrentFolderFile(cf.r, file)
  651. }
  652. // ConnectedTo returns true if we are connected to the named device.
  653. func (m *Model) ConnectedTo(deviceID protocol.DeviceID) bool {
  654. m.pmut.RLock()
  655. _, ok := m.protoConn[deviceID]
  656. m.pmut.RUnlock()
  657. if ok {
  658. m.deviceWasSeen(deviceID)
  659. }
  660. return ok
  661. }
  662. func (m *Model) GetIgnores(folder string) ([]string, []string, error) {
  663. var lines []string
  664. m.fmut.RLock()
  665. cfg, ok := m.folderCfgs[folder]
  666. m.fmut.RUnlock()
  667. if !ok {
  668. return lines, nil, fmt.Errorf("Folder %s does not exist", folder)
  669. }
  670. fd, err := os.Open(filepath.Join(cfg.Path, ".stignore"))
  671. if err != nil {
  672. if os.IsNotExist(err) {
  673. return lines, nil, nil
  674. }
  675. l.Warnln("Loading .stignore:", err)
  676. return lines, nil, err
  677. }
  678. defer fd.Close()
  679. scanner := bufio.NewScanner(fd)
  680. for scanner.Scan() {
  681. lines = append(lines, strings.TrimSpace(scanner.Text()))
  682. }
  683. m.fmut.RLock()
  684. var patterns []string
  685. if matcher := m.folderIgnores[folder]; matcher != nil {
  686. patterns = matcher.Patterns()
  687. }
  688. m.fmut.RUnlock()
  689. return lines, patterns, nil
  690. }
  691. func (m *Model) SetIgnores(folder string, content []string) error {
  692. cfg, ok := m.folderCfgs[folder]
  693. if !ok {
  694. return fmt.Errorf("Folder %s does not exist", folder)
  695. }
  696. fd, err := ioutil.TempFile(cfg.Path, ".syncthing.stignore-"+folder)
  697. if err != nil {
  698. l.Warnln("Saving .stignore:", err)
  699. return err
  700. }
  701. defer os.Remove(fd.Name())
  702. for _, line := range content {
  703. _, err = fmt.Fprintln(fd, line)
  704. if err != nil {
  705. l.Warnln("Saving .stignore:", err)
  706. return err
  707. }
  708. }
  709. err = fd.Close()
  710. if err != nil {
  711. l.Warnln("Saving .stignore:", err)
  712. return err
  713. }
  714. file := filepath.Join(cfg.Path, ".stignore")
  715. err = osutil.Rename(fd.Name(), file)
  716. if err != nil {
  717. l.Warnln("Saving .stignore:", err)
  718. return err
  719. }
  720. return m.ScanFolder(folder)
  721. }
  722. // AddConnection adds a new peer connection to the model. An initial index will
  723. // be sent to the connected peer, thereafter index updates whenever the local
  724. // folder changes.
  725. func (m *Model) AddConnection(rawConn io.Closer, protoConn protocol.Connection) {
  726. deviceID := protoConn.ID()
  727. m.pmut.Lock()
  728. if _, ok := m.protoConn[deviceID]; ok {
  729. panic("add existing device")
  730. }
  731. m.protoConn[deviceID] = protoConn
  732. if _, ok := m.rawConn[deviceID]; ok {
  733. panic("add existing device")
  734. }
  735. m.rawConn[deviceID] = rawConn
  736. cm := m.clusterConfig(deviceID)
  737. protoConn.ClusterConfig(cm)
  738. m.fmut.RLock()
  739. for _, folder := range m.deviceFolders[deviceID] {
  740. fs := m.folderFiles[folder]
  741. go sendIndexes(protoConn, folder, fs, m.folderIgnores[folder])
  742. }
  743. m.fmut.RUnlock()
  744. m.pmut.Unlock()
  745. m.deviceWasSeen(deviceID)
  746. }
  747. func (m *Model) deviceStatRef(deviceID protocol.DeviceID) *stats.DeviceStatisticsReference {
  748. m.fmut.Lock()
  749. defer m.fmut.Unlock()
  750. if sr, ok := m.deviceStatRefs[deviceID]; ok {
  751. return sr
  752. }
  753. sr := stats.NewDeviceStatisticsReference(m.db, deviceID)
  754. m.deviceStatRefs[deviceID] = sr
  755. return sr
  756. }
  757. func (m *Model) deviceWasSeen(deviceID protocol.DeviceID) {
  758. m.deviceStatRef(deviceID).WasSeen()
  759. }
  760. func (m *Model) folderStatRef(folder string) *stats.FolderStatisticsReference {
  761. m.fmut.Lock()
  762. defer m.fmut.Unlock()
  763. sr, ok := m.folderStatRefs[folder]
  764. if !ok {
  765. sr = stats.NewFolderStatisticsReference(m.db, folder)
  766. m.folderStatRefs[folder] = sr
  767. }
  768. return sr
  769. }
  770. func (m *Model) receivedFile(folder, filename string) {
  771. m.folderStatRef(folder).ReceivedFile(filename)
  772. }
  773. func sendIndexes(conn protocol.Connection, folder string, fs *files.Set, ignores *ignore.Matcher) {
  774. deviceID := conn.ID()
  775. name := conn.Name()
  776. var err error
  777. if debug {
  778. l.Debugf("sendIndexes for %s-%s/%q starting", deviceID, name, folder)
  779. }
  780. minLocalVer, err := sendIndexTo(true, 0, conn, folder, fs, ignores)
  781. for err == nil {
  782. time.Sleep(5 * time.Second)
  783. if fs.LocalVersion(protocol.LocalDeviceID) <= minLocalVer {
  784. continue
  785. }
  786. minLocalVer, err = sendIndexTo(false, minLocalVer, conn, folder, fs, ignores)
  787. }
  788. if debug {
  789. l.Debugf("sendIndexes for %s-%s/%q exiting: %v", deviceID, name, folder, err)
  790. }
  791. }
  792. func sendIndexTo(initial bool, minLocalVer uint64, conn protocol.Connection, folder string, fs *files.Set, ignores *ignore.Matcher) (uint64, error) {
  793. deviceID := conn.ID()
  794. name := conn.Name()
  795. batch := make([]protocol.FileInfo, 0, indexBatchSize)
  796. currentBatchSize := 0
  797. maxLocalVer := uint64(0)
  798. var err error
  799. fs.WithHave(protocol.LocalDeviceID, func(fi protocol.FileIntf) bool {
  800. f := fi.(protocol.FileInfo)
  801. if f.LocalVersion <= minLocalVer {
  802. return true
  803. }
  804. if f.LocalVersion > maxLocalVer {
  805. maxLocalVer = f.LocalVersion
  806. }
  807. if (ignores != nil && ignores.Match(f.Name)) || symlinkInvalid(f.IsSymlink()) {
  808. if debug {
  809. l.Debugln("not sending update for ignored/unsupported symlink", f)
  810. }
  811. return true
  812. }
  813. if len(batch) == indexBatchSize || currentBatchSize > indexTargetSize {
  814. if initial {
  815. if err = conn.Index(folder, batch); err != nil {
  816. return false
  817. }
  818. if debug {
  819. l.Debugf("sendIndexes for %s-%s/%q: %d files (<%d bytes) (initial index)", deviceID, name, folder, len(batch), currentBatchSize)
  820. }
  821. initial = false
  822. } else {
  823. if err = conn.IndexUpdate(folder, batch); err != nil {
  824. return false
  825. }
  826. if debug {
  827. l.Debugf("sendIndexes for %s-%s/%q: %d files (<%d bytes) (batched update)", deviceID, name, folder, len(batch), currentBatchSize)
  828. }
  829. }
  830. batch = make([]protocol.FileInfo, 0, indexBatchSize)
  831. currentBatchSize = 0
  832. }
  833. batch = append(batch, f)
  834. currentBatchSize += indexPerFileSize + len(f.Blocks)*IndexPerBlockSize
  835. return true
  836. })
  837. if initial && err == nil {
  838. err = conn.Index(folder, batch)
  839. if debug && err == nil {
  840. l.Debugf("sendIndexes for %s-%s/%q: %d files (small initial index)", deviceID, name, folder, len(batch))
  841. }
  842. } else if len(batch) > 0 && err == nil {
  843. err = conn.IndexUpdate(folder, batch)
  844. if debug && err == nil {
  845. l.Debugf("sendIndexes for %s-%s/%q: %d files (last batch)", deviceID, name, folder, len(batch))
  846. }
  847. }
  848. return maxLocalVer, err
  849. }
  850. func (m *Model) updateLocal(folder string, f protocol.FileInfo) {
  851. f.LocalVersion = 0
  852. m.fmut.RLock()
  853. m.folderFiles[folder].Update(protocol.LocalDeviceID, []protocol.FileInfo{f})
  854. m.fmut.RUnlock()
  855. events.Default.Log(events.LocalIndexUpdated, map[string]interface{}{
  856. "folder": folder,
  857. "name": f.Name,
  858. "modified": time.Unix(f.Modified, 0),
  859. "flags": fmt.Sprintf("0%o", f.Flags),
  860. "size": f.Size(),
  861. })
  862. }
  863. func (m *Model) requestGlobal(deviceID protocol.DeviceID, folder, name string, offset int64, size int, hash []byte) ([]byte, error) {
  864. m.pmut.RLock()
  865. nc, ok := m.protoConn[deviceID]
  866. m.pmut.RUnlock()
  867. if !ok {
  868. return nil, fmt.Errorf("requestGlobal: no such device: %s", deviceID)
  869. }
  870. if debug {
  871. l.Debugf("%v REQ(out): %s: %q / %q o=%d s=%d h=%x", m, deviceID, folder, name, offset, size, hash)
  872. }
  873. return nc.Request(folder, name, offset, size)
  874. }
  875. func (m *Model) AddFolder(cfg config.FolderConfiguration) {
  876. if m.started {
  877. panic("cannot add folder to started model")
  878. }
  879. if len(cfg.ID) == 0 {
  880. panic("cannot add empty folder id")
  881. }
  882. m.fmut.Lock()
  883. m.folderCfgs[cfg.ID] = cfg
  884. m.folderFiles[cfg.ID] = files.NewSet(cfg.ID, m.db)
  885. m.folderDevices[cfg.ID] = make([]protocol.DeviceID, len(cfg.Devices))
  886. for i, device := range cfg.Devices {
  887. m.folderDevices[cfg.ID][i] = device.DeviceID
  888. m.deviceFolders[device.DeviceID] = append(m.deviceFolders[device.DeviceID], cfg.ID)
  889. }
  890. ignores, _ := ignore.Load(filepath.Join(cfg.Path, ".stignore"), m.cfg.Options().CacheIgnoredFiles)
  891. m.folderIgnores[cfg.ID] = ignores
  892. m.addedFolder = true
  893. m.fmut.Unlock()
  894. }
  895. func (m *Model) ScanFolders() {
  896. m.fmut.RLock()
  897. var folders = make([]string, 0, len(m.folderCfgs))
  898. for folder := range m.folderCfgs {
  899. folders = append(folders, folder)
  900. }
  901. m.fmut.RUnlock()
  902. var wg sync.WaitGroup
  903. wg.Add(len(folders))
  904. for _, folder := range folders {
  905. folder := folder
  906. go func() {
  907. err := m.ScanFolder(folder)
  908. if err != nil {
  909. m.cfg.InvalidateFolder(folder, err.Error())
  910. }
  911. wg.Done()
  912. }()
  913. }
  914. wg.Wait()
  915. }
  916. func (m *Model) ScanFolder(folder string) error {
  917. return m.ScanFolderSub(folder, "")
  918. }
  919. func (m *Model) ScanFolderSub(folder, sub string) error {
  920. if p := filepath.Clean(filepath.Join(folder, sub)); !strings.HasPrefix(p, folder) {
  921. return errors.New("invalid subpath")
  922. }
  923. m.fmut.Lock()
  924. fs, ok := m.folderFiles[folder]
  925. dir := m.folderCfgs[folder].Path
  926. ignores, _ := ignore.Load(filepath.Join(dir, ".stignore"), m.cfg.Options().CacheIgnoredFiles)
  927. m.folderIgnores[folder] = ignores
  928. w := &scanner.Walker{
  929. Dir: dir,
  930. Sub: sub,
  931. Matcher: ignores,
  932. BlockSize: protocol.BlockSize,
  933. TempNamer: defTempNamer,
  934. TempLifetime: time.Duration(m.cfg.Options().KeepTemporariesH) * time.Hour,
  935. CurrentFiler: cFiler{m, folder},
  936. IgnorePerms: m.folderCfgs[folder].IgnorePerms,
  937. }
  938. m.fmut.Unlock()
  939. if !ok {
  940. return errors.New("no such folder")
  941. }
  942. m.setState(folder, FolderScanning)
  943. fchan, err := w.Walk()
  944. if err != nil {
  945. return err
  946. }
  947. batchSize := 100
  948. batch := make([]protocol.FileInfo, 0, batchSize)
  949. for f := range fchan {
  950. events.Default.Log(events.LocalIndexUpdated, map[string]interface{}{
  951. "folder": folder,
  952. "name": f.Name,
  953. "modified": time.Unix(f.Modified, 0),
  954. "flags": fmt.Sprintf("0%o", f.Flags),
  955. "size": f.Size(),
  956. })
  957. if len(batch) == batchSize {
  958. fs.Update(protocol.LocalDeviceID, batch)
  959. batch = batch[:0]
  960. }
  961. batch = append(batch, f)
  962. }
  963. if len(batch) > 0 {
  964. fs.Update(protocol.LocalDeviceID, batch)
  965. }
  966. batch = batch[:0]
  967. // TODO: We should limit the Have scanning to start at sub
  968. seenPrefix := false
  969. fs.WithHaveTruncated(protocol.LocalDeviceID, func(fi protocol.FileIntf) bool {
  970. f := fi.(protocol.FileInfoTruncated)
  971. if !strings.HasPrefix(f.Name, sub) {
  972. // Return true so that we keep iterating, until we get to the part
  973. // of the tree we are interested in. Then return false so we stop
  974. // iterating when we've passed the end of the subtree.
  975. return !seenPrefix
  976. }
  977. seenPrefix = true
  978. if !f.IsDeleted() {
  979. if f.IsInvalid() {
  980. return true
  981. }
  982. if len(batch) == batchSize {
  983. fs.Update(protocol.LocalDeviceID, batch)
  984. batch = batch[:0]
  985. }
  986. if (ignores != nil && ignores.Match(f.Name)) || symlinkInvalid(f.IsSymlink()) {
  987. // File has been ignored or an unsupported symlink. Set invalid bit.
  988. if debug {
  989. l.Debugln("setting invalid bit on ignored", f)
  990. }
  991. nf := protocol.FileInfo{
  992. Name: f.Name,
  993. Flags: f.Flags | protocol.FlagInvalid,
  994. Modified: f.Modified,
  995. Version: f.Version, // The file is still the same, so don't bump version
  996. }
  997. events.Default.Log(events.LocalIndexUpdated, map[string]interface{}{
  998. "folder": folder,
  999. "name": f.Name,
  1000. "modified": time.Unix(f.Modified, 0),
  1001. "flags": fmt.Sprintf("0%o", f.Flags),
  1002. "size": f.Size(),
  1003. })
  1004. batch = append(batch, nf)
  1005. } else if _, err := os.Lstat(filepath.Join(dir, f.Name)); err != nil && os.IsNotExist(err) {
  1006. // File has been deleted
  1007. nf := protocol.FileInfo{
  1008. Name: f.Name,
  1009. Flags: f.Flags | protocol.FlagDeleted,
  1010. Modified: f.Modified,
  1011. Version: lamport.Default.Tick(f.Version),
  1012. }
  1013. events.Default.Log(events.LocalIndexUpdated, map[string]interface{}{
  1014. "folder": folder,
  1015. "name": f.Name,
  1016. "modified": time.Unix(f.Modified, 0),
  1017. "flags": fmt.Sprintf("0%o", f.Flags),
  1018. "size": f.Size(),
  1019. })
  1020. batch = append(batch, nf)
  1021. }
  1022. }
  1023. return true
  1024. })
  1025. if len(batch) > 0 {
  1026. fs.Update(protocol.LocalDeviceID, batch)
  1027. }
  1028. m.setState(folder, FolderIdle)
  1029. return nil
  1030. }
  1031. // clusterConfig returns a ClusterConfigMessage that is correct for the given peer device
  1032. func (m *Model) clusterConfig(device protocol.DeviceID) protocol.ClusterConfigMessage {
  1033. cm := protocol.ClusterConfigMessage{
  1034. ClientName: m.clientName,
  1035. ClientVersion: m.clientVersion,
  1036. Options: []protocol.Option{
  1037. {
  1038. Key: "name",
  1039. Value: m.deviceName,
  1040. },
  1041. },
  1042. }
  1043. m.fmut.RLock()
  1044. for _, folder := range m.deviceFolders[device] {
  1045. cr := protocol.Folder{
  1046. ID: folder,
  1047. }
  1048. for _, device := range m.folderDevices[folder] {
  1049. // DeviceID is a value type, but with an underlying array. Copy it
  1050. // so we don't grab aliases to the same array later on in device[:]
  1051. device := device
  1052. // TODO: Set read only bit when relevant
  1053. cn := protocol.Device{
  1054. ID: device[:],
  1055. Flags: protocol.FlagShareTrusted,
  1056. }
  1057. if deviceCfg := m.cfg.Devices()[device]; deviceCfg.Introducer {
  1058. cn.Flags |= protocol.FlagIntroducer
  1059. }
  1060. cr.Devices = append(cr.Devices, cn)
  1061. }
  1062. cm.Folders = append(cm.Folders, cr)
  1063. }
  1064. m.fmut.RUnlock()
  1065. return cm
  1066. }
  1067. func (m *Model) setState(folder string, state folderState) {
  1068. m.smut.Lock()
  1069. oldState := m.folderState[folder]
  1070. changed, ok := m.folderStateChanged[folder]
  1071. if state != oldState {
  1072. m.folderState[folder] = state
  1073. m.folderStateChanged[folder] = time.Now()
  1074. eventData := map[string]interface{}{
  1075. "folder": folder,
  1076. "to": state.String(),
  1077. }
  1078. if ok {
  1079. eventData["duration"] = time.Since(changed).Seconds()
  1080. eventData["from"] = oldState.String()
  1081. }
  1082. events.Default.Log(events.StateChanged, eventData)
  1083. }
  1084. m.smut.Unlock()
  1085. }
  1086. func (m *Model) State(folder string) (string, time.Time) {
  1087. m.smut.RLock()
  1088. state := m.folderState[folder]
  1089. changed := m.folderStateChanged[folder]
  1090. m.smut.RUnlock()
  1091. return state.String(), changed
  1092. }
  1093. func (m *Model) Override(folder string) {
  1094. m.fmut.RLock()
  1095. fs := m.folderFiles[folder]
  1096. m.fmut.RUnlock()
  1097. m.setState(folder, FolderScanning)
  1098. batch := make([]protocol.FileInfo, 0, indexBatchSize)
  1099. fs.WithNeed(protocol.LocalDeviceID, func(fi protocol.FileIntf) bool {
  1100. need := fi.(protocol.FileInfo)
  1101. if len(batch) == indexBatchSize {
  1102. fs.Update(protocol.LocalDeviceID, batch)
  1103. batch = batch[:0]
  1104. }
  1105. have := fs.Get(protocol.LocalDeviceID, need.Name)
  1106. if have.Name != need.Name {
  1107. // We are missing the file
  1108. need.Flags |= protocol.FlagDeleted
  1109. need.Blocks = nil
  1110. } else {
  1111. // We have the file, replace with our version
  1112. need = have
  1113. }
  1114. need.Version = lamport.Default.Tick(need.Version)
  1115. need.LocalVersion = 0
  1116. batch = append(batch, need)
  1117. return true
  1118. })
  1119. if len(batch) > 0 {
  1120. fs.Update(protocol.LocalDeviceID, batch)
  1121. }
  1122. m.setState(folder, FolderIdle)
  1123. }
  1124. // CurrentLocalVersion returns the change version for the given folder.
  1125. // This is guaranteed to increment if the contents of the local folder has
  1126. // changed.
  1127. func (m *Model) CurrentLocalVersion(folder string) uint64 {
  1128. m.fmut.RLock()
  1129. fs, ok := m.folderFiles[folder]
  1130. m.fmut.RUnlock()
  1131. if !ok {
  1132. // The folder might not exist, since this can be called with a user
  1133. // specified folder name from the REST interface.
  1134. return 0
  1135. }
  1136. return fs.LocalVersion(protocol.LocalDeviceID)
  1137. }
  1138. // RemoteLocalVersion returns the change version for the given folder, as
  1139. // sent by remote peers. This is guaranteed to increment if the contents of
  1140. // the remote or global folder has changed.
  1141. func (m *Model) RemoteLocalVersion(folder string) uint64 {
  1142. m.fmut.RLock()
  1143. defer m.fmut.RUnlock()
  1144. fs, ok := m.folderFiles[folder]
  1145. if !ok {
  1146. // The folder might not exist, since this can be called with a user
  1147. // specified folder name from the REST interface.
  1148. return 0
  1149. }
  1150. var ver uint64
  1151. for _, n := range m.folderDevices[folder] {
  1152. ver += fs.LocalVersion(n)
  1153. }
  1154. return ver
  1155. }
  1156. func (m *Model) availability(folder string, file string) []protocol.DeviceID {
  1157. // Acquire this lock first, as the value returned from foldersFiles can
  1158. // gen heavily modified on Close()
  1159. m.pmut.RLock()
  1160. defer m.pmut.RUnlock()
  1161. m.fmut.RLock()
  1162. fs, ok := m.folderFiles[folder]
  1163. m.fmut.RUnlock()
  1164. if !ok {
  1165. return nil
  1166. }
  1167. availableDevices := []protocol.DeviceID{}
  1168. for _, device := range fs.Availability(file) {
  1169. _, ok := m.protoConn[device]
  1170. if ok {
  1171. availableDevices = append(availableDevices, device)
  1172. }
  1173. }
  1174. return availableDevices
  1175. }
  1176. func (m *Model) String() string {
  1177. return fmt.Sprintf("model@%p", m)
  1178. }
  1179. func (m *Model) leveldbPanicWorkaround() {
  1180. // When an inconsistency is detected in leveldb we panic(). This is
  1181. // appropriate because it should never happen, but currently it does for
  1182. // some reason. However it only seems to trigger in the asynchronous full-
  1183. // database scans that happen due to REST and usage-reporting calls. In
  1184. // those places we defer to this workaround to catch the panic instead of
  1185. // taking down syncthing.
  1186. // This is just a band-aid and should be removed as soon as we have found
  1187. // a real root cause.
  1188. if pnc := recover(); pnc != nil {
  1189. if err, ok := pnc.(error); ok && strings.Contains(err.Error(), "leveldb") {
  1190. l.Infoln("recovered:", err)
  1191. } else {
  1192. // Any non-leveldb error is genuine and should continue panicing.
  1193. panic(err)
  1194. }
  1195. }
  1196. }
  1197. func symlinkInvalid(isLink bool) bool {
  1198. if !symlinks.Supported && isLink {
  1199. SymlinkWarning.Do(func() {
  1200. l.Warnln("Symlinks are disabled, unsupported or require Administrator priviledges. This might cause your folder to appear out of sync.")
  1201. })
  1202. return true
  1203. }
  1204. return false
  1205. }