model.go 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021
  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 uint64
  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.Okln("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.Okln("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. events.Default.Log(events.FolderRejected, map[string]string{
  449. "folder": folder,
  450. "device": deviceID.String(),
  451. })
  452. 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)
  453. return
  454. }
  455. m.fmut.RLock()
  456. cfg := m.folderCfgs[folder]
  457. files, ok := m.folderFiles[folder]
  458. runner := m.folderRunners[folder]
  459. m.fmut.RUnlock()
  460. if runner != nil {
  461. // Runner may legitimately not be set if this is the "cleanup" Index
  462. // message at startup.
  463. defer runner.IndexUpdated()
  464. }
  465. if !ok {
  466. l.Fatalf("Index for nonexistant folder %q", folder)
  467. }
  468. fs = filterIndex(folder, fs, cfg.IgnoreDelete)
  469. files.Replace(deviceID, fs)
  470. events.Default.Log(events.RemoteIndexUpdated, map[string]interface{}{
  471. "device": deviceID.String(),
  472. "folder": folder,
  473. "items": len(fs),
  474. "version": files.LocalVersion(deviceID),
  475. })
  476. }
  477. // IndexUpdate is called for incremental updates to connected devices' indexes.
  478. // Implements the protocol.Model interface.
  479. func (m *Model) IndexUpdate(deviceID protocol.DeviceID, folder string, fs []protocol.FileInfo, flags uint32, options []protocol.Option) {
  480. if flags != 0 {
  481. l.Warnln("protocol error: unknown flags 0x%x in IndexUpdate message", flags)
  482. return
  483. }
  484. l.Debugf("%v IDXUP(in): %s / %q: %d files", m, deviceID, folder, len(fs))
  485. if !m.folderSharedWith(folder, deviceID) {
  486. 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)
  487. return
  488. }
  489. m.fmut.RLock()
  490. files := m.folderFiles[folder]
  491. cfg := m.folderCfgs[folder]
  492. runner, ok := m.folderRunners[folder]
  493. m.fmut.RUnlock()
  494. if !ok {
  495. l.Fatalf("IndexUpdate for nonexistant folder %q", folder)
  496. }
  497. fs = filterIndex(folder, fs, cfg.IgnoreDelete)
  498. files.Update(deviceID, fs)
  499. events.Default.Log(events.RemoteIndexUpdated, map[string]interface{}{
  500. "device": deviceID.String(),
  501. "folder": folder,
  502. "items": len(fs),
  503. "version": files.LocalVersion(deviceID),
  504. })
  505. runner.IndexUpdated()
  506. }
  507. func (m *Model) folderSharedWith(folder string, deviceID protocol.DeviceID) bool {
  508. m.fmut.RLock()
  509. defer m.fmut.RUnlock()
  510. for _, nfolder := range m.deviceFolders[deviceID] {
  511. if nfolder == folder {
  512. return true
  513. }
  514. }
  515. return false
  516. }
  517. func (m *Model) ClusterConfig(deviceID protocol.DeviceID, cm protocol.ClusterConfigMessage) {
  518. m.pmut.Lock()
  519. if cm.ClientName == "syncthing" {
  520. m.deviceVer[deviceID] = cm.ClientVersion
  521. } else {
  522. m.deviceVer[deviceID] = cm.ClientName + " " + cm.ClientVersion
  523. }
  524. event := map[string]string{
  525. "id": deviceID.String(),
  526. "deviceName": cm.DeviceName,
  527. "clientName": cm.ClientName,
  528. "clientVersion": cm.ClientVersion,
  529. }
  530. if conn, ok := m.conn[deviceID]; ok {
  531. event["type"] = conn.Type.String()
  532. addr := conn.RemoteAddr()
  533. if addr != nil {
  534. event["addr"] = addr.String()
  535. }
  536. }
  537. m.pmut.Unlock()
  538. events.Default.Log(events.DeviceConnected, event)
  539. l.Infof(`Device %s client is "%s %s" named "%s"`, deviceID, cm.ClientName, cm.ClientVersion, cm.DeviceName)
  540. var changed bool
  541. device, ok := m.cfg.Devices()[deviceID]
  542. if ok && device.Name == "" {
  543. device.Name = cm.DeviceName
  544. m.cfg.SetDevice(device)
  545. changed = true
  546. }
  547. if m.cfg.Devices()[deviceID].Introducer {
  548. // This device is an introducer. Go through the announced lists of folders
  549. // and devices and add what we are missing.
  550. for _, folder := range cm.Folders {
  551. // If we don't have this folder yet, skip it. Ideally, we'd
  552. // offer up something in the GUI to create the folder, but for the
  553. // moment we only handle folders that we already have.
  554. if _, ok := m.folderDevices[folder.ID]; !ok {
  555. continue
  556. }
  557. nextDevice:
  558. for _, device := range folder.Devices {
  559. var id protocol.DeviceID
  560. copy(id[:], device.ID)
  561. if _, ok := m.cfg.Devices()[id]; !ok {
  562. // The device is currently unknown. Add it to the config.
  563. addresses := []string{"dynamic"}
  564. for _, addr := range device.Addresses {
  565. if addr != "dynamic" {
  566. addresses = append(addresses, addr)
  567. }
  568. }
  569. l.Infof("Adding device %v to config (vouched for by introducer %v)", id, deviceID)
  570. newDeviceCfg := config.DeviceConfiguration{
  571. DeviceID: id,
  572. Name: device.Name,
  573. Compression: m.cfg.Devices()[deviceID].Compression,
  574. Addresses: addresses,
  575. CertName: device.CertName,
  576. }
  577. // The introducers' introducers are also our introducers.
  578. if device.Flags&protocol.FlagIntroducer != 0 {
  579. l.Infof("Device %v is now also an introducer", id)
  580. newDeviceCfg.Introducer = true
  581. }
  582. m.cfg.SetDevice(newDeviceCfg)
  583. changed = true
  584. }
  585. for _, er := range m.deviceFolders[id] {
  586. if er == folder.ID {
  587. // We already share the folder with this device, so
  588. // nothing to do.
  589. continue nextDevice
  590. }
  591. }
  592. // We don't yet share this folder with this device. Add the device
  593. // to sharing list of the folder.
  594. l.Infof("Adding device %v to share %q (vouched for by introducer %v)", id, folder.ID, deviceID)
  595. m.deviceFolders[id] = append(m.deviceFolders[id], folder.ID)
  596. m.folderDevices[folder.ID] = append(m.folderDevices[folder.ID], id)
  597. folderCfg := m.cfg.Folders()[folder.ID]
  598. folderCfg.Devices = append(folderCfg.Devices, config.FolderDeviceConfiguration{
  599. DeviceID: id,
  600. })
  601. m.cfg.SetFolder(folderCfg)
  602. changed = true
  603. }
  604. }
  605. }
  606. if changed {
  607. m.cfg.Save()
  608. }
  609. }
  610. // Close removes the peer from the model and closes the underlying connection if possible.
  611. // Implements the protocol.Model interface.
  612. func (m *Model) Close(device protocol.DeviceID, err error) {
  613. l.Infof("Connection to %s closed: %v", device, err)
  614. events.Default.Log(events.DeviceDisconnected, map[string]string{
  615. "id": device.String(),
  616. "error": err.Error(),
  617. })
  618. m.pmut.Lock()
  619. m.fmut.RLock()
  620. for _, folder := range m.deviceFolders[device] {
  621. m.folderFiles[folder].Replace(device, nil)
  622. }
  623. m.fmut.RUnlock()
  624. conn, ok := m.conn[device]
  625. if ok {
  626. closeRawConn(conn)
  627. }
  628. delete(m.conn, device)
  629. delete(m.deviceVer, device)
  630. m.pmut.Unlock()
  631. }
  632. // Request returns the specified data segment by reading it from local disk.
  633. // Implements the protocol.Model interface.
  634. func (m *Model) Request(deviceID protocol.DeviceID, folder, name string, offset int64, hash []byte, flags uint32, options []protocol.Option, buf []byte) error {
  635. if offset < 0 {
  636. return protocol.ErrInvalid
  637. }
  638. if !m.folderSharedWith(folder, deviceID) {
  639. l.Warnf("Request from %s for file %s in unshared folder %q", deviceID, name, folder)
  640. return protocol.ErrInvalid
  641. }
  642. if flags != 0 {
  643. // We don't currently support or expect any flags.
  644. return protocol.ErrInvalid
  645. }
  646. if deviceID != protocol.LocalDeviceID {
  647. l.Debugf("%v REQ(in): %s: %q / %q o=%d s=%d", m, deviceID, folder, name, offset, len(buf))
  648. }
  649. m.fmut.RLock()
  650. folderPath := m.folderCfgs[folder].Path()
  651. folderIgnores := m.folderIgnores[folder]
  652. m.fmut.RUnlock()
  653. // filepath.Join() returns a filepath.Clean()ed path, which (quoting the
  654. // docs for clarity here):
  655. //
  656. // Clean returns the shortest path name equivalent to path by purely lexical
  657. // processing. It applies the following rules iteratively until no further
  658. // processing can be done:
  659. //
  660. // 1. Replace multiple Separator elements with a single one.
  661. // 2. Eliminate each . path name element (the current directory).
  662. // 3. Eliminate each inner .. path name element (the parent directory)
  663. // along with the non-.. element that precedes it.
  664. // 4. Eliminate .. elements that begin a rooted path:
  665. // that is, replace "/.." by "/" at the beginning of a path,
  666. // assuming Separator is '/'.
  667. fn := filepath.Join(folderPath, name)
  668. if !strings.HasPrefix(fn, folderPath) {
  669. // Request tries to escape!
  670. l.Debugf("%v Invalid REQ(in) tries to escape: %s: %q / %q o=%d s=%d", m, deviceID, folder, name, offset, len(buf))
  671. return protocol.ErrInvalid
  672. }
  673. if folderIgnores != nil {
  674. // "rn" becomes the relative name of the file within the folder. This is
  675. // different than the original "name" parameter in that it's been
  676. // cleaned from any possible funny business.
  677. if rn, err := filepath.Rel(folderPath, fn); err != nil {
  678. return err
  679. } else if folderIgnores.Match(rn) {
  680. l.Debugf("%v REQ(in) for ignored file: %s: %q / %q o=%d s=%d", m, deviceID, folder, name, offset, len(buf))
  681. return protocol.ErrNoSuchFile
  682. }
  683. }
  684. var reader io.ReaderAt
  685. var err error
  686. if info, err := os.Lstat(fn); err == nil && info.Mode()&os.ModeSymlink != 0 {
  687. target, _, err := symlinks.Read(fn)
  688. if err != nil {
  689. l.Debugln("symlinks.Read:", err)
  690. if os.IsNotExist(err) {
  691. return protocol.ErrNoSuchFile
  692. }
  693. return protocol.ErrGeneric
  694. }
  695. reader = strings.NewReader(target)
  696. } else {
  697. // Cannot easily cache fd's because we might need to delete the file
  698. // at any moment.
  699. reader, err = os.Open(fn)
  700. if err != nil {
  701. l.Debugln("os.Open:", err)
  702. if os.IsNotExist(err) {
  703. return protocol.ErrNoSuchFile
  704. }
  705. return protocol.ErrGeneric
  706. }
  707. defer reader.(*os.File).Close()
  708. }
  709. _, err = reader.ReadAt(buf, offset)
  710. if err != nil {
  711. l.Debugln("reader.ReadAt:", err)
  712. return protocol.ErrGeneric
  713. }
  714. return nil
  715. }
  716. func (m *Model) CurrentFolderFile(folder string, file string) (protocol.FileInfo, bool) {
  717. m.fmut.RLock()
  718. fs, ok := m.folderFiles[folder]
  719. m.fmut.RUnlock()
  720. if !ok {
  721. return protocol.FileInfo{}, false
  722. }
  723. f, ok := fs.Get(protocol.LocalDeviceID, file)
  724. return f, ok
  725. }
  726. func (m *Model) CurrentGlobalFile(folder string, file string) (protocol.FileInfo, bool) {
  727. m.fmut.RLock()
  728. fs, ok := m.folderFiles[folder]
  729. m.fmut.RUnlock()
  730. if !ok {
  731. return protocol.FileInfo{}, false
  732. }
  733. f, ok := fs.GetGlobal(file)
  734. return f, ok
  735. }
  736. type cFiler struct {
  737. m *Model
  738. r string
  739. }
  740. // Implements scanner.CurrentFiler
  741. func (cf cFiler) CurrentFile(file string) (protocol.FileInfo, bool) {
  742. return cf.m.CurrentFolderFile(cf.r, file)
  743. }
  744. // ConnectedTo returns true if we are connected to the named device.
  745. func (m *Model) ConnectedTo(deviceID protocol.DeviceID) bool {
  746. m.pmut.RLock()
  747. _, ok := m.conn[deviceID]
  748. m.pmut.RUnlock()
  749. if ok {
  750. m.deviceWasSeen(deviceID)
  751. }
  752. return ok
  753. }
  754. func (m *Model) GetIgnores(folder string) ([]string, []string, error) {
  755. var lines []string
  756. m.fmut.RLock()
  757. cfg, ok := m.folderCfgs[folder]
  758. m.fmut.RUnlock()
  759. if !ok {
  760. return lines, nil, fmt.Errorf("Folder %s does not exist", folder)
  761. }
  762. fd, err := os.Open(filepath.Join(cfg.Path(), ".stignore"))
  763. if err != nil {
  764. if os.IsNotExist(err) {
  765. return lines, nil, nil
  766. }
  767. l.Warnln("Loading .stignore:", err)
  768. return lines, nil, err
  769. }
  770. defer fd.Close()
  771. scanner := bufio.NewScanner(fd)
  772. for scanner.Scan() {
  773. lines = append(lines, strings.TrimSpace(scanner.Text()))
  774. }
  775. m.fmut.RLock()
  776. patterns := m.folderIgnores[folder].Patterns()
  777. m.fmut.RUnlock()
  778. return lines, patterns, nil
  779. }
  780. func (m *Model) SetIgnores(folder string, content []string) error {
  781. cfg, ok := m.folderCfgs[folder]
  782. if !ok {
  783. return fmt.Errorf("Folder %s does not exist", folder)
  784. }
  785. path := filepath.Join(cfg.Path(), ".stignore")
  786. fd, err := osutil.CreateAtomic(path, 0644)
  787. if err != nil {
  788. l.Warnln("Saving .stignore:", err)
  789. return err
  790. }
  791. for _, line := range content {
  792. fmt.Fprintln(fd, line)
  793. }
  794. if err := fd.Close(); err != nil {
  795. l.Warnln("Saving .stignore:", err)
  796. return err
  797. }
  798. osutil.HideFile(path)
  799. return m.ScanFolder(folder)
  800. }
  801. // AddConnection adds a new peer connection to the model. An initial index will
  802. // be sent to the connected peer, thereafter index updates whenever the local
  803. // folder changes.
  804. func (m *Model) AddConnection(conn Connection) {
  805. deviceID := conn.ID()
  806. m.pmut.Lock()
  807. if _, ok := m.conn[deviceID]; ok {
  808. panic("add existing device")
  809. }
  810. m.conn[deviceID] = conn
  811. conn.Start()
  812. cm := m.generateClusterConfig(deviceID)
  813. conn.ClusterConfig(cm)
  814. m.fmut.RLock()
  815. for _, folder := range m.deviceFolders[deviceID] {
  816. fs := m.folderFiles[folder]
  817. go sendIndexes(conn, folder, fs, m.folderIgnores[folder])
  818. }
  819. m.fmut.RUnlock()
  820. m.pmut.Unlock()
  821. m.deviceWasSeen(deviceID)
  822. }
  823. func (m *Model) PauseDevice(device protocol.DeviceID) {
  824. m.pmut.Lock()
  825. m.devicePaused[device] = true
  826. _, ok := m.conn[device]
  827. m.pmut.Unlock()
  828. if ok {
  829. m.Close(device, errors.New("device paused"))
  830. }
  831. events.Default.Log(events.DevicePaused, map[string]string{"device": device.String()})
  832. }
  833. func (m *Model) ResumeDevice(device protocol.DeviceID) {
  834. m.pmut.Lock()
  835. m.devicePaused[device] = false
  836. m.pmut.Unlock()
  837. events.Default.Log(events.DeviceResumed, map[string]string{"device": device.String()})
  838. }
  839. func (m *Model) IsPaused(device protocol.DeviceID) bool {
  840. m.pmut.Lock()
  841. paused := m.devicePaused[device]
  842. m.pmut.Unlock()
  843. return paused
  844. }
  845. func (m *Model) deviceStatRef(deviceID protocol.DeviceID) *stats.DeviceStatisticsReference {
  846. m.fmut.Lock()
  847. defer m.fmut.Unlock()
  848. if sr, ok := m.deviceStatRefs[deviceID]; ok {
  849. return sr
  850. }
  851. sr := stats.NewDeviceStatisticsReference(m.db, deviceID.String())
  852. m.deviceStatRefs[deviceID] = sr
  853. return sr
  854. }
  855. func (m *Model) deviceWasSeen(deviceID protocol.DeviceID) {
  856. m.deviceStatRef(deviceID).WasSeen()
  857. }
  858. func (m *Model) folderStatRef(folder string) *stats.FolderStatisticsReference {
  859. m.fmut.Lock()
  860. defer m.fmut.Unlock()
  861. sr, ok := m.folderStatRefs[folder]
  862. if !ok {
  863. sr = stats.NewFolderStatisticsReference(m.db, folder)
  864. m.folderStatRefs[folder] = sr
  865. }
  866. return sr
  867. }
  868. func (m *Model) receivedFile(folder string, file protocol.FileInfo) {
  869. m.folderStatRef(folder).ReceivedFile(file.Name, file.IsDeleted())
  870. }
  871. func sendIndexes(conn protocol.Connection, folder string, fs *db.FileSet, ignores *ignore.Matcher) {
  872. deviceID := conn.ID()
  873. name := conn.Name()
  874. var err error
  875. l.Debugf("sendIndexes for %s-%s/%q starting", deviceID, name, folder)
  876. defer l.Debugf("sendIndexes for %s-%s/%q exiting: %v", deviceID, name, folder, err)
  877. minLocalVer, err := sendIndexTo(true, 0, conn, folder, fs, ignores)
  878. sub := events.Default.Subscribe(events.LocalIndexUpdated)
  879. defer events.Default.Unsubscribe(sub)
  880. for err == nil {
  881. // While we have sent a localVersion at least equal to the one
  882. // currently in the database, wait for the local index to update. The
  883. // local index may update for other folders than the one we are
  884. // sending for.
  885. if fs.LocalVersion(protocol.LocalDeviceID) <= minLocalVer {
  886. sub.Poll(time.Minute)
  887. continue
  888. }
  889. minLocalVer, err = sendIndexTo(false, minLocalVer, conn, folder, fs, ignores)
  890. // Wait a short amount of time before entering the next loop. If there
  891. // are continuous changes happening to the local index, this gives us
  892. // time to batch them up a little.
  893. time.Sleep(250 * time.Millisecond)
  894. }
  895. }
  896. func sendIndexTo(initial bool, minLocalVer int64, conn protocol.Connection, folder string, fs *db.FileSet, ignores *ignore.Matcher) (int64, error) {
  897. deviceID := conn.ID()
  898. name := conn.Name()
  899. batch := make([]protocol.FileInfo, 0, indexBatchSize)
  900. currentBatchSize := 0
  901. maxLocalVer := int64(0)
  902. var err error
  903. fs.WithHave(protocol.LocalDeviceID, func(fi db.FileIntf) bool {
  904. f := fi.(protocol.FileInfo)
  905. if f.LocalVersion <= minLocalVer {
  906. return true
  907. }
  908. if f.LocalVersion > maxLocalVer {
  909. maxLocalVer = f.LocalVersion
  910. }
  911. if ignores.Match(f.Name) || symlinkInvalid(folder, f) {
  912. l.Debugln("not sending update for ignored/unsupported symlink", f)
  913. return true
  914. }
  915. if len(batch) == indexBatchSize || currentBatchSize > indexTargetSize {
  916. if initial {
  917. if err = conn.Index(folder, batch, 0, nil); err != nil {
  918. return false
  919. }
  920. l.Debugf("sendIndexes for %s-%s/%q: %d files (<%d bytes) (initial index)", deviceID, name, folder, len(batch), currentBatchSize)
  921. initial = false
  922. } else {
  923. if err = conn.IndexUpdate(folder, batch, 0, nil); err != nil {
  924. return false
  925. }
  926. l.Debugf("sendIndexes for %s-%s/%q: %d files (<%d bytes) (batched update)", deviceID, name, folder, len(batch), currentBatchSize)
  927. }
  928. batch = make([]protocol.FileInfo, 0, indexBatchSize)
  929. currentBatchSize = 0
  930. }
  931. batch = append(batch, f)
  932. currentBatchSize += indexPerFileSize + len(f.Blocks)*indexPerBlockSize
  933. return true
  934. })
  935. if initial && err == nil {
  936. err = conn.Index(folder, batch, 0, nil)
  937. if err == nil {
  938. l.Debugf("sendIndexes for %s-%s/%q: %d files (small initial index)", deviceID, name, folder, len(batch))
  939. }
  940. } else if len(batch) > 0 && err == nil {
  941. err = conn.IndexUpdate(folder, batch, 0, nil)
  942. if err == nil {
  943. l.Debugf("sendIndexes for %s-%s/%q: %d files (last batch)", deviceID, name, folder, len(batch))
  944. }
  945. }
  946. return maxLocalVer, err
  947. }
  948. func (m *Model) updateLocals(folder string, fs []protocol.FileInfo) {
  949. m.fmut.RLock()
  950. files := m.folderFiles[folder]
  951. m.fmut.RUnlock()
  952. files.Update(protocol.LocalDeviceID, fs)
  953. events.Default.Log(events.LocalIndexUpdated, map[string]interface{}{
  954. "folder": folder,
  955. "items": len(fs),
  956. "version": files.LocalVersion(protocol.LocalDeviceID),
  957. })
  958. }
  959. func (m *Model) requestGlobal(deviceID protocol.DeviceID, folder, name string, offset int64, size int, hash []byte, flags uint32, options []protocol.Option) ([]byte, error) {
  960. m.pmut.RLock()
  961. nc, ok := m.conn[deviceID]
  962. m.pmut.RUnlock()
  963. if !ok {
  964. return nil, fmt.Errorf("requestGlobal: no such device: %s", deviceID)
  965. }
  966. 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)
  967. return nc.Request(folder, name, offset, size, hash, flags, options)
  968. }
  969. func (m *Model) AddFolder(cfg config.FolderConfiguration) {
  970. if len(cfg.ID) == 0 {
  971. panic("cannot add empty folder id")
  972. }
  973. m.fmut.Lock()
  974. m.folderCfgs[cfg.ID] = cfg
  975. m.folderFiles[cfg.ID] = db.NewFileSet(cfg.ID, m.db)
  976. m.folderDevices[cfg.ID] = make([]protocol.DeviceID, len(cfg.Devices))
  977. for i, device := range cfg.Devices {
  978. m.folderDevices[cfg.ID][i] = device.DeviceID
  979. m.deviceFolders[device.DeviceID] = append(m.deviceFolders[device.DeviceID], cfg.ID)
  980. }
  981. ignores := ignore.New(m.cacheIgnoredFiles)
  982. if err := ignores.Load(filepath.Join(cfg.Path(), ".stignore")); err != nil && !os.IsNotExist(err) {
  983. l.Warnln("Loading ignores:", err)
  984. }
  985. m.folderIgnores[cfg.ID] = ignores
  986. m.fmut.Unlock()
  987. }
  988. func (m *Model) ScanFolders() map[string]error {
  989. m.fmut.RLock()
  990. folders := make([]string, 0, len(m.folderCfgs))
  991. for folder := range m.folderCfgs {
  992. folders = append(folders, folder)
  993. }
  994. m.fmut.RUnlock()
  995. errors := make(map[string]error, len(m.folderCfgs))
  996. errorsMut := sync.NewMutex()
  997. wg := sync.NewWaitGroup()
  998. wg.Add(len(folders))
  999. for _, folder := range folders {
  1000. folder := folder
  1001. go func() {
  1002. err := m.ScanFolder(folder)
  1003. if err != nil {
  1004. errorsMut.Lock()
  1005. errors[folder] = err
  1006. errorsMut.Unlock()
  1007. // Potentially sets the error twice, once in the scanner just
  1008. // by doing a check, and once here, if the error returned is
  1009. // the same one as returned by CheckFolderHealth, though
  1010. // duplicate set is handled by setError.
  1011. m.fmut.RLock()
  1012. srv := m.folderRunners[folder]
  1013. m.fmut.RUnlock()
  1014. srv.setError(err)
  1015. }
  1016. wg.Done()
  1017. }()
  1018. }
  1019. wg.Wait()
  1020. return errors
  1021. }
  1022. func (m *Model) ScanFolder(folder string) error {
  1023. return m.ScanFolderSubs(folder, nil)
  1024. }
  1025. func (m *Model) ScanFolderSubs(folder string, subs []string) error {
  1026. m.fmut.Lock()
  1027. runner, ok := m.folderRunners[folder]
  1028. m.fmut.Unlock()
  1029. // Folders are added to folderRunners only when they are started. We can't
  1030. // scan them before they have started, so that's what we need to check for
  1031. // here.
  1032. if !ok {
  1033. return errors.New("no such folder")
  1034. }
  1035. return runner.Scan(subs)
  1036. }
  1037. func (m *Model) internalScanFolderSubs(folder string, subs []string) error {
  1038. for i, sub := range subs {
  1039. sub = osutil.NativeFilename(sub)
  1040. if p := filepath.Clean(filepath.Join(folder, sub)); !strings.HasPrefix(p, folder) {
  1041. return errors.New("invalid subpath")
  1042. }
  1043. subs[i] = sub
  1044. }
  1045. m.fmut.Lock()
  1046. fs := m.folderFiles[folder]
  1047. folderCfg := m.folderCfgs[folder]
  1048. ignores := m.folderIgnores[folder]
  1049. runner, ok := m.folderRunners[folder]
  1050. m.fmut.Unlock()
  1051. // Folders are added to folderRunners only when they are started. We can't
  1052. // scan them before they have started, so that's what we need to check for
  1053. // here.
  1054. if !ok {
  1055. return errors.New("no such folder")
  1056. }
  1057. if err := m.CheckFolderHealth(folder); err != nil {
  1058. runner.setError(err)
  1059. l.Infof("Stopping folder %s due to error: %s", folder, err)
  1060. return err
  1061. }
  1062. if err := ignores.Load(filepath.Join(folderCfg.Path(), ".stignore")); err != nil && !os.IsNotExist(err) {
  1063. err = fmt.Errorf("loading ignores: %v", err)
  1064. runner.setError(err)
  1065. l.Infof("Stopping folder %s due to error: %s", folder, err)
  1066. return err
  1067. }
  1068. // Required to make sure that we start indexing at a directory we're already
  1069. // aware off.
  1070. var unifySubs []string
  1071. nextSub:
  1072. for _, sub := range subs {
  1073. for sub != "" {
  1074. parent := filepath.Dir(sub)
  1075. if parent == "." || parent == string(filepath.Separator) {
  1076. parent = ""
  1077. }
  1078. if _, ok = fs.Get(protocol.LocalDeviceID, parent); ok {
  1079. break
  1080. }
  1081. sub = parent
  1082. }
  1083. for _, us := range unifySubs {
  1084. if strings.HasPrefix(sub, us) {
  1085. continue nextSub
  1086. }
  1087. }
  1088. unifySubs = append(unifySubs, sub)
  1089. }
  1090. subs = unifySubs
  1091. // The cancel channel is closed whenever we return (such as from an error),
  1092. // to signal the potentially still running walker to stop.
  1093. cancel := make(chan struct{})
  1094. defer close(cancel)
  1095. w := &scanner.Walker{
  1096. Folder: folderCfg.ID,
  1097. Dir: folderCfg.Path(),
  1098. Subs: subs,
  1099. Matcher: ignores,
  1100. BlockSize: protocol.BlockSize,
  1101. TempNamer: defTempNamer,
  1102. TempLifetime: time.Duration(m.cfg.Options().KeepTemporariesH) * time.Hour,
  1103. CurrentFiler: cFiler{m, folder},
  1104. MtimeRepo: db.NewVirtualMtimeRepo(m.db, folderCfg.ID),
  1105. IgnorePerms: folderCfg.IgnorePerms,
  1106. AutoNormalize: folderCfg.AutoNormalize,
  1107. Hashers: m.numHashers(folder),
  1108. ShortID: m.shortID,
  1109. ProgressTickIntervalS: folderCfg.ScanProgressIntervalS,
  1110. Cancel: cancel,
  1111. }
  1112. runner.setState(FolderScanning)
  1113. fchan, err := w.Walk()
  1114. if err != nil {
  1115. // The error we get here is likely an OS level error, which might not be
  1116. // as readable as our health check errors. Check if we can get a health
  1117. // check error first, and use that if it's available.
  1118. if ferr := m.CheckFolderHealth(folder); ferr != nil {
  1119. err = ferr
  1120. }
  1121. runner.setError(err)
  1122. return err
  1123. }
  1124. batchSizeFiles := 100
  1125. batchSizeBlocks := 2048 // about 256 MB
  1126. batch := make([]protocol.FileInfo, 0, batchSizeFiles)
  1127. blocksHandled := 0
  1128. for f := range fchan {
  1129. if len(batch) == batchSizeFiles || blocksHandled > batchSizeBlocks {
  1130. if err := m.CheckFolderHealth(folder); err != nil {
  1131. l.Infof("Stopping folder %s mid-scan due to folder error: %s", folder, err)
  1132. return err
  1133. }
  1134. m.updateLocals(folder, batch)
  1135. batch = batch[:0]
  1136. blocksHandled = 0
  1137. }
  1138. batch = append(batch, f)
  1139. blocksHandled += len(f.Blocks)
  1140. }
  1141. if err := m.CheckFolderHealth(folder); err != nil {
  1142. l.Infof("Stopping folder %s mid-scan due to folder error: %s", folder, err)
  1143. return err
  1144. } else if len(batch) > 0 {
  1145. m.updateLocals(folder, batch)
  1146. }
  1147. batch = batch[:0]
  1148. // TODO: We should limit the Have scanning to start at sub
  1149. seenPrefix := false
  1150. var iterError error
  1151. fs.WithHaveTruncated(protocol.LocalDeviceID, func(fi db.FileIntf) bool {
  1152. f := fi.(db.FileInfoTruncated)
  1153. hasPrefix := len(subs) == 0
  1154. for _, sub := range subs {
  1155. if strings.HasPrefix(f.Name, sub) {
  1156. hasPrefix = true
  1157. break
  1158. }
  1159. }
  1160. // Return true so that we keep iterating, until we get to the part
  1161. // of the tree we are interested in. Then return false so we stop
  1162. // iterating when we've passed the end of the subtree.
  1163. if !hasPrefix {
  1164. return !seenPrefix
  1165. }
  1166. seenPrefix = true
  1167. if !f.IsDeleted() {
  1168. if f.IsInvalid() {
  1169. return true
  1170. }
  1171. if len(batch) == batchSizeFiles {
  1172. if err := m.CheckFolderHealth(folder); err != nil {
  1173. iterError = err
  1174. return false
  1175. }
  1176. m.updateLocals(folder, batch)
  1177. batch = batch[:0]
  1178. }
  1179. if ignores.Match(f.Name) || symlinkInvalid(folder, f) {
  1180. // File has been ignored or an unsupported symlink. Set invalid bit.
  1181. l.Debugln("setting invalid bit on ignored", f)
  1182. nf := protocol.FileInfo{
  1183. Name: f.Name,
  1184. Flags: f.Flags | protocol.FlagInvalid,
  1185. Modified: f.Modified,
  1186. Version: f.Version, // The file is still the same, so don't bump version
  1187. }
  1188. batch = append(batch, nf)
  1189. } else if _, err := osutil.Lstat(filepath.Join(folderCfg.Path(), f.Name)); err != nil {
  1190. // File has been deleted.
  1191. // We don't specifically verify that the error is
  1192. // os.IsNotExist because there is a corner case when a
  1193. // directory is suddenly transformed into a file. When that
  1194. // happens, files that were in the directory (that is now a
  1195. // file) are deleted but will return a confusing error ("not a
  1196. // directory") when we try to Lstat() them.
  1197. nf := protocol.FileInfo{
  1198. Name: f.Name,
  1199. Flags: f.Flags | protocol.FlagDeleted,
  1200. Modified: f.Modified,
  1201. Version: f.Version.Update(m.shortID),
  1202. }
  1203. batch = append(batch, nf)
  1204. }
  1205. }
  1206. return true
  1207. })
  1208. if iterError != nil {
  1209. l.Infof("Stopping folder %s mid-scan due to folder error: %s", folder, iterError)
  1210. return iterError
  1211. }
  1212. if err := m.CheckFolderHealth(folder); err != nil {
  1213. l.Infof("Stopping folder %s mid-scan due to folder error: %s", folder, err)
  1214. return err
  1215. } else if len(batch) > 0 {
  1216. m.updateLocals(folder, batch)
  1217. }
  1218. runner.setState(FolderIdle)
  1219. return nil
  1220. }
  1221. func (m *Model) DelayScan(folder string, next time.Duration) {
  1222. m.fmut.Lock()
  1223. runner, ok := m.folderRunners[folder]
  1224. m.fmut.Unlock()
  1225. if !ok {
  1226. return
  1227. }
  1228. runner.DelayScan(next)
  1229. }
  1230. // numHashers returns the number of hasher routines to use for a given folder,
  1231. // taking into account configuration and available CPU cores.
  1232. func (m *Model) numHashers(folder string) int {
  1233. m.fmut.Lock()
  1234. folderCfg := m.folderCfgs[folder]
  1235. numFolders := len(m.folderCfgs)
  1236. m.fmut.Unlock()
  1237. if folderCfg.Hashers > 0 {
  1238. // Specific value set in the config, use that.
  1239. return folderCfg.Hashers
  1240. }
  1241. if runtime.GOOS == "windows" || runtime.GOOS == "darwin" {
  1242. // Interactive operating systems; don't load the system too heavily by
  1243. // default.
  1244. return 1
  1245. }
  1246. // For other operating systems and architectures, lets try to get some
  1247. // work done... Divide the available CPU cores among the configured
  1248. // folders.
  1249. if perFolder := runtime.GOMAXPROCS(-1) / numFolders; perFolder > 0 {
  1250. return perFolder
  1251. }
  1252. return 1
  1253. }
  1254. // generateClusterConfig returns a ClusterConfigMessage that is correct for
  1255. // the given peer device
  1256. func (m *Model) generateClusterConfig(device protocol.DeviceID) protocol.ClusterConfigMessage {
  1257. cm := protocol.ClusterConfigMessage{
  1258. DeviceName: m.deviceName,
  1259. ClientName: m.clientName,
  1260. ClientVersion: m.clientVersion,
  1261. }
  1262. m.fmut.RLock()
  1263. for _, folder := range m.deviceFolders[device] {
  1264. folderCfg := m.cfg.Folders()[folder]
  1265. cr := protocol.Folder{
  1266. ID: folder,
  1267. }
  1268. var flags uint32
  1269. if folderCfg.ReadOnly {
  1270. flags |= protocol.FlagFolderReadOnly
  1271. }
  1272. if folderCfg.IgnorePerms {
  1273. flags |= protocol.FlagFolderIgnorePerms
  1274. }
  1275. if folderCfg.IgnoreDelete {
  1276. flags |= protocol.FlagFolderIgnoreDelete
  1277. }
  1278. cr.Flags = flags
  1279. for _, device := range m.folderDevices[folder] {
  1280. // DeviceID is a value type, but with an underlying array. Copy it
  1281. // so we don't grab aliases to the same array later on in device[:]
  1282. device := device
  1283. // TODO: Set read only bit when relevant, and when we have per device
  1284. // access controls.
  1285. deviceCfg := m.cfg.Devices()[device]
  1286. cn := protocol.Device{
  1287. ID: device[:],
  1288. Name: deviceCfg.Name,
  1289. Addresses: deviceCfg.Addresses,
  1290. Compression: uint32(deviceCfg.Compression),
  1291. CertName: deviceCfg.CertName,
  1292. Flags: protocol.FlagShareTrusted,
  1293. }
  1294. if deviceCfg.Introducer {
  1295. cn.Flags |= protocol.FlagIntroducer
  1296. }
  1297. cr.Devices = append(cr.Devices, cn)
  1298. }
  1299. cm.Folders = append(cm.Folders, cr)
  1300. }
  1301. m.fmut.RUnlock()
  1302. return cm
  1303. }
  1304. func (m *Model) State(folder string) (string, time.Time, error) {
  1305. m.fmut.RLock()
  1306. runner, ok := m.folderRunners[folder]
  1307. m.fmut.RUnlock()
  1308. if !ok {
  1309. // The returned error should be an actual folder error, so returning
  1310. // errors.New("does not exist") or similar here would be
  1311. // inappropriate.
  1312. return "", time.Time{}, nil
  1313. }
  1314. state, changed, err := runner.getState()
  1315. return state.String(), changed, err
  1316. }
  1317. func (m *Model) Override(folder string) {
  1318. m.fmut.RLock()
  1319. fs, ok := m.folderFiles[folder]
  1320. runner := m.folderRunners[folder]
  1321. m.fmut.RUnlock()
  1322. if !ok {
  1323. return
  1324. }
  1325. runner.setState(FolderScanning)
  1326. batch := make([]protocol.FileInfo, 0, indexBatchSize)
  1327. fs.WithNeed(protocol.LocalDeviceID, func(fi db.FileIntf) bool {
  1328. need := fi.(protocol.FileInfo)
  1329. if len(batch) == indexBatchSize {
  1330. m.updateLocals(folder, batch)
  1331. batch = batch[:0]
  1332. }
  1333. have, ok := fs.Get(protocol.LocalDeviceID, need.Name)
  1334. if !ok || have.Name != need.Name {
  1335. // We are missing the file
  1336. need.Flags |= protocol.FlagDeleted
  1337. need.Blocks = nil
  1338. need.Version = need.Version.Update(m.shortID)
  1339. } else {
  1340. // We have the file, replace with our version
  1341. have.Version = have.Version.Merge(need.Version).Update(m.shortID)
  1342. need = have
  1343. }
  1344. need.LocalVersion = 0
  1345. batch = append(batch, need)
  1346. return true
  1347. })
  1348. if len(batch) > 0 {
  1349. m.updateLocals(folder, batch)
  1350. }
  1351. runner.setState(FolderIdle)
  1352. }
  1353. // CurrentLocalVersion returns the change version for the given folder.
  1354. // This is guaranteed to increment if the contents of the local folder has
  1355. // changed.
  1356. func (m *Model) CurrentLocalVersion(folder string) (int64, bool) {
  1357. m.fmut.RLock()
  1358. fs, ok := m.folderFiles[folder]
  1359. m.fmut.RUnlock()
  1360. if !ok {
  1361. // The folder might not exist, since this can be called with a user
  1362. // specified folder name from the REST interface.
  1363. return 0, false
  1364. }
  1365. return fs.LocalVersion(protocol.LocalDeviceID), true
  1366. }
  1367. // RemoteLocalVersion returns the change version for the given folder, as
  1368. // sent by remote peers. This is guaranteed to increment if the contents of
  1369. // the remote or global folder has changed.
  1370. func (m *Model) RemoteLocalVersion(folder string) (int64, bool) {
  1371. m.fmut.RLock()
  1372. defer m.fmut.RUnlock()
  1373. fs, ok := m.folderFiles[folder]
  1374. if !ok {
  1375. // The folder might not exist, since this can be called with a user
  1376. // specified folder name from the REST interface.
  1377. return 0, false
  1378. }
  1379. var ver int64
  1380. for _, n := range m.folderDevices[folder] {
  1381. ver += fs.LocalVersion(n)
  1382. }
  1383. return ver, true
  1384. }
  1385. func (m *Model) GlobalDirectoryTree(folder, prefix string, levels int, dirsonly bool) map[string]interface{} {
  1386. m.fmut.RLock()
  1387. files, ok := m.folderFiles[folder]
  1388. m.fmut.RUnlock()
  1389. if !ok {
  1390. return nil
  1391. }
  1392. output := make(map[string]interface{})
  1393. sep := string(filepath.Separator)
  1394. prefix = osutil.NativeFilename(prefix)
  1395. if prefix != "" && !strings.HasSuffix(prefix, sep) {
  1396. prefix = prefix + sep
  1397. }
  1398. files.WithPrefixedGlobalTruncated(prefix, func(fi db.FileIntf) bool {
  1399. f := fi.(db.FileInfoTruncated)
  1400. if f.IsInvalid() || f.IsDeleted() || f.Name == prefix {
  1401. return true
  1402. }
  1403. f.Name = strings.Replace(f.Name, prefix, "", 1)
  1404. var dir, base string
  1405. if f.IsDirectory() && !f.IsSymlink() {
  1406. dir = f.Name
  1407. } else {
  1408. dir = filepath.Dir(f.Name)
  1409. base = filepath.Base(f.Name)
  1410. }
  1411. if levels > -1 && strings.Count(f.Name, sep) > levels {
  1412. return true
  1413. }
  1414. last := output
  1415. if dir != "." {
  1416. for _, path := range strings.Split(dir, sep) {
  1417. directory, ok := last[path]
  1418. if !ok {
  1419. newdir := make(map[string]interface{})
  1420. last[path] = newdir
  1421. last = newdir
  1422. } else {
  1423. last = directory.(map[string]interface{})
  1424. }
  1425. }
  1426. }
  1427. if !dirsonly && base != "" {
  1428. last[base] = []interface{}{
  1429. time.Unix(f.Modified, 0), f.Size(),
  1430. }
  1431. }
  1432. return true
  1433. })
  1434. return output
  1435. }
  1436. func (m *Model) Availability(folder, file string) []protocol.DeviceID {
  1437. // Acquire this lock first, as the value returned from foldersFiles can
  1438. // get heavily modified on Close()
  1439. m.pmut.RLock()
  1440. defer m.pmut.RUnlock()
  1441. m.fmut.RLock()
  1442. fs, ok := m.folderFiles[folder]
  1443. m.fmut.RUnlock()
  1444. if !ok {
  1445. return nil
  1446. }
  1447. availableDevices := []protocol.DeviceID{}
  1448. for _, device := range fs.Availability(file) {
  1449. _, ok := m.conn[device]
  1450. if ok {
  1451. availableDevices = append(availableDevices, device)
  1452. }
  1453. }
  1454. return availableDevices
  1455. }
  1456. // BringToFront bumps the given files priority in the job queue.
  1457. func (m *Model) BringToFront(folder, file string) {
  1458. m.pmut.RLock()
  1459. defer m.pmut.RUnlock()
  1460. runner, ok := m.folderRunners[folder]
  1461. if ok {
  1462. runner.BringToFront(file)
  1463. }
  1464. }
  1465. // CheckFolderHealth checks the folder for common errors and returns the
  1466. // current folder error, or nil if the folder is healthy.
  1467. func (m *Model) CheckFolderHealth(id string) error {
  1468. folder, ok := m.cfg.Folders()[id]
  1469. if !ok {
  1470. return errors.New("folder does not exist")
  1471. }
  1472. if minFree := m.cfg.Options().MinHomeDiskFreePct; minFree > 0 {
  1473. if free, err := osutil.DiskFreePercentage(m.cfg.ConfigPath()); err == nil && free < minFree {
  1474. return errors.New("home disk has insufficient free space")
  1475. }
  1476. }
  1477. fi, err := os.Stat(folder.Path())
  1478. v, ok := m.CurrentLocalVersion(id)
  1479. indexHasFiles := ok && v > 0
  1480. if indexHasFiles {
  1481. // There are files in the folder according to the index, so it must
  1482. // have existed and had a correct marker at some point. Verify that
  1483. // this is still the case.
  1484. switch {
  1485. case err != nil || !fi.IsDir():
  1486. err = errors.New("folder path missing")
  1487. case !folder.HasMarker():
  1488. err = errors.New("folder marker missing")
  1489. case !folder.ReadOnly:
  1490. // Check for free space, if it isn't a master folder. We aren't
  1491. // going to change the contents of master folders, so we don't
  1492. // care about the amount of free space there.
  1493. if free, errDfp := osutil.DiskFreePercentage(folder.Path()); errDfp == nil && free < folder.MinDiskFreePct {
  1494. err = errors.New("insufficient free space")
  1495. }
  1496. }
  1497. } else {
  1498. // It's a blank folder, so this may the first time we're looking at
  1499. // it. Attempt to create and tag with our marker as appropriate.
  1500. if os.IsNotExist(err) {
  1501. err = osutil.MkdirAll(folder.Path(), 0700)
  1502. }
  1503. if err == nil && !folder.HasMarker() {
  1504. err = folder.CreateMarker()
  1505. }
  1506. }
  1507. m.fmut.RLock()
  1508. runner, runnerExists := m.folderRunners[folder.ID]
  1509. m.fmut.RUnlock()
  1510. var oldErr error
  1511. if runnerExists {
  1512. _, _, oldErr = runner.getState()
  1513. }
  1514. if err != nil {
  1515. if oldErr != nil && oldErr.Error() != err.Error() {
  1516. l.Infof("Folder %q error changed: %q -> %q", folder.ID, oldErr, err)
  1517. } else if oldErr == nil {
  1518. l.Warnf("Stopping folder %q - %v", folder.ID, err)
  1519. }
  1520. if runnerExists {
  1521. runner.setError(err)
  1522. }
  1523. } else if oldErr != nil {
  1524. l.Infof("Folder %q error is cleared, restarting", folder.ID)
  1525. if runnerExists {
  1526. runner.clearError()
  1527. }
  1528. }
  1529. return err
  1530. }
  1531. func (m *Model) ResetFolder(folder string) {
  1532. l.Infof("Cleaning data for folder %q", folder)
  1533. db.DropFolder(m.db, folder)
  1534. }
  1535. func (m *Model) String() string {
  1536. return fmt.Sprintf("model@%p", m)
  1537. }
  1538. func (m *Model) VerifyConfiguration(from, to config.Configuration) error {
  1539. return nil
  1540. }
  1541. func (m *Model) CommitConfiguration(from, to config.Configuration) bool {
  1542. // TODO: This should not use reflect, and should take more care to try to handle stuff without restart.
  1543. // Go through the folder configs and figure out if we need to restart or not.
  1544. fromFolders := mapFolders(from.Folders)
  1545. toFolders := mapFolders(to.Folders)
  1546. for folderID, cfg := range toFolders {
  1547. if _, ok := fromFolders[folderID]; !ok {
  1548. // A folder was added.
  1549. l.Debugln(m, "adding folder", folderID)
  1550. m.AddFolder(cfg)
  1551. if cfg.ReadOnly {
  1552. m.StartFolderRO(folderID)
  1553. } else {
  1554. m.StartFolderRW(folderID)
  1555. }
  1556. // Drop connections to all devices that can now share the new
  1557. // folder.
  1558. m.pmut.Lock()
  1559. for _, dev := range cfg.DeviceIDs() {
  1560. if conn, ok := m.conn[dev]; ok {
  1561. closeRawConn(conn)
  1562. }
  1563. }
  1564. m.pmut.Unlock()
  1565. }
  1566. }
  1567. for folderID, fromCfg := range fromFolders {
  1568. toCfg, ok := toFolders[folderID]
  1569. if !ok {
  1570. // The folder was removed.
  1571. m.RemoveFolder(folderID)
  1572. continue
  1573. }
  1574. // This folder exists on both sides. Compare the device lists, as we
  1575. // can handle adding a device (but not currently removing one).
  1576. fromDevs := mapDevices(fromCfg.DeviceIDs())
  1577. toDevs := mapDevices(toCfg.DeviceIDs())
  1578. for dev := range fromDevs {
  1579. if _, ok := toDevs[dev]; !ok {
  1580. // A device was removed. Requires restart.
  1581. l.Debugln(m, "requires restart, removing device", dev, "from folder", folderID)
  1582. return false
  1583. }
  1584. }
  1585. for dev := range toDevs {
  1586. if _, ok := fromDevs[dev]; !ok {
  1587. // A device was added. Handle it!
  1588. m.fmut.Lock()
  1589. m.pmut.Lock()
  1590. m.folderCfgs[folderID] = toCfg
  1591. m.folderDevices[folderID] = append(m.folderDevices[folderID], dev)
  1592. m.deviceFolders[dev] = append(m.deviceFolders[dev], folderID)
  1593. // If we already have a connection to this device, we should
  1594. // disconnect it so that we start sharing the folder with it.
  1595. // We close the underlying connection and let the normal error
  1596. // handling kick in to clean up and reconnect.
  1597. if conn, ok := m.conn[dev]; ok {
  1598. closeRawConn(conn)
  1599. }
  1600. m.pmut.Unlock()
  1601. m.fmut.Unlock()
  1602. }
  1603. }
  1604. // Check if anything else differs, apart from the device list.
  1605. fromCfg.Devices = nil
  1606. toCfg.Devices = nil
  1607. if !reflect.DeepEqual(fromCfg, toCfg) {
  1608. l.Debugln(m, "requires restart, folder", folderID, "configuration differs")
  1609. return false
  1610. }
  1611. }
  1612. // Removing a device requires restart
  1613. toDevs := mapDeviceCfgs(from.Devices)
  1614. for _, dev := range from.Devices {
  1615. if _, ok := toDevs[dev.DeviceID]; !ok {
  1616. l.Debugln(m, "requires restart, device", dev.DeviceID, "was removed")
  1617. return false
  1618. }
  1619. }
  1620. // All of the generic options require restart
  1621. if !reflect.DeepEqual(from.Options, to.Options) {
  1622. l.Debugln(m, "requires restart, options differ")
  1623. return false
  1624. }
  1625. return true
  1626. }
  1627. // mapFolders returns a map of folder ID to folder configuration for the given
  1628. // slice of folder configurations.
  1629. func mapFolders(folders []config.FolderConfiguration) map[string]config.FolderConfiguration {
  1630. m := make(map[string]config.FolderConfiguration, len(folders))
  1631. for _, cfg := range folders {
  1632. m[cfg.ID] = cfg
  1633. }
  1634. return m
  1635. }
  1636. // mapDevices returns a map of device ID to nothing for the given slice of
  1637. // device IDs.
  1638. func mapDevices(devices []protocol.DeviceID) map[protocol.DeviceID]struct{} {
  1639. m := make(map[protocol.DeviceID]struct{}, len(devices))
  1640. for _, dev := range devices {
  1641. m[dev] = struct{}{}
  1642. }
  1643. return m
  1644. }
  1645. // mapDeviceCfgs returns a map of device ID to nothing for the given slice of
  1646. // device configurations.
  1647. func mapDeviceCfgs(devices []config.DeviceConfiguration) map[protocol.DeviceID]struct{} {
  1648. m := make(map[protocol.DeviceID]struct{}, len(devices))
  1649. for _, dev := range devices {
  1650. m[dev.DeviceID] = struct{}{}
  1651. }
  1652. return m
  1653. }
  1654. func filterIndex(folder string, fs []protocol.FileInfo, dropDeletes bool) []protocol.FileInfo {
  1655. for i := 0; i < len(fs); {
  1656. if fs[i].Flags&^protocol.FlagsAll != 0 {
  1657. l.Debugln("dropping update for file with unknown bits set", fs[i])
  1658. fs[i] = fs[len(fs)-1]
  1659. fs = fs[:len(fs)-1]
  1660. } else if fs[i].IsDeleted() && dropDeletes {
  1661. l.Debugln("dropping update for undesired delete", fs[i])
  1662. fs[i] = fs[len(fs)-1]
  1663. fs = fs[:len(fs)-1]
  1664. } else if symlinkInvalid(folder, fs[i]) {
  1665. l.Debugln("dropping update for unsupported symlink", fs[i])
  1666. fs[i] = fs[len(fs)-1]
  1667. fs = fs[:len(fs)-1]
  1668. } else {
  1669. i++
  1670. }
  1671. }
  1672. return fs
  1673. }
  1674. func symlinkInvalid(folder string, fi db.FileIntf) bool {
  1675. if !symlinks.Supported && fi.IsSymlink() && !fi.IsInvalid() && !fi.IsDeleted() {
  1676. symlinkWarning.Do(func() {
  1677. l.Warnln("Symlinks are disabled, unsupported or require Administrator privileges. This might cause your folder to appear out of sync.")
  1678. })
  1679. // Need to type switch for the concrete type to be able to access fields...
  1680. var name string
  1681. switch fi := fi.(type) {
  1682. case protocol.FileInfo:
  1683. name = fi.Name
  1684. case db.FileInfoTruncated:
  1685. name = fi.Name
  1686. }
  1687. l.Infoln("Unsupported symlink", name, "in folder", folder)
  1688. return true
  1689. }
  1690. return false
  1691. }
  1692. // Skips `skip` elements and retrieves up to `get` elements from a given slice.
  1693. // Returns the resulting slice, plus how much elements are left to skip or
  1694. // copy to satisfy the values which were provided, given the slice is not
  1695. // big enough.
  1696. func getChunk(data []string, skip, get int) ([]string, int, int) {
  1697. l := len(data)
  1698. if l <= skip {
  1699. return []string{}, skip - l, get
  1700. } else if l < skip+get {
  1701. return data[skip:l], 0, get - (l - skip)
  1702. }
  1703. return data[skip : skip+get], 0, 0
  1704. }
  1705. func closeRawConn(conn io.Closer) error {
  1706. if conn, ok := conn.(*tls.Conn); ok {
  1707. // If the underlying connection is a *tls.Conn, Close() does more
  1708. // than it says on the tin. Specifically, it sends a TLS alert
  1709. // message, which might block forever if the connection is dead
  1710. // and we don't have a deadline set.
  1711. conn.SetWriteDeadline(time.Now().Add(250 * time.Millisecond))
  1712. }
  1713. return conn.Close()
  1714. }
  1715. func stringSliceWithout(ss []string, s string) []string {
  1716. for i := range ss {
  1717. if ss[i] == s {
  1718. copy(ss[i:], ss[i+1:])
  1719. ss = ss[:len(ss)-1]
  1720. return ss
  1721. }
  1722. }
  1723. return ss
  1724. }