model.go 35 KB

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