-
Notifications
You must be signed in to change notification settings - Fork 25
/
keyring_darwin.go
70 lines (61 loc) · 1.51 KB
/
keyring_darwin.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
package keyring
import (
"fmt"
"os/exec"
"regexp"
"strconv"
"syscall"
)
type osxProvider struct {
}
var pwRe = regexp.MustCompile(`password:\s+(?:0x[A-Fa-f0-9]+\s+)?"(.+)"`)
var escapeCodeRegexp = regexp.MustCompile(`\\([0-3][0-7]{2})`)
func unescapeOne(code []byte) []byte {
i, _ := strconv.ParseUint(string(code[1:]), 8, 8)
return []byte{byte(i)}
}
func unescape(raw string) string {
if !escapeCodeRegexp.MatchString(raw) {
return raw
} else {
return string(escapeCodeRegexp.ReplaceAllFunc([]byte(raw), unescapeOne))
}
}
func (p osxProvider) Get(Service, Username string) (string, error) {
args := []string{"find-generic-password",
"-s", Service,
"-a", Username,
"-g"}
c := exec.Command("/usr/bin/security", args...)
o, err := c.CombinedOutput()
if err != nil {
exitCode := c.ProcessState.Sys().(syscall.WaitStatus).ExitStatus()
// check particular exit code
if exitCode == 44 {
return "", ErrNotFound
}
return "", fmt.Errorf("/usr/bin/security: %s", err)
}
matches := pwRe.FindStringSubmatch(string(o))
if len(matches) != 2 {
return "", ErrNotFound
}
return unescape(matches[1]), nil
}
func (p osxProvider) Set(Service, Username, Password string) error {
args := []string{"add-generic-password",
"-s", Service,
"-a", Username,
"-w", Password,
"-U"}
c := exec.Command("/usr/bin/security", args...)
err := c.Run()
if err != nil {
o, _ := c.CombinedOutput()
return fmt.Errorf(string(o))
}
return nil
}
func initializeProvider() (provider, error) {
return osxProvider{}, nil
}