From 6884a8f5277b818b871c0a3f5782e0e4a08a0384 Mon Sep 17 00:00:00 2001 From: Jimmy Zelinskie Date: Thu, 2 Feb 2017 02:01:05 -0500 Subject: [PATCH] frontend/http: add TLS support Fixes #283. --- example_config.yaml | 4 ++++ frontend/http/frontend.go | 17 +++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/example_config.yaml b/example_config.yaml index 9fef721..6f4d6d3 100644 --- a/example_config.yaml +++ b/example_config.yaml @@ -29,6 +29,10 @@ chihaya: # This is only necessary if using a reverse proxy. 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. read_timeout: 5s write_timeout: 5s diff --git a/frontend/http/frontend.go b/frontend/http/frontend.go index 07fb670..86f7610 100644 --- a/frontend/http/frontend.go +++ b/frontend/http/frontend.go @@ -4,6 +4,7 @@ package http import ( "context" + "crypto/tls" "net" "net/http" "time" @@ -55,6 +56,8 @@ type Config struct { RequestTimeout time.Duration `yaml:"request_timeout"` AllowIPSpoofing bool `yaml:"allow_ip_spoofing"` 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. @@ -119,6 +122,20 @@ func (t *Frontend) ListenAndServe() error { } 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 opErr, ok := err.(*net.OpError); !ok || (ok && opErr.Op != "accept") { panic("http: failed to gracefully run HTTP server: " + err.Error())