-
Notifications
You must be signed in to change notification settings - Fork 443
/
ssl_proxy.go
92 lines (76 loc) · 2.1 KB
/
ssl_proxy.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
package v1helpers
import (
"context"
"crypto/tls"
"fmt"
"io"
"net"
"strconv"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/solo-io/gloo/test/helpers"
)
func StartSslProxy(ctx context.Context, port uint32) uint32 {
return StartSslProxyWithHelloCB(ctx, port, nil)
}
func StartSslProxyWithHelloCB(ctx context.Context, port uint32, cb func(chi *tls.ClientHelloInfo)) uint32 {
cert := []byte(helpers.Certificate())
key := []byte(helpers.PrivateKey())
cer, err := tls.X509KeyPair(cert, key)
Expect(err).NotTo(HaveOccurred())
config := &tls.Config{
GetCertificate: func(chi *tls.ClientHelloInfo) (*tls.Certificate, error) {
if cb != nil {
cb(chi)
}
return &cer, nil
},
}
listener, err := tls.Listen("tcp", ":0", config)
Expect(err).NotTo(HaveOccurred())
go func() {
defer GinkgoRecover()
<-ctx.Done()
listener.Close()
}()
go func() {
defer GinkgoRecover()
for {
conn, err := listener.Accept()
if ctx.Err() != nil {
return
}
Expect(err).NotTo(HaveOccurred())
go func() {
defer GinkgoRecover()
proxyConnection(ctx, conn, port)
}()
}
}()
addr := listener.Addr().String()
_, portstr, err := net.SplitHostPort(addr)
Expect(err).NotTo(HaveOccurred())
lport, err := strconv.Atoi(portstr)
Expect(err).NotTo(HaveOccurred())
fmt.Fprintf(GinkgoWriter, "starting ssl proxy to port %v to port %v\n", port, lport)
return uint32(lport)
}
func proxyConnection(ctx context.Context, conn net.Conn, port uint32) {
defer conn.Close()
fmt.Fprintf(GinkgoWriter, "proxing connection to to port %v\n", port)
defer fmt.Fprintf(GinkgoWriter, "proxing connection to to port %v done\n", port)
c, err := net.Dial("tcp", fmt.Sprintf("localhost:%d", port))
Expect(err).NotTo(HaveOccurred())
defer c.Close()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
copythings := func(dst io.Writer, src io.Reader) {
defer cancel()
fmt.Fprintf(GinkgoWriter, "proxing copying started\n")
w, err := io.Copy(dst, src)
fmt.Fprintf(GinkgoWriter, "proxing copying return w: %v err %v\n", w, err)
}
go copythings(conn, c)
go copythings(c, conn)
<-ctx.Done()
}