model.go 40 KB

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