model.go 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030
  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. filenames := make([]string, len(fs))
  954. for i, file := range fs {
  955. filenames[i] = file.Name
  956. }
  957. events.Default.Log(events.LocalIndexUpdated, map[string]interface{}{
  958. "folder": folder,
  959. "items": len(fs),
  960. "filenames": filenames,
  961. "version": files.LocalVersion(protocol.LocalDeviceID),
  962. })
  963. }
  964. func (m *Model) requestGlobal(deviceID protocol.DeviceID, folder, name string, offset int64, size int, hash []byte, flags uint32, options []protocol.Option) ([]byte, error) {
  965. m.pmut.RLock()
  966. nc, ok := m.conn[deviceID]
  967. m.pmut.RUnlock()
  968. if !ok {
  969. return nil, fmt.Errorf("requestGlobal: no such device: %s", deviceID)
  970. }
  971. 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)
  972. return nc.Request(folder, name, offset, size, hash, flags, options)
  973. }
  974. func (m *Model) AddFolder(cfg config.FolderConfiguration) {
  975. if len(cfg.ID) == 0 {
  976. panic("cannot add empty folder id")
  977. }
  978. m.fmut.Lock()
  979. m.folderCfgs[cfg.ID] = cfg
  980. m.folderFiles[cfg.ID] = db.NewFileSet(cfg.ID, m.db)
  981. m.folderDevices[cfg.ID] = make([]protocol.DeviceID, len(cfg.Devices))
  982. for i, device := range cfg.Devices {
  983. m.folderDevices[cfg.ID][i] = device.DeviceID
  984. m.deviceFolders[device.DeviceID] = append(m.deviceFolders[device.DeviceID], cfg.ID)
  985. }
  986. ignores := ignore.New(m.cacheIgnoredFiles)
  987. if err := ignores.Load(filepath.Join(cfg.Path(), ".stignore")); err != nil && !os.IsNotExist(err) {
  988. l.Warnln("Loading ignores:", err)
  989. }
  990. m.folderIgnores[cfg.ID] = ignores
  991. m.fmut.Unlock()
  992. }
  993. func (m *Model) ScanFolders() map[string]error {
  994. m.fmut.RLock()
  995. folders := make([]string, 0, len(m.folderCfgs))
  996. for folder := range m.folderCfgs {
  997. folders = append(folders, folder)
  998. }
  999. m.fmut.RUnlock()
  1000. errors := make(map[string]error, len(m.folderCfgs))
  1001. errorsMut := sync.NewMutex()
  1002. wg := sync.NewWaitGroup()
  1003. wg.Add(len(folders))
  1004. for _, folder := range folders {
  1005. folder := folder
  1006. go func() {
  1007. err := m.ScanFolder(folder)
  1008. if err != nil {
  1009. errorsMut.Lock()
  1010. errors[folder] = err
  1011. errorsMut.Unlock()
  1012. // Potentially sets the error twice, once in the scanner just
  1013. // by doing a check, and once here, if the error returned is
  1014. // the same one as returned by CheckFolderHealth, though
  1015. // duplicate set is handled by setError.
  1016. m.fmut.RLock()
  1017. srv := m.folderRunners[folder]
  1018. m.fmut.RUnlock()
  1019. srv.setError(err)
  1020. }
  1021. wg.Done()
  1022. }()
  1023. }
  1024. wg.Wait()
  1025. return errors
  1026. }
  1027. func (m *Model) ScanFolder(folder string) error {
  1028. return m.ScanFolderSubs(folder, nil)
  1029. }
  1030. func (m *Model) ScanFolderSubs(folder string, subs []string) error {
  1031. m.fmut.Lock()
  1032. runner, ok := m.folderRunners[folder]
  1033. m.fmut.Unlock()
  1034. // Folders are added to folderRunners only when they are started. We can't
  1035. // scan them before they have started, so that's what we need to check for
  1036. // here.
  1037. if !ok {
  1038. return errors.New("no such folder")
  1039. }
  1040. return runner.Scan(subs)
  1041. }
  1042. func (m *Model) internalScanFolderSubs(folder string, subs []string) error {
  1043. for i, sub := range subs {
  1044. sub = osutil.NativeFilename(sub)
  1045. if p := filepath.Clean(filepath.Join(folder, sub)); !strings.HasPrefix(p, folder) {
  1046. return errors.New("invalid subpath")
  1047. }
  1048. subs[i] = sub
  1049. }
  1050. m.fmut.Lock()
  1051. fs := m.folderFiles[folder]
  1052. folderCfg := m.folderCfgs[folder]
  1053. ignores := m.folderIgnores[folder]
  1054. runner, ok := m.folderRunners[folder]
  1055. m.fmut.Unlock()
  1056. // Folders are added to folderRunners only when they are started. We can't
  1057. // scan them before they have started, so that's what we need to check for
  1058. // here.
  1059. if !ok {
  1060. return errors.New("no such folder")
  1061. }
  1062. if err := m.CheckFolderHealth(folder); err != nil {
  1063. runner.setError(err)
  1064. l.Infof("Stopping folder %s due to error: %s", folder, err)
  1065. return err
  1066. }
  1067. if err := ignores.Load(filepath.Join(folderCfg.Path(), ".stignore")); err != nil && !os.IsNotExist(err) {
  1068. err = fmt.Errorf("loading ignores: %v", err)
  1069. runner.setError(err)
  1070. l.Infof("Stopping folder %s due to error: %s", folder, err)
  1071. return err
  1072. }
  1073. // Required to make sure that we start indexing at a directory we're already
  1074. // aware off.
  1075. var unifySubs []string
  1076. nextSub:
  1077. for _, sub := range subs {
  1078. for sub != "" {
  1079. parent := filepath.Dir(sub)
  1080. if parent == "." || parent == string(filepath.Separator) {
  1081. parent = ""
  1082. }
  1083. if _, ok = fs.Get(protocol.LocalDeviceID, parent); ok {
  1084. break
  1085. }
  1086. sub = parent
  1087. }
  1088. for _, us := range unifySubs {
  1089. if strings.HasPrefix(sub, us) {
  1090. continue nextSub
  1091. }
  1092. }
  1093. unifySubs = append(unifySubs, sub)
  1094. }
  1095. subs = unifySubs
  1096. // The cancel channel is closed whenever we return (such as from an error),
  1097. // to signal the potentially still running walker to stop.
  1098. cancel := make(chan struct{})
  1099. defer close(cancel)
  1100. w := &scanner.Walker{
  1101. Folder: folderCfg.ID,
  1102. Dir: folderCfg.Path(),
  1103. Subs: subs,
  1104. Matcher: ignores,
  1105. BlockSize: protocol.BlockSize,
  1106. TempNamer: defTempNamer,
  1107. TempLifetime: time.Duration(m.cfg.Options().KeepTemporariesH) * time.Hour,
  1108. CurrentFiler: cFiler{m, folder},
  1109. MtimeRepo: db.NewVirtualMtimeRepo(m.db, folderCfg.ID),
  1110. IgnorePerms: folderCfg.IgnorePerms,
  1111. AutoNormalize: folderCfg.AutoNormalize,
  1112. Hashers: m.numHashers(folder),
  1113. ShortID: m.shortID,
  1114. ProgressTickIntervalS: folderCfg.ScanProgressIntervalS,
  1115. Cancel: cancel,
  1116. }
  1117. runner.setState(FolderScanning)
  1118. fchan, err := w.Walk()
  1119. if err != nil {
  1120. // The error we get here is likely an OS level error, which might not be
  1121. // as readable as our health check errors. Check if we can get a health
  1122. // check error first, and use that if it's available.
  1123. if ferr := m.CheckFolderHealth(folder); ferr != nil {
  1124. err = ferr
  1125. }
  1126. runner.setError(err)
  1127. return err
  1128. }
  1129. batchSizeFiles := 100
  1130. batchSizeBlocks := 2048 // about 256 MB
  1131. batch := make([]protocol.FileInfo, 0, batchSizeFiles)
  1132. blocksHandled := 0
  1133. for f := range fchan {
  1134. if len(batch) == batchSizeFiles || blocksHandled > batchSizeBlocks {
  1135. if err := m.CheckFolderHealth(folder); err != nil {
  1136. l.Infof("Stopping folder %s mid-scan due to folder error: %s", folder, err)
  1137. return err
  1138. }
  1139. m.updateLocals(folder, batch)
  1140. batch = batch[:0]
  1141. blocksHandled = 0
  1142. }
  1143. batch = append(batch, f)
  1144. blocksHandled += len(f.Blocks)
  1145. }
  1146. if err := m.CheckFolderHealth(folder); err != nil {
  1147. l.Infof("Stopping folder %s mid-scan due to folder error: %s", folder, err)
  1148. return err
  1149. } else if len(batch) > 0 {
  1150. m.updateLocals(folder, batch)
  1151. }
  1152. batch = batch[:0]
  1153. // TODO: We should limit the Have scanning to start at sub
  1154. seenPrefix := false
  1155. var iterError error
  1156. fs.WithHaveTruncated(protocol.LocalDeviceID, func(fi db.FileIntf) bool {
  1157. f := fi.(db.FileInfoTruncated)
  1158. hasPrefix := len(subs) == 0
  1159. for _, sub := range subs {
  1160. if strings.HasPrefix(f.Name, sub) {
  1161. hasPrefix = true
  1162. break
  1163. }
  1164. }
  1165. // Return true so that we keep iterating, until we get to the part
  1166. // of the tree we are interested in. Then return false so we stop
  1167. // iterating when we've passed the end of the subtree.
  1168. if !hasPrefix {
  1169. return !seenPrefix
  1170. }
  1171. seenPrefix = true
  1172. if !f.IsDeleted() {
  1173. if f.IsInvalid() {
  1174. return true
  1175. }
  1176. if len(batch) == batchSizeFiles {
  1177. if err := m.CheckFolderHealth(folder); err != nil {
  1178. iterError = err
  1179. return false
  1180. }
  1181. m.updateLocals(folder, batch)
  1182. batch = batch[:0]
  1183. }
  1184. if ignores.Match(f.Name) || symlinkInvalid(folder, f) {
  1185. // File has been ignored or an unsupported symlink. Set invalid bit.
  1186. l.Debugln("setting invalid bit on ignored", f)
  1187. nf := protocol.FileInfo{
  1188. Name: f.Name,
  1189. Flags: f.Flags | protocol.FlagInvalid,
  1190. Modified: f.Modified,
  1191. Version: f.Version, // The file is still the same, so don't bump version
  1192. }
  1193. batch = append(batch, nf)
  1194. } else if _, err := osutil.Lstat(filepath.Join(folderCfg.Path(), f.Name)); err != nil {
  1195. // File has been deleted.
  1196. // We don't specifically verify that the error is
  1197. // os.IsNotExist because there is a corner case when a
  1198. // directory is suddenly transformed into a file. When that
  1199. // happens, files that were in the directory (that is now a
  1200. // file) are deleted but will return a confusing error ("not a
  1201. // directory") when we try to Lstat() them.
  1202. nf := protocol.FileInfo{
  1203. Name: f.Name,
  1204. Flags: f.Flags | protocol.FlagDeleted,
  1205. Modified: f.Modified,
  1206. Version: f.Version.Update(m.shortID),
  1207. }
  1208. batch = append(batch, nf)
  1209. }
  1210. }
  1211. return true
  1212. })
  1213. if iterError != nil {
  1214. l.Infof("Stopping folder %s mid-scan due to folder error: %s", folder, iterError)
  1215. return iterError
  1216. }
  1217. if err := m.CheckFolderHealth(folder); err != nil {
  1218. l.Infof("Stopping folder %s mid-scan due to folder error: %s", folder, err)
  1219. return err
  1220. } else if len(batch) > 0 {
  1221. m.updateLocals(folder, batch)
  1222. }
  1223. runner.setState(FolderIdle)
  1224. return nil
  1225. }
  1226. func (m *Model) DelayScan(folder string, next time.Duration) {
  1227. m.fmut.Lock()
  1228. runner, ok := m.folderRunners[folder]
  1229. m.fmut.Unlock()
  1230. if !ok {
  1231. return
  1232. }
  1233. runner.DelayScan(next)
  1234. }
  1235. // numHashers returns the number of hasher routines to use for a given folder,
  1236. // taking into account configuration and available CPU cores.
  1237. func (m *Model) numHashers(folder string) int {
  1238. m.fmut.Lock()
  1239. folderCfg := m.folderCfgs[folder]
  1240. numFolders := len(m.folderCfgs)
  1241. m.fmut.Unlock()
  1242. if folderCfg.Hashers > 0 {
  1243. // Specific value set in the config, use that.
  1244. return folderCfg.Hashers
  1245. }
  1246. if runtime.GOOS == "windows" || runtime.GOOS == "darwin" {
  1247. // Interactive operating systems; don't load the system too heavily by
  1248. // default.
  1249. return 1
  1250. }
  1251. // For other operating systems and architectures, lets try to get some
  1252. // work done... Divide the available CPU cores among the configured
  1253. // folders.
  1254. if perFolder := runtime.GOMAXPROCS(-1) / numFolders; perFolder > 0 {
  1255. return perFolder
  1256. }
  1257. return 1
  1258. }
  1259. // generateClusterConfig returns a ClusterConfigMessage that is correct for
  1260. // the given peer device
  1261. func (m *Model) generateClusterConfig(device protocol.DeviceID) protocol.ClusterConfigMessage {
  1262. cm := protocol.ClusterConfigMessage{
  1263. DeviceName: m.deviceName,
  1264. ClientName: m.clientName,
  1265. ClientVersion: m.clientVersion,
  1266. }
  1267. m.fmut.RLock()
  1268. for _, folder := range m.deviceFolders[device] {
  1269. folderCfg := m.cfg.Folders()[folder]
  1270. cr := protocol.Folder{
  1271. ID: folder,
  1272. }
  1273. var flags uint32
  1274. if folderCfg.ReadOnly {
  1275. flags |= protocol.FlagFolderReadOnly
  1276. }
  1277. if folderCfg.IgnorePerms {
  1278. flags |= protocol.FlagFolderIgnorePerms
  1279. }
  1280. if folderCfg.IgnoreDelete {
  1281. flags |= protocol.FlagFolderIgnoreDelete
  1282. }
  1283. cr.Flags = flags
  1284. for _, device := range m.folderDevices[folder] {
  1285. // DeviceID is a value type, but with an underlying array. Copy it
  1286. // so we don't grab aliases to the same array later on in device[:]
  1287. device := device
  1288. // TODO: Set read only bit when relevant, and when we have per device
  1289. // access controls.
  1290. deviceCfg := m.cfg.Devices()[device]
  1291. cn := protocol.Device{
  1292. ID: device[:],
  1293. Name: deviceCfg.Name,
  1294. Addresses: deviceCfg.Addresses,
  1295. Compression: uint32(deviceCfg.Compression),
  1296. CertName: deviceCfg.CertName,
  1297. Flags: protocol.FlagShareTrusted,
  1298. }
  1299. if deviceCfg.Introducer {
  1300. cn.Flags |= protocol.FlagIntroducer
  1301. }
  1302. cr.Devices = append(cr.Devices, cn)
  1303. }
  1304. cm.Folders = append(cm.Folders, cr)
  1305. }
  1306. m.fmut.RUnlock()
  1307. return cm
  1308. }
  1309. func (m *Model) State(folder string) (string, time.Time, error) {
  1310. m.fmut.RLock()
  1311. runner, ok := m.folderRunners[folder]
  1312. m.fmut.RUnlock()
  1313. if !ok {
  1314. // The returned error should be an actual folder error, so returning
  1315. // errors.New("does not exist") or similar here would be
  1316. // inappropriate.
  1317. return "", time.Time{}, nil
  1318. }
  1319. state, changed, err := runner.getState()
  1320. return state.String(), changed, err
  1321. }
  1322. func (m *Model) Override(folder string) {
  1323. m.fmut.RLock()
  1324. fs, ok := m.folderFiles[folder]
  1325. runner := m.folderRunners[folder]
  1326. m.fmut.RUnlock()
  1327. if !ok {
  1328. return
  1329. }
  1330. runner.setState(FolderScanning)
  1331. batch := make([]protocol.FileInfo, 0, indexBatchSize)
  1332. fs.WithNeed(protocol.LocalDeviceID, func(fi db.FileIntf) bool {
  1333. need := fi.(protocol.FileInfo)
  1334. if len(batch) == indexBatchSize {
  1335. m.updateLocals(folder, batch)
  1336. batch = batch[:0]
  1337. }
  1338. have, ok := fs.Get(protocol.LocalDeviceID, need.Name)
  1339. if !ok || have.Name != need.Name {
  1340. // We are missing the file
  1341. need.Flags |= protocol.FlagDeleted
  1342. need.Blocks = nil
  1343. need.Version = need.Version.Update(m.shortID)
  1344. } else {
  1345. // We have the file, replace with our version
  1346. have.Version = have.Version.Merge(need.Version).Update(m.shortID)
  1347. need = have
  1348. }
  1349. need.LocalVersion = 0
  1350. batch = append(batch, need)
  1351. return true
  1352. })
  1353. if len(batch) > 0 {
  1354. m.updateLocals(folder, batch)
  1355. }
  1356. runner.setState(FolderIdle)
  1357. }
  1358. // CurrentLocalVersion returns the change version for the given folder.
  1359. // This is guaranteed to increment if the contents of the local folder has
  1360. // changed.
  1361. func (m *Model) CurrentLocalVersion(folder string) (int64, bool) {
  1362. m.fmut.RLock()
  1363. fs, ok := m.folderFiles[folder]
  1364. m.fmut.RUnlock()
  1365. if !ok {
  1366. // The folder might not exist, since this can be called with a user
  1367. // specified folder name from the REST interface.
  1368. return 0, false
  1369. }
  1370. return fs.LocalVersion(protocol.LocalDeviceID), true
  1371. }
  1372. // RemoteLocalVersion returns the change version for the given folder, as
  1373. // sent by remote peers. This is guaranteed to increment if the contents of
  1374. // the remote or global folder has changed.
  1375. func (m *Model) RemoteLocalVersion(folder string) (int64, bool) {
  1376. m.fmut.RLock()
  1377. defer m.fmut.RUnlock()
  1378. fs, ok := m.folderFiles[folder]
  1379. if !ok {
  1380. // The folder might not exist, since this can be called with a user
  1381. // specified folder name from the REST interface.
  1382. return 0, false
  1383. }
  1384. var ver int64
  1385. for _, n := range m.folderDevices[folder] {
  1386. ver += fs.LocalVersion(n)
  1387. }
  1388. return ver, true
  1389. }
  1390. func (m *Model) GlobalDirectoryTree(folder, prefix string, levels int, dirsonly bool) map[string]interface{} {
  1391. m.fmut.RLock()
  1392. files, ok := m.folderFiles[folder]
  1393. m.fmut.RUnlock()
  1394. if !ok {
  1395. return nil
  1396. }
  1397. output := make(map[string]interface{})
  1398. sep := string(filepath.Separator)
  1399. prefix = osutil.NativeFilename(prefix)
  1400. if prefix != "" && !strings.HasSuffix(prefix, sep) {
  1401. prefix = prefix + sep
  1402. }
  1403. files.WithPrefixedGlobalTruncated(prefix, func(fi db.FileIntf) bool {
  1404. f := fi.(db.FileInfoTruncated)
  1405. if f.IsInvalid() || f.IsDeleted() || f.Name == prefix {
  1406. return true
  1407. }
  1408. f.Name = strings.Replace(f.Name, prefix, "", 1)
  1409. var dir, base string
  1410. if f.IsDirectory() && !f.IsSymlink() {
  1411. dir = f.Name
  1412. } else {
  1413. dir = filepath.Dir(f.Name)
  1414. base = filepath.Base(f.Name)
  1415. }
  1416. if levels > -1 && strings.Count(f.Name, sep) > levels {
  1417. return true
  1418. }
  1419. last := output
  1420. if dir != "." {
  1421. for _, path := range strings.Split(dir, sep) {
  1422. directory, ok := last[path]
  1423. if !ok {
  1424. newdir := make(map[string]interface{})
  1425. last[path] = newdir
  1426. last = newdir
  1427. } else {
  1428. last = directory.(map[string]interface{})
  1429. }
  1430. }
  1431. }
  1432. if !dirsonly && base != "" {
  1433. last[base] = []interface{}{
  1434. time.Unix(f.Modified, 0), f.Size(),
  1435. }
  1436. }
  1437. return true
  1438. })
  1439. return output
  1440. }
  1441. func (m *Model) Availability(folder, file string) []protocol.DeviceID {
  1442. // Acquire this lock first, as the value returned from foldersFiles can
  1443. // get heavily modified on Close()
  1444. m.pmut.RLock()
  1445. defer m.pmut.RUnlock()
  1446. m.fmut.RLock()
  1447. fs, ok := m.folderFiles[folder]
  1448. m.fmut.RUnlock()
  1449. if !ok {
  1450. return nil
  1451. }
  1452. availableDevices := []protocol.DeviceID{}
  1453. for _, device := range fs.Availability(file) {
  1454. _, ok := m.conn[device]
  1455. if ok {
  1456. availableDevices = append(availableDevices, device)
  1457. }
  1458. }
  1459. return availableDevices
  1460. }
  1461. // BringToFront bumps the given files priority in the job queue.
  1462. func (m *Model) BringToFront(folder, file string) {
  1463. m.pmut.RLock()
  1464. defer m.pmut.RUnlock()
  1465. runner, ok := m.folderRunners[folder]
  1466. if ok {
  1467. runner.BringToFront(file)
  1468. }
  1469. }
  1470. // CheckFolderHealth checks the folder for common errors and returns the
  1471. // current folder error, or nil if the folder is healthy.
  1472. func (m *Model) CheckFolderHealth(id string) error {
  1473. folder, ok := m.cfg.Folders()[id]
  1474. if !ok {
  1475. return errors.New("folder does not exist")
  1476. }
  1477. if minFree := m.cfg.Options().MinHomeDiskFreePct; minFree > 0 {
  1478. if free, err := osutil.DiskFreePercentage(m.cfg.ConfigPath()); err == nil && free < minFree {
  1479. return errors.New("home disk has insufficient free space")
  1480. }
  1481. }
  1482. fi, err := os.Stat(folder.Path())
  1483. v, ok := m.CurrentLocalVersion(id)
  1484. indexHasFiles := ok && v > 0
  1485. if indexHasFiles {
  1486. // There are files in the folder according to the index, so it must
  1487. // have existed and had a correct marker at some point. Verify that
  1488. // this is still the case.
  1489. switch {
  1490. case err != nil || !fi.IsDir():
  1491. err = errors.New("folder path missing")
  1492. case !folder.HasMarker():
  1493. err = errors.New("folder marker missing")
  1494. case !folder.ReadOnly:
  1495. // Check for free space, if it isn't a master folder. We aren't
  1496. // going to change the contents of master folders, so we don't
  1497. // care about the amount of free space there.
  1498. diskFreeP, errDfp := osutil.DiskFreePercentage(folder.Path())
  1499. if errDfp == nil && diskFreeP < folder.MinDiskFreePct {
  1500. diskFreeBytes, _ := osutil.DiskFreeBytes(folder.Path())
  1501. str := fmt.Sprintf("insufficient free space (%d MiB, %.2f%%)", diskFreeBytes/1024/1024, diskFreeP)
  1502. err = errors.New(str)
  1503. }
  1504. }
  1505. } else {
  1506. // It's a blank folder, so this may the first time we're looking at
  1507. // it. Attempt to create and tag with our marker as appropriate.
  1508. if os.IsNotExist(err) {
  1509. err = osutil.MkdirAll(folder.Path(), 0700)
  1510. }
  1511. if err == nil && !folder.HasMarker() {
  1512. err = folder.CreateMarker()
  1513. }
  1514. }
  1515. m.fmut.RLock()
  1516. runner, runnerExists := m.folderRunners[folder.ID]
  1517. m.fmut.RUnlock()
  1518. var oldErr error
  1519. if runnerExists {
  1520. _, _, oldErr = runner.getState()
  1521. }
  1522. if err != nil {
  1523. if oldErr != nil && oldErr.Error() != err.Error() {
  1524. l.Infof("Folder %q error changed: %q -> %q", folder.ID, oldErr, err)
  1525. } else if oldErr == nil {
  1526. l.Warnf("Stopping folder %q - %v", folder.ID, err)
  1527. }
  1528. if runnerExists {
  1529. runner.setError(err)
  1530. }
  1531. } else if oldErr != nil {
  1532. l.Infof("Folder %q error is cleared, restarting", folder.ID)
  1533. if runnerExists {
  1534. runner.clearError()
  1535. }
  1536. }
  1537. return err
  1538. }
  1539. func (m *Model) ResetFolder(folder string) {
  1540. l.Infof("Cleaning data for folder %q", folder)
  1541. db.DropFolder(m.db, folder)
  1542. }
  1543. func (m *Model) String() string {
  1544. return fmt.Sprintf("model@%p", m)
  1545. }
  1546. func (m *Model) VerifyConfiguration(from, to config.Configuration) error {
  1547. return nil
  1548. }
  1549. func (m *Model) CommitConfiguration(from, to config.Configuration) bool {
  1550. // TODO: This should not use reflect, and should take more care to try to handle stuff without restart.
  1551. // Go through the folder configs and figure out if we need to restart or not.
  1552. fromFolders := mapFolders(from.Folders)
  1553. toFolders := mapFolders(to.Folders)
  1554. for folderID, cfg := range toFolders {
  1555. if _, ok := fromFolders[folderID]; !ok {
  1556. // A folder was added.
  1557. l.Debugln(m, "adding folder", folderID)
  1558. m.AddFolder(cfg)
  1559. if cfg.ReadOnly {
  1560. m.StartFolderRO(folderID)
  1561. } else {
  1562. m.StartFolderRW(folderID)
  1563. }
  1564. // Drop connections to all devices that can now share the new
  1565. // folder.
  1566. m.pmut.Lock()
  1567. for _, dev := range cfg.DeviceIDs() {
  1568. if conn, ok := m.conn[dev]; ok {
  1569. closeRawConn(conn)
  1570. }
  1571. }
  1572. m.pmut.Unlock()
  1573. }
  1574. }
  1575. for folderID, fromCfg := range fromFolders {
  1576. toCfg, ok := toFolders[folderID]
  1577. if !ok {
  1578. // The folder was removed.
  1579. m.RemoveFolder(folderID)
  1580. continue
  1581. }
  1582. // This folder exists on both sides. Compare the device lists, as we
  1583. // can handle adding a device (but not currently removing one).
  1584. fromDevs := mapDevices(fromCfg.DeviceIDs())
  1585. toDevs := mapDevices(toCfg.DeviceIDs())
  1586. for dev := range fromDevs {
  1587. if _, ok := toDevs[dev]; !ok {
  1588. // A device was removed. Requires restart.
  1589. l.Debugln(m, "requires restart, removing device", dev, "from folder", folderID)
  1590. return false
  1591. }
  1592. }
  1593. for dev := range toDevs {
  1594. if _, ok := fromDevs[dev]; !ok {
  1595. // A device was added. Handle it!
  1596. m.fmut.Lock()
  1597. m.pmut.Lock()
  1598. m.folderCfgs[folderID] = toCfg
  1599. m.folderDevices[folderID] = append(m.folderDevices[folderID], dev)
  1600. m.deviceFolders[dev] = append(m.deviceFolders[dev], folderID)
  1601. // If we already have a connection to this device, we should
  1602. // disconnect it so that we start sharing the folder with it.
  1603. // We close the underlying connection and let the normal error
  1604. // handling kick in to clean up and reconnect.
  1605. if conn, ok := m.conn[dev]; ok {
  1606. closeRawConn(conn)
  1607. }
  1608. m.pmut.Unlock()
  1609. m.fmut.Unlock()
  1610. }
  1611. }
  1612. // Check if anything else differs, apart from the device list.
  1613. fromCfg.Devices = nil
  1614. toCfg.Devices = nil
  1615. if !reflect.DeepEqual(fromCfg, toCfg) {
  1616. l.Debugln(m, "requires restart, folder", folderID, "configuration differs")
  1617. return false
  1618. }
  1619. }
  1620. // Removing a device requires restart
  1621. toDevs := mapDeviceCfgs(from.Devices)
  1622. for _, dev := range from.Devices {
  1623. if _, ok := toDevs[dev.DeviceID]; !ok {
  1624. l.Debugln(m, "requires restart, device", dev.DeviceID, "was removed")
  1625. return false
  1626. }
  1627. }
  1628. // All of the generic options require restart
  1629. if !reflect.DeepEqual(from.Options, to.Options) {
  1630. l.Debugln(m, "requires restart, options differ")
  1631. return false
  1632. }
  1633. return true
  1634. }
  1635. // mapFolders returns a map of folder ID to folder configuration for the given
  1636. // slice of folder configurations.
  1637. func mapFolders(folders []config.FolderConfiguration) map[string]config.FolderConfiguration {
  1638. m := make(map[string]config.FolderConfiguration, len(folders))
  1639. for _, cfg := range folders {
  1640. m[cfg.ID] = cfg
  1641. }
  1642. return m
  1643. }
  1644. // mapDevices returns a map of device ID to nothing for the given slice of
  1645. // device IDs.
  1646. func mapDevices(devices []protocol.DeviceID) map[protocol.DeviceID]struct{} {
  1647. m := make(map[protocol.DeviceID]struct{}, len(devices))
  1648. for _, dev := range devices {
  1649. m[dev] = struct{}{}
  1650. }
  1651. return m
  1652. }
  1653. // mapDeviceCfgs returns a map of device ID to nothing for the given slice of
  1654. // device configurations.
  1655. func mapDeviceCfgs(devices []config.DeviceConfiguration) map[protocol.DeviceID]struct{} {
  1656. m := make(map[protocol.DeviceID]struct{}, len(devices))
  1657. for _, dev := range devices {
  1658. m[dev.DeviceID] = struct{}{}
  1659. }
  1660. return m
  1661. }
  1662. func filterIndex(folder string, fs []protocol.FileInfo, dropDeletes bool) []protocol.FileInfo {
  1663. for i := 0; i < len(fs); {
  1664. if fs[i].Flags&^protocol.FlagsAll != 0 {
  1665. l.Debugln("dropping update for file with unknown bits set", fs[i])
  1666. fs[i] = fs[len(fs)-1]
  1667. fs = fs[:len(fs)-1]
  1668. } else if fs[i].IsDeleted() && dropDeletes {
  1669. l.Debugln("dropping update for undesired delete", fs[i])
  1670. fs[i] = fs[len(fs)-1]
  1671. fs = fs[:len(fs)-1]
  1672. } else if symlinkInvalid(folder, fs[i]) {
  1673. l.Debugln("dropping update for unsupported symlink", fs[i])
  1674. fs[i] = fs[len(fs)-1]
  1675. fs = fs[:len(fs)-1]
  1676. } else {
  1677. i++
  1678. }
  1679. }
  1680. return fs
  1681. }
  1682. func symlinkInvalid(folder string, fi db.FileIntf) bool {
  1683. if !symlinks.Supported && fi.IsSymlink() && !fi.IsInvalid() && !fi.IsDeleted() {
  1684. symlinkWarning.Do(func() {
  1685. l.Warnln("Symlinks are disabled, unsupported or require Administrator privileges. This might cause your folder to appear out of sync.")
  1686. })
  1687. // Need to type switch for the concrete type to be able to access fields...
  1688. var name string
  1689. switch fi := fi.(type) {
  1690. case protocol.FileInfo:
  1691. name = fi.Name
  1692. case db.FileInfoTruncated:
  1693. name = fi.Name
  1694. }
  1695. l.Infoln("Unsupported symlink", name, "in folder", folder)
  1696. return true
  1697. }
  1698. return false
  1699. }
  1700. // Skips `skip` elements and retrieves up to `get` elements from a given slice.
  1701. // Returns the resulting slice, plus how much elements are left to skip or
  1702. // copy to satisfy the values which were provided, given the slice is not
  1703. // big enough.
  1704. func getChunk(data []string, skip, get int) ([]string, int, int) {
  1705. l := len(data)
  1706. if l <= skip {
  1707. return []string{}, skip - l, get
  1708. } else if l < skip+get {
  1709. return data[skip:l], 0, get - (l - skip)
  1710. }
  1711. return data[skip : skip+get], 0, 0
  1712. }
  1713. func closeRawConn(conn io.Closer) error {
  1714. if conn, ok := conn.(*tls.Conn); ok {
  1715. // If the underlying connection is a *tls.Conn, Close() does more
  1716. // than it says on the tin. Specifically, it sends a TLS alert
  1717. // message, which might block forever if the connection is dead
  1718. // and we don't have a deadline set.
  1719. conn.SetWriteDeadline(time.Now().Add(250 * time.Millisecond))
  1720. }
  1721. return conn.Close()
  1722. }
  1723. func stringSliceWithout(ss []string, s string) []string {
  1724. for i := range ss {
  1725. if ss[i] == s {
  1726. copy(ss[i:], ss[i+1:])
  1727. ss = ss[:len(ss)-1]
  1728. return ss
  1729. }
  1730. }
  1731. return ss
  1732. }