model.go 39 KB

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