model.go 70 KB

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