2014-01-20 21:59:33 +04:00
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/tls"
|
|
|
|
"net"
|
2014-07-05 19:24:23 +04:00
|
|
|
"time"
|
2014-03-14 02:47:27 +04:00
|
|
|
|
|
|
|
"github.com/coreos/etcd/log"
|
2014-01-20 21:59:33 +04:00
|
|
|
)
|
|
|
|
|
2014-03-25 03:49:30 +04:00
|
|
|
// TLSServerConfig generates tls configuration based on TLSInfo
|
|
|
|
// If any error happens, this function will call log.Fatal
|
|
|
|
func TLSServerConfig(info *TLSInfo) *tls.Config {
|
|
|
|
if info.KeyFile == "" || info.CertFile == "" {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
cfg, err := info.ServerConfig()
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal("TLS info error: ", err)
|
|
|
|
}
|
|
|
|
return cfg
|
|
|
|
}
|
|
|
|
|
2014-03-14 02:47:27 +04:00
|
|
|
// NewListener creates a net.Listener
|
2014-03-26 09:51:52 +04:00
|
|
|
// If the given scheme is "https", it will use TLS config to set listener.
|
2014-03-14 02:47:27 +04:00
|
|
|
// If any error happens, this function will call log.Fatal
|
2014-03-25 03:49:30 +04:00
|
|
|
func NewListener(scheme, addr string, cfg *tls.Config) net.Listener {
|
2014-03-14 02:47:27 +04:00
|
|
|
if scheme == "https" {
|
|
|
|
l, err := newTLSListener(addr, cfg)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal("Failed to create TLS listener: ", err)
|
|
|
|
}
|
|
|
|
return l
|
|
|
|
}
|
|
|
|
|
|
|
|
l, err := newListener(addr)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal("Failed to create listener: ", err)
|
|
|
|
}
|
|
|
|
return l
|
|
|
|
}
|
|
|
|
|
|
|
|
func newListener(addr string) (net.Listener, error) {
|
2014-01-20 21:59:33 +04:00
|
|
|
if addr == "" {
|
|
|
|
addr = ":http"
|
|
|
|
}
|
|
|
|
l, e := net.Listen("tcp", addr)
|
|
|
|
if e != nil {
|
|
|
|
return nil, e
|
|
|
|
}
|
|
|
|
return l, nil
|
|
|
|
}
|
|
|
|
|
2014-03-14 02:47:27 +04:00
|
|
|
func newTLSListener(addr string, cfg *tls.Config) (net.Listener, error) {
|
2014-01-20 21:59:33 +04:00
|
|
|
if addr == "" {
|
|
|
|
addr = ":https"
|
|
|
|
}
|
2014-02-01 04:56:15 +04:00
|
|
|
|
2014-01-20 21:59:33 +04:00
|
|
|
conn, err := net.Listen("tcp", addr)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2014-02-04 08:46:27 +04:00
|
|
|
return tls.NewListener(conn, cfg), nil
|
2014-01-20 21:59:33 +04:00
|
|
|
}
|