forked from gammazero/nexus
/
newclient.go
174 lines (157 loc) · 4.7 KB
/
newclient.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
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
/*
Package newclient provides a function to create a new client with the socket
type and serialization specified by command like arguments. This is used for
all the sample clients.
*/
package newclient
import (
"context"
"crypto/tls"
"crypto/x509"
"encoding/pem"
"errors"
"flag"
"fmt"
"log"
"os"
"github.com/dtegapp/nexus/v3/client"
)
const (
defaultRealm = "realm1"
defaultAddr = "localhost"
defaultUnix = "/tmp/exmpl_nexus_sock"
defaultWsPort = 8080
defaultWssPort = 8443
defaultTcpPort = 8000
defaultTcpsPort = 8001
)
func NewClient(logger *log.Logger) (*client.Client, error) {
var (
skipVerify, compress bool
port int
addr, caFile, certFile, keyFile, realm, scheme, serType string
)
flag.StringVar(&addr, "addr", "",
fmt.Sprintf("router address. (default %q or %q for network or unix socket)", defaultAddr, defaultUnix))
flag.IntVar(&port, "port", 0,
fmt.Sprintf("router port. (default %d, %d, %d, %d for scheme ws, wss, tcp, tcps)", defaultWsPort, defaultWssPort, defaultTcpPort, defaultTcpsPort))
flag.StringVar(&realm, "realm", defaultRealm, "realm name")
flag.StringVar(&scheme, "scheme", "ws", "[ws, wss, tcp, tcps, unix]")
flag.StringVar(&serType, "serialize", "json", "\"json\" or \"msgpack\" or \"cbor\"")
flag.BoolVar(&skipVerify, "skipverify", false,
"accept any certificate presented by the server")
flag.StringVar(&caFile, "trust", "",
"CA or self-signed certificate to trust in PEM encoded file")
flag.StringVar(&certFile, "cert", "",
"certificate file with PEM encoded data")
flag.StringVar(&keyFile, "key", "",
"private key file with PEM encoded data")
flag.BoolVar(&compress, "compress", false, "enable websocket compression")
flag.Parse()
// Get requested serialization.
serialization := client.JSON
switch serType {
case "json":
case "msgpack":
serialization = client.MSGPACK
case "cbor":
serialization = client.CBOR
default:
return nil, errors.New(
"invalid serialization, muse be one of: json, msgpack, cbor")
}
if addr == "" {
if scheme == "unix" {
addr = defaultUnix
} else {
addr = defaultAddr
}
}
cfg := client.Config{
Realm: realm,
Serialization: serialization,
Logger: logger,
}
if scheme == "https" || scheme == "wss" || scheme == "tcps" {
// If TLS requested, then set up TLS configuration.
tlscfg := &tls.Config{
InsecureSkipVerify: skipVerify,
}
// If asked to load a client certificate to present to server.
if certFile != "" || keyFile != "" {
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return nil, fmt.Errorf("error loading X509 key pair: %s", err)
}
tlscfg.Certificates = append(tlscfg.Certificates, cert)
}
// If not skipping verification and told to trust a certificate.
if !skipVerify && caFile != "" {
// Load PEM-encoded certificate to trust.
certPEM, err := os.ReadFile(caFile)
if err != nil {
return nil, err
}
// Create CertPool containing the certificate to trust.
roots := x509.NewCertPool()
if !roots.AppendCertsFromPEM(certPEM) {
return nil, errors.New("failed to import certificate to trust")
}
// Trust the certificate by putting it into the pool of root CAs.
tlscfg.RootCAs = roots
// Decode and parse the server cert to extract the subject info.
block, _ := pem.Decode(certPEM)
if block == nil {
return nil, errors.New("failed to decode certificate to trust")
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, err
}
log.Println("Trusting certificate", caFile, "with CN:",
cert.Subject.CommonName)
// Set ServerName in TLS config to CN from trusted cert so that
// certificate will validate if CN does not match DNS name.
tlscfg.ServerName = cert.Subject.CommonName
}
cfg.TlsCfg = tlscfg
}
if compress {
cfg.WsCfg.EnableCompression = true
}
// Create client with requested transport type.
var cli *client.Client
var err error
switch scheme {
case "http", "ws":
if port == 0 {
port = defaultWsPort
}
addr = fmt.Sprintf("ws://%s:%d/ws", addr, port)
case "https", "wss":
if port == 0 {
port = defaultWssPort
}
addr = fmt.Sprintf("wss://%s:%d/ws", addr, port)
case "tcp":
if port == 0 {
port = defaultTcpPort
}
addr = fmt.Sprintf("tcp://%s:%d/", addr, port)
case "tcps":
if port == 0 {
port = defaultTcpsPort
}
addr = fmt.Sprintf("tcps://%s:%d/", addr, port)
case "unix":
addr = fmt.Sprintf("unix://%s", addr)
default:
return nil, errors.New("scheme must be one of: http, https, ws, wss, tcp, tcps, unix")
}
cli, err = client.ConnectNet(context.Background(), addr, cfg)
if err != nil {
return nil, err
}
logger.Println("Connected to", addr, "using", serType, "serialization")
return cli, nil
}