model.go 39 KB

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