summaryrefslogtreecommitdiff
path: root/pkg/config/version/checknewer.go
blob: 78b5b31cc4351f59055ee9e77086037d725dea3c (plain)
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
package version

import (
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"runtime"
	"strings"
)

const verURI = "https://downloads.leap.se/RiseupVPN/"

// returns true if there's a newer version string published on the server
// this needs to manually bump latest version for every platform in the
// downloads server.
// at the moment, we hardcode RiseupVPN in the path, assuming that all clients
// stay in sync.
func CanUpgrade() bool {
	if os.Getenv("SKIP_VERSION_CHECK") == "1" {
		return false
	}
	log.Println("Checking for updates...")
	uri := verURI
	switch runtime.GOOS {
	case "windows":
		uri += "windows"
	case "darwin":
		uri += "osx"
	case "linux":
		fallthrough
	default:
		uri += "linux"
	}
	uri += "/lastver"
	resp, err := http.Get(uri)
	if err != nil {
		log.Println(err)
		return false
	}
	defer resp.Body.Close()
	verStr, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Println(err)
		return false
	}
	r := strings.TrimSpace(string(verStr))
	if strings.Count(r, "\n") > 1 {
		log.Println("No remote version found at " + uri)
		return false
	}
	canUpgrade := versionOrdinal(r) > versionOrdinal(VERSION)
	if os.Getenv("DEBUG") == "1" {
		log.Println(">>> Remote version:  " + r)
		log.Println(">>> Current version: " + VERSION)
	}
	if canUpgrade {
		log.Println("There's a newer version available:", r)
	}
	return canUpgrade
}

// https://stackoverflow.com/a/18411978
func versionOrdinal(version string) string {
	const maxByte = 1<<8 - 1
	vo := make([]byte, 0, len(version)+8)
	j := -1
	for i := 0; i < len(version); i++ {
		b := version[i]
		if '0' > b || b > '9' {
			vo = append(vo, b)
			j = -1
			continue
		}
		if j == -1 {
			vo = append(vo, 0x00)
			j = len(vo) - 1
		}
		if vo[j] == 1 && vo[j+1] == '0' {
			vo[j+1] = b
			continue
		}
		if vo[j]+1 > maxByte {
			log.Println("VersionOrdinal: invalid version")
			return string(vo)
		}
		vo = append(vo, b)
		vo[j]++
	}
	return string(vo)
}