2015-03-13 16:37:32 +00:00
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
2015-03-13 16:56:08 +00:00
|
|
|
"crypto/tls"
|
2015-03-13 16:37:32 +00:00
|
|
|
"fmt"
|
|
|
|
"net"
|
|
|
|
)
|
|
|
|
|
|
|
|
// ListenerFactory is the factory function to create a listener.
|
2015-04-04 19:06:41 +00:00
|
|
|
type ListenerFactory func(map[string]string) (net.Listener, map[string]string, error)
|
2015-03-13 16:37:32 +00:00
|
|
|
|
|
|
|
// BuiltinListeners is the list of built-in listener types.
|
|
|
|
var BuiltinListeners = map[string]ListenerFactory{
|
|
|
|
"tcp": tcpListenerFactory,
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewListener creates a new listener of the given type with the given
|
|
|
|
// configuration. The type is looked up in the BuiltinListeners map.
|
2015-04-04 19:06:41 +00:00
|
|
|
func NewListener(t string, config map[string]string) (net.Listener, map[string]string, error) {
|
2015-03-13 16:37:32 +00:00
|
|
|
f, ok := BuiltinListeners[t]
|
|
|
|
if !ok {
|
2015-04-04 19:06:41 +00:00
|
|
|
return nil, nil, fmt.Errorf("unknown listener type: %s", t)
|
2015-03-13 16:37:32 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return f(config)
|
|
|
|
}
|
2015-03-13 16:56:08 +00:00
|
|
|
|
|
|
|
func listenerWrapTLS(
|
2015-04-04 19:06:41 +00:00
|
|
|
ln net.Listener,
|
|
|
|
props map[string]string,
|
|
|
|
config map[string]string) (net.Listener, map[string]string, error) {
|
|
|
|
props["tls"] = "disabled"
|
|
|
|
|
2015-03-13 16:56:08 +00:00
|
|
|
if v, ok := config["tls_disable"]; ok && v != "" {
|
2015-04-04 19:06:41 +00:00
|
|
|
return ln, props, nil
|
2015-03-13 16:56:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
certFile, ok := config["tls_cert_file"]
|
|
|
|
if !ok {
|
2015-04-04 19:06:41 +00:00
|
|
|
return nil, nil, fmt.Errorf("'tls_cert_file' must be set")
|
2015-03-13 16:56:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
keyFile, ok := config["tls_key_file"]
|
|
|
|
if !ok {
|
2015-04-04 19:06:41 +00:00
|
|
|
return nil, nil, fmt.Errorf("'tls_key_file' must be set")
|
2015-03-13 16:56:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
|
|
|
|
if err != nil {
|
2015-04-04 19:06:41 +00:00
|
|
|
return nil, nil, fmt.Errorf("error loading TLS cert: %s", err)
|
2015-03-13 16:56:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
tlsConf := &tls.Config{}
|
|
|
|
tlsConf.Certificates = []tls.Certificate{cert}
|
|
|
|
tlsConf.NextProtos = []string{"http/1.1"}
|
2015-04-13 20:00:01 +00:00
|
|
|
tlsConf.MinVersion = tls.VersionTLS12 // Minimum version is TLS 1.2
|
2015-05-20 23:01:40 +00:00
|
|
|
tlsConf.ClientAuth = tls.RequestClientCert
|
2015-03-13 16:56:08 +00:00
|
|
|
|
|
|
|
ln = tls.NewListener(ln, tlsConf)
|
2015-04-04 19:06:41 +00:00
|
|
|
props["tls"] = "enabled"
|
|
|
|
return ln, props, nil
|
2015-03-13 16:56:08 +00:00
|
|
|
}
|