From daa4de572e92668e8b40024c641cdd3d9fa6f21c Mon Sep 17 00:00:00 2001
From: Matthew Holt <mholt@users.noreply.github.com>
Date: Thu, 9 Jun 2016 19:12:11 -0600
Subject: [PATCH] Ensure certificate has a non-nil config when caching (fixes
 #875)

Also we change the scheme of the site's address if TLS is enabled and
no other scheme is explicitly set; this makes it appear as "https" when
we print it; otherwise it would show "http" when TLS is turned on
implicitly, and that is confusing/incorrect.
---
 caddyhttp/httpserver/plugin.go | 12 +++++++++++-
 caddytls/certificates.go       |  3 +++
 caddytls/config.go             |  2 +-
 3 files changed, 15 insertions(+), 2 deletions(-)

diff --git a/caddyhttp/httpserver/plugin.go b/caddyhttp/httpserver/plugin.go
index 0e284ba78..07b4a919e 100644
--- a/caddyhttp/httpserver/plugin.go
+++ b/caddyhttp/httpserver/plugin.go
@@ -115,9 +115,19 @@ func (h *httpContext) MakeServers() ([]caddy.Server, error) {
 	// make sure TLS is disabled for explicitly-HTTP sites
 	// (necessary when HTTP address shares a block containing tls)
 	for _, cfg := range h.siteConfigs {
-		if cfg.TLS.Enabled && (cfg.Addr.Port == "80" || cfg.Addr.Scheme == "http") {
+		if !cfg.TLS.Enabled {
+			continue
+		}
+		if cfg.Addr.Port == "80" || cfg.Addr.Scheme == "http" {
 			cfg.TLS.Enabled = false
 			log.Printf("[WARNING] TLS disabled for %s", cfg.Addr)
+		} else if cfg.Addr.Scheme == "" {
+			// set scheme to https ourselves, since TLS is enabled
+			// and it was not explicitly set to something else. this
+			// makes it appear as "https" when we print the list of
+			// running sites; otherwise "http" would be assumed which
+			// is incorrect for this site.
+			cfg.Addr.Scheme = "https"
 		}
 	}
 
diff --git a/caddytls/certificates.go b/caddytls/certificates.go
index b91180ba5..5151d0187 100644
--- a/caddytls/certificates.go
+++ b/caddytls/certificates.go
@@ -205,6 +205,9 @@ func makeCertificate(certPEMBlock, keyPEMBlock []byte) (Certificate, error) {
 //
 // This function is safe for concurrent use.
 func cacheCertificate(cert Certificate) {
+	if cert.Config == nil {
+		cert.Config = new(Config)
+	}
 	certCacheMu.Lock()
 	if _, ok := certCache[""]; !ok {
 		// use as default - must be *appended* to list, or bad things happen!
diff --git a/caddytls/config.go b/caddytls/config.go
index 550da2101..5250ecc32 100644
--- a/caddytls/config.go
+++ b/caddytls/config.go
@@ -17,7 +17,7 @@ type Config struct {
 	// The hostname or class of hostnames this config is
 	// designated for; can contain wildcard characters
 	// according to RFC 6125 ยง6.4.3 - this field MUST
-	// NOT be empty in order for things to work smoothly
+	// be set in order for things to work as expected
 	Hostname string
 
 	// Whether TLS is enabled