model.go 40 KB

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