/
helpers.go
429 lines (376 loc) · 11.4 KB
/
helpers.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
// Copyright © 2017 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package helpers
import (
"archive/tar"
"bytes"
"compress/gzip"
"context"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"io"
"io/ioutil"
"log"
"math/big"
"net/http"
"os"
"os/exec"
"path/filepath"
"sort"
"strings"
"time"
"github.com/pkg/errors"
)
// CreateCertTemplate will construct the template for needed openssl metadata
// instead of using an attributes.cnf file
func CreateCertTemplate() *x509.Certificate {
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialnumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
log.Println(errors.Wrap(err, "ERROR: Failed to generate serial number"))
}
template := x509.Certificate{
SerialNumber: serialnumber,
Subject: pkix.Name{Organization: []string{"Mixer"}},
SignatureAlgorithm: x509.SHA256WithRSA,
NotBefore: time.Now(),
NotAfter: time.Now().AddDate(1, 0, 0),
BasicConstraintsValid: true,
IsCA: false, // This could be true since we are self signed, but set false for correctness
KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature | x509.KeyUsageCRLSign,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageCodeSigning},
}
return &template
}
// CreateKeyPair constructs an RSA keypair in memory
func CreateKeyPair() (*rsa.PrivateKey, error) {
rootKey, err := rsa.GenerateKey(rand.Reader, 4096)
if err != nil {
log.Println(errors.Wrap(err, "ERROR: Failed to generate random key"))
}
return rootKey, nil
}
// GenerateCertificate will create the private signing key and public
// certificate for clients to use and writes them to disk
func GenerateCertificate(cert string, template, parent *x509.Certificate, pubkey interface{}, privkey interface{}) error {
if _, err := os.Stat(cert); os.IsNotExist(err) {
der, err := x509.CreateCertificate(rand.Reader, template, parent, pubkey, privkey)
if err != nil {
return err
}
// Write the public certficiate out for clients to use
certOut, err := os.Create(cert)
if err != nil {
return err
}
err = pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: der})
if err != nil {
return err
}
err = certOut.Close()
if err != nil {
return err
}
// Write the private signing key out
keyOut, err := os.OpenFile(filepath.Dir(cert)+"/private.pem", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return err
}
defer func() {
_ = keyOut.Close()
}()
// Need type assertion for Marshal to work
priv := privkey.(*rsa.PrivateKey)
err = pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)})
if err != nil {
return err
}
}
return nil
}
// ReadFileAndSplit tokenizes the given file and converts in into a slice split
// by the newline character.
func ReadFileAndSplit(filename string) ([]string, error) {
builder, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
data := string(builder)
lines := strings.Split(data, "\n")
return lines, nil
}
// UnpackFile unpacks a .tar or .tar.gz/.tgz file to a given directory.
// Should be roughly equivalent to "tar -x[z]f file -C dest". Does not
// overwrite; returns error if file being unpacked already exists.
func UnpackFile(file string, dest string) error {
fr, err := os.Open(file)
if err != nil {
return err
}
defer func() {
_ = fr.Close()
}()
var tr *tar.Reader
// If it's a compressed tarball
if strings.HasSuffix(file, ".tar.gz") || strings.HasSuffix(file, ".tgz") {
gzr, err := gzip.NewReader(fr)
if err != nil {
return errors.Wrapf(err, "Error decompressing tarball: %s", file)
}
defer func() {
_ = gzr.Close()
}()
tr = tar.NewReader(gzr)
} else {
tr = tar.NewReader(fr)
}
for {
hdr, err := tr.Next()
if err == io.EOF {
// end of archive
break
} else if err != nil {
return errors.Wrapf(err, "Error reading contents of tarball: %s", file)
}
out := filepath.Join(dest, hdr.Name)
switch hdr.Typeflag {
// Skip GitHub generated "extended header" file
case tar.TypeXGlobalHeader:
continue
case tar.TypeDir:
if err = os.MkdirAll(out, os.FileMode(hdr.Mode)); err != nil {
return errors.Wrapf(err, "Error unpacking directory: %s", out)
}
case tar.TypeReg:
of, err := os.OpenFile(out, os.O_CREATE|os.O_RDWR|os.O_EXCL, os.FileMode(hdr.Mode))
if err != nil {
return errors.Wrapf(err, "Error unpacking file: %s", out)
}
_, err = io.Copy(of, tr)
_ = of.Close()
if err != nil {
return errors.Wrapf(err, "Error unpacking file: %s", out)
}
default:
return errors.Errorf("Error unpacking file: %s", out)
}
}
return nil
}
// CopyFile copies a file, overwriting the destination if it exists.
func CopyFile(dest string, src string) error {
return copyFileWithFlags(dest, src, os.O_RDWR|os.O_CREATE|os.O_TRUNC)
}
// CopyFileNoOverwrite copies a file only if the destination file does not exist.
func CopyFileNoOverwrite(dest string, src string) error {
return copyFileWithFlags(dest, src, os.O_RDWR|os.O_CREATE|os.O_EXCL)
}
// copyFileWithFlags General purpose copy file function
func copyFileWithFlags(dest string, src string, flags int) error {
source, err := os.Open(src)
if err != nil {
return err
}
defer func() {
_ = source.Close()
}()
destination, err := os.OpenFile(dest, flags, 0666)
if err != nil {
return err
}
defer func() {
_ = destination.Close()
}()
_, err = io.Copy(destination, source)
if err != nil {
return err
}
err = destination.Sync()
if err != nil {
return err
}
return nil
}
// Git runs git with arguments and returns in case of failure.
// IMPORTANT: the 'args' passed to this function _must_ be validated,
// as to avoid cases where input is received from a third party source.
// Such inputs could be something the likes of 'status; rm -rf .*'
// and need to be escaped or avoided properly.
func Git(args ...string) error {
cmd := exec.Command("git", args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err := cmd.Run()
if err != nil {
return errors.Wrapf(err, "ERROR: failed to run: git %s", strings.Join(args, " "))
}
return nil
}
// RunCommand runs the given command with args and prints output
func RunCommand(cmdname string, args ...string) error {
return RunCommandInput(nil, cmdname, args...)
}
// RunCommandInput runs the given command with args and input from an io.Reader,
// and prints output
func RunCommandInput(in io.Reader, cmdname string, args ...string) error {
cmd := exec.Command(cmdname, args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = in
err := cmd.Run()
if err != nil {
return errors.Wrapf(err, "failed to execute %s", strings.Join(cmd.Args, " "))
}
return nil
}
// RunCommandSilent runs the given command with args and does not print output
func RunCommandSilent(cmdname string, args ...string) error {
_, err := RunCommandOutput(cmdname, args...)
return err
}
// RunCommandTimeout runs the given command with timeout + args and does not print command output
func RunCommandTimeout(timeout int, cmdname string, args ...string) error {
ctx := context.Background()
// 0 means infinite timeout, ONLY set timeouts when value is > 0
if timeout > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second)
defer cancel()
}
cmd := exec.CommandContext(ctx, cmdname, args...)
cmd.Stdout = nil
cmd.Stderr = nil
err := cmd.Run()
if ctx.Err() == context.DeadlineExceeded {
return errors.Errorf("Command: %s timed out\n", cmdname)
}
return err
}
// RunCommandOutput executes the command with arguments and stores its output in
// memory. If the command succeeds returns that output, if it fails, return err that
// contains both the out and err streams from the execution.
func RunCommandOutput(cmdname string, args ...string) (*bytes.Buffer, error) {
return RunCommandOutputEnv(cmdname, args, []string{})
}
// RunCommandOutputEnv executes the command with arguments and environment and stores
// its output in memory. If the command succeeds returns that output, if it fails,
// return err that contains both the out and err streams from the execution.
func RunCommandOutputEnv(cmdname string, args []string, envs []string) (*bytes.Buffer, error) {
cmd := exec.Command(cmdname, args...)
var outBuf bytes.Buffer
var errBuf bytes.Buffer
cmd.Stdout = &outBuf
cmd.Stderr = &errBuf
cmd.Env = append(os.Environ(), envs...)
runError := cmd.Run()
if runError != nil {
var buf bytes.Buffer
logger := log.New(&buf, "", log.Ldate|log.Ltime)
logger.Printf("failed to execute %s", strings.Join(cmd.Args, " "))
if outBuf.Len() > 0 {
logger.Printf("\nSTDOUT:\n%s", outBuf.Bytes())
}
if errBuf.Len() > 0 {
logger.Printf("\nSTDERR:\n%s", errBuf.Bytes())
}
if outBuf.Len() > 0 || errBuf.Len() > 0 {
// Finish without a newline to wrap well with the err.
logger.Printf("failed to execute")
}
return &outBuf, errors.Wrap(runError, buf.String())
}
return &outBuf, nil
}
// ListVisibleFiles reads the directory named by dirname and returns a sorted list
// of names
func ListVisibleFiles(dirname string) ([]string, error) {
f, err := os.Open(dirname)
if err != nil {
return nil, err
}
list, err := f.Readdirnames(-1)
_ = f.Close()
if err != nil && err != io.EOF {
return nil, err
}
filtered := make([]string, 0, len(list))
for i := range list {
if list[i][0] != '.' {
filtered = append(filtered, list[i])
}
}
sort.Strings(filtered)
return filtered, nil
}
func getDownloadFileReader(url string) (*io.ReadCloser, error) {
resp, err := http.Get(url)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("got status %q when downloading: %s", resp.Status, url)
}
return &resp.Body, nil
}
// DownloadFileAsString will download a file from the passed URL and return the
// result as a string.
func DownloadFileAsString(url string) (string, error) {
fr, err := getDownloadFileReader(url)
if err != nil {
return "", err
}
defer func() {
_ = (*fr).Close()
}()
content, err := ioutil.ReadAll(*fr)
if err != nil {
return "", err
}
return string(content), nil
}
// DownloadFile will download a file from the passed URL and write that file to
// the supplied file path. If the path is left empty, the file name will be
// inferred from the source and written to PWD.
func DownloadFile(url string, filePath string) error {
fr, err := getDownloadFileReader(url)
if err != nil {
return errors.Wrap(err, "Failed to download file")
}
defer func() {
_ = (*fr).Close()
}()
// If no filePath, infer from url
if filePath == "" {
_, filePath = filepath.Split(url)
}
out, err := os.Create(filePath)
if err != nil {
return err
}
defer func() {
_ = out.Close()
}()
_, err = io.Copy(out, *fr)
if err != nil {
if rmErr := os.RemoveAll(filePath); rmErr != nil {
return errors.Wrap(err, rmErr.Error())
}
return err
}
return nil
}