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