This repository has been archived by the owner on Jan 8, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 21
/
updater.go
569 lines (495 loc) · 17.1 KB
/
updater.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
// Copyright 2015 Keybase, Inc. All rights reserved. Use of
// this source code is governed by the included BSD license.
package updater
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
"github.com/keybase/go-updater/util"
)
// Version is the updater version
const Version = "0.3.8"
// Updater knows how to find and apply updates
type Updater struct {
source UpdateSource
config Config
log Log
guiBusyCount int
tickDuration time.Duration
}
// UpdateSource defines where the updater can find updates
type UpdateSource interface {
// Description is a short description about the update source
Description() string
// FindUpdate finds an update given options
FindUpdate(options UpdateOptions) (*Update, error)
}
// Context defines options, UI and hooks for the updater.
// This is where you can define custom behavior specific to your apps.
type Context interface {
GetUpdateUI() UpdateUI
UpdateOptions() UpdateOptions
Verify(update Update) error
BeforeUpdatePrompt(update Update, options UpdateOptions) error
BeforeApply(update Update) error
Apply(update Update, options UpdateOptions, tmpDir string) error
AfterApply(update Update) error
ReportError(err error, update *Update, options UpdateOptions)
ReportAction(updatePromptResponse UpdatePromptResponse, update *Update, options UpdateOptions)
ReportSuccess(update *Update, options UpdateOptions)
AfterUpdateCheck(update *Update)
GetAppStatePath() string
IsCheckCommand() bool
DeepClean()
}
// Config defines configuration for the Updater
type Config interface {
GetUpdateAuto() (bool, bool)
SetUpdateAuto(b bool) error
GetUpdateAutoOverride() bool
SetUpdateAutoOverride(bool) error
GetInstallID() string
SetInstallID(installID string) error
IsLastUpdateCheckTimeRecent(d time.Duration) bool
SetLastUpdateCheckTime()
SetLastAppliedVersion(string) error
GetLastAppliedVersion() string
}
// Log is the logging interface for this package
type Log interface {
Debug(...interface{})
Info(...interface{})
Debugf(s string, args ...interface{})
Infof(s string, args ...interface{})
Warningf(s string, args ...interface{})
Errorf(s string, args ...interface{})
}
// NewUpdater constructs an Updater
func NewUpdater(source UpdateSource, config Config, log Log) *Updater {
return &Updater{
source: source,
config: config,
log: log,
tickDuration: DefaultTickDuration,
}
}
func (u *Updater) SetTickDuration(dur time.Duration) {
u.tickDuration = dur
}
// Update checks, downloads and performs an update
func (u *Updater) Update(ctx Context) (*Update, error) {
options := ctx.UpdateOptions()
update, err := u.update(ctx, options)
report(ctx, err, update, options)
return update, err
}
// update returns the update received, and an error if the update was not
// performed. The error with be of type Error. The error may be due to the user
// (or system) canceling an update, in which case error.IsCancel() will be true.
func (u *Updater) update(ctx Context, options UpdateOptions) (*Update, error) {
update, err := u.checkForUpdate(ctx, options)
if err != nil {
return nil, findErr(err)
}
if update == nil || !update.NeedUpdate {
// No update available
return nil, nil
}
u.log.Infof("Got update with version: %s", update.Version)
if update.missingAsset() {
return update, nil
}
if err := u.CleanupPreviousUpdates(); err != nil {
u.log.Infof("Error cleaning up previous downloads: %v", err)
}
tmpDir := u.tempDir()
defer u.Cleanup(tmpDir)
if err := u.downloadAsset(update.Asset, tmpDir, options); err != nil {
return update, downloadErr(err)
}
err = ctx.BeforeUpdatePrompt(*update, options)
if err != nil {
return update, err
}
// Prompt for update
updatePromptResponse, err := u.promptForUpdateAction(ctx, *update, options)
if err != nil {
return update, promptErr(err)
}
switch updatePromptResponse.Action {
case UpdateActionApply:
ctx.ReportAction(updatePromptResponse, update, options)
case UpdateActionAuto:
ctx.ReportAction(updatePromptResponse, update, options)
case UpdateActionSnooze:
ctx.ReportAction(updatePromptResponse, update, options)
return update, CancelErr(fmt.Errorf("Snoozed update"))
case UpdateActionCancel:
ctx.ReportAction(updatePromptResponse, update, options)
return update, CancelErr(fmt.Errorf("Canceled"))
case UpdateActionError:
return update, promptErr(fmt.Errorf("Unknown prompt error"))
case UpdateActionContinue:
// Continue
case UpdateActionUIBusy:
// Return nil so that AfterUpdateCheck won't exit the service
return nil, guiBusyErr(fmt.Errorf("User active, retrying later"))
}
// If we are auto-updating, do a final check if the user is active before
// killing the app. Note this can cause some churn with re-downloading the
// update on the next attempt.
if updatePromptResponse.Action == UpdateActionAuto && !ctx.IsCheckCommand() {
isActive, err := u.checkUserActive(ctx)
if err == nil && isActive {
return nil, guiBusyErr(fmt.Errorf("User active, retrying later"))
}
}
u.log.Infof("Verify asset: %s", update.Asset.LocalPath)
if err := ctx.Verify(*update); err != nil {
return update, verifyErr(err)
}
if err := u.apply(ctx, *update, options, tmpDir); err != nil {
return update, err
}
return update, nil
}
func (u *Updater) ApplyDownloaded(ctx Context) (bool, error) {
options := ctx.UpdateOptions()
// 1. check with the api server again for the latest update to be sure that a
// new update has not come out since our last call to CheckAndDownload
u.log.Infof("Attempting to apply previously downloaded update")
update, err := u.checkForUpdate(ctx, options)
if err != nil {
return false, findErr(err)
}
// Only report apply success/failure
applied, err := u.applyDownloaded(ctx, update, options)
defer report(ctx, err, update, options)
if err != nil {
return false, err
}
return applied, nil
}
// ApplyDownloaded will look for an previously downloaded update and attempt to apply it without prompting.
// CheckAndDownload must be called first so that we have a download asset available to apply.
func (u *Updater) applyDownloaded(ctx Context, update *Update, options UpdateOptions) (applied bool, err error) {
if update == nil || !update.NeedUpdate {
return false, fmt.Errorf("No previously downloaded update to apply since client is update to date")
}
u.log.Infof("Got update with version: %s", update.Version)
if update.missingAsset() {
return false, fmt.Errorf("Update contained no asset to apply. Update version: %s", update.Version)
}
// 2. check the disk via FindDownloadedAsset. Compare our API result to this
// result. If the downloaded update is stale, clear it and start over.
downloadedAssetPath, err := u.FindDownloadedAsset(update.Asset.Name)
if err != nil {
return false, err
}
defer func() {
if err := u.CleanupPreviousUpdates(); err != nil {
u.log.Infof("Error cleaning up previous downloads: %v", err)
}
}()
if downloadedAssetPath == "" {
return false, fmt.Errorf("No downloaded asset found for version: %s", update.Version)
}
update.Asset.LocalPath = downloadedAssetPath
// 3. otherwise use the update on disk and apply it.
if err = util.CheckDigest(update.Asset.Digest, downloadedAssetPath, u.log); err != nil {
return false, verifyErr(err)
}
u.log.Infof("Verify asset: %s", downloadedAssetPath)
if err := ctx.Verify(*update); err != nil {
return false, verifyErr(err)
}
tmpDir := os.TempDir()
if err := u.apply(ctx, *update, options, tmpDir); err != nil {
return false, err
}
return true, nil
}
func (u *Updater) apply(ctx Context, update Update, options UpdateOptions, tmpDir string) error {
u.log.Info("Before apply")
if err := ctx.BeforeApply(update); err != nil {
return applyErr(err)
}
u.log.Info("Applying update")
if err := ctx.Apply(update, options, tmpDir); err != nil {
u.log.Info("Apply error: %v", err)
return applyErr(err)
}
u.log.Info("After apply")
if err := ctx.AfterApply(update); err != nil {
return applyErr(err)
}
return nil
}
// downloadAsset will download the update to a temporary path (if not cached),
// check the digest, and set the LocalPath property on the asset.
func (u *Updater) downloadAsset(asset *Asset, tmpDir string, options UpdateOptions) error {
if asset == nil {
return fmt.Errorf("No asset to download")
}
downloadOptions := util.DownloadURLOptions{
Digest: asset.Digest,
RequireDigest: true,
UseETag: true,
Log: u.log,
}
downloadPath := filepath.Join(tmpDir, asset.Name)
// If asset had a file extension, lets add it back on
if err := util.DownloadURL(asset.URL, downloadPath, downloadOptions); err != nil {
return err
}
asset.LocalPath = downloadPath
return nil
}
// checkForUpdate checks a update source (like a remote API) for an update.
// It may set an InstallID, if the server tells us to.
func (u *Updater) checkForUpdate(ctx Context, options UpdateOptions) (*Update, error) {
u.log.Infof("Checking for update, current version is %s", options.Version)
u.log.Infof("Using updater source: %s", u.source.Description())
u.log.Debugf("Using options: %#v", options)
update, findErr := u.source.FindUpdate(options)
if findErr != nil {
return nil, findErr
}
if update == nil {
return nil, nil
}
// Save InstallID if we received one
if update.InstallID != "" && u.config.GetInstallID() != update.InstallID {
u.log.Debugf("Saving install ID: %s", update.InstallID)
if err := u.config.SetInstallID(update.InstallID); err != nil {
u.log.Warningf("Error saving install ID: %s", err)
ctx.ReportError(configErr(fmt.Errorf("Error saving install ID: %s", err)), update, options)
}
}
return update, nil
}
// NeedUpdate returns true if we are out-of-date.
func (u *Updater) NeedUpdate(ctx Context) (upToDate bool, err error) {
update, err := u.checkForUpdate(ctx, ctx.UpdateOptions())
if err != nil {
return false, err
}
return update.NeedUpdate, nil
}
func (u *Updater) CheckAndDownload(ctx Context) (updateAvailable, updateWasDownloaded bool, err error) {
options := ctx.UpdateOptions()
update, err := u.checkForUpdate(ctx, options)
if err != nil {
return false, false, err
}
if !update.NeedUpdate || update.missingAsset() {
return false, false, nil
}
var tmpDir string
defer func() {
// If anything in this process errors cleanup the downloaded asset
if err != nil {
if err := u.CleanupPreviousUpdates(); err != nil {
u.log.Infof("Error cleaning up previous downloads: %v", err)
}
}
if tmpDir != "" {
u.Cleanup(tmpDir)
}
}()
var digestChecked bool
downloadedAssetPath, err := u.FindDownloadedAsset(update.Asset.Name)
if downloadedAssetPath == "" || err != nil {
u.log.Infof("Could not find existing download asset for version: %s. Downloading new asset.", update.Version)
tmpDir = u.tempDir()
// This will set update.Asset.LocalPath
if err := u.downloadAsset(update.Asset, tmpDir, options); err != nil {
return false, false, downloadErr(err)
}
updateWasDownloaded = true
digestChecked = true
downloadedAssetPath = update.Asset.LocalPath
}
// Verify depends on LocalPath being set to the downloaded asset
update.Asset.LocalPath = downloadedAssetPath
u.log.Infof("Verify asset: %s", downloadedAssetPath)
if err := ctx.Verify(*update); err != nil {
return false, false, verifyErr(err)
}
if !digestChecked {
if err = util.CheckDigest(update.Asset.Digest, downloadedAssetPath, u.log); err != nil {
return false, false, verifyErr(err)
}
}
return true, updateWasDownloaded, nil
}
// promptForUpdateAction prompts the user for permission to apply an update
func (u *Updater) promptForUpdateAction(ctx Context, update Update, options UpdateOptions) (UpdatePromptResponse, error) {
u.log.Debug("Prompt for update")
auto, autoSet := u.config.GetUpdateAuto()
autoOverride := u.config.GetUpdateAutoOverride()
u.log.Debugf("Auto update: %s (set=%s autoOverride=%s)", strconv.FormatBool(auto), strconv.FormatBool(autoSet), strconv.FormatBool(autoOverride))
if auto && !autoOverride {
if !ctx.IsCheckCommand() {
// If there's an error getting active status, we'll just update
isActive, err := u.checkUserActive(ctx)
if err == nil && isActive {
return UpdatePromptResponse{UpdateActionUIBusy, false, 0}, nil
}
u.guiBusyCount = 0
}
return UpdatePromptResponse{UpdateActionAuto, false, 0}, nil
}
updateUI := ctx.GetUpdateUI()
// If auto update never set, default to true
autoUpdate := auto || !autoSet
promptOptions := UpdatePromptOptions{AutoUpdate: autoUpdate}
updatePromptResponse, err := updateUI.UpdatePrompt(update, options, promptOptions)
if err != nil {
return UpdatePromptResponse{UpdateActionError, false, 0}, err
}
if updatePromptResponse == nil {
return UpdatePromptResponse{UpdateActionError, false, 0}, fmt.Errorf("No response")
}
if updatePromptResponse.Action != UpdateActionContinue {
u.log.Debugf("Update prompt response: %#v", updatePromptResponse)
if err := u.config.SetUpdateAuto(updatePromptResponse.AutoUpdate); err != nil {
u.log.Warningf("Error setting auto preference: %s", err)
ctx.ReportError(configErr(fmt.Errorf("Error setting auto preference: %s", err)), &update, options)
}
}
return *updatePromptResponse, nil
}
type guiAppState struct {
IsUserActive bool `json:"isUserActive"`
ChangedAtMs int64 `json:"changedAtMs"`
}
func (u *Updater) checkUserActive(ctx Context) (bool, error) {
if time.Duration(u.guiBusyCount)*u.tickDuration >= time.Hour*6 { // Allow the update through after 6 hours
u.log.Warningf("Waited for GUI %d times - ignoring busy", u.guiBusyCount)
return false, nil
}
// Read app-state.json, written by the GUI
rawState, err := util.ReadFile(ctx.GetAppStatePath())
if err != nil {
u.log.Warningf("Error reading GUI state - proceeding", err)
return false, err
}
guistate := guiAppState{}
if err = json.Unmarshal(rawState, &guistate); err != nil {
u.log.Warningf("Error parsing GUI state - proceeding", err)
return false, err
}
// check if the user is currently active or was active in the last 5
// minutes.
isActive := guistate.IsUserActive || time.Since(time.Unix(guistate.ChangedAtMs/1000, 0)) <= time.Minute*5
if isActive {
u.guiBusyCount++
u.log.Infof("GUI busy on attempt %d", u.guiBusyCount)
}
return isActive, nil
}
func report(ctx Context, err error, update *Update, options UpdateOptions) {
if err != nil {
// Don't report cancels or GUI busy
if e, ok := err.(Error); ok {
if e.IsCancel() || e.IsGUIBusy() {
return
}
}
ctx.ReportError(err, update, options)
} else if update != nil {
ctx.ReportSuccess(update, options)
}
}
// tempDir, if specified, will contain files that were replaced during an update
// and will be removed after an update. The temp dir should already exist.
func (u *Updater) tempDir() string {
tmpDir := util.TempPath("", "KeybaseUpdater.")
if err := util.MakeDirs(tmpDir, 0700, u.log); err != nil {
u.log.Warningf("Error trying to create temp dir: %s", err)
return ""
}
return tmpDir
}
var tempDirRE = regexp.MustCompile(`^KeybaseUpdater.([ABCDEFGHIJKLMNOPQRSTUVWXYZ234567]{52}|\d{18,})$`)
// CleanupPreviousUpdates removes temporary files from previous updates.
func (u *Updater) CleanupPreviousUpdates() (err error) {
parent := os.TempDir()
if parent == "" || parent == "." {
return fmt.Errorf("temp directory is '%v'", parent)
}
files, err := os.ReadDir(parent)
if err != nil {
return fmt.Errorf("listing parent directory: %v", err)
}
for _, fi := range files {
if !fi.IsDir() {
continue
}
if tempDirRE.MatchString(fi.Name()) {
targetPath := filepath.Join(parent, fi.Name())
u.log.Debugf("Cleaning old download: %v", targetPath)
err = os.RemoveAll(targetPath)
if err != nil {
u.log.Infof("Error deleting old temp dir %v: %v", fi.Name(), err)
}
}
}
return nil
}
// Cleanup removes temporary files from this update
func (u *Updater) Cleanup(tmpDir string) {
if tmpDir != "" {
u.log.Debugf("Remove temporary directory: %q", tmpDir)
if err := os.RemoveAll(tmpDir); err != nil {
u.log.Warningf("Error removing temporary directory %q: %s", tmpDir, err)
}
}
}
// Inspect previously downloaded updates to avoid redownloading
func (u *Updater) FindDownloadedAsset(assetName string) (matchingAssetPath string, err error) {
if assetName == "" {
return "", fmt.Errorf("No asset name provided")
}
parent := os.TempDir()
if parent == "" || parent == "." {
return matchingAssetPath, fmt.Errorf("temp directory is %v", parent)
}
files, err := os.ReadDir(parent)
if err != nil {
return matchingAssetPath, fmt.Errorf("listing parent directory: %v", err)
}
for _, fi := range files {
if !fi.IsDir() || !tempDirRE.MatchString(fi.Name()) {
continue
}
keybaseTempDirAbs := filepath.Join(parent, fi.Name())
walkErr := filepath.Walk(keybaseTempDirAbs, func(fullPath string, info os.FileInfo, inErr error) (err error) {
if inErr != nil {
return inErr
}
if info.IsDir() {
if fullPath == keybaseTempDirAbs {
return nil
}
return filepath.SkipDir
}
path := strings.TrimPrefix(fullPath, keybaseTempDirAbs+string(filepath.Separator))
if path == assetName {
matchingAssetPath = fullPath
return filepath.SkipDir
}
return nil
})
if walkErr != nil {
return "", walkErr
}
}
return matchingAssetPath, nil
}