model.go 58 KB

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