~ancarda/tls-redirector

ref: e4636a57dc63f656f5b8db32dd716c84038a09be tls-redirector/http.go -rw-r--r-- 2.3 KiB
e4636a57Mark Dain 2.4: Nice looking HTML error pages 8 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package main

import (
	"fmt"
	"html"
	"io/ioutil"
	"net/http"
	"os"
	"strings"

	"git.sr.ht/~ancarda/tls-redirector/fancy"

	"github.com/spf13/afero"
)

type app struct {
	fs               afero.Fs
	acmeChallengeDir string
}

func newApp(acd string) app {
	return app{afero.NewOsFs(), acd}
}

func (a app) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Server", "tls-redirector/"+version)
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	w.Header().Set("X-Content-Type-Options", "nosniff")

	// If we haven't been given a host, just abort.
	if r.Host == "" {
		w.WriteHeader(http.StatusBadRequest)
		w.Write(fancy.ErrorPage(
			"Bad Request",
			fancy.GenericMessage,
			fancy.EmptyHostHeader,
			version,
		))
		return
	}

	// If we've seen a direct request, such as an IP address,
	// we'll discard it now. Not only is it uncommon to see
	// X.509 certificates for IP addresses, it's very likely
	// to be junk traffic (scanning bots). We can save the
	// real web server some effort by dropping it now.
	if isIPAddress(r.Host) {
		w.WriteHeader(http.StatusBadRequest)
		w.Write(fancy.ErrorPage(
			"400 Bad Request",
			fancy.GenericMessage,
			fmt.Sprintf(
				fancy.HostHeaderIsIPTechInfo,
				html.EscapeString(r.Host),
			),
			version,
		))
		return
	}

	// If we are serving the ACME HTTP challenges, handle that here.
	if a.acmeChallengeDir != "" {
		if strings.HasPrefix(r.URL.Path, acmeChallengeURLPrefix) {
			id := strings.TrimPrefix(r.URL.Path,
				acmeChallengeURLPrefix)
			b, err := readFile(a.fs,
				a.acmeChallengeDir+string(os.PathSeparator)+id)
			if err != nil {
				w.WriteHeader(http.StatusNotFound)
				w.Write(fancy.ErrorPage(
					"404 File Not Found",
					fancy.Acme404Message,
					fmt.Sprintf(fancy.Acme404TI,
						html.EscapeString(r.URL.Path)),
					version,
				))
				return
			}

			w.Header().Set("Content-Type", "text/plain")
			w.Write(b)
			return
		}
	}

	// Overwrite the scheme to https:// and redirect.
	// Change host as well as in r.URL, it's empty.
	r.URL.Host = r.Host
	r.URL.Scheme = "https"
	http.Redirect(w, r, r.URL.String(), http.StatusMovedPermanently)
}

func readFile(fs afero.Fs, filename string) ([]byte, error) {
	f, err := fs.Open(filename)
	if err != nil {
		return nil, err
	}
	defer f.Close()

	return ioutil.ReadAll(f)
}