model.go 33 KB

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