model.go 39 KB

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