model.go 43 KB

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