model.go 43 KB

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