-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathupdater.go
396 lines (365 loc) · 11.8 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
// Package updater implements updating the different parts of a running gokrazy
// installation (boot/root file systems and MBR).
package updater
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"hash"
"hash/crc32"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"strings"
)
// ErrUpdateHandlerNotImplemented is returned when the requested update
// destination is not yet implemented on the target device. Callers can
// programmatically distinguish this error to print an according message and
// possibly proceed with the update.
var ErrUpdateHandlerNotImplemented = errors.New("update handler not implemented")
// A HTTPDoer is satisfied by any *http.Client, but also easy to implement in
// case extra middleware is desired.
type HTTPDoer interface {
Do(*http.Request) (*http.Response, error)
}
// Target represents a gokrazy installation to be updated.
type Target struct {
doer HTTPDoer
baseURL string
supports []string
eeprom EEPROMVersion
}
// NewTarget queries the target for supported update protocol features and
// returns a ready-to-use updater Target.
func NewTarget(baseURL string, httpClient HTTPDoer) (*Target, error) {
target := &Target{
baseURL: baseURL,
doer: httpClient,
}
if err := target.requestFeatures(); err != nil {
return nil, err
}
return target, nil
}
// A ProtocolFeature represents an optionally available feature of the update
// protocol, i.e. features that might possibly be missing in older gokrazy
// installations.
type ProtocolFeature string
const (
// ProtocolFeaturePARTUUID signals that the target understands the PARTUUID=
// Linux kernel parameter and uses it in its cmdline.txt bootloader config,
// i.e. is ready to accept an update that is using PARTUUID, too.
ProtocolFeaturePARTUUID ProtocolFeature = "partuuid"
// ProtocolFeatureUpdateHash signals that the target understands the
// X-Gokrazy-Update-Hash HTTP header and at least the “crc32” value, which
// is significantly faster than SHA256, which is used by default.
ProtocolFeatureUpdateHash ProtocolFeature = "updatehash"
)
// Supports returns whether the target is known to support the specified update
// protocol feature.
func (t *Target) Supports(feature ProtocolFeature) bool {
for _, f := range t.supports {
if f == string(feature) {
return true
}
}
return false
}
// StreamTo streams from the specified io.Reader to the specified destination:
//
// - mbr: stream content directly onto the root block device
// - root: stream content to the currently inactive root partition
// - boot: stream content to the boot partition
//
// When updating only the boot partition and not also the root partition
// (e.g. in gokrazy’s Continuous Integration), the following suffix should be
// used:
//
// - bootonly: stream content to the boot partition, then update the boot
// partition so that the currently active root stays active.
//
// You can keep track of progress by passing in an io.TeeReader(r,
// &countingWriter{}).
func (t *Target) StreamTo(dest string, r io.Reader) error {
updateHash := t.Supports("updatehash")
var hash hash.Hash
if updateHash {
hash = crc32.NewIEEE()
} else {
hash = sha256.New()
}
req, err := http.NewRequest(http.MethodPut, t.baseURL+"update/"+dest, io.TeeReader(r, hash))
if err != nil {
return err
}
if updateHash {
req.Header.Set("X-Gokrazy-Update-Hash", "crc32")
}
resp, err := t.doer.Do(req)
if err != nil {
return err
}
if got, want := resp.StatusCode, http.StatusOK; got != want {
body, _ := ioutil.ReadAll(resp.Body)
return fmt.Errorf("unexpected HTTP status code: got %v, want %v (body %q)", resp.Status, want, string(body))
}
remoteHash, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
if bytes.HasPrefix(remoteHash, []byte("<!DOCTYPE html>")) {
return ErrUpdateHandlerNotImplemented
}
decoded := make([]byte, hex.DecodedLen(len(remoteHash)))
n, err := hex.Decode(decoded, remoteHash)
if err != nil {
return err
}
if got, want := decoded[:n], hash.Sum(nil); !bytes.Equal(got, want) {
return fmt.Errorf("unexpected checksum: got %x, want %x", got, want)
}
return nil
}
// Put streams a file to the specified HTTP endpoint, without verifying its
// hash. This is not suited for updating the system, which should be done via
// StreamTo() instead. This function is useful for the /uploadtemp/ handler.
func (t *Target) Put(dest string, r io.Reader) error {
req, err := http.NewRequest(http.MethodPut, t.baseURL+dest, r)
if err != nil {
return err
}
resp, err := t.doer.Do(req)
if err != nil {
return err
}
if got, want := resp.StatusCode, http.StatusOK; got != want {
if resp.StatusCode == http.StatusNotFound {
return fmt.Errorf("/uploadtemp/ handler not found, is your gokrazy installation too old?")
}
body, _ := ioutil.ReadAll(resp.Body)
return fmt.Errorf("unexpected HTTP status code: got %v, want %v (body %q)", resp.Status, want, strings.TrimSpace(string(body)))
}
return nil
}
// Switch changes the active root partition from the currently running root
// partition to the currently inactive root partition.
func (t *Target) Switch() error {
req, err := http.NewRequest("POST", t.baseURL+"update/switch", nil)
if err != nil {
return err
}
resp, err := t.doer.Do(req)
if err != nil {
return err
}
if got, want := resp.StatusCode, http.StatusOK; got != want {
body, _ := ioutil.ReadAll(resp.Body)
return fmt.Errorf("unexpected HTTP status code: got %d, want %d (body %q)", got, want, string(body))
}
return nil
}
// Testboot marks the inactive root partition to be tested upon the next boot,
// and made active if the test boot succeeds.
func (t *Target) Testboot() error {
req, err := http.NewRequest("POST", t.baseURL+"update/testboot", nil)
if err != nil {
return err
}
resp, err := t.doer.Do(req)
if err != nil {
return err
}
if got, want := resp.StatusCode, http.StatusOK; got != want {
body, _ := ioutil.ReadAll(resp.Body)
return fmt.Errorf("unexpected HTTP status code: got %d, want %d (body %q)", got, want, string(body))
}
return nil
}
// Reboot reboots the target, picking up the updated partitions.
func (t *Target) Reboot() error {
req, err := http.NewRequest("POST", t.baseURL+"reboot", nil)
if err != nil {
return err
}
resp, err := t.doer.Do(req)
if err != nil {
return err
}
if got, want := resp.StatusCode, http.StatusOK; got != want {
body, _ := ioutil.ReadAll(resp.Body)
return fmt.Errorf("unexpected HTTP status code: got %d, want %d (body %q)", got, want, string(body))
}
return nil
}
// RebootWithoutKexec reboots the target without kexec, picking up the updated
// partitions. This is useful for continuous integration testing to ensure the
// bootloader is tested.
func (t *Target) RebootWithoutKexec() error {
req, err := http.NewRequest("POST", t.baseURL+"reboot?kexec=off", nil)
if err != nil {
return err
}
resp, err := t.doer.Do(req)
if err != nil {
return err
}
if got, want := resp.StatusCode, http.StatusOK; got != want {
body, _ := ioutil.ReadAll(resp.Body)
return fmt.Errorf("unexpected HTTP status code: got %d, want %d (body %q)", got, want, string(body))
}
return nil
}
// Divert makes gokrazy use the temporary binary (diversion) instead of
// /user/<basename>. Includes an automatic service restart.
func (t *Target) Divert(path, diversion string, serviceFlags, commandLineFlags []string) error {
u, err := url.Parse(t.baseURL + "divert")
if err != nil {
return err
}
body, err := json.Marshal(struct {
Path string
Diversion string
Flags []string
}{
Path: path,
Diversion: diversion,
Flags: append(serviceFlags, commandLineFlags...),
})
if err != nil {
return err
}
req, err := http.NewRequest("POST", u.String(), bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
if err != nil {
return err
}
var resp *http.Response
resp, err = t.doer.Do(req)
if err != nil {
return err
}
if resp.StatusCode == http.StatusBadRequest {
// A BadRequest could indicate that the server is running an older
// version of gokrazy which took diversion options as query
// parameters. Try this approach before giving up.
if len(commandLineFlags) > 0 {
return fmt.Errorf("running version of gokrazy does not support command line arguments; try upgrading")
}
values := u.Query()
values.Set("path", path)
values.Set("diversion", diversion)
u.RawQuery = values.Encode()
req, err := http.NewRequest("POST", u.String(), nil)
if err != nil {
return err
}
resp, err = t.doer.Do(req)
if err != nil {
return err
}
}
if got, want := resp.StatusCode, http.StatusOK; got != want {
body, _ := ioutil.ReadAll(resp.Body)
return fmt.Errorf("unexpected HTTP status code: got %d, want %d (body %q)", got, want, strings.TrimSpace(string(body)))
}
return nil
}
// InstalledEEPROM returns the Raspberry Pi EEPROM version currently installed
// on the target device.
func (t *Target) InstalledEEPROM() EEPROMVersion {
return t.eeprom
}
func (t *Target) requestFeatures() error {
req, err := http.NewRequest("GET", t.baseURL+"update/features", nil)
if err != nil {
return err
}
resp, err := t.doer.Do(req)
if err != nil {
return err
}
if resp.StatusCode == http.StatusNotFound {
// Target device does not support /features handler yet, so no features
// are supported.
return nil
}
if got, want := resp.StatusCode, http.StatusOK; got != want {
body, _ := ioutil.ReadAll(resp.Body)
return fmt.Errorf("unexpected HTTP status code: got %d, want %d (body %q)", got, want, string(body))
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
if strings.HasPrefix(resp.Header.Get("Content-Type"), "text/plain") {
// Target replied with a text/plain response (old behavior).
// Fall back to fetching the EEPROM version with a separate request.
er, err := t.getEEPROMFromStatus()
if err != nil {
log.Printf("could not get EEPROM version: %v", err)
er = &EEPROMVersion{}
}
t.supports = strings.Split(strings.TrimSpace(string(body)), ",")
t.eeprom = *er
return nil
}
// Target replied with a JSON response, including the EEPROM version.
var featuresResp struct {
Features string `json:"features"`
EEPROM EEPROMVersion `json:"EEPROM"`
}
if err := json.Unmarshal(body, &featuresResp); err != nil {
return err
}
t.supports = strings.Split(strings.TrimSpace(featuresResp.Features), ",")
t.eeprom = featuresResp.EEPROM
return nil
}
const jsonMIME = "application/json"
// EEPROMVersion contains the signatures of a set of Raspberry Pi EEPROM files
// (pieeprom.sig and vl805.sig). The signatures are sha256 sums (hexadecimal),
// but you should treat them as opaque strings and only compare them.
type EEPROMVersion struct {
PieepromSHA256 string // pieeprom.sig
VL805SHA256 string // vl805.sig
}
func (t *Target) getEEPROMFromStatus() (*EEPROMVersion, error) {
req, err := http.NewRequest("GET", t.baseURL, nil)
if err != nil {
return nil, err
}
// See
// https://github.com/gokrazy/gokrazy/commit/d7743d90caf04e03c1d51b2d2e4a6d6984026228
// for why send the Content-Type header.
//
// TODO(after 2024): remove Content-Type, send only Accept
req.Header.Set("Content-Type", jsonMIME)
req.Header.Set("Accept", jsonMIME)
resp, err := t.doer.Do(req)
if err != nil {
return nil, err
}
if got, want := resp.StatusCode, http.StatusOK; got != want {
body, _ := ioutil.ReadAll(resp.Body)
return nil, fmt.Errorf("unexpected HTTP status code: got %d, want %d (body %q)", got, want, strings.TrimSpace(string(body)))
}
if got, want := resp.Header.Get("Content-Type"), jsonMIME; got != want {
return nil, fmt.Errorf("unexpected Content-Type: got %q, want %q", got, want)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var er struct {
EEPROM EEPROMVersion `json:"EEPROM"`
}
if err := json.Unmarshal(body, &er); err != nil {
return nil, fmt.Errorf("decoding response: %v", err)
}
return &er.EEPROM, nil
}