-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathsdk.go
330 lines (277 loc) · 8.38 KB
/
sdk.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
package equinox
import (
"bytes"
"crypto"
"crypto/sha256"
"crypto/x509"
"encoding/hex"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"runtime"
"time"
"github.com/equinox-io/equinox/internal/go-update"
"github.com/equinox-io/equinox/internal/osext"
"github.com/equinox-io/equinox/proto"
)
const protocolVersion = "1"
const defaultCheckURL = "https://update.equinox.io/check"
const userAgent = "EquinoxSDK/1.0"
var NotAvailableErr = errors.New("No update available")
type Options struct {
// Channel specifies the name of an Equinox release channel to check for
// a newer version of the application.
//
// If empty, defaults to 'stable'.
Channel string
// Version requests an update to a specific version of the application.
// If specified, `Channel` is ignored.
Version string
// TargetPath defines the path to the file to update.
// The emptry string means 'the executable file of the running program'.
TargetPath string
// Create TargetPath replacement with this file mode. If zero, defaults to 0755.
TargetMode os.FileMode
// Public key to use for signature verification. If nil, no signature
// verification is done. Use `SetPublicKeyPEM` to set this field with PEM data.
PublicKey crypto.PublicKey
// Target operating system of the update. Uses the same standard OS names used
// by Go build tags (windows, darwin, linux, etc).
// If empty, it will be populated by consulting runtime.GOOS
OS string
// Target architecture of the update. Uses the same standard Arch names used
// by Go build tags (amd64, 386, arm, etc).
// If empty, it will be populated by consulting runtime.GOARCH
Arch string
// Target ARM architecture, if a specific one if required. Uses the same names
// as the GOARM environment variable (5, 6, 7).
//
// GoARM is ignored if Arch != 'arm'.
// GoARM is ignored if it is the empty string. Omit it if you do not need
// to distinguish between ARM versions.
GoARM string
// The current application version. This is used for statistics and reporting only,
// it is optional.
CurrentVersion string
// CheckURL is the URL to request an update check from. You should only set
// this if you are running an on-prem Equinox server.
// If empty the default Equinox update service endpoint is used.
CheckURL string
// HTTPClient is used to make all HTTP requests necessary for the update check protocol.
// You may configure it to use custom timeouts, proxy servers or other behaviors.
HTTPClient *http.Client
}
// Response is returned by Check when an update is available. It may be
// passed to Apply to perform the update.
type Response struct {
// Version of the release that will be updated to if applied.
ReleaseVersion string
// Title of the the release
ReleaseTitle string
// Additional details about the release
ReleaseDescription string
// Creation date of the release
ReleaseDate time.Time
downloadURL string
checksum []byte
signature []byte
patch proto.PatchKind
opts Options
}
// SetPublicKeyPEM is a convenience method to set the PublicKey property
// used for checking a completed update's signature by parsing a
// Public Key formatted as PEM data.
func (o *Options) SetPublicKeyPEM(pembytes []byte) error {
block, _ := pem.Decode(pembytes)
if block == nil {
return errors.New("couldn't parse PEM data")
}
pub, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return err
}
o.PublicKey = pub
return nil
}
// Check communicates with an Equinox update service to determine if
// an update for the given application matching the specified options is
// available. The returned error is nil only if an update is available.
//
// The appID is issued to you when creating an application at https://equinox.io
//
// You can compare the returned error to NotAvailableErr to differentiate between
// a successful check that found no update from other errors like a failed
// network connection.
func Check(appID string, opts Options) (Response, error) {
var req, err = checkRequest(appID, &opts)
if err != nil {
return Response{}, err
}
return doCheckRequest(opts, req)
}
func checkRequest(appID string, opts *Options) (*http.Request, error) {
if opts.Channel == "" {
opts.Channel = "stable"
}
if opts.TargetPath == "" {
var err error
opts.TargetPath, err = osext.Executable()
if err != nil {
return nil, err
}
}
if opts.OS == "" {
opts.OS = runtime.GOOS
}
if opts.Arch == "" {
opts.Arch = runtime.GOARCH
}
if opts.CheckURL == "" {
opts.CheckURL = defaultCheckURL
}
if opts.HTTPClient == nil {
opts.HTTPClient = new(http.Client)
}
opts.HTTPClient.Transport = newUserAgentTransport(userAgent, opts.HTTPClient.Transport)
checksum := computeChecksum(opts.TargetPath)
payload, err := json.Marshal(proto.Request{
AppID: appID,
Channel: opts.Channel,
OS: opts.OS,
Arch: opts.Arch,
GoARM: opts.GoARM,
TargetVersion: opts.Version,
CurrentVersion: opts.CurrentVersion,
CurrentSHA256: checksum,
})
req, err := http.NewRequest("POST", opts.CheckURL, bytes.NewReader(payload))
if err != nil {
return nil, err
}
req.Header.Set("Accept", fmt.Sprintf("application/json; q=1; version=%s; charset=utf-8", protocolVersion))
req.Header.Set("Content-Type", "application/json; charset=utf-8")
req.Close = true
return req, err
}
func doCheckRequest(opts Options, req *http.Request) (r Response, err error) {
resp, err := opts.HTTPClient.Do(req)
if err != nil {
return r, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
body, _ := ioutil.ReadAll(resp.Body)
return r, fmt.Errorf("Server responded with %s: %s", resp.Status, body)
}
var protoResp proto.Response
err = json.NewDecoder(resp.Body).Decode(&protoResp)
if err != nil {
return r, err
}
if !protoResp.Available {
return r, NotAvailableErr
}
r.ReleaseVersion = protoResp.Release.Version
r.ReleaseTitle = protoResp.Release.Title
r.ReleaseDescription = protoResp.Release.Description
r.ReleaseDate = protoResp.Release.CreateDate
r.downloadURL = protoResp.DownloadURL
r.patch = protoResp.Patch
r.opts = opts
r.checksum, err = hex.DecodeString(protoResp.Checksum)
if err != nil {
return r, err
}
r.signature, err = hex.DecodeString(protoResp.Signature)
if err != nil {
return r, err
}
return r, nil
}
func computeChecksum(path string) string {
f, err := os.Open(path)
if err != nil {
return ""
}
defer f.Close()
h := sha256.New()
_, err = io.Copy(h, f)
if err != nil {
return ""
}
return hex.EncodeToString(h.Sum(nil))
}
// Apply performs an update of the current executable (or TargetFile, if it was
// set on the Options) with the update specified by Response.
//
// Error is nil if and only if the entire update completes successfully.
func (r Response) Apply() error {
var req, opts, err = r.applyRequest()
if err != nil {
return err
}
return r.applyUpdate(req, opts)
}
func (r Response) applyRequest() (*http.Request, update.Options, error) {
opts := update.Options{
TargetPath: r.opts.TargetPath,
TargetMode: r.opts.TargetMode,
Checksum: r.checksum,
Signature: r.signature,
Verifier: update.NewECDSAVerifier(),
PublicKey: r.opts.PublicKey,
}
switch r.patch {
case proto.PatchBSDiff:
opts.Patcher = update.NewBSDiffPatcher()
}
if err := opts.CheckPermissions(); err != nil {
return nil, opts, err
}
req, err := http.NewRequest("GET", r.downloadURL, nil)
return req, opts, err
}
func (r Response) applyUpdate(req *http.Request, opts update.Options) error {
// fetch the update
req.Close = true
resp, err := r.opts.HTTPClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
// check that we got a patch
if resp.StatusCode >= 400 {
msg := "error downloading patch"
id := resp.Header.Get("Request-Id")
if id != "" {
msg += ", request " + id
}
blob, err := ioutil.ReadAll(resp.Body)
if err == nil {
msg += ": " + string(bytes.TrimSpace(blob))
}
return fmt.Errorf(msg)
}
return update.Apply(resp.Body, opts)
}
type userAgentTransport struct {
userAgent string
http.RoundTripper
}
func newUserAgentTransport(userAgent string, rt http.RoundTripper) *userAgentTransport {
if rt == nil {
rt = http.DefaultTransport
}
return &userAgentTransport{userAgent, rt}
}
func (t *userAgentTransport) RoundTrip(r *http.Request) (*http.Response, error) {
if r.Header.Get("User-Agent") == "" {
r.Header.Set("User-Agent", t.userAgent)
}
return t.RoundTripper.RoundTrip(r)
}