model.go 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397
  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.New(m.cfg.Options().CacheIgnoredFiles)
  891. _ = ignores.Load(filepath.Join(cfg.Path, ".stignore")) // Ignore error, there might not be an .stignore
  892. m.folderIgnores[cfg.ID] = ignores
  893. m.addedFolder = true
  894. m.fmut.Unlock()
  895. }
  896. func (m *Model) ScanFolders() {
  897. m.fmut.RLock()
  898. var folders = make([]string, 0, len(m.folderCfgs))
  899. for folder := range m.folderCfgs {
  900. folders = append(folders, folder)
  901. }
  902. m.fmut.RUnlock()
  903. var wg sync.WaitGroup
  904. wg.Add(len(folders))
  905. for _, folder := range folders {
  906. folder := folder
  907. go func() {
  908. err := m.ScanFolder(folder)
  909. if err != nil {
  910. m.cfg.InvalidateFolder(folder, err.Error())
  911. }
  912. wg.Done()
  913. }()
  914. }
  915. wg.Wait()
  916. }
  917. func (m *Model) ScanFolder(folder string) error {
  918. return m.ScanFolderSub(folder, "")
  919. }
  920. func (m *Model) ScanFolderSub(folder, sub string) error {
  921. if p := filepath.Clean(filepath.Join(folder, sub)); !strings.HasPrefix(p, folder) {
  922. return errors.New("invalid subpath")
  923. }
  924. m.fmut.Lock()
  925. fs, ok := m.folderFiles[folder]
  926. dir := m.folderCfgs[folder].Path
  927. ignores := m.folderIgnores[folder]
  928. _ = ignores.Load(filepath.Join(dir, ".stignore")) // Ignore error, there might not be an .stignore
  929. w := &scanner.Walker{
  930. Dir: dir,
  931. Sub: sub,
  932. Matcher: ignores,
  933. BlockSize: protocol.BlockSize,
  934. TempNamer: defTempNamer,
  935. TempLifetime: time.Duration(m.cfg.Options().KeepTemporariesH) * time.Hour,
  936. CurrentFiler: cFiler{m, folder},
  937. IgnorePerms: m.folderCfgs[folder].IgnorePerms,
  938. }
  939. m.fmut.Unlock()
  940. if !ok {
  941. return errors.New("no such folder")
  942. }
  943. m.setState(folder, FolderScanning)
  944. fchan, err := w.Walk()
  945. if err != nil {
  946. return err
  947. }
  948. batchSize := 100
  949. batch := make([]protocol.FileInfo, 0, batchSize)
  950. for f := range fchan {
  951. events.Default.Log(events.LocalIndexUpdated, map[string]interface{}{
  952. "folder": folder,
  953. "name": f.Name,
  954. "modified": time.Unix(f.Modified, 0),
  955. "flags": fmt.Sprintf("0%o", f.Flags),
  956. "size": f.Size(),
  957. })
  958. if len(batch) == batchSize {
  959. fs.Update(protocol.LocalDeviceID, batch)
  960. batch = batch[:0]
  961. }
  962. batch = append(batch, f)
  963. }
  964. if len(batch) > 0 {
  965. fs.Update(protocol.LocalDeviceID, batch)
  966. }
  967. batch = batch[:0]
  968. // TODO: We should limit the Have scanning to start at sub
  969. seenPrefix := false
  970. fs.WithHaveTruncated(protocol.LocalDeviceID, func(fi protocol.FileIntf) bool {
  971. f := fi.(protocol.FileInfoTruncated)
  972. if !strings.HasPrefix(f.Name, sub) {
  973. // Return true so that we keep iterating, until we get to the part
  974. // of the tree we are interested in. Then return false so we stop
  975. // iterating when we've passed the end of the subtree.
  976. return !seenPrefix
  977. }
  978. seenPrefix = true
  979. if !f.IsDeleted() {
  980. if f.IsInvalid() {
  981. return true
  982. }
  983. if len(batch) == batchSize {
  984. fs.Update(protocol.LocalDeviceID, batch)
  985. batch = batch[:0]
  986. }
  987. if (ignores != nil && ignores.Match(f.Name)) || symlinkInvalid(f.IsSymlink()) {
  988. // File has been ignored or an unsupported symlink. Set invalid bit.
  989. if debug {
  990. l.Debugln("setting invalid bit on ignored", f)
  991. }
  992. nf := protocol.FileInfo{
  993. Name: f.Name,
  994. Flags: f.Flags | protocol.FlagInvalid,
  995. Modified: f.Modified,
  996. Version: f.Version, // The file is still the same, so don't bump version
  997. }
  998. events.Default.Log(events.LocalIndexUpdated, map[string]interface{}{
  999. "folder": folder,
  1000. "name": f.Name,
  1001. "modified": time.Unix(f.Modified, 0),
  1002. "flags": fmt.Sprintf("0%o", f.Flags),
  1003. "size": f.Size(),
  1004. })
  1005. batch = append(batch, nf)
  1006. } else if _, err := os.Lstat(filepath.Join(dir, f.Name)); err != nil && os.IsNotExist(err) {
  1007. // File has been deleted
  1008. nf := protocol.FileInfo{
  1009. Name: f.Name,
  1010. Flags: f.Flags | protocol.FlagDeleted,
  1011. Modified: f.Modified,
  1012. Version: lamport.Default.Tick(f.Version),
  1013. }
  1014. events.Default.Log(events.LocalIndexUpdated, map[string]interface{}{
  1015. "folder": folder,
  1016. "name": f.Name,
  1017. "modified": time.Unix(f.Modified, 0),
  1018. "flags": fmt.Sprintf("0%o", f.Flags),
  1019. "size": f.Size(),
  1020. })
  1021. batch = append(batch, nf)
  1022. }
  1023. }
  1024. return true
  1025. })
  1026. if len(batch) > 0 {
  1027. fs.Update(protocol.LocalDeviceID, batch)
  1028. }
  1029. m.setState(folder, FolderIdle)
  1030. return nil
  1031. }
  1032. // clusterConfig returns a ClusterConfigMessage that is correct for the given peer device
  1033. func (m *Model) clusterConfig(device protocol.DeviceID) protocol.ClusterConfigMessage {
  1034. cm := protocol.ClusterConfigMessage{
  1035. ClientName: m.clientName,
  1036. ClientVersion: m.clientVersion,
  1037. Options: []protocol.Option{
  1038. {
  1039. Key: "name",
  1040. Value: m.deviceName,
  1041. },
  1042. },
  1043. }
  1044. m.fmut.RLock()
  1045. for _, folder := range m.deviceFolders[device] {
  1046. cr := protocol.Folder{
  1047. ID: folder,
  1048. }
  1049. for _, device := range m.folderDevices[folder] {
  1050. // DeviceID is a value type, but with an underlying array. Copy it
  1051. // so we don't grab aliases to the same array later on in device[:]
  1052. device := device
  1053. // TODO: Set read only bit when relevant
  1054. cn := protocol.Device{
  1055. ID: device[:],
  1056. Flags: protocol.FlagShareTrusted,
  1057. }
  1058. if deviceCfg := m.cfg.Devices()[device]; deviceCfg.Introducer {
  1059. cn.Flags |= protocol.FlagIntroducer
  1060. }
  1061. cr.Devices = append(cr.Devices, cn)
  1062. }
  1063. cm.Folders = append(cm.Folders, cr)
  1064. }
  1065. m.fmut.RUnlock()
  1066. return cm
  1067. }
  1068. func (m *Model) setState(folder string, state folderState) {
  1069. m.smut.Lock()
  1070. oldState := m.folderState[folder]
  1071. changed, ok := m.folderStateChanged[folder]
  1072. if state != oldState {
  1073. m.folderState[folder] = state
  1074. m.folderStateChanged[folder] = time.Now()
  1075. eventData := map[string]interface{}{
  1076. "folder": folder,
  1077. "to": state.String(),
  1078. }
  1079. if ok {
  1080. eventData["duration"] = time.Since(changed).Seconds()
  1081. eventData["from"] = oldState.String()
  1082. }
  1083. events.Default.Log(events.StateChanged, eventData)
  1084. }
  1085. m.smut.Unlock()
  1086. }
  1087. func (m *Model) State(folder string) (string, time.Time) {
  1088. m.smut.RLock()
  1089. state := m.folderState[folder]
  1090. changed := m.folderStateChanged[folder]
  1091. m.smut.RUnlock()
  1092. return state.String(), changed
  1093. }
  1094. func (m *Model) Override(folder string) {
  1095. m.fmut.RLock()
  1096. fs := m.folderFiles[folder]
  1097. m.fmut.RUnlock()
  1098. m.setState(folder, FolderScanning)
  1099. batch := make([]protocol.FileInfo, 0, indexBatchSize)
  1100. fs.WithNeed(protocol.LocalDeviceID, func(fi protocol.FileIntf) bool {
  1101. need := fi.(protocol.FileInfo)
  1102. if len(batch) == indexBatchSize {
  1103. fs.Update(protocol.LocalDeviceID, batch)
  1104. batch = batch[:0]
  1105. }
  1106. have := fs.Get(protocol.LocalDeviceID, need.Name)
  1107. if have.Name != need.Name {
  1108. // We are missing the file
  1109. need.Flags |= protocol.FlagDeleted
  1110. need.Blocks = nil
  1111. } else {
  1112. // We have the file, replace with our version
  1113. need = have
  1114. }
  1115. need.Version = lamport.Default.Tick(need.Version)
  1116. need.LocalVersion = 0
  1117. batch = append(batch, need)
  1118. return true
  1119. })
  1120. if len(batch) > 0 {
  1121. fs.Update(protocol.LocalDeviceID, batch)
  1122. }
  1123. m.setState(folder, FolderIdle)
  1124. }
  1125. // CurrentLocalVersion returns the change version for the given folder.
  1126. // This is guaranteed to increment if the contents of the local folder has
  1127. // changed.
  1128. func (m *Model) CurrentLocalVersion(folder string) uint64 {
  1129. m.fmut.RLock()
  1130. fs, ok := m.folderFiles[folder]
  1131. m.fmut.RUnlock()
  1132. if !ok {
  1133. // The folder might not exist, since this can be called with a user
  1134. // specified folder name from the REST interface.
  1135. return 0
  1136. }
  1137. return fs.LocalVersion(protocol.LocalDeviceID)
  1138. }
  1139. // RemoteLocalVersion returns the change version for the given folder, as
  1140. // sent by remote peers. This is guaranteed to increment if the contents of
  1141. // the remote or global folder has changed.
  1142. func (m *Model) RemoteLocalVersion(folder string) uint64 {
  1143. m.fmut.RLock()
  1144. defer m.fmut.RUnlock()
  1145. fs, ok := m.folderFiles[folder]
  1146. if !ok {
  1147. // The folder might not exist, since this can be called with a user
  1148. // specified folder name from the REST interface.
  1149. return 0
  1150. }
  1151. var ver uint64
  1152. for _, n := range m.folderDevices[folder] {
  1153. ver += fs.LocalVersion(n)
  1154. }
  1155. return ver
  1156. }
  1157. func (m *Model) availability(folder string, file string) []protocol.DeviceID {
  1158. // Acquire this lock first, as the value returned from foldersFiles can
  1159. // gen heavily modified on Close()
  1160. m.pmut.RLock()
  1161. defer m.pmut.RUnlock()
  1162. m.fmut.RLock()
  1163. fs, ok := m.folderFiles[folder]
  1164. m.fmut.RUnlock()
  1165. if !ok {
  1166. return nil
  1167. }
  1168. availableDevices := []protocol.DeviceID{}
  1169. for _, device := range fs.Availability(file) {
  1170. _, ok := m.protoConn[device]
  1171. if ok {
  1172. availableDevices = append(availableDevices, device)
  1173. }
  1174. }
  1175. return availableDevices
  1176. }
  1177. func (m *Model) String() string {
  1178. return fmt.Sprintf("model@%p", m)
  1179. }
  1180. func (m *Model) leveldbPanicWorkaround() {
  1181. // When an inconsistency is detected in leveldb we panic(). This is
  1182. // appropriate because it should never happen, but currently it does for
  1183. // some reason. However it only seems to trigger in the asynchronous full-
  1184. // database scans that happen due to REST and usage-reporting calls. In
  1185. // those places we defer to this workaround to catch the panic instead of
  1186. // taking down syncthing.
  1187. // This is just a band-aid and should be removed as soon as we have found
  1188. // a real root cause.
  1189. if pnc := recover(); pnc != nil {
  1190. if err, ok := pnc.(error); ok && strings.Contains(err.Error(), "leveldb") {
  1191. l.Infoln("recovered:", err)
  1192. } else {
  1193. // Any non-leveldb error is genuine and should continue panicing.
  1194. panic(err)
  1195. }
  1196. }
  1197. }
  1198. func symlinkInvalid(isLink bool) bool {
  1199. if !symlinks.Supported && isLink {
  1200. SymlinkWarning.Do(func() {
  1201. l.Warnln("Symlinks are disabled, unsupported or require Administrator priviledges. This might cause your folder to appear out of sync.")
  1202. })
  1203. return true
  1204. }
  1205. return false
  1206. }