updates.go 2.32 KB
Newer Older
1 2 3
package updates

import (
4
	"fmt"
5 6
	"os"

Henry's avatar
Henry committed
7
	"github.com/jbenet/go-ipfs/config"
8 9
	u "github.com/jbenet/go-ipfs/util"

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
10
	"github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/coreos/go-semver/semver"
11 12
	"github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/inconshreveable/go-update"
	"github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/inconshreveable/go-update/check"
13 14 15
)

const (
16 17 18 19 20 21 22 23 24
	// Version is the current application's version literal
	Version = "0.1.1"

	updateEndpointURL = "https://api.equinox.io/1/Updates"
	updateAppID       = "CHANGEME"

	updatePubKey = `-----BEGIN RSA PUBLIC KEY-----
CHANGEME
-----END RSA PUBLIC KEY-----`
25 26
)

27 28
var log = u.Logger("updates")

29 30 31 32
var currentVersion *semver.Version

func init() {
	var err error
33
	currentVersion, err = parseVersion()
34
	if err != nil {
35
		log.Error("illegal version number in code: %q\n", Version)
36 37 38 39
		os.Exit(1)
	}
}

40 41 42
func parseVersion() (*semver.Version, error) {
	return semver.NewVersion(Version)
}
43

44
// CheckForUpdate checks the equinox.io api if there is an update available
45 46 47
func CheckForUpdate() (*check.Result, error) {
	param := check.Params{
		AppVersion: Version,
48
		AppId:      updateAppID,
49
		Channel:    "stable",
50
	}
51

52 53 54 55 56 57 58 59 60 61 62
	up, err := update.New().VerifySignatureWithPEM([]byte(updatePubKey))
	if err != nil {
		return nil, fmt.Errorf("Failed to parse public key: %v", err)
	}

	return param.CheckForUpdate(updateEndpointURL, up)
}

// AbleToApply cheks if the running process is able to update itself
func AbleToApply() error {
	return update.New().CanUpdate()
63
}
Henry's avatar
Henry committed
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

// ShouldAutoUpdate decides wether a new version should be applied
// checks against config setting and new version string. returns false in case of error
func ShouldAutoUpdate(setting, newVer string) bool {
	if setting == config.UpdateNever {
		return false
	}

	nv, err := semver.NewVersion(newVer)
	if err != nil {
		log.Error("could not parse version string: %s", err)
		return false
	}

	n := nv.Slice()
	c := currentVersion.Slice()

	switch setting {

	case config.UpdatePatch:
		if n[0] < c[0] {
			return false
		}

		if n[1] < c[1] {
			return false
		}

		return n[2] > c[2]

	case config.UpdateMinor:
		if n[0] != c[0] {
			return false
		}

		return n[1] > c[1] || (n[1] == c[1] && n[2] > c[2])

	case config.UpdateMajor:
		for i := 0; i < 3; i++ {
			if n[i] < c[i] {
				return false
			}
		}
		return true
	}

	return false
}