model.go 39 KB

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