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
|
package main
import (
"crypto"
"crypto/tls"
"crypto/x509"
"errors"
"io"
"os"
"path"
"syscall"
"dim13.org/acme"
)
var ErrNotFound = errors.New("file not found")
func NewFile(fname string, mode os.FileMode) (io.WriteCloser, error) {
err := os.Rename(fname, fname+".bak")
if err != nil {
if e, ok := err.(*os.LinkError); ok && e.Err != syscall.ENOENT {
return nil, err
}
}
flags := os.O_WRONLY | os.O_CREATE | os.O_TRUNC
return os.OpenFile(fname, flags, mode)
}
func (d domain) Save(cert tls.Certificate) error {
if err := os.MkdirAll(path.Dir(d.KeyFile), 0700); err != nil {
return err
}
fd, err := NewFile(d.KeyFile, 0600)
if err != nil {
return err
}
defer fd.Close()
err = acme.SaveKey(fd, cert.PrivateKey)
if err != nil {
return err
}
if err := os.MkdirAll(path.Dir(d.CrtFile), 0755); err != nil {
return err
}
fd, err = NewFile(d.CrtFile, 0644)
if err != nil {
return err
}
defer fd.Close()
for _, crt := range cert.Certificate {
if err := acme.SaveCert(fd, crt); err != nil {
return err
}
}
return nil
}
func (d domain) Load() (tls.Certificate, error) {
crt, err := tls.LoadX509KeyPair(d.CrtFile, d.KeyFile)
if err != nil {
if e, ok := err.(*os.PathError); ok && e.Err == syscall.ENOENT {
err = ErrNotFound
}
return tls.Certificate{}, err
}
crt.Leaf, err = x509.ParseCertificate(crt.Certificate[0])
return crt, err
}
func (a account) Save(key crypto.PrivateKey) error {
if err := os.MkdirAll(path.Dir(a.KeyFile), 0700); err != nil {
return err
}
fd, err := NewFile(a.KeyFile, 0600)
if err != nil {
return err
}
defer fd.Close()
return acme.SaveKey(fd, key)
}
func (a account) Load() (crypto.PrivateKey, error) {
fd, err := os.Open(a.KeyFile)
if err != nil {
if e, ok := err.(*os.PathError); ok && e.Err == syscall.ENOENT {
err = ErrNotFound
}
return nil, err
}
defer fd.Close()
return acme.LoadKey(fd)
}
|