model.go 39 KB

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