model.go 39 KB

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