-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlib.go
More file actions
212 lines (185 loc) · 4.81 KB
/
lib.go
File metadata and controls
212 lines (185 loc) · 4.81 KB
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
package truststore
import (
"errors"
"fmt"
"log"
"net"
"net/mail"
"net/url"
"os"
"regexp"
"golang.org/x/net/idna"
)
var hostnameRegexp = regexp.MustCompile(`(?i)^(\*\.)?[0-9a-z_-]([0-9a-z._-]*[0-9a-z_-])?$`)
// Print controls whether or not log messages should be printed.
//
// As `mkcert` is originally a cli-based tool, there are verbose print
// statements littered throughout. For library usage, we want to silence them
// by default, but it may be useful to re-enable under some conditions.
var Print = false
type MkcertLib struct {
m *mkcert
}
type Cert struct {
CertFile string
KeyFile string
}
// Exists returns true if both the CertFile and KeyFile exist
func (c Cert) Exists() bool {
if c.CertFile == "" || c.KeyFile == "" {
return false
}
return exists(c.CertFile) && exists(c.KeyFile)
}
// GetCAROOT returns the computed CAROOT path. See `getCAROOT` for search order.
func GetCAROOT() string {
return getCAROOT()
}
// NewLib initializes a new instance of MkcertLib. It will automatically
// initialize a new CA, as needed, however it will *not* install it in the
// system.
//
// Since output is silenced by default, in order to troubleshoot errors while
// creating a new CA or loading an existing one, it may be useful to run twice
// if an error is returned, like so:
//
// ml, err := truststore.NewLib()
// if err != nil {
// truststore.Print = true
// truststore.NewLib()
// // handle err...
// }
func NewLib() (mlib *MkcertLib, err error) {
ml := &MkcertLib{
m: &mkcert{
CAROOT: GetCAROOT(),
},
}
err = trap(func() {
ml.m.loadCA()
})
if err != nil {
return nil, err
}
return ml, nil
}
// CertFile generates the output filenames for the given host(s)
func (ml *MkcertLib) CertFile(hosts []string, targetOutputPath string) (cert Cert, err error) {
err = validateHosts(hosts)
if err != nil {
return Cert{}, err
}
certFile, keyFile, _ := ml.m.fileNames(hosts, targetOutputPath)
cert = Cert{certFile, keyFile}
return cert, nil
}
// MakeCert with the given host names.
//
// All names must be valid hostnames or IP addresses. See `validateHosts`.
//
// *NOTE* A single cert will be created which is valid for all given hosts. To
// create multiple files, call this method once per host.
func (ml *MkcertLib) MakeCert(hosts []string, targetOutputPath string) (cert Cert, err error) {
cert, err = ml.CertFile(hosts, targetOutputPath)
if err != nil {
return
}
err = trap(func() {
ml.m.makeCert(hosts, targetOutputPath)
})
if err != nil {
return Cert{}, err
}
return
}
// Install the CA into the system trust stores
func (ml *MkcertLib) Install() (err error) {
err = trap(func() {
ml.m.install()
})
cleanupCertutil()
return
}
// Uninstall the CA from the system trust stores
func (ml *MkcertLib) Uninstall() (err error) {
err = trap(func() {
ml.m.uninstall()
})
cleanupCertutil()
return
}
// validateHosts method extracted from cli program's `run` method.
func validateHosts(hosts []string) error {
for i, name := range hosts {
if ip := net.ParseIP(name); ip != nil {
continue
}
if email, err := mail.ParseAddress(name); err == nil && email.Address == name {
continue
}
if uriName, err := url.Parse(name); err == nil && uriName.Scheme != "" && uriName.Host != "" {
continue
}
punycode, err := idna.ToASCII(name)
if err != nil {
return fmt.Errorf("ERROR: %q is not a valid hostname, IP, URL or email: %s", name, err)
}
hosts[i] = punycode
if !hostnameRegexp.MatchString(punycode) {
return fmt.Errorf("ERROR: %q is not a valid hostname, IP, URL or email", name)
}
}
return nil
}
// trap panic raised by the given function.
//
// This ugly hack allows us to make the smallest change possible to the existing
// codebase. Rather than convert each method so that errors are bubbled up, this
// lets us get away with a smaller change and will make it easier to pull
// new changes in the future.
func trap(f func()) (err error) {
defer func() {
x := recover()
if x != nil {
if a, ok := x.(error); ok {
err = a
} else if a, ok := x.(string); ok {
err = errors.New(a)
} else {
err = fmt.Errorf("caught panic: %v", x)
}
}
}()
f()
return
}
// Simple stub for log.Fatalln which is used throughout the codebase. Instead of
// exiting, raise a panic which we can catch with `trap` above.
func logFatalln(v ...interface{}) {
panic(errors.New(fmt.Sprintln(v...)))
}
func logPrint(v ...interface{}) {
if Print {
log.Print(v...)
}
}
func logPrintf(format string, v ...interface{}) {
if Print {
log.Printf(format, v...)
}
}
func logPrintln(v ...interface{}) {
if Print {
log.Println(v...)
}
}
// exists tests the existence of the given file
func exists(file string) bool {
_, err := os.Stat(file)
return err == nil
}
// Main exposes the package main method so we can call from our real main
// in bin/main.go
func Main() {
main()
}