model.go 70 KB

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