model.go 40 KB

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