model.go 57 KB

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