/
server.go
220 lines (184 loc) · 5.44 KB
/
server.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
package server
import (
"context"
"crypto"
"crypto/tls"
"crypto/x509"
"fmt"
"log"
"net"
"net/http"
"github.com/Arieshui/dynamiclistener-100"
"github.com/Arieshui/dynamiclistener-100/factory"
"github.com/Arieshui/dynamiclistener-100/storage/file"
"github.com/Arieshui/dynamiclistener-100/storage/kubernetes"
"github.com/Arieshui/dynamiclistener-100/storage/memory"
v1 "github.com/rancher/wrangler-api/pkg/generated/controllers/core/v1"
"github.com/sirupsen/logrus"
"golang.org/x/crypto/acme/autocert"
)
type ListenOpts struct {
CA *x509.Certificate
CAKey crypto.Signer
Storage dynamiclistener.TLSStorage
Secrets v1.SecretController
CertNamespace string
CertName string
CANamespace string
CAName string
CertBackup string
AcmeDomains []string
BindHost string
NoRedirect bool
TLSListenerConfig dynamiclistener.Config
}
func ListenAndServe(ctx context.Context, httpsPort, httpPort int, handler http.Handler, opts *ListenOpts) error {
if opts == nil {
opts = &ListenOpts{}
}
if opts.TLSListenerConfig.TLSConfig == nil {
opts.TLSListenerConfig.TLSConfig = &tls.Config{}
}
logger := logrus.StandardLogger()
errorLog := log.New(logger.WriterLevel(logrus.DebugLevel), "", log.LstdFlags)
if httpsPort > 0 {
tlsTCPListener, err := dynamiclistener.NewTCPListener(opts.BindHost, httpsPort)
if err != nil {
return err
}
tlsTCPListener, handler, err = getTLSListener(ctx, tlsTCPListener, handler, *opts)
if err != nil {
return err
}
if !opts.NoRedirect {
handler = dynamiclistener.HTTPRedirect(handler)
}
tlsServer := http.Server{
Handler: handler,
ErrorLog: errorLog,
}
go func() {
logrus.Infof("Listening on %s:%d", opts.BindHost, httpsPort)
err := tlsServer.Serve(tlsTCPListener)
if err != http.ErrServerClosed && err != nil {
logrus.Fatalf("https server failed: %v", err)
}
}()
go func() {
<-ctx.Done()
tlsServer.Shutdown(context.Background())
}()
}
if httpPort > 0 {
httpServer := http.Server{
Addr: fmt.Sprintf("%s:%d", opts.BindHost, httpPort),
Handler: handler,
ErrorLog: errorLog,
}
go func() {
logrus.Infof("Listening on %s:%d", opts.BindHost, httpPort)
err := httpServer.ListenAndServe()
if err != http.ErrServerClosed && err != nil {
logrus.Fatalf("http server failed: %v", err)
}
}()
go func() {
<-ctx.Done()
httpServer.Shutdown(context.Background())
}()
}
return nil
}
func getTLSListener(ctx context.Context, tcp net.Listener, handler http.Handler, opts ListenOpts) (net.Listener, http.Handler, error) {
if len(opts.TLSListenerConfig.TLSConfig.NextProtos) == 0 {
opts.TLSListenerConfig.TLSConfig.NextProtos = []string{"h2", "http/1.1"}
}
if len(opts.TLSListenerConfig.TLSConfig.Certificates) > 0 {
return tls.NewListener(tcp, opts.TLSListenerConfig.TLSConfig), handler, nil
}
if len(opts.AcmeDomains) > 0 {
return acmeListener(tcp, handler, opts)
}
storage := opts.Storage
if storage == nil {
storage = newStorage(ctx, opts)
}
caCert, caKey, err := getCA(opts)
if err != nil {
return nil, nil, err
}
listener, dynHandler, err := dynamiclistener.NewListener(tcp, storage, caCert, caKey, opts.TLSListenerConfig)
if err != nil {
return nil, nil, err
}
return listener, wrapHandler(dynHandler, handler), nil
}
func getCA(opts ListenOpts) (*x509.Certificate, crypto.Signer, error) {
if opts.CA != nil && opts.CAKey != nil {
return opts.CA, opts.CAKey, nil
}
if opts.Secrets == nil {
return factory.LoadOrGenCA()
}
if opts.CAName == "" {
opts.CAName = "serving-ca"
}
if opts.CANamespace == "" {
opts.CANamespace = opts.CertNamespace
}
if opts.CANamespace == "" {
opts.CANamespace = "kube-system"
}
return kubernetes.LoadOrGenCA(opts.Secrets, opts.CANamespace, opts.CAName)
}
func newStorage(ctx context.Context, opts ListenOpts) dynamiclistener.TLSStorage {
var result dynamiclistener.TLSStorage
if opts.CertBackup == "" {
result = memory.New()
} else {
result = memory.NewBacked(file.New(opts.CertBackup))
}
if opts.Secrets == nil {
return result
}
if opts.CertName == "" {
opts.CertName = "serving-cert"
}
if opts.CertNamespace == "" {
opts.CertNamespace = "kube-system"
}
return kubernetes.Load(ctx, opts.Secrets, opts.CertNamespace, opts.CertName, result)
}
func wrapHandler(handler http.Handler, next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
handler.ServeHTTP(rw, req)
next.ServeHTTP(rw, req)
})
}
func acmeListener(tcp net.Listener, handler http.Handler, opts ListenOpts) (net.Listener, http.Handler, error) {
hosts := map[string]bool{}
for _, domain := range opts.AcmeDomains {
hosts[domain] = true
}
manager := autocert.Manager{
Cache: autocert.DirCache("certs-cache"),
Prompt: func(tosURL string) bool {
return true
},
HostPolicy: func(ctx context.Context, host string) error {
if !hosts[host] {
return fmt.Errorf("host %s is not configured", host)
}
return nil
},
}
opts.TLSListenerConfig.TLSConfig.GetCertificate = func(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
if hello.ServerName == "localhost" || hello.ServerName == "" {
newHello := *hello
newHello.ServerName = opts.AcmeDomains[0]
return manager.GetCertificate(&newHello)
}
return manager.GetCertificate(hello)
}
return tls.NewListener(tcp, opts.TLSListenerConfig.TLSConfig), manager.HTTPHandler(handler), nil
}