forked from arduino/arduino-create-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
update.go
436 lines (394 loc) · 9.75 KB
/
update.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
//
// update.go
//
// Created by Martino Facchin
// Code from github.com/sanbornm and github.com/sanderhahn
// Copyright (c) 2015 Arduino LLC
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
//
package main
import (
"archive/zip"
"bytes"
"compress/gzip"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"math/rand"
"net/http"
"os"
"path"
"path/filepath"
"runtime"
"strings"
"time"
"github.com/inconshreveable/go-update"
"github.com/kardianos/osext"
"github.com/kr/binarydist"
"github.com/termie/go-shutil"
patch "github.com/sanderhahn/gozip/patchzip"
)
func IsZip(path string) bool {
r, err := zip.OpenReader(path)
if err == nil {
r.Close()
return true
}
return false
}
func Zip(path string, dirs []string) (err error) {
if IsZip(path) {
return errors.New(path + " is already a zip file")
}
f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
if err != nil {
return
}
defer f.Close()
startoffset, err := f.Seek(0, os.SEEK_END)
if err != nil {
return
}
w := patch.NewWriterAt(f, startoffset)
for _, dir := range dirs {
err = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
fh, err := patch.FileInfoHeader(info)
if err != nil {
return err
}
fh.Name = path
p, err := w.CreateHeader(fh)
if err != nil {
return err
}
if !info.IsDir() {
content, err := ioutil.ReadFile(path)
if err != nil {
return err
}
_, err = p.Write(content)
if err != nil {
return err
}
}
return err
})
}
err = w.Close()
return
}
func Unzip(zippath string, destination string) (err error) {
r, err := zip.OpenReader(zippath)
if err != nil {
return err
}
for _, f := range r.File {
fullname := path.Join(destination, f.Name)
if f.FileInfo().IsDir() {
os.MkdirAll(fullname, f.FileInfo().Mode().Perm())
} else {
os.MkdirAll(filepath.Dir(fullname), 0755)
perms := f.FileInfo().Mode().Perm()
out, err := os.OpenFile(fullname, os.O_CREATE|os.O_RDWR, perms)
if err != nil {
return err
}
rc, err := f.Open()
if err != nil {
return err
}
_, err = io.CopyN(out, rc, f.FileInfo().Size())
if err != nil {
return err
}
rc.Close()
out.Close()
mtime := f.FileInfo().ModTime()
err = os.Chtimes(fullname, mtime, mtime)
if err != nil {
return err
}
}
}
return
}
func UnzipList(path string) (list []string, err error) {
r, err := zip.OpenReader(path)
if err != nil {
return
}
for _, f := range r.File {
list = append(list, f.Name)
}
return
}
// Update protocol:
//
// GET hk.heroku.com/hk/linux-amd64.json
//
// 200 ok
// {
// "Version": "2",
// "Sha256": "..." // base64
// }
//
// then
//
// GET hkpatch.s3.amazonaws.com/hk/1/2/linux-amd64
//
// 200 ok
// [bsdiff data]
//
// or
//
// GET hkdist.s3.amazonaws.com/hk/2/linux-amd64.gz
//
// 200 ok
// [gzipped executable data]
//
//
const (
plat = runtime.GOOS + "-" + runtime.GOARCH
)
const devValidTime = 7 * 24 * time.Hour
var ErrHashMismatch = errors.New("new file hash mismatch after patch")
var up = update.New()
// Updater is the configuration and runtime data for doing an update.
//
// Note that ApiURL, BinURL and DiffURL should have the same value if all files are available at the same location.
//
// Example:
//
// updater := &selfupdate.Updater{
// CurrentVersion: version,
// ApiURL: "http://updates.yourdomain.com/",
// BinURL: "http://updates.yourdownmain.com/",
// DiffURL: "http://updates.yourdomain.com/",
// Dir: "update/",
// CmdName: "myapp", // app name
// }
// if updater != nil {
// go updater.BackgroundRun()
// }
type Updater struct {
CurrentVersion string // Currently running version.
ApiURL string // Base URL for API requests (json files).
CmdName string // Command name is appended to the ApiURL like http://apiurl/CmdName/. This represents one binary.
BinURL string // Base URL for full binary downloads.
DiffURL string // Base URL for diff downloads.
Dir string // Directory to store selfupdate state.
Info struct {
Version string
Sha256 []byte
}
}
func (u *Updater) getExecRelativeDir(dir string) string {
filename, _ := osext.Executable()
path := filepath.Join(filepath.Dir(filename), dir)
return path
}
// BackgroundRun starts the update check and apply cycle.
func (u *Updater) BackgroundRun() error {
os.MkdirAll(u.getExecRelativeDir(u.Dir), 0777)
if u.wantUpdate() {
if err := up.CanUpdate(); err != nil {
// fail
return err
}
//self, err := osext.Executable()
//if err != nil {
// fail update, couldn't figure out path to self
//return
//}
// TODO(bgentry): logger isn't on Windows. Replace w/ proper error reports.
if err := u.update(); err != nil {
return err
}
}
return nil
}
func (u *Updater) wantUpdate() bool {
if strings.Contains(u.CurrentVersion, "dev") {
return false
} else {
return true
}
}
func (u *Updater) update() error {
path, err := osext.Executable()
if err != nil {
return err
}
old, err := os.Open(path)
if err != nil {
return err
}
defer old.Close()
err = u.fetchInfo()
if err != nil {
return err
}
if u.Info.Version == u.CurrentVersion {
return nil
}
bin, err := u.fetchAndVerifyPatch(old)
if err != nil {
if err == ErrHashMismatch {
log.Println("update: hash mismatch from patched binary")
} else {
if u.DiffURL != "" {
log.Println("update: patching binary,", err)
}
}
bin, err = u.fetchAndVerifyFullBin()
if err != nil {
if err == ErrHashMismatch {
log.Println("update: hash mismatch from full binary")
} else {
log.Println("update: fetching full binary,", err)
}
return err
}
}
// close the old binary before installing because on windows
// it can't be renamed if a handle to the file is still open
old.Close()
err, errRecover := up.FromStream(bytes.NewBuffer(bin))
if errRecover != nil {
return fmt.Errorf("update and recovery errors: %q %q", err, errRecover)
}
if err != nil {
return err
}
// remove config.ini so at restart the package will extract again
shutil.CopyFile(*configIni, *configIni+".bak", false)
os.Remove(*configIni)
// update done, we should decide if we need to restart ASAP (maybe a field in update json?)
// BIG issue: the file has been renamed in the meantime
return nil
}
func (u *Updater) fetchInfo() error {
r, err := fetch(u.ApiURL + u.CmdName + "/" + plat + ".json")
if err != nil {
return err
}
defer r.Close()
err = json.NewDecoder(r).Decode(&u.Info)
if err != nil {
return err
}
if len(u.Info.Sha256) != sha256.Size {
return errors.New("bad cmd hash in info")
}
return nil
}
func (u *Updater) fetchAndVerifyPatch(old io.Reader) ([]byte, error) {
bin, err := u.fetchAndApplyPatch(old)
if err != nil {
return nil, err
}
if !verifySha(bin, u.Info.Sha256) {
return nil, ErrHashMismatch
}
return bin, nil
}
func (u *Updater) fetchAndApplyPatch(old io.Reader) ([]byte, error) {
r, err := fetch(u.DiffURL + u.CmdName + "/" + u.CurrentVersion + "/" + u.Info.Version + "/" + plat)
if err != nil {
return nil, err
}
defer r.Close()
var buf bytes.Buffer
err = binarydist.Patch(old, &buf, r)
return buf.Bytes(), err
}
func (u *Updater) fetchAndVerifyFullBin() ([]byte, error) {
bin, err := u.fetchBin()
if err != nil {
return nil, err
}
verified := verifySha(bin, u.Info.Sha256)
if !verified {
return nil, ErrHashMismatch
}
return bin, nil
}
func (u *Updater) fetchBin() ([]byte, error) {
r, err := fetch(u.BinURL + u.CmdName + "/" + u.Info.Version + "/" + plat + ".gz")
if err != nil {
return nil, err
}
defer r.Close()
buf := new(bytes.Buffer)
gz, err := gzip.NewReader(r)
if err != nil {
return nil, err
}
if _, err = io.Copy(buf, gz); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// returns a random duration in [0,n).
func randDuration(n time.Duration) time.Duration {
return time.Duration(rand.Int63n(int64(n)))
}
func fetch(url string) (io.ReadCloser, error) {
resp, err := http.Get(url)
if err != nil {
return nil, err
}
if resp.StatusCode != 200 {
return nil, fmt.Errorf("bad http status from %s: %v", url, resp.Status)
}
return resp.Body, nil
}
func readTime(path string) time.Time {
p, err := ioutil.ReadFile(path)
if os.IsNotExist(err) {
return time.Time{}
}
if err != nil {
return time.Now().Add(1000 * time.Hour)
}
t, err := time.Parse(time.RFC3339, string(p))
if err != nil {
return time.Now().Add(1000 * time.Hour)
}
return t
}
func verifySha(bin []byte, sha []byte) bool {
h := sha256.New()
h.Write(bin)
return bytes.Equal(h.Sum(nil), sha)
}
func writeTime(path string, t time.Time) bool {
return ioutil.WriteFile(path, []byte(t.Format(time.RFC3339)), 0644) == nil
}