forked from awoodbeck/gnp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tls_echo.go
111 lines (93 loc) · 1.94 KB
/
tls_echo.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
package ch11
import (
"context"
"crypto/tls"
"fmt"
"net"
"time"
)
func NewTLSServer(ctx context.Context, address string,
maxIdle time.Duration, tlsConfig *tls.Config) *Server {
return &Server{
ctx: ctx,
ready: make(chan struct{}),
addr: address,
maxIdle: maxIdle,
tlsConfig: tlsConfig,
}
}
type Server struct {
ctx context.Context
ready chan struct{}
addr string
maxIdle time.Duration
tlsConfig *tls.Config
}
func (s *Server) Ready() {
if s.ready != nil {
<-s.ready
}
}
func (s *Server) ListenAndServeTLS(certFn, keyFn string) error {
if s.addr == "" {
s.addr = "localhost:443"
}
l, err := net.Listen("tcp", s.addr)
if err != nil {
return fmt.Errorf("binding to tcp %s: %w", s.addr, err)
}
if s.ctx != nil {
go func() {
<-s.ctx.Done()
_ = l.Close()
}()
}
return s.ServeTLS(l, certFn, keyFn)
}
func (s Server) ServeTLS(l net.Listener, certFn, keyFn string) error {
if s.tlsConfig == nil {
s.tlsConfig = &tls.Config{
CurvePreferences: []tls.CurveID{tls.CurveP256},
MinVersion: tls.VersionTLS12,
PreferServerCipherSuites: true,
}
}
if len(s.tlsConfig.Certificates) == 0 &&
s.tlsConfig.GetCertificate == nil {
cert, err := tls.LoadX509KeyPair(certFn, keyFn)
if err != nil {
return fmt.Errorf("loading key pair: %v", err)
}
s.tlsConfig.Certificates = []tls.Certificate{cert}
}
tlsListener := tls.NewListener(l, s.tlsConfig)
if s.ready != nil {
close(s.ready)
}
for {
conn, err := tlsListener.Accept()
if err != nil {
return fmt.Errorf("accept: %v", err)
}
go func() {
defer func() { _ = conn.Close() }()
for {
if s.maxIdle > 0 {
err := conn.SetDeadline(time.Now().Add(s.maxIdle))
if err != nil {
return
}
}
buf := make([]byte, 1024)
n, err := conn.Read(buf)
if err != nil {
return
}
_, err = conn.Write(buf[:n])
if err != nil {
return
}
}
}()
}
}