model.go 63 KB

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