-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
93 lines (77 loc) · 2.19 KB
/
client.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
88
89
90
91
92
93
package memguarded
import (
"crypto/tls"
"crypto/x509"
"github.com/n0rad/go-erlog/data"
"github.com/n0rad/go-erlog/errs"
"github.com/n0rad/go-erlog/logs"
"log"
"net"
"time"
)
type Client struct {
SocketPath string
CertPassphrase *Service
CertKey string
CertPem string
conn net.Conn
}
func (c *Client) Connect() error {
cert, err := loadX509KeyPair(c.CertPem, c.CertKey, c.CertPassphrase)
if err != nil {
return errs.WithE(err, "Failed to load key pair")
}
config := tls.Config{Certificates: []tls.Certificate{cert}, InsecureSkipVerify: true}
conn, err := tls.Dial("unix", c.SocketPath, &config)
if err != nil {
return errs.WithEF(err, data.WithField("socketPath", c.SocketPath), "Failed to connect to socketPath")
}
c.conn = net.Conn(conn)
state := conn.ConnectionState()
for _, v := range state.PeerCertificates {
key, err := x509.MarshalPKIXPublicKey(v.PublicKey)
if err != nil {
return errs.WithE(err, "failed to marshal public key")
}
logs.WithF(data.WithField("key", key)).Debug("Server public key")
}
log.Println("client: handshake: ", state.HandshakeComplete)
log.Println("client: mutual: ", state.NegotiatedProtocolIsMutual)
if err := conn.SetDeadline(time.Now().Add(10 * time.Second)); err != nil {
return errs.WithE(err, "Failed to set deadline")
}
return nil
}
func (c *Client) Close() {
if c.conn != nil {
c.conn.Close()
c.conn = nil
}
}
func (c *Client) SetSecret(secretService *Service) error {
if c.conn == nil {
return errs.With("Not connected")
}
if err := WriteBytes(c.conn, []byte("set_secret ")); err != nil {
return errs.WithE(err, "Failed to write command")
}
if err := secretService.Write(c.conn); err != nil {
return errs.WithE(err, "Failed to write key")
}
if err := WriteBytes(c.conn, []byte{'\n'}); err != nil {
return err
}
return nil
}
func (c *Client) GetSecret(secretService *Service) error {
if c.conn == nil {
return errs.With("Not connected")
}
if err := WriteBytes(c.conn, []byte("get_secret\n")); err != nil {
return errs.WithE(err, "Failed to write command")
}
if err := secretService.FromReaderUntilNewLine(c.conn); err != nil {
return errs.WithE(err, "Failed to get secret")
}
return nil
}