-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
87 lines (75 loc) · 2.31 KB
/
config.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
package client
import (
"context"
"crypto/tls"
"fmt"
"log"
"os"
"path"
"time"
"github.com/pion/dtls/v2"
)
// Config for Client.
type Config struct {
DTLSConfig *dtls.Config
SpanUDPAddr string
SpanCOAPAddr string
}
const (
defaultSpanUDPAddr = "data.lab5e.com:1234"
defaultSpanCOAPAddr = "data.lab5e.com:5684"
certsDirFragment = ".devcli/certs"
certFile = "cert.crt"
keyFile = "key.pem"
defaultDTLSTimeout = 30 * time.Second
)
// NewDefaultConfig creates a new default configuration. This requires you to have
// a .devcli/certs directory under your home directory where the cert.crt and key.pem
// are stored. This function is a bit ugly since it terminates if anything goes wrong,
// so it is only useful in clients where this behavior is acceptable. If you want
// to be able to do proper error handling please see the NewConfig function.
func NewDefaultConfig() Config {
userHomedir, err := os.UserHomeDir()
if err != nil {
log.Fatalf("can't figure out user home directory: %v", err)
}
certsDir := path.Join(userHomedir, certsDirFragment)
certBytes, err := os.ReadFile(certsDir + "/" + certFile)
if err != nil {
log.Fatalf("Error reading cert file: %v", err)
}
keyBytes, err := os.ReadFile(certsDir + "/" + keyFile)
if err != nil {
log.Fatalf("Error reading key file: %v", err)
}
cfg, err := NewConfig(certBytes, keyBytes)
if err != nil {
log.Fatal(err)
}
return cfg
}
// NewConfig creates a new configuration from certBytes and keyBytes. Note that both
// certBytes and keyBytes are expected to be PEM-encoded.
func NewConfig(certBytes []byte, keyBytes []byte) (Config, error) {
cert, err := tls.X509KeyPair(certBytes, keyBytes)
if err != nil {
return Config{}, fmt.Errorf("%w: %v", ErrCannotReadKeyPair, err)
}
intermediates, roots, err := loadCertPool(certBytes)
if err != nil {
return Config{}, fmt.Errorf("%w: %v", ErrCannotLoadCertPool, err)
}
return Config{
DTLSConfig: &dtls.Config{
Certificates: []tls.Certificate{cert},
InsecureSkipVerify: false,
RootCAs: roots,
ClientCAs: intermediates,
ConnectContextMaker: func() (context.Context, func()) {
return context.WithTimeout(context.Background(), defaultDTLSTimeout)
},
},
SpanUDPAddr: defaultSpanUDPAddr,
SpanCOAPAddr: defaultSpanCOAPAddr,
}, nil
}