model.go 66 KB

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