frontend/http: add TLS support

Fixes #283.
This commit is contained in:
Jimmy Zelinskie 2017-02-02 02:01:05 -05:00
parent 738e496929
commit 6884a8f527
2 changed files with 21 additions and 0 deletions

View file

@ -29,6 +29,10 @@ chihaya:
# This is only necessary if using a reverse proxy. # This is only necessary if using a reverse proxy.
real_ip_header: "x-real-ip" real_ip_header: "x-real-ip"
# The path to the required files to listen via HTTPS.
tls_cert_path: ""
tls_key_path: ""
# The timeout durations for HTTP requests. # The timeout durations for HTTP requests.
read_timeout: 5s read_timeout: 5s
write_timeout: 5s write_timeout: 5s

View file

@ -4,6 +4,7 @@ package http
import ( import (
"context" "context"
"crypto/tls"
"net" "net"
"net/http" "net/http"
"time" "time"
@ -55,6 +56,8 @@ type Config struct {
RequestTimeout time.Duration `yaml:"request_timeout"` RequestTimeout time.Duration `yaml:"request_timeout"`
AllowIPSpoofing bool `yaml:"allow_ip_spoofing"` AllowIPSpoofing bool `yaml:"allow_ip_spoofing"`
RealIPHeader string `yaml:"real_ip_header"` RealIPHeader string `yaml:"real_ip_header"`
TLSCertPath string `yaml:"tls_cert_path"`
TLSKeyPath string `yaml:"tls_key_path"`
} }
// Frontend holds the state of an HTTP BitTorrent Frontend. // Frontend holds the state of an HTTP BitTorrent Frontend.
@ -119,6 +122,20 @@ func (t *Frontend) ListenAndServe() error {
} }
t.grace.SetKeepAlivesEnabled(false) t.grace.SetKeepAlivesEnabled(false)
// If TLS is enabled, create a key pair and add it to the HTTP server.
if t.Config.TLSCertPath != "" && t.Config.TLSKeyPath != "" {
var err error
tlsCfg := &tls.Config{
Certificates: make([]tls.Certificate, 1),
}
tlsCfg.Certificates[0], err = tls.LoadX509KeyPair(t.Config.TLSCertPath, t.Config.TLSKeyPath)
if err != nil {
return err
}
t.grace.Server.TLSConfig = tlsCfg
}
// Start the HTTP server and gracefully handle any network errors.
if err := t.grace.ListenAndServe(); err != nil { if err := t.grace.ListenAndServe(); err != nil {
if opErr, ok := err.(*net.OpError); !ok || (ok && opErr.Op != "accept") { if opErr, ok := err.(*net.OpError); !ok || (ok && opErr.Op != "accept") {
panic("http: failed to gracefully run HTTP server: " + err.Error()) panic("http: failed to gracefully run HTTP server: " + err.Error())