/
updater.go
328 lines (268 loc) · 7.36 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
package updater
import (
"crypto/rand"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"runtime"
"github.com/axllent/semver"
)
var (
// AllowPrereleases defines whether pre-releases may be included
AllowPrereleases = false
tempDir string
)
// Releases struct for Github releases json
type Releases []struct {
Name string `json:"name"` // release name
Tag string `json:"tag_name"` // release tag
Prerelease bool `json:"prerelease"` // Github pre-release
Assets []struct {
BrowserDownloadURL string `json:"browser_download_url"`
ID int64 `json:"id"`
Name string `json:"name"`
Size int64 `json:"size"`
} `json:"assets"`
}
// Release struct contains the file data for downloadable release
type Release struct {
Name string
Tag string
URL string
Size int64
}
// GithubLatest fetches the latest release info & returns release tag, filename & download url
func GithubLatest(repo, name string) (string, string, string, error) {
releaseURL := fmt.Sprintf("https://api.github.com/repos/%s/releases", repo)
resp, err := http.Get(releaseURL) // #nosec
if err != nil {
return "", "", "", err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", "", "", err
}
linkOS := runtime.GOOS
linkArch := runtime.GOARCH
linkExt := ".tar.gz"
if linkOS == "windows" {
// Windows uses .zip instead
linkExt = ".zip"
}
var allReleases = []Release{}
var releases Releases
if err := json.Unmarshal(body, &releases); err != nil {
return "", "", "", err
}
archiveName := fmt.Sprintf("%s_%s_%s%s", name, linkOS, linkArch, linkExt)
// loop through releases
for _, r := range releases {
if !semver.IsValid(r.Tag) {
// Invalid semversion, skip
continue
}
if !AllowPrereleases && (semver.Prerelease(r.Tag) != "" || r.Prerelease) {
// we don't accept AllowPrereleases, skip
continue
}
for _, a := range r.Assets {
if a.Name == archiveName {
thisRelease := Release{a.Name, r.Tag, a.BrowserDownloadURL, a.Size}
allReleases = append(allReleases, thisRelease)
break
}
}
}
if len(allReleases) == 0 {
// no releases with suitable assets found
return "", "", "", fmt.Errorf("No binary releases found")
}
var latestRelease = Release{}
for _, r := range allReleases {
// detect the latest release
if semver.Compare(r.Tag, latestRelease.Tag) == 1 {
latestRelease = r
}
}
return latestRelease.Tag, latestRelease.Name, latestRelease.URL, nil
}
// GreaterThan compares the current version to a different version
// returning < 1 not upgradeable
func GreaterThan(toVer, fromVer string) bool {
return semver.Compare(toVer, fromVer) == 1
}
// GithubUpdate the running binary with the latest release binary from Github
func GithubUpdate(repo, appName, currentVersion string) (string, error) {
ver, filename, downloadURL, err := GithubLatest(repo, appName)
if err != nil {
return "", err
}
if ver == currentVersion {
return "", fmt.Errorf("No new release found")
}
if semver.Compare(ver, currentVersion) < 1 {
return "", fmt.Errorf("No newer releases found (latest %s)", ver)
}
tmpDir := getTempDir()
// outFile can be a tar.gz or a zip, depending on architecture
outFile := filepath.Join(tmpDir, filename)
if err := downloadToFile(downloadURL, outFile); err != nil {
return "", err
}
newExec := filepath.Join(tmpDir, "adguard-home-bg")
if runtime.GOOS == "windows" {
if _, err := Unzip(outFile, tmpDir); err != nil {
return "", err
}
newExec = filepath.Join(tmpDir, "adguard-home-bg.exe")
} else {
if err := TarGZExtract(outFile, tmpDir); err != nil {
return "", err
}
}
// get the running binary
oldExec, err := os.Executable()
if err != nil {
panic(err)
}
if err = replaceFile(oldExec, newExec); err != nil {
return "", err
}
return ver, nil
}
// DownloadToFile downloads a URL to a file
func downloadToFile(url, filepath string) error {
// Get the data
resp, err := http.Get(url) // #nosec
if err != nil {
return err
}
defer resp.Body.Close()
// Create the file
out, err := os.Create(filepath)
if err != nil {
return err
}
defer func() {
if err := out.Close(); err != nil {
fmt.Printf("Error closing file: %s\n", err)
}
}()
// Write the body to file
_, err = io.Copy(out, resp.Body)
return err
}
// ReplaceFile replaces one file with another.
// Running files cannot be overwritten, so it has to be moved
// and the new binary saved to the original path. This requires
// read & write permissions to both the original file and directory.
// Note, on Windows it is not possible to delete a running program,
// so the old exe is renamed and moved to os.TempDir()
func replaceFile(dst, src string) error {
// open the source file for reading
source, err := os.Open(filepath.Clean(src))
if err != nil {
return err
}
// destination directory eg: /usr/local/bin
dstDir := filepath.Dir(dst)
// binary filename
binaryFilename := filepath.Base(dst)
// old binary tmp name
dstOld := fmt.Sprintf("%s.old", binaryFilename)
// new binary tmp name
dstNew := fmt.Sprintf("%s.new", binaryFilename)
// absolute path of new tmp file
newTmpAbs := filepath.Join(dstDir, dstNew)
// absolute path of old tmp file
oldTmpAbs := filepath.Join(dstDir, dstOld)
// get src permissions
fi, _ := os.Stat(dst)
srcPerms := fi.Mode().Perm()
// create the new file
tmpNew, err := os.OpenFile(filepath.Clean(newTmpAbs), os.O_CREATE|os.O_RDWR, srcPerms) // #nosec
if err != nil {
return err
}
// copy new binary to <binary>.new
if _, err := io.Copy(tmpNew, source); err != nil {
return err
}
// close immediately else Windows has a fit
if err := tmpNew.Close(); err != nil {
return err
}
if err := source.Close(); err != nil {
return err
}
// rename the current executable to <binary>.old
if err := os.Rename(dst, oldTmpAbs); err != nil {
return err
}
// rename the <binary>.new to current executable
if err := os.Rename(newTmpAbs, dst); err != nil {
return err
}
// delete the old binary
if runtime.GOOS == "windows" {
tmpDir := os.TempDir()
delFile := filepath.Join(tmpDir, filepath.Base(oldTmpAbs))
if err := os.Rename(oldTmpAbs, delFile); err != nil {
return err
}
} else {
if err := os.Remove(oldTmpAbs); err != nil {
return err
}
}
// remove the src file
if err := os.Remove(src); err != nil {
return err
}
return nil
}
// GetTempDir will create & return a temporary directory if one has not been specified
func getTempDir() string {
if tempDir == "" {
randBytes := make([]byte, 6)
if _, err := rand.Read(randBytes); err != nil {
panic(err)
}
tempDir = filepath.Join(os.TempDir(), "updater-"+hex.EncodeToString(randBytes))
}
if err := mkDirIfNotExists(tempDir); err != nil {
// need a better way to exit
fmt.Printf("Error: %v", err)
os.Exit(2)
}
return tempDir
}
// MkDirIfNotExists will create a directory if it doesn't exist
func mkDirIfNotExists(path string) error {
if !isDir(path) {
return os.MkdirAll(path, os.ModePerm)
}
return nil
}
// IsFile returns if a path is a file
func isFile(path string) bool {
info, err := os.Stat(path)
if os.IsNotExist(err) || !info.Mode().IsRegular() {
return false
}
return true
}
// IsDir returns if a path is a directory
func isDir(path string) bool {
info, err := os.Stat(path)
if os.IsNotExist(err) || !info.IsDir() {
return false
}
return true
}