model.go 38 KB

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