From 31841975e7244f51cd08df9c24cd3ee0ac380983 Mon Sep 17 00:00:00 2001
From: ale <ale@incal.net>
Date: Sat, 25 Apr 2020 08:20:03 +0100
Subject: [PATCH] Ensure that all redirects respect the request protocol

---
 node/http.go | 29 +++++++++++++++++++++++------
 1 file changed, 23 insertions(+), 6 deletions(-)

diff --git a/node/http.go b/node/http.go
index a6fe51ea..558a2f15 100644
--- a/node/http.go
+++ b/node/http.go
@@ -195,20 +195,30 @@ func serveRedirect(lb *loadBalancer, mount *pb.Mount, w http.ResponseWriter, r *
 		return
 	}
 
-	targetURL := fmt.Sprintf("http://%s%s", targetAddr, autoradio.MountPathToIcecastPath(mount.Path))
-	sendRedirect(w, r, targetURL)
+	targetURL := url.URL{
+		Scheme: schemeFromRequest(r),
+		Host:   targetAddr,
+		Path:   autoradio.MountPathToIcecastPath(mount.Path),
+	}
+
+	sendRedirect(w, r, targetURL.String())
 }
 
 // Serve a M3U response. This simply points back at the stream
 // redirect handler by dropping the .m3u suffix in the request URL.
 func sendM3U(w http.ResponseWriter, r *http.Request) {
-	// Build a fully qualified URL using the Host header.
-	m3u := fmt.Sprintf("http://%s%s\n", r.Host, strings.TrimSuffix(r.URL.Path, ".m3u"))
+	// Build a fully qualified URL using the Host header from the incoming request.
+	m3url := url.URL{
+		Scheme: schemeFromRequest(r),
+		Host:   r.Host,
+		Path:   strings.TrimSuffix(r.URL.Path, ".m3u"),
+	}
+	m3us := m3url.String()
 
-	w.Header().Set("Content-Length", strconv.Itoa(len(m3u)))
+	w.Header().Set("Content-Length", strconv.Itoa(len(m3us)))
 	w.Header().Set("Content-Type", "audio/x-mpegurl")
 	addDefaultHeaders(w)
-	io.WriteString(w, m3u) //nolint
+	io.WriteString(w, m3us) //nolint
 }
 
 func sendRedirect(w http.ResponseWriter, r *http.Request, targetURL string) {
@@ -231,6 +241,13 @@ func addDefaultHeaders(w http.ResponseWriter) {
 	w.Header().Set("Cache-Control", "no-cache,no-store")
 }
 
+func schemeFromRequest(r *http.Request) string {
+	if r.TLS != nil {
+		return "https"
+	}
+	return "http"
+}
+
 // Parse the templates that are embedded with the binary (in bindata.go).
 func mustParseEmbeddedTemplates() *template.Template {
 	root := template.New("")
-- 
GitLab