forked from keybase/client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
393 lines (345 loc) · 8.42 KB
/
util.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
// Copyright 2015 Keybase, Inc. All rights reserved. Use of
// this source code is governed by the included BSD license.
package libkb
import (
"bufio"
"bytes"
"crypto/hmac"
"crypto/rand"
"encoding/base32"
"encoding/hex"
"fmt"
"github.com/keybase/client/go/logger"
keybase1 "github.com/keybase/client/go/protocol"
"io"
"math"
"math/big"
"os"
"path/filepath"
"regexp"
"strings"
"time"
"unicode"
)
func ErrToOk(err error) string {
if err == nil {
return "ok"
}
return "ERROR: " + err.Error()
}
// exists returns whether the given file or directory exists or not
func FileExists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
func MakeParentDirs(filename string) error {
dir, _ := filepath.Split(filename)
exists, err := FileExists(dir)
if err != nil {
G.Log.Errorf("Can't see if parent dir %s exists", dir)
return err
}
if !exists {
err = os.MkdirAll(dir, PermDir)
if err != nil {
G.Log.Errorf("Can't make parent dir %s", dir)
return err
}
G.Log.Debug("Created parent directory %s", dir)
}
return nil
}
func FastByteArrayEq(a, b []byte) bool {
return bytes.Equal(a, b)
}
func SecureByteArrayEq(a, b []byte) bool {
return hmac.Equal(a, b)
}
func FormatTime(tm time.Time) string {
layout := "2006-01-02 15:04:05 MST"
return tm.Format(layout)
}
func Cicmp(s1, s2 string) bool {
return strings.ToLower(s1) == strings.ToLower(s2)
}
func TrimCicmp(s1, s2 string) bool {
return Cicmp(strings.TrimSpace(s1), strings.TrimSpace(s2))
}
func NameTrim(s string) string {
s = strings.ToLower(strings.TrimSpace(s))
strip := func(r rune) rune {
switch {
case r == '_', r == '-', r == '+', r == '\'':
return -1
case unicode.IsSpace(r):
return -1
}
return r
}
return strings.Map(strip, s)
}
// NameCmp removes whitespace and underscores, compares tolower.
func NameCmp(n1, n2 string) bool {
return NameTrim(n1) == NameTrim(n2)
}
func PickFirstError(errors ...error) error {
for _, e := range errors {
if e != nil {
return e
}
}
return nil
}
type FirstErrorPicker struct {
e error
}
func (p *FirstErrorPicker) Push(e error) {
if e != nil && p.e == nil {
p.e = e
}
}
func (p *FirstErrorPicker) Error() error {
return p.e
}
func GiveMeAnS(i int) string {
if i != 1 {
return "s"
}
return ""
}
func KeybaseEmailAddress(s string) string {
return s + "@keybase.io"
}
func DrainPipe(rc io.Reader, sink func(string)) error {
scanner := bufio.NewScanner(rc)
for scanner.Scan() {
sink(scanner.Text())
}
return scanner.Err()
}
type SafeWriter interface {
GetFilename() string
WriteTo(io.Writer) (int64, error)
}
// SafeWriteToFile to safely write to a file. Use mode=0 for default permissions.
func SafeWriteToFile(t SafeWriter, mode os.FileMode) error {
fn := t.GetFilename()
G.Log.Debug(fmt.Sprintf("+ Writing to %s", fn))
tmpfn, tmp, err := TempFile(fn, mode)
G.Log.Debug(fmt.Sprintf("| Temporary file generated: %s", tmpfn))
if err != nil {
return err
}
_, err = t.WriteTo(tmp)
if err == nil {
err = tmp.Close()
if err == nil {
err = os.Rename(tmpfn, fn)
} else {
G.Log.Error(fmt.Sprintf("Error closing temporary file %s: %s", tmpfn, err))
os.Remove(tmpfn)
}
} else {
G.Log.Error(fmt.Sprintf("Error writing temporary file %s: %s", tmpfn, err))
tmp.Close()
os.Remove(tmpfn)
}
G.Log.Debug(fmt.Sprintf("- Wrote to %s -> %s", fn, ErrToOk(err)))
return err
}
// Pluralize returns pluralized string with value.
// For example,
// Pluralize(1, "zebra", "zebras", true) => "1 zebra"
// Pluralize(2, "zebra", "zebras", true) => "2 zebras"
// Pluralize(2, "zebra", "zebras", false) => "zebras"
func Pluralize(n int, singular string, plural string, nshow bool) string {
if n == 1 {
if nshow {
return fmt.Sprintf("%d %s", n, singular)
}
return singular
}
if nshow {
return fmt.Sprintf("%d %s", n, plural)
}
return plural
}
// IsIn checks for needle in haystack, ci means case-insensitive.
func IsIn(needle string, haystack []string, ci bool) bool {
for _, h := range haystack {
if (ci && Cicmp(h, needle)) || (!ci && h == needle) {
return true
}
}
return false
}
func IsValidHostname(s string) bool {
parts := strings.Split(s, ".")
// Found regex here: http://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address
rxx := regexp.MustCompile("^(?i:[a-z0-9]|[a-z0-9][a-z0-9-]*[a-z0-9])$")
if len(parts) < 2 {
return false
}
for _, p := range parts {
if !rxx.MatchString(p) {
return false
}
}
// TLDs must be >=2 chars
if len(parts[len(parts)-1]) < 2 {
return false
}
return true
}
func RandBytes(length int) ([]byte, error) {
buf := make([]byte, length)
if _, err := rand.Read(buf); err != nil {
return nil, err
}
return buf, nil
}
func XORBytes(dst, a, b []byte) int {
n := len(a)
if len(b) < n {
n = len(b)
}
for i := 0; i < n; i++ {
dst[i] = a[i] ^ b[i]
}
return n
}
// The standard time.Unix() converter interprets 0 as the Unix epoch (1970).
// But in PGP, an expiry time of zero indicates that a key never expires, and
// it would be nice to be able to check for that case with Time.IsZero(). This
// conversion special-cases 0 to be time.Time's zero-value (1 AD), so that we
// get that nice property.
func UnixToTimeMappingZero(unixTime int64) time.Time {
if unixTime == 0 {
var zeroTime time.Time
return zeroTime
}
return time.Unix(unixTime, 0)
}
func Unquote(data []byte) string { return keybase1.Unquote(data) }
func HexDecodeQuoted(data []byte) ([]byte, error) {
return hex.DecodeString(Unquote(data))
}
func IsArmored(buf []byte) bool {
return bytes.HasPrefix(bytes.TrimSpace(buf), []byte("-----"))
}
var clearStart = []byte("-----BEGIN PGP SIGNED MESSAGE-----")
func IsClearsign(p *Peeker) bool {
// there should be a newline at the start, so add 1 to length.
// (but this will accept a message without the newline)
start := make([]byte, len(clearStart)+1)
_, err := p.Peek(start)
if err != nil {
return false
}
return bytes.HasPrefix(bytes.TrimSpace(start), clearStart)
}
func PGPDetect(p *Peeker) (armored, clearsign bool) {
start := make([]byte, len(clearStart)+1)
_, err := p.Peek(start)
if err != nil {
return
}
clearsign = bytes.HasPrefix(bytes.TrimSpace(start), clearStart)
armored = IsArmored(start)
return
}
func RandInt64() (int64, error) {
max := big.NewInt(math.MaxInt64)
x, err := rand.Int(rand.Reader, max)
if err != nil {
return 0, err
}
return x.Int64(), nil
}
func RandInt() (int, error) {
x, err := RandInt64()
if err != nil {
return 0, err
}
return int(x), nil
}
func RandIntn(n int) int {
x, err := RandInt()
if err != nil {
G.Log.Warning("RandInt error: %s", err)
return 0
}
return x % n
}
// OpenLogFile opens the standard Keybase logfile, and returns its
// name, its File object, or an Error if it didn't work out.
func OpenLogFile() (name string, file *os.File, err error) {
name = G.Env.GetLogFile()
return logger.OpenLogFile(name)
}
// MakeURI makes a URI string out of the given protocol and
// host strings, adding necessary punctuation in between.
func MakeURI(prot string, host string) string {
if prot == "" {
return host
}
if prot[len(prot)-1] != ':' {
prot += ":"
}
return prot + "//" + host
}
// RemoveNilErrors returns error slice with ni errors removed.
func RemoveNilErrors(errs []error) []error {
var r []error
for _, err := range errs {
if err != nil {
r = append(r, err)
}
}
return r
}
// CombineErrors returns a single error for multiple errors, or nil if none.
func CombineErrors(errs ...error) error {
errs = RemoveNilErrors(errs)
if len(errs) == 0 {
return nil
} else if len(errs) == 1 {
return errs[0]
}
msgs := []string{}
for _, err := range errs {
msgs = append(msgs, err.Error())
}
return fmt.Errorf("There were multiple errors: %s", strings.Join(msgs, "; "))
}
// IsDirEmpty returns whether directory has any files.
func IsDirEmpty(dir string) (bool, error) {
f, err := os.Open(dir)
if err != nil {
return false, err
}
defer f.Close()
_, err = f.Readdir(1)
if err == io.EOF {
return true, nil
}
return false, err // Either not empty or error, suits both cases
}
// RandString returns random (base32) string with prefix.
func RandString(prefix string, numbytes int) (string, error) {
buf, err := RandBytes(numbytes)
if err != nil {
return "", err
}
str := base32.StdEncoding.EncodeToString(buf)
if prefix != "" {
str = strings.Join([]string{prefix, str}, "")
}
return str, nil
}