model.go 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006
  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. "net"
  15. "os"
  16. "path/filepath"
  17. "reflect"
  18. "runtime"
  19. "strings"
  20. stdsync "sync"
  21. "time"
  22. "github.com/syncthing/syncthing/lib/config"
  23. "github.com/syncthing/syncthing/lib/db"
  24. "github.com/syncthing/syncthing/lib/events"
  25. "github.com/syncthing/syncthing/lib/ignore"
  26. "github.com/syncthing/syncthing/lib/osutil"
  27. "github.com/syncthing/syncthing/lib/protocol"
  28. "github.com/syncthing/syncthing/lib/scanner"
  29. "github.com/syncthing/syncthing/lib/stats"
  30. "github.com/syncthing/syncthing/lib/symlinks"
  31. "github.com/syncthing/syncthing/lib/sync"
  32. "github.com/syncthing/syncthing/lib/versioner"
  33. "github.com/syndtr/goleveldb/leveldb"
  34. "github.com/thejerf/suture"
  35. )
  36. // How many files to send in each Index/IndexUpdate message.
  37. const (
  38. indexTargetSize = 250 * 1024 // Aim for making index messages no larger than 250 KiB (uncompressed)
  39. indexPerFileSize = 250 // Each FileInfo is approximately this big, in bytes, excluding BlockInfos
  40. indexPerBlockSize = 40 // Each BlockInfo is approximately this big
  41. indexBatchSize = 1000 // Either way, don't include more files than this
  42. reqValidationTime = time.Hour // How long to cache validation entries for Request messages
  43. reqValidationCacheSize = 1000 // How many entries to aim for in the validation cache size
  44. )
  45. type service interface {
  46. Serve()
  47. Stop()
  48. Jobs() ([]string, []string) // In progress, Queued
  49. BringToFront(string)
  50. DelayScan(d time.Duration)
  51. IndexUpdated() // Remote index was updated notification
  52. Scan(subs []string) error
  53. setState(state folderState)
  54. setError(err error)
  55. clearError()
  56. getState() (folderState, time.Time, error)
  57. }
  58. type Model struct {
  59. *suture.Supervisor
  60. cfg *config.Wrapper
  61. db *leveldb.DB
  62. finder *db.BlockFinder
  63. progressEmitter *ProgressEmitter
  64. id protocol.DeviceID
  65. shortID uint64
  66. cacheIgnoredFiles bool
  67. deviceName string
  68. clientName string
  69. clientVersion string
  70. folderCfgs map[string]config.FolderConfiguration // folder -> cfg
  71. folderFiles map[string]*db.FileSet // folder -> files
  72. folderDevices map[string][]protocol.DeviceID // folder -> deviceIDs
  73. deviceFolders map[protocol.DeviceID][]string // deviceID -> folders
  74. deviceStatRefs map[protocol.DeviceID]*stats.DeviceStatisticsReference // deviceID -> statsRef
  75. folderIgnores map[string]*ignore.Matcher // folder -> matcher object
  76. folderRunners map[string]service // folder -> puller or scanner
  77. folderStatRefs map[string]*stats.FolderStatisticsReference // folder -> statsRef
  78. fmut sync.RWMutex // protects the above
  79. conn map[protocol.DeviceID]Connection
  80. deviceVer map[protocol.DeviceID]string
  81. devicePaused map[protocol.DeviceID]bool
  82. pmut sync.RWMutex // protects the above
  83. reqValidationCache map[string]time.Time // folder / file name => time when confirmed to exist
  84. rvmut sync.RWMutex // protects reqValidationCache
  85. }
  86. var (
  87. symlinkWarning = stdsync.Once{}
  88. )
  89. // NewModel creates and starts a new model. The model starts in read-only mode,
  90. // where it sends index information to connected peers and responds to requests
  91. // for file data without altering the local folder in any way.
  92. func NewModel(cfg *config.Wrapper, id protocol.DeviceID, deviceName, clientName, clientVersion string, ldb *leveldb.DB) *Model {
  93. m := &Model{
  94. Supervisor: suture.New("model", suture.Spec{
  95. Log: func(line string) {
  96. if debug {
  97. l.Debugln(line)
  98. }
  99. },
  100. }),
  101. cfg: cfg,
  102. db: ldb,
  103. finder: db.NewBlockFinder(ldb),
  104. progressEmitter: NewProgressEmitter(cfg),
  105. id: id,
  106. shortID: id.Short(),
  107. cacheIgnoredFiles: cfg.Options().CacheIgnoredFiles,
  108. deviceName: deviceName,
  109. clientName: clientName,
  110. clientVersion: clientVersion,
  111. folderCfgs: make(map[string]config.FolderConfiguration),
  112. folderFiles: make(map[string]*db.FileSet),
  113. folderDevices: make(map[string][]protocol.DeviceID),
  114. deviceFolders: make(map[protocol.DeviceID][]string),
  115. deviceStatRefs: make(map[protocol.DeviceID]*stats.DeviceStatisticsReference),
  116. folderIgnores: make(map[string]*ignore.Matcher),
  117. folderRunners: make(map[string]service),
  118. folderStatRefs: make(map[string]*stats.FolderStatisticsReference),
  119. conn: make(map[protocol.DeviceID]Connection),
  120. deviceVer: make(map[protocol.DeviceID]string),
  121. devicePaused: make(map[protocol.DeviceID]bool),
  122. reqValidationCache: make(map[string]time.Time),
  123. fmut: sync.NewRWMutex(),
  124. pmut: sync.NewRWMutex(),
  125. rvmut: sync.NewRWMutex(),
  126. }
  127. if cfg.Options().ProgressUpdateIntervalS > -1 {
  128. go m.progressEmitter.Serve()
  129. }
  130. return m
  131. }
  132. // StartDeadlockDetector starts a deadlock detector on the models locks which
  133. // causes panics in case the locks cannot be acquired in the given timeout
  134. // period.
  135. func (m *Model) StartDeadlockDetector(timeout time.Duration) {
  136. l.Infof("Starting deadlock detector with %v timeout", timeout)
  137. deadlockDetect(m.fmut, timeout)
  138. deadlockDetect(m.pmut, timeout)
  139. }
  140. // StartFolderRW starts read/write processing on the current model. When in
  141. // read/write mode the model will attempt to keep in sync with the cluster by
  142. // pulling needed files from peer devices.
  143. func (m *Model) StartFolderRW(folder string) {
  144. m.fmut.Lock()
  145. cfg, ok := m.folderCfgs[folder]
  146. if !ok {
  147. panic("cannot start nonexistent folder " + folder)
  148. }
  149. _, ok = m.folderRunners[folder]
  150. if ok {
  151. panic("cannot start already running folder " + folder)
  152. }
  153. p := newRWFolder(m, m.shortID, cfg)
  154. m.folderRunners[folder] = p
  155. m.fmut.Unlock()
  156. if len(cfg.Versioning.Type) > 0 {
  157. factory, ok := versioner.Factories[cfg.Versioning.Type]
  158. if !ok {
  159. l.Fatalf("Requested versioning type %q that does not exist", cfg.Versioning.Type)
  160. }
  161. versioner := factory(folder, cfg.Path(), cfg.Versioning.Params)
  162. if service, ok := versioner.(suture.Service); ok {
  163. // The versioner implements the suture.Service interface, so
  164. // expects to be run in the background in addition to being called
  165. // when files are going to be archived.
  166. m.Add(service)
  167. }
  168. p.versioner = versioner
  169. }
  170. m.Add(p)
  171. l.Okln("Ready to synchronize", folder, "(read-write)")
  172. }
  173. // StartFolderRO starts read only processing on the current model. When in
  174. // read only mode the model will announce files to the cluster but not pull in
  175. // any external changes.
  176. func (m *Model) StartFolderRO(folder string) {
  177. m.fmut.Lock()
  178. cfg, ok := m.folderCfgs[folder]
  179. if !ok {
  180. panic("cannot start nonexistent folder " + folder)
  181. }
  182. _, ok = m.folderRunners[folder]
  183. if ok {
  184. panic("cannot start already running folder " + folder)
  185. }
  186. s := newROFolder(m, folder, time.Duration(cfg.RescanIntervalS)*time.Second)
  187. m.folderRunners[folder] = s
  188. m.fmut.Unlock()
  189. m.Add(s)
  190. l.Okln("Ready to synchronize", folder, "(read only; no external updates accepted)")
  191. }
  192. type ConnectionInfo struct {
  193. protocol.Statistics
  194. Connected bool
  195. Paused bool
  196. Address string
  197. ClientVersion string
  198. Type ConnectionType
  199. }
  200. func (info ConnectionInfo) MarshalJSON() ([]byte, error) {
  201. return json.Marshal(map[string]interface{}{
  202. "at": info.At,
  203. "inBytesTotal": info.InBytesTotal,
  204. "outBytesTotal": info.OutBytesTotal,
  205. "connected": info.Connected,
  206. "paused": info.Paused,
  207. "address": info.Address,
  208. "clientVersion": info.ClientVersion,
  209. "type": info.Type.String(),
  210. })
  211. }
  212. // ConnectionStats returns a map with connection statistics for each connected device.
  213. func (m *Model) ConnectionStats() map[string]interface{} {
  214. type remoteAddrer interface {
  215. RemoteAddr() net.Addr
  216. }
  217. m.pmut.RLock()
  218. m.fmut.RLock()
  219. res := make(map[string]interface{})
  220. devs := m.cfg.Devices()
  221. conns := make(map[string]ConnectionInfo, len(devs))
  222. for device := range devs {
  223. ci := ConnectionInfo{
  224. ClientVersion: m.deviceVer[device],
  225. Paused: m.devicePaused[device],
  226. }
  227. if conn, ok := m.conn[device]; ok {
  228. ci.Type = conn.Type
  229. ci.Connected = ok
  230. ci.Statistics = conn.Statistics()
  231. if addr := conn.RemoteAddr(); addr != nil {
  232. ci.Address = addr.String()
  233. }
  234. }
  235. conns[device.String()] = ci
  236. }
  237. res["connections"] = conns
  238. m.fmut.RUnlock()
  239. m.pmut.RUnlock()
  240. in, out := protocol.TotalInOut()
  241. res["total"] = ConnectionInfo{
  242. Statistics: protocol.Statistics{
  243. At: time.Now(),
  244. InBytesTotal: in,
  245. OutBytesTotal: out,
  246. },
  247. }
  248. return res
  249. }
  250. // DeviceStatistics returns statistics about each device
  251. func (m *Model) DeviceStatistics() map[string]stats.DeviceStatistics {
  252. var res = make(map[string]stats.DeviceStatistics)
  253. for id := range m.cfg.Devices() {
  254. res[id.String()] = m.deviceStatRef(id).GetStatistics()
  255. }
  256. return res
  257. }
  258. // FolderStatistics returns statistics about each folder
  259. func (m *Model) FolderStatistics() map[string]stats.FolderStatistics {
  260. var res = make(map[string]stats.FolderStatistics)
  261. for id := range m.cfg.Folders() {
  262. res[id] = m.folderStatRef(id).GetStatistics()
  263. }
  264. return res
  265. }
  266. // Completion returns the completion status, in percent, for the given device
  267. // and folder.
  268. func (m *Model) Completion(device protocol.DeviceID, folder string) float64 {
  269. var tot int64
  270. m.fmut.RLock()
  271. rf, ok := m.folderFiles[folder]
  272. m.fmut.RUnlock()
  273. if !ok {
  274. return 0 // Folder doesn't exist, so we hardly have any of it
  275. }
  276. rf.WithGlobalTruncated(func(f db.FileIntf) bool {
  277. if !f.IsDeleted() {
  278. tot += f.Size()
  279. }
  280. return true
  281. })
  282. if tot == 0 {
  283. return 100 // Folder is empty, so we have all of it
  284. }
  285. var need int64
  286. rf.WithNeedTruncated(device, func(f db.FileIntf) bool {
  287. if !f.IsDeleted() {
  288. need += f.Size()
  289. }
  290. return true
  291. })
  292. res := 100 * (1 - float64(need)/float64(tot))
  293. if debug {
  294. l.Debugf("%v Completion(%s, %q): %f (%d / %d)", m, device, folder, res, need, tot)
  295. }
  296. return res
  297. }
  298. func sizeOf(fs []protocol.FileInfo) (files, deleted int, bytes int64) {
  299. for _, f := range fs {
  300. fs, de, by := sizeOfFile(f)
  301. files += fs
  302. deleted += de
  303. bytes += by
  304. }
  305. return
  306. }
  307. func sizeOfFile(f db.FileIntf) (files, deleted int, bytes int64) {
  308. if !f.IsDeleted() {
  309. files++
  310. } else {
  311. deleted++
  312. }
  313. bytes += f.Size()
  314. return
  315. }
  316. // GlobalSize returns the number of files, deleted files and total bytes for all
  317. // files in the global model.
  318. func (m *Model) GlobalSize(folder string) (nfiles, deleted int, bytes int64) {
  319. m.fmut.RLock()
  320. defer m.fmut.RUnlock()
  321. if rf, ok := m.folderFiles[folder]; ok {
  322. rf.WithGlobalTruncated(func(f db.FileIntf) bool {
  323. fs, de, by := sizeOfFile(f)
  324. nfiles += fs
  325. deleted += de
  326. bytes += by
  327. return true
  328. })
  329. }
  330. return
  331. }
  332. // LocalSize returns the number of files, deleted files and total bytes for all
  333. // files in the local folder.
  334. func (m *Model) LocalSize(folder string) (nfiles, deleted int, bytes int64) {
  335. m.fmut.RLock()
  336. defer m.fmut.RUnlock()
  337. if rf, ok := m.folderFiles[folder]; ok {
  338. rf.WithHaveTruncated(protocol.LocalDeviceID, func(f db.FileIntf) bool {
  339. if f.IsInvalid() {
  340. return true
  341. }
  342. fs, de, by := sizeOfFile(f)
  343. nfiles += fs
  344. deleted += de
  345. bytes += by
  346. return true
  347. })
  348. }
  349. return
  350. }
  351. // NeedSize returns the number and total size of currently needed files.
  352. func (m *Model) NeedSize(folder string) (nfiles int, bytes int64) {
  353. m.fmut.RLock()
  354. defer m.fmut.RUnlock()
  355. if rf, ok := m.folderFiles[folder]; ok {
  356. rf.WithNeedTruncated(protocol.LocalDeviceID, func(f db.FileIntf) bool {
  357. fs, de, by := sizeOfFile(f)
  358. nfiles += fs + de
  359. bytes += by
  360. return true
  361. })
  362. }
  363. bytes -= m.progressEmitter.BytesCompleted(folder)
  364. if debug {
  365. l.Debugf("%v NeedSize(%q): %d %d", m, folder, nfiles, bytes)
  366. }
  367. return
  368. }
  369. // NeedFolderFiles returns paginated list of currently needed files in
  370. // progress, queued, and to be queued on next puller iteration, as well as the
  371. // total number of files currently needed.
  372. func (m *Model) NeedFolderFiles(folder string, page, perpage int) ([]db.FileInfoTruncated, []db.FileInfoTruncated, []db.FileInfoTruncated, int) {
  373. m.fmut.RLock()
  374. defer m.fmut.RUnlock()
  375. total := 0
  376. rf, ok := m.folderFiles[folder]
  377. if !ok {
  378. return nil, nil, nil, 0
  379. }
  380. var progress, queued, rest []db.FileInfoTruncated
  381. var seen map[string]struct{}
  382. skip := (page - 1) * perpage
  383. get := perpage
  384. runner, ok := m.folderRunners[folder]
  385. if ok {
  386. allProgressNames, allQueuedNames := runner.Jobs()
  387. var progressNames, queuedNames []string
  388. progressNames, skip, get = getChunk(allProgressNames, skip, get)
  389. queuedNames, skip, get = getChunk(allQueuedNames, skip, get)
  390. progress = make([]db.FileInfoTruncated, len(progressNames))
  391. queued = make([]db.FileInfoTruncated, len(queuedNames))
  392. seen = make(map[string]struct{}, len(progressNames)+len(queuedNames))
  393. for i, name := range progressNames {
  394. if f, ok := rf.GetGlobalTruncated(name); ok {
  395. progress[i] = f
  396. seen[name] = struct{}{}
  397. }
  398. }
  399. for i, name := range queuedNames {
  400. if f, ok := rf.GetGlobalTruncated(name); ok {
  401. queued[i] = f
  402. seen[name] = struct{}{}
  403. }
  404. }
  405. }
  406. rest = make([]db.FileInfoTruncated, 0, perpage)
  407. rf.WithNeedTruncated(protocol.LocalDeviceID, func(f db.FileIntf) bool {
  408. total++
  409. if skip > 0 {
  410. skip--
  411. return true
  412. }
  413. if get > 0 {
  414. ft := f.(db.FileInfoTruncated)
  415. if _, ok := seen[ft.Name]; !ok {
  416. rest = append(rest, ft)
  417. get--
  418. }
  419. }
  420. return true
  421. })
  422. return progress, queued, rest, total
  423. }
  424. // Index is called when a new device is connected and we receive their full index.
  425. // Implements the protocol.Model interface.
  426. func (m *Model) Index(deviceID protocol.DeviceID, folder string, fs []protocol.FileInfo, flags uint32, options []protocol.Option) {
  427. if flags != 0 {
  428. l.Warnln("protocol error: unknown flags 0x%x in Index message", flags)
  429. return
  430. }
  431. if debug {
  432. l.Debugf("IDX(in): %s %q: %d files", deviceID, folder, len(fs))
  433. }
  434. if !m.folderSharedWith(folder, deviceID) {
  435. events.Default.Log(events.FolderRejected, map[string]string{
  436. "folder": folder,
  437. "device": deviceID.String(),
  438. })
  439. 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)
  440. return
  441. }
  442. m.fmut.RLock()
  443. cfg := m.folderCfgs[folder]
  444. files, ok := m.folderFiles[folder]
  445. runner := m.folderRunners[folder]
  446. m.fmut.RUnlock()
  447. if runner != nil {
  448. // Runner may legitimately not be set if this is the "cleanup" Index
  449. // message at startup.
  450. defer runner.IndexUpdated()
  451. }
  452. if !ok {
  453. l.Fatalf("Index for nonexistant folder %q", folder)
  454. }
  455. fs = filterIndex(folder, fs, cfg.IgnoreDelete)
  456. files.Replace(deviceID, fs)
  457. events.Default.Log(events.RemoteIndexUpdated, map[string]interface{}{
  458. "device": deviceID.String(),
  459. "folder": folder,
  460. "items": len(fs),
  461. "version": files.LocalVersion(deviceID),
  462. })
  463. }
  464. // IndexUpdate is called for incremental updates to connected devices' indexes.
  465. // Implements the protocol.Model interface.
  466. func (m *Model) IndexUpdate(deviceID protocol.DeviceID, folder string, fs []protocol.FileInfo, flags uint32, options []protocol.Option) {
  467. if flags != 0 {
  468. l.Warnln("protocol error: unknown flags 0x%x in IndexUpdate message", flags)
  469. return
  470. }
  471. if debug {
  472. l.Debugf("%v IDXUP(in): %s / %q: %d files", m, deviceID, folder, len(fs))
  473. }
  474. if !m.folderSharedWith(folder, deviceID) {
  475. 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)
  476. return
  477. }
  478. m.fmut.RLock()
  479. files := m.folderFiles[folder]
  480. cfg := m.folderCfgs[folder]
  481. runner, ok := m.folderRunners[folder]
  482. m.fmut.RUnlock()
  483. if !ok {
  484. l.Fatalf("IndexUpdate for nonexistant folder %q", folder)
  485. }
  486. fs = filterIndex(folder, fs, cfg.IgnoreDelete)
  487. files.Update(deviceID, fs)
  488. events.Default.Log(events.RemoteIndexUpdated, map[string]interface{}{
  489. "device": deviceID.String(),
  490. "folder": folder,
  491. "items": len(fs),
  492. "version": files.LocalVersion(deviceID),
  493. })
  494. runner.IndexUpdated()
  495. }
  496. func (m *Model) folderSharedWith(folder string, deviceID protocol.DeviceID) bool {
  497. m.fmut.RLock()
  498. defer m.fmut.RUnlock()
  499. for _, nfolder := range m.deviceFolders[deviceID] {
  500. if nfolder == folder {
  501. return true
  502. }
  503. }
  504. return false
  505. }
  506. func (m *Model) ClusterConfig(deviceID protocol.DeviceID, cm protocol.ClusterConfigMessage) {
  507. m.pmut.Lock()
  508. if cm.ClientName == "syncthing" {
  509. m.deviceVer[deviceID] = cm.ClientVersion
  510. } else {
  511. m.deviceVer[deviceID] = cm.ClientName + " " + cm.ClientVersion
  512. }
  513. event := map[string]string{
  514. "id": deviceID.String(),
  515. "clientName": cm.ClientName,
  516. "clientVersion": cm.ClientVersion,
  517. }
  518. if conn, ok := m.conn[deviceID]; ok {
  519. event["type"] = conn.Type.String()
  520. addr := conn.RemoteAddr()
  521. if addr != nil {
  522. event["addr"] = addr.String()
  523. }
  524. }
  525. m.pmut.Unlock()
  526. events.Default.Log(events.DeviceConnected, event)
  527. l.Infof(`Device %s client is "%s %s"`, deviceID, cm.ClientName, cm.ClientVersion)
  528. var changed bool
  529. if name := cm.GetOption("name"); name != "" {
  530. l.Infof("Device %s name is %q", deviceID, name)
  531. device, ok := m.cfg.Devices()[deviceID]
  532. if ok && device.Name == "" {
  533. device.Name = name
  534. m.cfg.SetDevice(device)
  535. changed = true
  536. }
  537. }
  538. if m.cfg.Devices()[deviceID].Introducer {
  539. // This device is an introducer. Go through the announced lists of folders
  540. // and devices and add what we are missing.
  541. for _, folder := range cm.Folders {
  542. // If we don't have this folder yet, skip it. Ideally, we'd
  543. // offer up something in the GUI to create the folder, but for the
  544. // moment we only handle folders that we already have.
  545. if _, ok := m.folderDevices[folder.ID]; !ok {
  546. continue
  547. }
  548. nextDevice:
  549. for _, device := range folder.Devices {
  550. var id protocol.DeviceID
  551. copy(id[:], device.ID)
  552. if _, ok := m.cfg.Devices()[id]; !ok {
  553. // The device is currently unknown. Add it to the config.
  554. l.Infof("Adding device %v to config (vouched for by introducer %v)", id, deviceID)
  555. newDeviceCfg := config.DeviceConfiguration{
  556. DeviceID: id,
  557. Compression: m.cfg.Devices()[deviceID].Compression,
  558. Addresses: []string{"dynamic"},
  559. }
  560. // The introducers' introducers are also our introducers.
  561. if device.Flags&protocol.FlagIntroducer != 0 {
  562. l.Infof("Device %v is now also an introducer", id)
  563. newDeviceCfg.Introducer = true
  564. }
  565. m.cfg.SetDevice(newDeviceCfg)
  566. changed = true
  567. }
  568. for _, er := range m.deviceFolders[id] {
  569. if er == folder.ID {
  570. // We already share the folder with this device, so
  571. // nothing to do.
  572. continue nextDevice
  573. }
  574. }
  575. // We don't yet share this folder with this device. Add the device
  576. // to sharing list of the folder.
  577. l.Infof("Adding device %v to share %q (vouched for by introducer %v)", id, folder.ID, deviceID)
  578. m.deviceFolders[id] = append(m.deviceFolders[id], folder.ID)
  579. m.folderDevices[folder.ID] = append(m.folderDevices[folder.ID], id)
  580. folderCfg := m.cfg.Folders()[folder.ID]
  581. folderCfg.Devices = append(folderCfg.Devices, config.FolderDeviceConfiguration{
  582. DeviceID: id,
  583. })
  584. m.cfg.SetFolder(folderCfg)
  585. changed = true
  586. }
  587. }
  588. }
  589. if changed {
  590. m.cfg.Save()
  591. }
  592. }
  593. // Close removes the peer from the model and closes the underlying connection if possible.
  594. // Implements the protocol.Model interface.
  595. func (m *Model) Close(device protocol.DeviceID, err error) {
  596. l.Infof("Connection to %s closed: %v", device, err)
  597. events.Default.Log(events.DeviceDisconnected, map[string]string{
  598. "id": device.String(),
  599. "error": err.Error(),
  600. })
  601. m.pmut.Lock()
  602. m.fmut.RLock()
  603. for _, folder := range m.deviceFolders[device] {
  604. m.folderFiles[folder].Replace(device, nil)
  605. }
  606. m.fmut.RUnlock()
  607. conn, ok := m.conn[device]
  608. if ok {
  609. closeRawConn(conn)
  610. }
  611. delete(m.conn, device)
  612. delete(m.deviceVer, device)
  613. m.pmut.Unlock()
  614. }
  615. // Request returns the specified data segment by reading it from local disk.
  616. // Implements the protocol.Model interface.
  617. func (m *Model) Request(deviceID protocol.DeviceID, folder, name string, offset int64, hash []byte, flags uint32, options []protocol.Option, buf []byte) error {
  618. if offset < 0 {
  619. return protocol.ErrNoSuchFile
  620. }
  621. if !m.folderSharedWith(folder, deviceID) {
  622. l.Warnf("Request from %s for file %s in unshared folder %q", deviceID, name, folder)
  623. return protocol.ErrNoSuchFile
  624. }
  625. if flags != 0 {
  626. // We don't currently support or expect any flags.
  627. return fmt.Errorf("protocol error: unknown flags 0x%x in Request message", flags)
  628. }
  629. // Verify that the requested file exists in the local model. We only need
  630. // to validate this file if we haven't done so recently, so we keep a
  631. // cache of successfull results. "Recently" can be quite a long time, as
  632. // we remove validation cache entries when we detect local changes. If
  633. // we're out of sync here and the file actually doesn't exist any more, or
  634. // has shrunk or something, then we'll anyway get a read error that we
  635. // pass on to the other side.
  636. m.rvmut.RLock()
  637. validated := m.reqValidationCache[folder+"/"+name]
  638. m.rvmut.RUnlock()
  639. if time.Since(validated) > reqValidationTime {
  640. m.fmut.RLock()
  641. folderFiles, ok := m.folderFiles[folder]
  642. m.fmut.RUnlock()
  643. if !ok {
  644. l.Warnf("Request from %s for file %s in nonexistent folder %q", deviceID, name, folder)
  645. return protocol.ErrNoSuchFile
  646. }
  647. // This call is really expensive for large files, as we load the full
  648. // block list which may be megabytes and megabytes of data to allocate
  649. // space for, read, and deserialize.
  650. lf, ok := folderFiles.Get(protocol.LocalDeviceID, name)
  651. if !ok {
  652. return protocol.ErrNoSuchFile
  653. }
  654. if lf.IsInvalid() || lf.IsDeleted() {
  655. if debug {
  656. l.Debugf("%v REQ(in): %s: %q / %q o=%d s=%d; invalid: %v", m, deviceID, folder, name, offset, len(buf), lf)
  657. }
  658. return protocol.ErrInvalid
  659. }
  660. if offset > lf.Size() {
  661. if debug {
  662. l.Debugf("%v REQ(in; nonexistent): %s: %q o=%d s=%d", m, deviceID, name, offset, len(buf))
  663. }
  664. return protocol.ErrNoSuchFile
  665. }
  666. m.rvmut.Lock()
  667. m.reqValidationCache[folder+"/"+name] = time.Now()
  668. if len(m.reqValidationCache) > reqValidationCacheSize {
  669. // Don't let the cache grow infinitely
  670. for name, validated := range m.reqValidationCache {
  671. if time.Since(validated) > time.Minute {
  672. delete(m.reqValidationCache, name)
  673. }
  674. }
  675. if len(m.reqValidationCache) > reqValidationCacheSize*9/10 {
  676. // The first clean didn't help much, we're still over 90%
  677. // full; we may have synced a lot of files lately. Prune the
  678. // cache more aggressively by removing every other item so we
  679. // don't get stuck doing useless cache cleaning.
  680. i := 0
  681. for name := range m.reqValidationCache {
  682. if i%2 == 0 {
  683. delete(m.reqValidationCache, name)
  684. }
  685. i++
  686. }
  687. }
  688. }
  689. m.rvmut.Unlock()
  690. }
  691. if debug && deviceID != protocol.LocalDeviceID {
  692. l.Debugf("%v REQ(in): %s: %q / %q o=%d s=%d", m, deviceID, folder, name, offset, len(buf))
  693. }
  694. m.fmut.RLock()
  695. fn := filepath.Join(m.folderCfgs[folder].Path(), name)
  696. m.fmut.RUnlock()
  697. var reader io.ReaderAt
  698. var err error
  699. if info, err := os.Lstat(fn); err == nil && info.Mode()&os.ModeSymlink != 0 {
  700. target, _, err := symlinks.Read(fn)
  701. if err != nil {
  702. return err
  703. }
  704. reader = strings.NewReader(target)
  705. } else {
  706. // Cannot easily cache fd's because we might need to delete the file
  707. // at any moment.
  708. reader, err = os.Open(fn)
  709. if err != nil {
  710. return err
  711. }
  712. defer reader.(*os.File).Close()
  713. }
  714. _, err = reader.ReadAt(buf, offset)
  715. if err != nil {
  716. return err
  717. }
  718. return nil
  719. }
  720. func (m *Model) CurrentFolderFile(folder string, file string) (protocol.FileInfo, bool) {
  721. m.fmut.RLock()
  722. fs, ok := m.folderFiles[folder]
  723. m.fmut.RUnlock()
  724. if !ok {
  725. return protocol.FileInfo{}, false
  726. }
  727. f, ok := fs.Get(protocol.LocalDeviceID, file)
  728. return f, ok
  729. }
  730. func (m *Model) CurrentGlobalFile(folder string, file string) (protocol.FileInfo, bool) {
  731. m.fmut.RLock()
  732. fs, ok := m.folderFiles[folder]
  733. m.fmut.RUnlock()
  734. if !ok {
  735. return protocol.FileInfo{}, false
  736. }
  737. f, ok := fs.GetGlobal(file)
  738. return f, ok
  739. }
  740. type cFiler struct {
  741. m *Model
  742. r string
  743. }
  744. // Implements scanner.CurrentFiler
  745. func (cf cFiler) CurrentFile(file string) (protocol.FileInfo, bool) {
  746. return cf.m.CurrentFolderFile(cf.r, file)
  747. }
  748. // ConnectedTo returns true if we are connected to the named device.
  749. func (m *Model) ConnectedTo(deviceID protocol.DeviceID) bool {
  750. m.pmut.RLock()
  751. _, ok := m.conn[deviceID]
  752. m.pmut.RUnlock()
  753. if ok {
  754. m.deviceWasSeen(deviceID)
  755. }
  756. return ok
  757. }
  758. func (m *Model) GetIgnores(folder string) ([]string, []string, error) {
  759. var lines []string
  760. m.fmut.RLock()
  761. cfg, ok := m.folderCfgs[folder]
  762. m.fmut.RUnlock()
  763. if !ok {
  764. return lines, nil, fmt.Errorf("Folder %s does not exist", folder)
  765. }
  766. fd, err := os.Open(filepath.Join(cfg.Path(), ".stignore"))
  767. if err != nil {
  768. if os.IsNotExist(err) {
  769. return lines, nil, nil
  770. }
  771. l.Warnln("Loading .stignore:", err)
  772. return lines, nil, err
  773. }
  774. defer fd.Close()
  775. scanner := bufio.NewScanner(fd)
  776. for scanner.Scan() {
  777. lines = append(lines, strings.TrimSpace(scanner.Text()))
  778. }
  779. m.fmut.RLock()
  780. patterns := m.folderIgnores[folder].Patterns()
  781. m.fmut.RUnlock()
  782. return lines, patterns, nil
  783. }
  784. func (m *Model) SetIgnores(folder string, content []string) error {
  785. cfg, ok := m.folderCfgs[folder]
  786. if !ok {
  787. return fmt.Errorf("Folder %s does not exist", folder)
  788. }
  789. path := filepath.Join(cfg.Path(), ".stignore")
  790. fd, err := osutil.CreateAtomic(path, 0644)
  791. if err != nil {
  792. l.Warnln("Saving .stignore:", err)
  793. return err
  794. }
  795. for _, line := range content {
  796. fmt.Fprintln(fd, line)
  797. }
  798. if err := fd.Close(); err != nil {
  799. l.Warnln("Saving .stignore:", err)
  800. return err
  801. }
  802. osutil.HideFile(path)
  803. return m.ScanFolder(folder)
  804. }
  805. // AddConnection adds a new peer connection to the model. An initial index will
  806. // be sent to the connected peer, thereafter index updates whenever the local
  807. // folder changes.
  808. func (m *Model) AddConnection(conn Connection) {
  809. deviceID := conn.ID()
  810. m.pmut.Lock()
  811. if _, ok := m.conn[deviceID]; ok {
  812. panic("add existing device")
  813. }
  814. m.conn[deviceID] = conn
  815. conn.Start()
  816. cm := m.clusterConfig(deviceID)
  817. conn.ClusterConfig(cm)
  818. m.fmut.RLock()
  819. for _, folder := range m.deviceFolders[deviceID] {
  820. fs := m.folderFiles[folder]
  821. go sendIndexes(conn, folder, fs, m.folderIgnores[folder])
  822. }
  823. m.fmut.RUnlock()
  824. m.pmut.Unlock()
  825. m.deviceWasSeen(deviceID)
  826. }
  827. func (m *Model) PauseDevice(device protocol.DeviceID) {
  828. m.pmut.Lock()
  829. m.devicePaused[device] = true
  830. _, ok := m.conn[device]
  831. m.pmut.Unlock()
  832. if ok {
  833. m.Close(device, errors.New("device paused"))
  834. }
  835. events.Default.Log(events.DevicePaused, map[string]string{"device": device.String()})
  836. }
  837. func (m *Model) ResumeDevice(device protocol.DeviceID) {
  838. m.pmut.Lock()
  839. m.devicePaused[device] = false
  840. m.pmut.Unlock()
  841. events.Default.Log(events.DeviceResumed, map[string]string{"device": device.String()})
  842. }
  843. func (m *Model) IsPaused(device protocol.DeviceID) bool {
  844. m.pmut.Lock()
  845. paused := m.devicePaused[device]
  846. m.pmut.Unlock()
  847. return paused
  848. }
  849. func (m *Model) deviceStatRef(deviceID protocol.DeviceID) *stats.DeviceStatisticsReference {
  850. m.fmut.Lock()
  851. defer m.fmut.Unlock()
  852. if sr, ok := m.deviceStatRefs[deviceID]; ok {
  853. return sr
  854. }
  855. sr := stats.NewDeviceStatisticsReference(m.db, deviceID.String())
  856. m.deviceStatRefs[deviceID] = sr
  857. return sr
  858. }
  859. func (m *Model) deviceWasSeen(deviceID protocol.DeviceID) {
  860. m.deviceStatRef(deviceID).WasSeen()
  861. }
  862. func (m *Model) folderStatRef(folder string) *stats.FolderStatisticsReference {
  863. m.fmut.Lock()
  864. defer m.fmut.Unlock()
  865. sr, ok := m.folderStatRefs[folder]
  866. if !ok {
  867. sr = stats.NewFolderStatisticsReference(m.db, folder)
  868. m.folderStatRefs[folder] = sr
  869. }
  870. return sr
  871. }
  872. func (m *Model) receivedFile(folder string, file protocol.FileInfo) {
  873. m.folderStatRef(folder).ReceivedFile(file.Name, file.IsDeleted())
  874. }
  875. func sendIndexes(conn protocol.Connection, folder string, fs *db.FileSet, ignores *ignore.Matcher) {
  876. deviceID := conn.ID()
  877. name := conn.Name()
  878. var err error
  879. if debug {
  880. l.Debugf("sendIndexes for %s-%s/%q starting", deviceID, name, folder)
  881. }
  882. minLocalVer, err := sendIndexTo(true, 0, conn, folder, fs, ignores)
  883. sub := events.Default.Subscribe(events.LocalIndexUpdated)
  884. defer events.Default.Unsubscribe(sub)
  885. for err == nil {
  886. // While we have sent a localVersion at least equal to the one
  887. // currently in the database, wait for the local index to update. The
  888. // local index may update for other folders than the one we are
  889. // sending for.
  890. if fs.LocalVersion(protocol.LocalDeviceID) <= minLocalVer {
  891. sub.Poll(time.Minute)
  892. continue
  893. }
  894. minLocalVer, err = sendIndexTo(false, minLocalVer, conn, folder, fs, ignores)
  895. // Wait a short amount of time before entering the next loop. If there
  896. // are continous changes happening to the local index, this gives us
  897. // time to batch them up a little.
  898. time.Sleep(250 * time.Millisecond)
  899. }
  900. if debug {
  901. l.Debugf("sendIndexes for %s-%s/%q exiting: %v", deviceID, name, folder, err)
  902. }
  903. }
  904. func sendIndexTo(initial bool, minLocalVer int64, conn protocol.Connection, folder string, fs *db.FileSet, ignores *ignore.Matcher) (int64, error) {
  905. deviceID := conn.ID()
  906. name := conn.Name()
  907. batch := make([]protocol.FileInfo, 0, indexBatchSize)
  908. currentBatchSize := 0
  909. maxLocalVer := int64(0)
  910. var err error
  911. fs.WithHave(protocol.LocalDeviceID, func(fi db.FileIntf) bool {
  912. f := fi.(protocol.FileInfo)
  913. if f.LocalVersion <= minLocalVer {
  914. return true
  915. }
  916. if f.LocalVersion > maxLocalVer {
  917. maxLocalVer = f.LocalVersion
  918. }
  919. if ignores.Match(f.Name) || symlinkInvalid(folder, f) {
  920. if debug {
  921. l.Debugln("not sending update for ignored/unsupported symlink", f)
  922. }
  923. return true
  924. }
  925. if len(batch) == indexBatchSize || currentBatchSize > indexTargetSize {
  926. if initial {
  927. if err = conn.Index(folder, batch, 0, nil); err != nil {
  928. return false
  929. }
  930. if debug {
  931. l.Debugf("sendIndexes for %s-%s/%q: %d files (<%d bytes) (initial index)", deviceID, name, folder, len(batch), currentBatchSize)
  932. }
  933. initial = false
  934. } else {
  935. if err = conn.IndexUpdate(folder, batch, 0, nil); err != nil {
  936. return false
  937. }
  938. if debug {
  939. l.Debugf("sendIndexes for %s-%s/%q: %d files (<%d bytes) (batched update)", deviceID, name, folder, len(batch), currentBatchSize)
  940. }
  941. }
  942. batch = make([]protocol.FileInfo, 0, indexBatchSize)
  943. currentBatchSize = 0
  944. }
  945. batch = append(batch, f)
  946. currentBatchSize += indexPerFileSize + len(f.Blocks)*indexPerBlockSize
  947. return true
  948. })
  949. if initial && err == nil {
  950. err = conn.Index(folder, batch, 0, nil)
  951. if debug && err == nil {
  952. l.Debugf("sendIndexes for %s-%s/%q: %d files (small initial index)", deviceID, name, folder, len(batch))
  953. }
  954. } else if len(batch) > 0 && err == nil {
  955. err = conn.IndexUpdate(folder, batch, 0, nil)
  956. if debug && err == nil {
  957. l.Debugf("sendIndexes for %s-%s/%q: %d files (last batch)", deviceID, name, folder, len(batch))
  958. }
  959. }
  960. return maxLocalVer, err
  961. }
  962. func (m *Model) updateLocals(folder string, fs []protocol.FileInfo) {
  963. m.fmut.RLock()
  964. files := m.folderFiles[folder]
  965. m.fmut.RUnlock()
  966. files.Update(protocol.LocalDeviceID, fs)
  967. m.rvmut.Lock()
  968. for _, f := range fs {
  969. delete(m.reqValidationCache, folder+"/"+f.Name)
  970. }
  971. m.rvmut.Unlock()
  972. events.Default.Log(events.LocalIndexUpdated, map[string]interface{}{
  973. "folder": folder,
  974. "items": len(fs),
  975. "version": files.LocalVersion(protocol.LocalDeviceID),
  976. })
  977. }
  978. func (m *Model) requestGlobal(deviceID protocol.DeviceID, folder, name string, offset int64, size int, hash []byte, flags uint32, options []protocol.Option) ([]byte, error) {
  979. m.pmut.RLock()
  980. nc, ok := m.conn[deviceID]
  981. m.pmut.RUnlock()
  982. if !ok {
  983. return nil, fmt.Errorf("requestGlobal: no such device: %s", deviceID)
  984. }
  985. if debug {
  986. 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)
  987. }
  988. return nc.Request(folder, name, offset, size, hash, flags, options)
  989. }
  990. func (m *Model) AddFolder(cfg config.FolderConfiguration) {
  991. if len(cfg.ID) == 0 {
  992. panic("cannot add empty folder id")
  993. }
  994. m.fmut.Lock()
  995. m.folderCfgs[cfg.ID] = cfg
  996. m.folderFiles[cfg.ID] = db.NewFileSet(cfg.ID, m.db)
  997. m.folderDevices[cfg.ID] = make([]protocol.DeviceID, len(cfg.Devices))
  998. for i, device := range cfg.Devices {
  999. m.folderDevices[cfg.ID][i] = device.DeviceID
  1000. m.deviceFolders[device.DeviceID] = append(m.deviceFolders[device.DeviceID], cfg.ID)
  1001. }
  1002. ignores := ignore.New(m.cacheIgnoredFiles)
  1003. _ = ignores.Load(filepath.Join(cfg.Path(), ".stignore")) // Ignore error, there might not be an .stignore
  1004. m.folderIgnores[cfg.ID] = ignores
  1005. m.fmut.Unlock()
  1006. }
  1007. func (m *Model) ScanFolders() map[string]error {
  1008. m.fmut.RLock()
  1009. folders := make([]string, 0, len(m.folderCfgs))
  1010. for folder := range m.folderCfgs {
  1011. folders = append(folders, folder)
  1012. }
  1013. m.fmut.RUnlock()
  1014. errors := make(map[string]error, len(m.folderCfgs))
  1015. errorsMut := sync.NewMutex()
  1016. wg := sync.NewWaitGroup()
  1017. wg.Add(len(folders))
  1018. for _, folder := range folders {
  1019. folder := folder
  1020. go func() {
  1021. err := m.ScanFolder(folder)
  1022. if err != nil {
  1023. errorsMut.Lock()
  1024. errors[folder] = err
  1025. errorsMut.Unlock()
  1026. // Potentially sets the error twice, once in the scanner just
  1027. // by doing a check, and once here, if the error returned is
  1028. // the same one as returned by CheckFolderHealth, though
  1029. // duplicate set is handled by setError.
  1030. m.fmut.RLock()
  1031. srv := m.folderRunners[folder]
  1032. m.fmut.RUnlock()
  1033. srv.setError(err)
  1034. }
  1035. wg.Done()
  1036. }()
  1037. }
  1038. wg.Wait()
  1039. return errors
  1040. }
  1041. func (m *Model) ScanFolder(folder string) error {
  1042. return m.ScanFolderSubs(folder, nil)
  1043. }
  1044. func (m *Model) ScanFolderSubs(folder string, subs []string) error {
  1045. m.fmut.Lock()
  1046. runner, ok := m.folderRunners[folder]
  1047. m.fmut.Unlock()
  1048. // Folders are added to folderRunners only when they are started. We can't
  1049. // scan them before they have started, so that's what we need to check for
  1050. // here.
  1051. if !ok {
  1052. return errors.New("no such folder")
  1053. }
  1054. return runner.Scan(subs)
  1055. }
  1056. func (m *Model) internalScanFolderSubs(folder string, subs []string) error {
  1057. for i, sub := range subs {
  1058. sub = osutil.NativeFilename(sub)
  1059. if p := filepath.Clean(filepath.Join(folder, sub)); !strings.HasPrefix(p, folder) {
  1060. return errors.New("invalid subpath")
  1061. }
  1062. subs[i] = sub
  1063. }
  1064. m.fmut.Lock()
  1065. fs := m.folderFiles[folder]
  1066. folderCfg := m.folderCfgs[folder]
  1067. ignores := m.folderIgnores[folder]
  1068. runner, ok := m.folderRunners[folder]
  1069. m.fmut.Unlock()
  1070. // Folders are added to folderRunners only when they are started. We can't
  1071. // scan them before they have started, so that's what we need to check for
  1072. // here.
  1073. if !ok {
  1074. return errors.New("no such folder")
  1075. }
  1076. if err := m.CheckFolderHealth(folder); err != nil {
  1077. return err
  1078. }
  1079. _ = ignores.Load(filepath.Join(folderCfg.Path(), ".stignore")) // Ignore error, there might not be an .stignore
  1080. // Required to make sure that we start indexing at a directory we're already
  1081. // aware off.
  1082. var unifySubs []string
  1083. nextSub:
  1084. for _, sub := range subs {
  1085. for sub != "" {
  1086. parent := filepath.Dir(sub)
  1087. if parent == "." || parent == string(filepath.Separator) {
  1088. parent = ""
  1089. }
  1090. if _, ok = fs.Get(protocol.LocalDeviceID, parent); ok {
  1091. break
  1092. }
  1093. sub = parent
  1094. }
  1095. for _, us := range unifySubs {
  1096. if strings.HasPrefix(sub, us) {
  1097. continue nextSub
  1098. }
  1099. }
  1100. unifySubs = append(unifySubs, sub)
  1101. }
  1102. subs = unifySubs
  1103. w := &scanner.Walker{
  1104. Folder: folderCfg.ID,
  1105. Dir: folderCfg.Path(),
  1106. Subs: subs,
  1107. Matcher: ignores,
  1108. BlockSize: protocol.BlockSize,
  1109. TempNamer: defTempNamer,
  1110. TempLifetime: time.Duration(m.cfg.Options().KeepTemporariesH) * time.Hour,
  1111. CurrentFiler: cFiler{m, folder},
  1112. MtimeRepo: db.NewVirtualMtimeRepo(m.db, folderCfg.ID),
  1113. IgnorePerms: folderCfg.IgnorePerms,
  1114. AutoNormalize: folderCfg.AutoNormalize,
  1115. Hashers: m.numHashers(folder),
  1116. ShortID: m.shortID,
  1117. ProgressTickIntervalS: folderCfg.ScanProgressIntervalS,
  1118. }
  1119. runner.setState(FolderScanning)
  1120. fchan, err := w.Walk()
  1121. if err != nil {
  1122. // The error we get here is likely an OS level error, which might not be
  1123. // as readable as our health check errors. Check if we can get a health
  1124. // check error first, and use that if it's available.
  1125. if ferr := m.CheckFolderHealth(folder); ferr != nil {
  1126. err = ferr
  1127. }
  1128. runner.setError(err)
  1129. return err
  1130. }
  1131. batchSizeFiles := 100
  1132. batchSizeBlocks := 2048 // about 256 MB
  1133. batch := make([]protocol.FileInfo, 0, batchSizeFiles)
  1134. blocksHandled := 0
  1135. for f := range fchan {
  1136. if len(batch) == batchSizeFiles || blocksHandled > batchSizeBlocks {
  1137. if err := m.CheckFolderHealth(folder); err != nil {
  1138. l.Infof("Stopping folder %s mid-scan due to folder error: %s", folder, err)
  1139. return err
  1140. }
  1141. m.updateLocals(folder, batch)
  1142. batch = batch[:0]
  1143. blocksHandled = 0
  1144. }
  1145. batch = append(batch, f)
  1146. blocksHandled += len(f.Blocks)
  1147. }
  1148. if err := m.CheckFolderHealth(folder); err != nil {
  1149. l.Infof("Stopping folder %s mid-scan due to folder error: %s", folder, err)
  1150. return err
  1151. } else if len(batch) > 0 {
  1152. m.updateLocals(folder, batch)
  1153. }
  1154. batch = batch[:0]
  1155. // TODO: We should limit the Have scanning to start at sub
  1156. seenPrefix := false
  1157. var iterError error
  1158. fs.WithHaveTruncated(protocol.LocalDeviceID, func(fi db.FileIntf) bool {
  1159. f := fi.(db.FileInfoTruncated)
  1160. hasPrefix := len(subs) == 0
  1161. for _, sub := range subs {
  1162. if strings.HasPrefix(f.Name, sub) {
  1163. hasPrefix = true
  1164. break
  1165. }
  1166. }
  1167. // Return true so that we keep iterating, until we get to the part
  1168. // of the tree we are interested in. Then return false so we stop
  1169. // iterating when we've passed the end of the subtree.
  1170. if !hasPrefix {
  1171. return !seenPrefix
  1172. }
  1173. seenPrefix = true
  1174. if !f.IsDeleted() {
  1175. if f.IsInvalid() {
  1176. return true
  1177. }
  1178. if len(batch) == batchSizeFiles {
  1179. if err := m.CheckFolderHealth(folder); err != nil {
  1180. iterError = err
  1181. return false
  1182. }
  1183. m.updateLocals(folder, batch)
  1184. batch = batch[:0]
  1185. }
  1186. if ignores.Match(f.Name) || symlinkInvalid(folder, f) {
  1187. // File has been ignored or an unsupported symlink. Set invalid bit.
  1188. if debug {
  1189. l.Debugln("setting invalid bit on ignored", f)
  1190. }
  1191. nf := protocol.FileInfo{
  1192. Name: f.Name,
  1193. Flags: f.Flags | protocol.FlagInvalid,
  1194. Modified: f.Modified,
  1195. Version: f.Version, // The file is still the same, so don't bump version
  1196. }
  1197. batch = append(batch, nf)
  1198. } else if _, err := osutil.Lstat(filepath.Join(folderCfg.Path(), f.Name)); err != nil {
  1199. // File has been deleted.
  1200. // We don't specifically verify that the error is
  1201. // os.IsNotExist because there is a corner case when a
  1202. // directory is suddenly transformed into a file. When that
  1203. // happens, files that were in the directory (that is now a
  1204. // file) are deleted but will return a confusing error ("not a
  1205. // directory") when we try to Lstat() them.
  1206. nf := protocol.FileInfo{
  1207. Name: f.Name,
  1208. Flags: f.Flags | protocol.FlagDeleted,
  1209. Modified: f.Modified,
  1210. Version: f.Version.Update(m.shortID),
  1211. }
  1212. batch = append(batch, nf)
  1213. }
  1214. }
  1215. return true
  1216. })
  1217. if iterError != nil {
  1218. l.Infof("Stopping folder %s mid-scan due to folder error: %s", folder, iterError)
  1219. return iterError
  1220. }
  1221. if err := m.CheckFolderHealth(folder); err != nil {
  1222. l.Infof("Stopping folder %s mid-scan due to folder error: %s", folder, err)
  1223. return err
  1224. } else if len(batch) > 0 {
  1225. m.updateLocals(folder, batch)
  1226. }
  1227. runner.setState(FolderIdle)
  1228. return nil
  1229. }
  1230. func (m *Model) DelayScan(folder string, next time.Duration) {
  1231. m.fmut.Lock()
  1232. runner, ok := m.folderRunners[folder]
  1233. m.fmut.Unlock()
  1234. if !ok {
  1235. return
  1236. }
  1237. runner.DelayScan(next)
  1238. }
  1239. // numHashers returns the number of hasher routines to use for a given folder,
  1240. // taking into account configuration and available CPU cores.
  1241. func (m *Model) numHashers(folder string) int {
  1242. m.fmut.Lock()
  1243. folderCfg := m.folderCfgs[folder]
  1244. numFolders := len(m.folderCfgs)
  1245. m.fmut.Unlock()
  1246. if folderCfg.Hashers > 0 {
  1247. // Specific value set in the config, use that.
  1248. return folderCfg.Hashers
  1249. }
  1250. if runtime.GOOS == "windows" || runtime.GOOS == "darwin" {
  1251. // Interactive operating systems; don't load the system too heavily by
  1252. // default.
  1253. return 1
  1254. }
  1255. // For other operating systems and architectures, lets try to get some
  1256. // work done... Divide the available CPU cores among the configured
  1257. // folders.
  1258. if perFolder := runtime.GOMAXPROCS(-1) / numFolders; perFolder > 0 {
  1259. return perFolder
  1260. }
  1261. return 1
  1262. }
  1263. // clusterConfig returns a ClusterConfigMessage that is correct for the given peer device
  1264. func (m *Model) clusterConfig(device protocol.DeviceID) protocol.ClusterConfigMessage {
  1265. cm := protocol.ClusterConfigMessage{
  1266. ClientName: m.clientName,
  1267. ClientVersion: m.clientVersion,
  1268. Options: []protocol.Option{
  1269. {
  1270. Key: "name",
  1271. Value: m.deviceName,
  1272. },
  1273. },
  1274. }
  1275. m.fmut.RLock()
  1276. for _, folder := range m.deviceFolders[device] {
  1277. cr := protocol.Folder{
  1278. ID: folder,
  1279. }
  1280. for _, device := range m.folderDevices[folder] {
  1281. // DeviceID is a value type, but with an underlying array. Copy it
  1282. // so we don't grab aliases to the same array later on in device[:]
  1283. device := device
  1284. // TODO: Set read only bit when relevant
  1285. cn := protocol.Device{
  1286. ID: device[:],
  1287. Flags: protocol.FlagShareTrusted,
  1288. }
  1289. if deviceCfg := m.cfg.Devices()[device]; deviceCfg.Introducer {
  1290. cn.Flags |= protocol.FlagIntroducer
  1291. }
  1292. cr.Devices = append(cr.Devices, cn)
  1293. }
  1294. cm.Folders = append(cm.Folders, cr)
  1295. }
  1296. m.fmut.RUnlock()
  1297. return cm
  1298. }
  1299. func (m *Model) State(folder string) (string, time.Time, error) {
  1300. m.fmut.RLock()
  1301. runner, ok := m.folderRunners[folder]
  1302. m.fmut.RUnlock()
  1303. if !ok {
  1304. // The returned error should be an actual folder error, so returning
  1305. // errors.New("does not exist") or similar here would be
  1306. // inappropriate.
  1307. return "", time.Time{}, nil
  1308. }
  1309. state, changed, err := runner.getState()
  1310. return state.String(), changed, err
  1311. }
  1312. func (m *Model) Override(folder string) {
  1313. m.fmut.RLock()
  1314. fs, ok := m.folderFiles[folder]
  1315. runner := m.folderRunners[folder]
  1316. m.fmut.RUnlock()
  1317. if !ok {
  1318. return
  1319. }
  1320. runner.setState(FolderScanning)
  1321. batch := make([]protocol.FileInfo, 0, indexBatchSize)
  1322. fs.WithNeed(protocol.LocalDeviceID, func(fi db.FileIntf) bool {
  1323. need := fi.(protocol.FileInfo)
  1324. if len(batch) == indexBatchSize {
  1325. m.updateLocals(folder, batch)
  1326. batch = batch[:0]
  1327. }
  1328. have, ok := fs.Get(protocol.LocalDeviceID, need.Name)
  1329. if !ok || have.Name != need.Name {
  1330. // We are missing the file
  1331. need.Flags |= protocol.FlagDeleted
  1332. need.Blocks = nil
  1333. need.Version = need.Version.Update(m.shortID)
  1334. } else {
  1335. // We have the file, replace with our version
  1336. have.Version = have.Version.Merge(need.Version).Update(m.shortID)
  1337. need = have
  1338. }
  1339. need.LocalVersion = 0
  1340. batch = append(batch, need)
  1341. return true
  1342. })
  1343. if len(batch) > 0 {
  1344. m.updateLocals(folder, batch)
  1345. }
  1346. runner.setState(FolderIdle)
  1347. }
  1348. // CurrentLocalVersion returns the change version for the given folder.
  1349. // This is guaranteed to increment if the contents of the local folder has
  1350. // changed.
  1351. func (m *Model) CurrentLocalVersion(folder string) (int64, bool) {
  1352. m.fmut.RLock()
  1353. fs, ok := m.folderFiles[folder]
  1354. m.fmut.RUnlock()
  1355. if !ok {
  1356. // The folder might not exist, since this can be called with a user
  1357. // specified folder name from the REST interface.
  1358. return 0, false
  1359. }
  1360. return fs.LocalVersion(protocol.LocalDeviceID), true
  1361. }
  1362. // RemoteLocalVersion returns the change version for the given folder, as
  1363. // sent by remote peers. This is guaranteed to increment if the contents of
  1364. // the remote or global folder has changed.
  1365. func (m *Model) RemoteLocalVersion(folder string) (int64, bool) {
  1366. m.fmut.RLock()
  1367. defer m.fmut.RUnlock()
  1368. fs, ok := m.folderFiles[folder]
  1369. if !ok {
  1370. // The folder might not exist, since this can be called with a user
  1371. // specified folder name from the REST interface.
  1372. return 0, false
  1373. }
  1374. var ver int64
  1375. for _, n := range m.folderDevices[folder] {
  1376. ver += fs.LocalVersion(n)
  1377. }
  1378. return ver, true
  1379. }
  1380. func (m *Model) GlobalDirectoryTree(folder, prefix string, levels int, dirsonly bool) map[string]interface{} {
  1381. m.fmut.RLock()
  1382. files, ok := m.folderFiles[folder]
  1383. m.fmut.RUnlock()
  1384. if !ok {
  1385. return nil
  1386. }
  1387. output := make(map[string]interface{})
  1388. sep := string(filepath.Separator)
  1389. prefix = osutil.NativeFilename(prefix)
  1390. if prefix != "" && !strings.HasSuffix(prefix, sep) {
  1391. prefix = prefix + sep
  1392. }
  1393. files.WithPrefixedGlobalTruncated(prefix, func(fi db.FileIntf) bool {
  1394. f := fi.(db.FileInfoTruncated)
  1395. if f.IsInvalid() || f.IsDeleted() || f.Name == prefix {
  1396. return true
  1397. }
  1398. f.Name = strings.Replace(f.Name, prefix, "", 1)
  1399. var dir, base string
  1400. if f.IsDirectory() && !f.IsSymlink() {
  1401. dir = f.Name
  1402. } else {
  1403. dir = filepath.Dir(f.Name)
  1404. base = filepath.Base(f.Name)
  1405. }
  1406. if levels > -1 && strings.Count(f.Name, sep) > levels {
  1407. return true
  1408. }
  1409. last := output
  1410. if dir != "." {
  1411. for _, path := range strings.Split(dir, sep) {
  1412. directory, ok := last[path]
  1413. if !ok {
  1414. newdir := make(map[string]interface{})
  1415. last[path] = newdir
  1416. last = newdir
  1417. } else {
  1418. last = directory.(map[string]interface{})
  1419. }
  1420. }
  1421. }
  1422. if !dirsonly && base != "" {
  1423. last[base] = []interface{}{
  1424. time.Unix(f.Modified, 0), f.Size(),
  1425. }
  1426. }
  1427. return true
  1428. })
  1429. return output
  1430. }
  1431. func (m *Model) Availability(folder, file string) []protocol.DeviceID {
  1432. // Acquire this lock first, as the value returned from foldersFiles can
  1433. // get heavily modified on Close()
  1434. m.pmut.RLock()
  1435. defer m.pmut.RUnlock()
  1436. m.fmut.RLock()
  1437. fs, ok := m.folderFiles[folder]
  1438. m.fmut.RUnlock()
  1439. if !ok {
  1440. return nil
  1441. }
  1442. availableDevices := []protocol.DeviceID{}
  1443. for _, device := range fs.Availability(file) {
  1444. _, ok := m.conn[device]
  1445. if ok {
  1446. availableDevices = append(availableDevices, device)
  1447. }
  1448. }
  1449. return availableDevices
  1450. }
  1451. // BringToFront bumps the given files priority in the job queue.
  1452. func (m *Model) BringToFront(folder, file string) {
  1453. m.pmut.RLock()
  1454. defer m.pmut.RUnlock()
  1455. runner, ok := m.folderRunners[folder]
  1456. if ok {
  1457. runner.BringToFront(file)
  1458. }
  1459. }
  1460. // CheckFolderHealth checks the folder for common errors and returns the
  1461. // current folder error, or nil if the folder is healthy.
  1462. func (m *Model) CheckFolderHealth(id string) error {
  1463. if minFree := m.cfg.Options().MinHomeDiskFreePct; minFree > 0 {
  1464. if free, err := osutil.DiskFreePercentage(m.cfg.ConfigPath()); err == nil && free < minFree {
  1465. return errors.New("home disk is out of space")
  1466. }
  1467. }
  1468. folder, ok := m.cfg.Folders()[id]
  1469. if !ok {
  1470. return errors.New("folder does not exist")
  1471. }
  1472. fi, err := os.Stat(folder.Path())
  1473. if v, ok := m.CurrentLocalVersion(id); ok && v > 0 {
  1474. // Safety check. If the cached index contains files but the
  1475. // folder doesn't exist, we have a problem. We would assume
  1476. // that all files have been deleted which might not be the case,
  1477. // so mark it as invalid instead.
  1478. if err != nil || !fi.IsDir() {
  1479. err = errors.New("folder path missing")
  1480. } else if !folder.HasMarker() {
  1481. err = errors.New("folder marker missing")
  1482. } else if free, errDfp := osutil.DiskFreePercentage(folder.Path()); errDfp == nil && free < folder.MinDiskFreePct {
  1483. err = errors.New("out of disk space")
  1484. }
  1485. } else if os.IsNotExist(err) {
  1486. // If we don't have any files in the index, and the directory
  1487. // doesn't exist, try creating it.
  1488. err = osutil.MkdirAll(folder.Path(), 0700)
  1489. if err == nil {
  1490. err = folder.CreateMarker()
  1491. }
  1492. } else if !folder.HasMarker() {
  1493. // If we don't have any files in the index, and the path does exist
  1494. // but the marker is not there, create it.
  1495. err = folder.CreateMarker()
  1496. }
  1497. m.fmut.RLock()
  1498. runner, runnerExists := m.folderRunners[folder.ID]
  1499. m.fmut.RUnlock()
  1500. var oldErr error
  1501. if runnerExists {
  1502. _, _, oldErr = runner.getState()
  1503. }
  1504. if err != nil {
  1505. if oldErr != nil && oldErr.Error() != err.Error() {
  1506. l.Infof("Folder %q error changed: %q -> %q", folder.ID, oldErr, err)
  1507. } else if oldErr == nil {
  1508. l.Warnf("Stopping folder %q - %v", folder.ID, err)
  1509. }
  1510. if runnerExists {
  1511. runner.setError(err)
  1512. }
  1513. } else if oldErr != nil {
  1514. l.Infof("Folder %q error is cleared, restarting", folder.ID)
  1515. if runnerExists {
  1516. runner.clearError()
  1517. }
  1518. }
  1519. return err
  1520. }
  1521. func (m *Model) ResetFolder(folder string) {
  1522. l.Infof("Cleaning data for folder %q", folder)
  1523. db.DropFolder(m.db, folder)
  1524. }
  1525. func (m *Model) String() string {
  1526. return fmt.Sprintf("model@%p", m)
  1527. }
  1528. func (m *Model) VerifyConfiguration(from, to config.Configuration) error {
  1529. return nil
  1530. }
  1531. func (m *Model) CommitConfiguration(from, to config.Configuration) bool {
  1532. // TODO: This should not use reflect, and should take more care to try to handle stuff without restart.
  1533. // Go through the folder configs and figure out if we need to restart or not.
  1534. fromFolders := mapFolders(from.Folders)
  1535. toFolders := mapFolders(to.Folders)
  1536. for folderID, cfg := range toFolders {
  1537. if _, ok := fromFolders[folderID]; !ok {
  1538. // A folder was added.
  1539. if debug {
  1540. l.Debugln(m, "adding folder", folderID)
  1541. }
  1542. m.AddFolder(cfg)
  1543. if cfg.ReadOnly {
  1544. m.StartFolderRO(folderID)
  1545. } else {
  1546. m.StartFolderRW(folderID)
  1547. }
  1548. // Drop connections to all devices that can now share the new
  1549. // folder.
  1550. m.pmut.Lock()
  1551. for _, dev := range cfg.DeviceIDs() {
  1552. if conn, ok := m.conn[dev]; ok {
  1553. closeRawConn(conn)
  1554. }
  1555. }
  1556. m.pmut.Unlock()
  1557. }
  1558. }
  1559. for folderID, fromCfg := range fromFolders {
  1560. toCfg, ok := toFolders[folderID]
  1561. if !ok {
  1562. // A folder was removed. Requires restart.
  1563. if debug {
  1564. l.Debugln(m, "requires restart, removing folder", folderID)
  1565. }
  1566. return false
  1567. }
  1568. // This folder exists on both sides. Compare the device lists, as we
  1569. // can handle adding a device (but not currently removing one).
  1570. fromDevs := mapDevices(fromCfg.DeviceIDs())
  1571. toDevs := mapDevices(toCfg.DeviceIDs())
  1572. for dev := range fromDevs {
  1573. if _, ok := toDevs[dev]; !ok {
  1574. // A device was removed. Requires restart.
  1575. if debug {
  1576. l.Debugln(m, "requires restart, removing device", dev, "from folder", folderID)
  1577. }
  1578. return false
  1579. }
  1580. }
  1581. for dev := range toDevs {
  1582. if _, ok := fromDevs[dev]; !ok {
  1583. // A device was added. Handle it!
  1584. m.fmut.Lock()
  1585. m.pmut.Lock()
  1586. m.folderCfgs[folderID] = toCfg
  1587. m.folderDevices[folderID] = append(m.folderDevices[folderID], dev)
  1588. m.deviceFolders[dev] = append(m.deviceFolders[dev], folderID)
  1589. // If we already have a connection to this device, we should
  1590. // disconnect it so that we start sharing the folder with it.
  1591. // We close the underlying connection and let the normal error
  1592. // handling kick in to clean up and reconnect.
  1593. if conn, ok := m.conn[dev]; ok {
  1594. closeRawConn(conn)
  1595. }
  1596. m.pmut.Unlock()
  1597. m.fmut.Unlock()
  1598. }
  1599. }
  1600. // Check if anything else differs, apart from the device list.
  1601. fromCfg.Devices = nil
  1602. toCfg.Devices = nil
  1603. if !reflect.DeepEqual(fromCfg, toCfg) {
  1604. if debug {
  1605. l.Debugln(m, "requires restart, folder", folderID, "configuration differs")
  1606. }
  1607. return false
  1608. }
  1609. }
  1610. // Removing a device requres restart
  1611. toDevs := mapDeviceCfgs(from.Devices)
  1612. for _, dev := range from.Devices {
  1613. if _, ok := toDevs[dev.DeviceID]; !ok {
  1614. if debug {
  1615. l.Debugln(m, "requires restart, device", dev.DeviceID, "was removed")
  1616. }
  1617. return false
  1618. }
  1619. }
  1620. // All of the generic options require restart
  1621. if !reflect.DeepEqual(from.Options, to.Options) {
  1622. if debug {
  1623. l.Debugln(m, "requires restart, options differ")
  1624. }
  1625. return false
  1626. }
  1627. return true
  1628. }
  1629. // mapFolders returns a map of folder ID to folder configuration for the given
  1630. // slice of folder configurations.
  1631. func mapFolders(folders []config.FolderConfiguration) map[string]config.FolderConfiguration {
  1632. m := make(map[string]config.FolderConfiguration, len(folders))
  1633. for _, cfg := range folders {
  1634. m[cfg.ID] = cfg
  1635. }
  1636. return m
  1637. }
  1638. // mapDevices returns a map of device ID to nothing for the given slice of
  1639. // device IDs.
  1640. func mapDevices(devices []protocol.DeviceID) map[protocol.DeviceID]struct{} {
  1641. m := make(map[protocol.DeviceID]struct{}, len(devices))
  1642. for _, dev := range devices {
  1643. m[dev] = struct{}{}
  1644. }
  1645. return m
  1646. }
  1647. // mapDeviceCfgs returns a map of device ID to nothing for the given slice of
  1648. // device configurations.
  1649. func mapDeviceCfgs(devices []config.DeviceConfiguration) map[protocol.DeviceID]struct{} {
  1650. m := make(map[protocol.DeviceID]struct{}, len(devices))
  1651. for _, dev := range devices {
  1652. m[dev.DeviceID] = struct{}{}
  1653. }
  1654. return m
  1655. }
  1656. func filterIndex(folder string, fs []protocol.FileInfo, dropDeletes bool) []protocol.FileInfo {
  1657. for i := 0; i < len(fs); {
  1658. if fs[i].Flags&^protocol.FlagsAll != 0 {
  1659. if debug {
  1660. l.Debugln("dropping update for file with unknown bits set", fs[i])
  1661. }
  1662. fs[i] = fs[len(fs)-1]
  1663. fs = fs[:len(fs)-1]
  1664. } else if fs[i].IsDeleted() && dropDeletes {
  1665. if debug {
  1666. l.Debugln("dropping update for undesired delete", fs[i])
  1667. }
  1668. fs[i] = fs[len(fs)-1]
  1669. fs = fs[:len(fs)-1]
  1670. } else if symlinkInvalid(folder, fs[i]) {
  1671. if debug {
  1672. l.Debugln("dropping update for unsupported symlink", fs[i])
  1673. }
  1674. fs[i] = fs[len(fs)-1]
  1675. fs = fs[:len(fs)-1]
  1676. } else {
  1677. i++
  1678. }
  1679. }
  1680. return fs
  1681. }
  1682. func symlinkInvalid(folder string, fi db.FileIntf) bool {
  1683. if !symlinks.Supported && fi.IsSymlink() && !fi.IsInvalid() && !fi.IsDeleted() {
  1684. symlinkWarning.Do(func() {
  1685. l.Warnln("Symlinks are disabled, unsupported or require Administrator privileges. This might cause your folder to appear out of sync.")
  1686. })
  1687. // Need to type switch for the concrete type to be able to access fields...
  1688. var name string
  1689. switch fi := fi.(type) {
  1690. case protocol.FileInfo:
  1691. name = fi.Name
  1692. case db.FileInfoTruncated:
  1693. name = fi.Name
  1694. }
  1695. l.Infoln("Unsupported symlink", name, "in folder", folder)
  1696. return true
  1697. }
  1698. return false
  1699. }
  1700. // Skips `skip` elements and retrieves up to `get` elements from a given slice.
  1701. // Returns the resulting slice, plus how much elements are left to skip or
  1702. // copy to satisfy the values which were provided, given the slice is not
  1703. // big enough.
  1704. func getChunk(data []string, skip, get int) ([]string, int, int) {
  1705. l := len(data)
  1706. if l <= skip {
  1707. return []string{}, skip - l, get
  1708. } else if l < skip+get {
  1709. return data[skip:l], 0, get - (l - skip)
  1710. }
  1711. return data[skip : skip+get], 0, 0
  1712. }
  1713. func closeRawConn(conn io.Closer) error {
  1714. if conn, ok := conn.(*tls.Conn); ok {
  1715. // If the underlying connection is a *tls.Conn, Close() does more
  1716. // than it says on the tin. Specifically, it sends a TLS alert
  1717. // message, which might block forever if the connection is dead
  1718. // and we don't have a deadline set.
  1719. conn.SetWriteDeadline(time.Now().Add(250 * time.Millisecond))
  1720. }
  1721. return conn.Close()
  1722. }