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
|
package main
import (
"crypto/tls"
"crypto/x509"
"io"
"log"
"os"
"path"
"path/filepath"
"dim13.org/acme"
)
type Cert struct {
tls.Certificate
keyFile string
crtFile string
}
func loadFiles(crtFile, keyFile string) (Cert, error) {
crt, err := tls.LoadX509KeyPair(crtFile, keyFile)
if err != nil {
return Cert{}, err
}
crt.Leaf, err = x509.ParseCertificate(crt.Certificate[0])
if err != nil {
return Cert{}, err
}
return Cert{Certificate: crt, keyFile: keyFile, crtFile: crtFile}, nil
}
func newFile(fname string, mode os.FileMode) (io.WriteCloser, error) {
os.Rename(fname, fname[:len(fname)-4]+".old")
return os.OpenFile(fname, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, mode)
}
func (c Cert) saveFiles() error {
fd, err := newFile(c.keyFile, 0600)
if err != nil {
return err
}
defer fd.Close()
if err := acme.SaveKey(fd, c.Certificate.PrivateKey); err != nil {
return err
}
fd, err = newFile(c.crtFile, 0644)
if err != nil {
return err
}
defer fd.Close()
for _, crt := range c.Certificate.Certificate {
if err := acme.SaveCert(fd, crt); err != nil {
return err
}
}
return nil
}
func scanFiles(dir string) ([]Cert, error) {
var certs []Cert
keys, err := filepath.Glob(path.Join(dir, "private", "*.key"))
if err != nil {
return nil, err
}
for _, k := range keys {
c := filepath.Join(dir, "certs", filepath.Base(k[:len(k)-4])+".pem")
crt, err := loadFiles(c, k)
if err != nil {
log.Println(err)
continue
}
certs = append(certs, crt)
}
return certs, nil
}
|