forked from canonical/lxd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnetwork.go
521 lines (425 loc) · 12 KB
/
network.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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
package shared
import (
"context"
"crypto/tls"
"crypto/x509"
"encoding/pem"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"os"
"strings"
"sync"
"time"
"github.com/gorilla/websocket"
"github.com/lxc/lxd/shared/logger"
)
// connectErrorPrefix used as prefix to error returned from RFC3493Dialer.
const connectErrorPrefix = "Unable to connect to"
// RFC3493Dialer connects to the specified server and returns the connection.
// If the connection cannot be established then an error with the connectErrorPrefix is returned.
func RFC3493Dialer(context context.Context, network string, address string) (net.Conn, error) {
host, port, err := net.SplitHostPort(address)
if err != nil {
return nil, err
}
addrs, err := net.LookupHost(host)
if err != nil {
return nil, err
}
var errs []error
for _, a := range addrs {
c, err := net.DialTimeout(network, net.JoinHostPort(a, port), 10*time.Second)
if err != nil {
errs = append(errs, err)
continue
}
tc, ok := c.(*net.TCPConn)
if ok {
_ = tc.SetKeepAlive(true)
_ = tc.SetKeepAlivePeriod(3 * time.Second)
}
return c, nil
}
return nil, fmt.Errorf("%s: %s (%v)", connectErrorPrefix, address, errs)
}
// IsConnectionError returns true if the given error is due to the dialer not being able to connect to the target
// LXD server.
func IsConnectionError(err error) bool {
// FIXME: unfortunately the LXD client currently does not provide a way to differentiate between errors.
return strings.Contains(err.Error(), connectErrorPrefix)
}
// InitTLSConfig returns a tls.Config populated with default encryption
// parameters. This is used as baseline config for both client and server
// certificates used by LXD.
func InitTLSConfig() *tls.Config {
config := &tls.Config{}
// Restrict to TLS 1.3 unless LXD_INSECURE_TLS is set.
if IsFalseOrEmpty(os.Getenv("LXD_INSECURE_TLS")) {
config.MinVersion = tls.VersionTLS13
} else {
config.MinVersion = tls.VersionTLS12
}
return config
}
func finalizeTLSConfig(tlsConfig *tls.Config, tlsRemoteCert *x509.Certificate) {
// Setup RootCA
if tlsConfig.RootCAs == nil {
tlsConfig.RootCAs, _ = systemCertPool()
}
// Trusted certificates
if tlsRemoteCert != nil {
if tlsConfig.RootCAs == nil {
tlsConfig.RootCAs = x509.NewCertPool()
}
// Make it a valid RootCA
tlsRemoteCert.IsCA = true
tlsRemoteCert.KeyUsage = x509.KeyUsageCertSign
// Setup the pool
tlsConfig.RootCAs.AddCert(tlsRemoteCert)
// Set the ServerName
if tlsRemoteCert.DNSNames != nil {
tlsConfig.ServerName = tlsRemoteCert.DNSNames[0]
}
}
tlsConfig.BuildNameToCertificate()
}
func GetTLSConfig(tlsClientCertFile string, tlsClientKeyFile string, tlsClientCAFile string, tlsRemoteCert *x509.Certificate) (*tls.Config, error) {
tlsConfig := InitTLSConfig()
// Client authentication
if tlsClientCertFile != "" && tlsClientKeyFile != "" {
cert, err := tls.LoadX509KeyPair(tlsClientCertFile, tlsClientKeyFile)
if err != nil {
return nil, err
}
tlsConfig.Certificates = []tls.Certificate{cert}
}
if tlsClientCAFile != "" {
caCertificates, err := ioutil.ReadFile(tlsClientCAFile)
if err != nil {
return nil, err
}
caPool := x509.NewCertPool()
caPool.AppendCertsFromPEM(caCertificates)
tlsConfig.RootCAs = caPool
}
finalizeTLSConfig(tlsConfig, tlsRemoteCert)
return tlsConfig, nil
}
func GetTLSConfigMem(tlsClientCert string, tlsClientKey string, tlsClientCA string, tlsRemoteCertPEM string, insecureSkipVerify bool) (*tls.Config, error) {
tlsConfig := InitTLSConfig()
tlsConfig.InsecureSkipVerify = insecureSkipVerify
// Client authentication
if tlsClientCert != "" && tlsClientKey != "" {
cert, err := tls.X509KeyPair([]byte(tlsClientCert), []byte(tlsClientKey))
if err != nil {
return nil, err
}
tlsConfig.Certificates = []tls.Certificate{cert}
}
var tlsRemoteCert *x509.Certificate
if tlsRemoteCertPEM != "" {
// Ignore any content outside of the PEM bytes we care about
certBlock, _ := pem.Decode([]byte(tlsRemoteCertPEM))
if certBlock == nil {
return nil, fmt.Errorf("Invalid remote certificate")
}
var err error
tlsRemoteCert, err = x509.ParseCertificate(certBlock.Bytes)
if err != nil {
return nil, err
}
}
if tlsClientCA != "" {
caPool := x509.NewCertPool()
caPool.AppendCertsFromPEM([]byte(tlsClientCA))
tlsConfig.RootCAs = caPool
}
finalizeTLSConfig(tlsConfig, tlsRemoteCert)
return tlsConfig, nil
}
func IsLoopback(iface *net.Interface) bool {
return int(iface.Flags&net.FlagLoopback) > 0
}
func WebsocketSendStream(conn *websocket.Conn, r io.Reader, bufferSize int) chan bool {
ch := make(chan bool)
if r == nil {
close(ch)
return ch
}
go func(conn *websocket.Conn, r io.Reader) {
in := ReaderToChannel(r, bufferSize)
for {
buf, ok := <-in
if !ok {
break
}
err := conn.WriteMessage(websocket.BinaryMessage, buf)
if err != nil {
logger.Debug("Got err writing", logger.Ctx{"err": err})
break
}
}
_ = conn.WriteMessage(websocket.TextMessage, []byte{})
ch <- true
}(conn, r)
return ch
}
func WebsocketRecvStream(w io.Writer, conn *websocket.Conn) chan bool {
ch := make(chan bool)
go func(w io.Writer, conn *websocket.Conn) {
for {
mt, r, err := conn.NextReader()
if mt == websocket.CloseMessage {
logger.Debug("WebsocketRecvStream got close message for reader")
break
}
if mt == websocket.TextMessage {
logger.Debug("WebsocketRecvStream got message barrier")
break
}
if err != nil {
logger.Debug("WebsocketRecvStream got error getting next reader", logger.Ctx{"err": err})
break
}
buf, err := ioutil.ReadAll(r)
if err != nil {
logger.Debug("WebsocketRecvStream got error writing to writer", logger.Ctx{"err": err})
break
}
if w == nil {
continue
}
i, err := w.Write(buf)
if i != len(buf) {
logger.Debug("WebsocketRecvStream didn't write all of buf")
break
}
if err != nil {
logger.Debug("WebsocketRecvStream error writing buf", logger.Ctx{"err": err})
break
}
}
ch <- true
}(w, conn)
return ch
}
func WebsocketProxy(source *websocket.Conn, target *websocket.Conn) chan struct{} {
// Forwarder between two websockets, closes channel upon disconnection.
forward := func(in *websocket.Conn, out *websocket.Conn, ch chan struct{}) {
for {
mt, r, err := in.NextReader()
if err != nil {
break
}
w, err := out.NextWriter(mt)
if err != nil {
break
}
_, err = io.Copy(w, r)
_ = w.Close()
if err != nil {
break
}
}
close(ch)
}
// Spawn forwarders in both directions.
chSend := make(chan struct{})
go forward(source, target, chSend)
chRecv := make(chan struct{})
go forward(target, source, chRecv)
// Close main channel and disconnect upon completion of either forwarder.
ch := make(chan struct{})
go func() {
select {
case <-chSend:
case <-chRecv:
}
_ = source.Close()
_ = target.Close()
close(ch)
}()
return ch
}
func defaultReader(conn *websocket.Conn, r io.ReadCloser, readDone chan<- bool) {
/* For now, we don't need to adjust buffer sizes in
* WebsocketMirror, since it's used for interactive things like
* exec.
*/
in := ReaderToChannel(r, -1)
for {
buf, ok := <-in
if !ok {
_ = r.Close()
logger.Debug("Sending write barrier")
_ = conn.WriteMessage(websocket.TextMessage, []byte{})
readDone <- true
return
}
err := conn.WriteMessage(websocket.BinaryMessage, buf)
if err != nil {
logger.Debug("Got err writing", logger.Ctx{"err": err})
break
}
}
closeMsg := websocket.FormatCloseMessage(websocket.CloseNormalClosure, "")
_ = conn.WriteMessage(websocket.CloseMessage, closeMsg)
readDone <- true
_ = r.Close()
}
func DefaultWriter(conn *websocket.Conn, w io.WriteCloser, writeDone chan<- bool) {
for {
mt, r, err := conn.NextReader()
if err != nil {
logger.Debug("DefaultWriter got error getting next reader", logger.Ctx{"err": err})
break
}
if mt == websocket.CloseMessage {
logger.Debug("DefaultWriter got close message for reader")
break
}
if mt == websocket.TextMessage {
logger.Debug("DefaultWriter got message barrier, resetting stream")
break
}
buf, err := ioutil.ReadAll(r)
if err != nil {
logger.Debug("DefaultWriter got error writing to writer", logger.Ctx{"err": err})
break
}
i, err := w.Write(buf)
if i != len(buf) {
logger.Debug("DefaultWriter didn't write all of buf")
break
}
if err != nil {
logger.Debug("DefaultWriter error writing buf", logger.Ctx{"err": err})
break
}
}
writeDone <- true
_ = w.Close()
}
// WebsocketIO is a wrapper implementing ReadWriteCloser on top of websocket.
type WebsocketIO struct {
Conn *websocket.Conn
reader io.Reader
mu sync.Mutex
}
func (w *WebsocketIO) Read(p []byte) (n int, err error) {
// First read from this message
if w.reader == nil {
var mt int
mt, w.reader, err = w.Conn.NextReader()
if err != nil {
return 0, err
}
if mt == websocket.CloseMessage {
return 0, io.EOF
}
if mt == websocket.TextMessage {
return 0, io.EOF
}
}
// Perform the read itself
n, err = w.reader.Read(p)
if err == io.EOF {
// At the end of the message, reset reader
w.reader = nil
return n, nil
}
if err != nil {
return 0, err
}
return n, nil
}
func (w *WebsocketIO) Write(p []byte) (n int, err error) {
w.mu.Lock()
defer w.mu.Unlock()
wr, err := w.Conn.NextWriter(websocket.BinaryMessage)
if err != nil {
return -1, err
}
n, err = wr.Write(p)
if err != nil {
return -1, err
}
return n, wr.Close()
}
// Close sends a control message indicating the stream is finished, but it does not actually close
// the socket.
func (w *WebsocketIO) Close() error {
w.mu.Lock()
defer w.mu.Unlock()
// Target expects to get a control message indicating stream is finished.
return w.Conn.WriteMessage(websocket.TextMessage, []byte{})
}
// WebsocketMirror allows mirroring a reader to a websocket and taking the
// result and writing it to a writer. This function allows for multiple
// mirrorings and correctly negotiates stream endings. However, it means any
// websocket.Conns passed to it are live when it returns, and must be closed
// explicitly.
type WebSocketMirrorReader func(conn *websocket.Conn, r io.ReadCloser, readDone chan<- bool)
type WebSocketMirrorWriter func(conn *websocket.Conn, w io.WriteCloser, writeDone chan<- bool)
func WebsocketMirror(conn *websocket.Conn, w io.WriteCloser, r io.ReadCloser, Reader WebSocketMirrorReader, Writer WebSocketMirrorWriter) (chan bool, chan bool) {
readDone := make(chan bool, 1)
writeDone := make(chan bool, 1)
ReadFunc := Reader
if ReadFunc == nil {
ReadFunc = defaultReader
}
WriteFunc := Writer
if WriteFunc == nil {
WriteFunc = DefaultWriter
}
go ReadFunc(conn, r, readDone)
go WriteFunc(conn, w, writeDone)
return readDone, writeDone
}
func WebsocketConsoleMirror(conn *websocket.Conn, w io.WriteCloser, r io.ReadCloser) (chan bool, chan bool) {
readDone := make(chan bool, 1)
writeDone := make(chan bool, 1)
go DefaultWriter(conn, w, writeDone)
go func(conn *websocket.Conn, r io.ReadCloser) {
in := ReaderToChannel(r, -1)
for {
buf, ok := <-in
if !ok {
_ = r.Close()
logger.Debugf("Sending write barrier")
_ = conn.WriteMessage(websocket.BinaryMessage, []byte("\r"))
_ = conn.WriteMessage(websocket.TextMessage, []byte{})
readDone <- true
return
}
err := conn.WriteMessage(websocket.BinaryMessage, buf)
if err != nil {
logger.Debugf("Got err writing %s", err)
break
}
}
closeMsg := websocket.FormatCloseMessage(websocket.CloseNormalClosure, "")
_ = conn.WriteMessage(websocket.CloseMessage, closeMsg)
readDone <- true
_ = r.Close()
}(conn, r)
return readDone, writeDone
}
var WebsocketUpgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool { return true },
}
// AllocatePort asks the kernel for a free open port that is ready to use.
func AllocatePort() (int, error) {
addr, err := net.ResolveTCPAddr("tcp", "localhost:0")
if err != nil {
return -1, err
}
l, err := net.ListenTCP("tcp", addr)
if err != nil {
return -1, err
}
return l.Addr().(*net.TCPAddr).Port, l.Close()
}