model.go 33 KB

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