~emersion/kimchi

kimchi/server.go -rw-r--r-- 5.6 KiB
1ec4ec62Simon Ser man: update example with kimchi directives 2 months ago
                                                                                
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
package main

import (
	"context"
	"crypto/tls"
	"fmt"
	"log"
	"net"
	"net/http"
	"sync"

	"github.com/pires/go-proxyproto"
	"github.com/pires/go-proxyproto/tlvparse"
	"golang.org/x/net/http2"
)

type contextKey string

const (
	contextKeyProtocol contextKey = "protocol"
	contextKeyTLSState contextKey = "tlsState"
)

func contextProtocol(ctx context.Context) string {
	return ctx.Value(contextKeyProtocol).(string)
}

func contextTLSState(ctx context.Context) *tls.ConnectionState {
	return ctx.Value(contextKeyTLSState).(*tls.ConnectionState)
}

type listenerKey struct {
	network string
	address string
}

type Server struct {
	listeners map[listenerKey]*Listener
}

func NewServer() *Server {
	return &Server{
		listeners: make(map[listenerKey]*Listener),
	}
}

func (srv *Server) Start() error {
	for _, ln := range srv.listeners {
		if err := ln.Start(); err != nil {
			return err
		}
	}

	return nil
}

func (srv *Server) AddListener(network, addr string) *Listener {
	k := listenerKey{network, addr}
	if ln, ok := srv.listeners[k]; ok {
		return ln
	}

	ln := newListener(network, addr)
	srv.listeners[k] = ln
	return ln
}

type Listener struct {
	Network  string
	Address  string
	Mux      *http.ServeMux
	Insecure bool

	h1Server   *http.Server
	h1Listener *pipeListener

	h2Server *http2.Server
}

func newListener(network, addr string) *Listener {
	ln := &Listener{
		Network: network,
		Address: addr,
	}
	ln.h1Listener = newPipeListener()
	ln.h1Server = &http.Server{
		Handler: ln,
		ConnContext: func(ctx context.Context, conn net.Conn) context.Context {
			return conn.(*Conn).Context(ctx)
		},
	}
	ln.h2Server = &http2.Server{}
	ln.Mux = http.NewServeMux()
	return ln
}

func (ln *Listener) Start() error {
	netLn, err := net.Listen(ln.Network, ln.Address)
	if err != nil {
		return err
	}
	log.Printf("HTTP server listening on %q", ln.Address)

	go func() {
		if err := ln.serve(netLn); err != nil {
			log.Fatalf("failed to serve listener %q: %v", ln.Address, err)
		}
	}()

	go func() {
		if err := ln.h1Server.Serve(ln.h1Listener); err != nil {
			log.Fatalf("HTTP/1 server: %v", err)
		}
	}()

	return nil
}

func (ln *Listener) serve(netLn net.Listener) error {
	for {
		conn, err := netLn.Accept()
		if err != nil {
			return fmt.Errorf("failed to accept connection: %v", err)
		}

		go func() {
			if err := ln.serveConn(conn); err != nil {
				log.Printf("listener %q: %v", ln.Address, err)
			}
		}()
	}
}

func (ln *Listener) serveConn(conn net.Conn) error {
	var proto string
	var tlsState *tls.ConnectionState
	remoteAddr := conn.RemoteAddr()
	// TODO: read proto and TLS state from conn, if it's a TLS connection

	// TODO: only accept PROXY protocol from trusted sources
	proxyConn := proxyproto.NewConn(conn)
	if proxyHeader := proxyConn.ProxyHeader(); proxyHeader != nil {
		if proxyHeader.SourceAddr != nil {
			remoteAddr = proxyHeader.SourceAddr
		}

		tlvs, err := proxyHeader.TLVs()
		if err != nil {
			conn.Close()
			return err
		}
		for _, tlv := range tlvs {
			switch tlv.Type {
			case proxyproto.PP2_TYPE_ALPN:
				proto = string(tlv.Value)
			case proxyproto.PP2_TYPE_SSL:
				tlsState = parseSSLTLV(tlv)
			}
		}
	}
	conn = proxyConn

	conn = &Conn{
		Conn:       conn,
		proto:      proto,
		tlsState:   tlsState,
		remoteAddr: remoteAddr,
	}

	switch proto {
	case "h2", "h2c":
		defer conn.Close()
		opts := http2.ServeConnOpts{
			Context: conn.(*Conn).Context(context.Background()),
			Handler: ln,
		}
		ln.h2Server.ServeConn(conn, &opts)
		return nil
	case "", "http/1.0", "http/1.1":
		return ln.h1Listener.ServeConn(conn)
	default:
		conn.Close()
		return fmt.Errorf("unsupported protocol %q", proto)
	}
}

func (ln *Listener) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	r.TLS = contextTLSState(r.Context())

	if r.TLS == nil && !ln.Insecure {
		http.Redirect(w, r, "https://"+r.Host+r.RequestURI, http.StatusMovedPermanently)
		return
	}

	ln.Mux.ServeHTTP(w, r)
}

func parseSSLTLV(tlv proxyproto.TLV) *tls.ConnectionState {
	ssl, err := tlvparse.SSL(tlv)
	if err != nil {
		log.Printf("failed to parse PROXY SSL TLV: %v", err)
		return nil
	}
	if !ssl.ClientSSL() {
		return nil
	}
	// TODO: parse PP2_SUBTYPE_SSL_VERSION, PP2_SUBTYPE_SSL_CIPHER,
	// PP2_SUBTYPE_SSL_SIG_ALG, PP2_SUBTYPE_SSL_KEY_ALG
	return &tls.ConnectionState{}
}

type Conn struct {
	net.Conn
	proto      string
	tlsState   *tls.ConnectionState
	remoteAddr net.Addr
}

func (c *Conn) Context(ctx context.Context) context.Context {
	ctx = context.WithValue(ctx, contextKeyProtocol, c.proto)
	ctx = context.WithValue(ctx, contextKeyTLSState, c.tlsState)
	return ctx
}

func (c *Conn) RemoteAddr() net.Addr {
	return c.remoteAddr
}

var errPipeListenerClosed = fmt.Errorf("pipe listener closed")

// pipeListener is a hack to workaround the lack of http.Server.ServeConn.
// See: https://github.com/golang/go/issues/36673
type pipeListener struct {
	ch     chan net.Conn
	closed bool
	mu     sync.Mutex
}

func newPipeListener() *pipeListener {
	return &pipeListener{
		ch: make(chan net.Conn, 64),
	}
}

func (ln *pipeListener) Accept() (net.Conn, error) {
	conn, ok := <-ln.ch
	if !ok {
		return nil, errPipeListenerClosed
	}
	return conn, nil
}

func (ln *pipeListener) Close() error {
	ln.mu.Lock()
	defer ln.mu.Unlock()

	if ln.closed {
		return errPipeListenerClosed
	}
	ln.closed = true
	close(ln.ch)
	return nil
}

func (ln *pipeListener) ServeConn(conn net.Conn) error {
	ln.mu.Lock()
	defer ln.mu.Unlock()

	if ln.closed {
		return errPipeListenerClosed
	}
	ln.ch <- conn
	return nil
}

func (ln *pipeListener) Addr() net.Addr {
	return pipeAddr{}
}

type pipeAddr struct{}

func (pipeAddr) Network() string {
	return "pipe"
}

func (pipeAddr) String() string {
	return "pipe"
}