2019-03-26 13:00:54 -05:00
|
|
|
package caddyhttp
|
|
|
|
|
|
|
|
import (
|
2019-03-26 20:42:52 -05:00
|
|
|
"context"
|
2019-04-25 14:54:48 -05:00
|
|
|
"crypto/tls"
|
2019-03-26 16:45:51 -05:00
|
|
|
"fmt"
|
2019-03-26 13:00:54 -05:00
|
|
|
"log"
|
2019-04-11 21:42:55 -05:00
|
|
|
mathrand "math/rand"
|
2019-03-26 16:45:51 -05:00
|
|
|
"net"
|
|
|
|
"net/http"
|
|
|
|
"strconv"
|
|
|
|
"strings"
|
|
|
|
"time"
|
2019-03-26 13:00:54 -05:00
|
|
|
|
|
|
|
"bitbucket.org/lightcodelabs/caddy2"
|
2019-04-25 14:54:48 -05:00
|
|
|
"bitbucket.org/lightcodelabs/caddy2/modules/caddytls"
|
|
|
|
"github.com/mholt/certmagic"
|
2019-03-26 13:00:54 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
func init() {
|
2019-04-25 14:54:48 -05:00
|
|
|
mathrand.Seed(time.Now().UnixNano())
|
|
|
|
|
2019-03-26 13:00:54 -05:00
|
|
|
err := caddy2.RegisterModule(caddy2.Module{
|
|
|
|
Name: "http",
|
2019-03-26 16:45:51 -05:00
|
|
|
New: func() (interface{}, error) { return new(httpModuleConfig), nil },
|
2019-03-26 13:00:54 -05:00
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
type httpModuleConfig struct {
|
2019-04-25 14:54:48 -05:00
|
|
|
Servers map[string]*httpServerConfig `json:"servers"`
|
2019-03-26 20:42:52 -05:00
|
|
|
|
|
|
|
servers []*http.Server
|
2019-03-26 13:00:54 -05:00
|
|
|
}
|
|
|
|
|
2019-04-25 14:54:48 -05:00
|
|
|
func (hc *httpModuleConfig) Provision() error {
|
2019-03-31 21:41:29 -05:00
|
|
|
// TODO: Either prevent overlapping listeners on different servers, or combine them into one
|
2019-03-26 16:45:51 -05:00
|
|
|
for _, srv := range hc.Servers {
|
2019-04-11 21:42:55 -05:00
|
|
|
err := srv.Routes.setup()
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("setting up server routes: %v", err)
|
|
|
|
}
|
|
|
|
err = srv.Errors.Routes.setup()
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("setting up server error handling routes: %v", err)
|
2019-03-31 21:41:29 -05:00
|
|
|
}
|
2019-04-25 14:54:48 -05:00
|
|
|
}
|
2019-03-31 21:41:29 -05:00
|
|
|
|
2019-04-25 14:54:48 -05:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (hc *httpModuleConfig) Start(handle caddy2.Handle) error {
|
|
|
|
err := hc.automaticHTTPS(handle)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("enabling automatic HTTPS: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
for srvName, srv := range hc.Servers {
|
2019-03-26 20:42:52 -05:00
|
|
|
s := &http.Server{
|
2019-03-26 16:45:51 -05:00
|
|
|
ReadTimeout: time.Duration(srv.ReadTimeout),
|
|
|
|
ReadHeaderTimeout: time.Duration(srv.ReadHeaderTimeout),
|
2019-03-31 21:41:29 -05:00
|
|
|
Handler: srv,
|
2019-03-26 16:45:51 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
for _, lnAddr := range srv.Listen {
|
2019-03-31 21:41:29 -05:00
|
|
|
network, addrs, err := parseListenAddr(lnAddr)
|
2019-03-26 16:45:51 -05:00
|
|
|
if err != nil {
|
2019-04-25 14:54:48 -05:00
|
|
|
return fmt.Errorf("%s: parsing listen address '%s': %v", srvName, lnAddr, err)
|
2019-03-26 16:45:51 -05:00
|
|
|
}
|
|
|
|
for _, addr := range addrs {
|
2019-03-31 21:41:29 -05:00
|
|
|
ln, err := caddy2.Listen(network, addr)
|
2019-03-26 16:45:51 -05:00
|
|
|
if err != nil {
|
2019-03-31 21:41:29 -05:00
|
|
|
return fmt.Errorf("%s: listening on %s: %v", network, addr, err)
|
2019-03-26 16:45:51 -05:00
|
|
|
}
|
2019-04-25 14:54:48 -05:00
|
|
|
|
|
|
|
// enable HTTP/2 by default
|
|
|
|
for _, pol := range srv.TLSConnPolicies {
|
|
|
|
if len(pol.ALPN) == 0 {
|
|
|
|
pol.ALPN = append(pol.ALPN, defaultALPN...)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// enable TLS
|
|
|
|
if len(srv.TLSConnPolicies) > 0 {
|
|
|
|
tlsCfg, err := srv.TLSConnPolicies.TLSConfig(handle)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("%s/%s: making TLS configuration: %v", network, addr, err)
|
|
|
|
}
|
|
|
|
ln = tls.NewListener(ln, tlsCfg)
|
|
|
|
}
|
|
|
|
|
2019-03-26 16:45:51 -05:00
|
|
|
go s.Serve(ln)
|
2019-03-27 13:36:30 -05:00
|
|
|
hc.servers = append(hc.servers, s)
|
2019-03-26 16:45:51 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2019-04-25 14:54:48 -05:00
|
|
|
func (hc *httpModuleConfig) Stop() error {
|
2019-03-26 20:42:52 -05:00
|
|
|
for _, s := range hc.servers {
|
|
|
|
err := s.Shutdown(context.Background()) // TODO
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2019-04-25 14:54:48 -05:00
|
|
|
func (hc *httpModuleConfig) automaticHTTPS(handle caddy2.Handle) error {
|
2019-04-29 10:22:00 -05:00
|
|
|
tlsAppIface, err := handle.App("tls")
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("getting tls app: %v", err)
|
|
|
|
}
|
|
|
|
tlsApp := tlsAppIface.(*caddytls.TLS)
|
2019-04-25 14:54:48 -05:00
|
|
|
|
|
|
|
for srvName, srv := range hc.Servers {
|
|
|
|
srv.tlsApp = tlsApp
|
|
|
|
|
|
|
|
if srv.DisableAutoHTTPS {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2019-04-29 10:22:00 -05:00
|
|
|
// find all qualifying domain names, de-duplicated
|
2019-04-25 14:54:48 -05:00
|
|
|
domainSet := make(map[string]struct{})
|
|
|
|
for _, route := range srv.Routes {
|
|
|
|
for _, m := range route.matchers {
|
|
|
|
if hm, ok := m.(*matchHost); ok {
|
|
|
|
for _, d := range *hm {
|
|
|
|
if !certmagic.HostQualifies(d) {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
domainSet[d] = struct{}{}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2019-04-29 10:22:00 -05:00
|
|
|
|
|
|
|
if len(domainSet) > 0 {
|
|
|
|
// marshal the domains into a slice
|
|
|
|
var domains []string
|
|
|
|
for d := range domainSet {
|
|
|
|
domains = append(domains, d)
|
|
|
|
}
|
|
|
|
|
|
|
|
// manage their certificates
|
2019-04-25 14:54:48 -05:00
|
|
|
err := tlsApp.Manage(domains)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("%s: managing certificate for %s: %s", srvName, domains, err)
|
|
|
|
}
|
2019-04-29 10:22:00 -05:00
|
|
|
|
|
|
|
// tell the server to use TLS
|
2019-04-25 14:54:48 -05:00
|
|
|
srv.TLSConnPolicies = caddytls.ConnectionPolicies{
|
2019-04-29 10:22:00 -05:00
|
|
|
{ALPN: defaultALPN},
|
2019-04-25 14:54:48 -05:00
|
|
|
}
|
2019-04-29 10:22:00 -05:00
|
|
|
|
|
|
|
// TODO: create HTTP->HTTPS redirects
|
2019-04-25 14:54:48 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
var defaultALPN = []string{"h2", "http/1.1"}
|
|
|
|
|
2019-03-31 21:41:29 -05:00
|
|
|
type httpServerConfig struct {
|
2019-05-04 14:21:20 -05:00
|
|
|
Listen []string `json:"listen"`
|
|
|
|
ReadTimeout caddy2.Duration `json:"read_timeout"`
|
|
|
|
ReadHeaderTimeout caddy2.Duration `json:"read_header_timeout"`
|
|
|
|
HiddenFiles []string `json:"hidden_files"` // TODO:... experimenting with shared/common state
|
|
|
|
Routes routeList `json:"routes"`
|
|
|
|
Errors httpErrorConfig `json:"errors"`
|
|
|
|
TLSConnPolicies caddytls.ConnectionPolicies `json:"tls_connection_policies"`
|
|
|
|
DisableAutoHTTPS bool `json:"disable_auto_https"`
|
|
|
|
DisableAutoHTTPSRedir bool `json:"disable_auto_https_redir"`
|
2019-04-25 14:54:48 -05:00
|
|
|
|
|
|
|
tlsApp *caddytls.TLS
|
2019-04-11 21:42:55 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
type httpErrorConfig struct {
|
|
|
|
Routes routeList `json:"routes"`
|
|
|
|
// TODO: some way to configure the logging of errors, probably? standardize the logging configuration first.
|
2019-03-31 21:41:29 -05:00
|
|
|
}
|
|
|
|
|
2019-04-11 21:42:55 -05:00
|
|
|
// ServeHTTP is the entry point for all HTTP requests.
|
2019-03-31 21:41:29 -05:00
|
|
|
func (s httpServerConfig) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
2019-04-25 14:54:48 -05:00
|
|
|
if s.tlsApp.HandleHTTPChallenge(w, r) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-05-04 14:21:20 -05:00
|
|
|
// set up the replacer
|
|
|
|
repl := &Replacer{req: r, resp: w, custom: make(map[string]string)}
|
|
|
|
ctx := context.WithValue(r.Context(), ReplacerCtxKey, repl)
|
|
|
|
r = r.WithContext(ctx)
|
|
|
|
|
|
|
|
// build and execute the main middleware chain
|
2019-04-11 21:42:55 -05:00
|
|
|
stack := s.Routes.buildMiddlewareChain(w, r)
|
|
|
|
err := executeMiddlewareChain(w, r, stack)
|
|
|
|
if err != nil {
|
|
|
|
// add the error value to the request context so
|
|
|
|
// it can be accessed by error handlers
|
|
|
|
c := context.WithValue(r.Context(), ErrorCtxKey, err)
|
|
|
|
r = r.WithContext(c)
|
|
|
|
|
|
|
|
if len(s.Errors.Routes) == 0 {
|
|
|
|
// TODO: implement a default error handler?
|
|
|
|
log.Printf("[ERROR] %s", err)
|
|
|
|
} else {
|
|
|
|
errStack := s.Errors.Routes.buildMiddlewareChain(w, r)
|
|
|
|
err := executeMiddlewareChain(w, r, errStack)
|
|
|
|
if err != nil {
|
|
|
|
// TODO: what should we do if the error handler has an error?
|
|
|
|
log.Printf("[ERROR] handling error: %v", err)
|
2019-03-31 21:41:29 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2019-04-11 21:42:55 -05:00
|
|
|
}
|
2019-03-31 21:41:29 -05:00
|
|
|
|
2019-04-11 21:42:55 -05:00
|
|
|
// executeMiddlewareChain executes stack with w and r. This function handles
|
|
|
|
// the special ErrRehandle error value, which reprocesses requests through
|
|
|
|
// the stack again. Any error value returned from this function would be an
|
|
|
|
// actual error that needs to be handled.
|
|
|
|
func executeMiddlewareChain(w http.ResponseWriter, r *http.Request, stack Handler) error {
|
|
|
|
const maxRehandles = 3
|
|
|
|
var err error
|
|
|
|
for i := 0; i < maxRehandles; i++ {
|
|
|
|
err = stack.ServeHTTP(w, r)
|
|
|
|
if err != ErrRehandle {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
if i == maxRehandles-1 {
|
|
|
|
return fmt.Errorf("too many rehandles")
|
2019-03-31 21:41:29 -05:00
|
|
|
}
|
|
|
|
}
|
2019-04-11 21:42:55 -05:00
|
|
|
return err
|
2019-03-31 21:41:29 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
// RouteMatcher is a type that can match to a request.
|
|
|
|
// A route matcher MUST NOT modify the request.
|
|
|
|
type RouteMatcher interface {
|
|
|
|
Match(*http.Request) bool
|
|
|
|
}
|
|
|
|
|
|
|
|
// Middleware chains one Handler to the next by being passed
|
|
|
|
// the next Handler in the chain.
|
|
|
|
type Middleware func(HandlerFunc) HandlerFunc
|
|
|
|
|
|
|
|
// MiddlewareHandler is a Handler that includes a reference
|
|
|
|
// to the next middleware handler in the chain. Middleware
|
|
|
|
// handlers MUST NOT call Write() or WriteHeader() on the
|
|
|
|
// response writer; doing so will panic. See Handler godoc
|
|
|
|
// for more information.
|
|
|
|
type MiddlewareHandler interface {
|
|
|
|
ServeHTTP(http.ResponseWriter, *http.Request, Handler) error
|
|
|
|
}
|
|
|
|
|
|
|
|
// Handler is like http.Handler except ServeHTTP may return an error.
|
|
|
|
//
|
|
|
|
// Middleware and responder handlers both implement this method.
|
|
|
|
// Middleware must not call Write or WriteHeader on the ResponseWriter;
|
|
|
|
// doing so will cause a panic. Responders should write to the response
|
|
|
|
// if there was not an error.
|
|
|
|
//
|
|
|
|
// If any handler encounters an error, it should be returned for proper
|
|
|
|
// handling. Return values should be propagated down the middleware chain
|
|
|
|
// by returning it unchanged.
|
|
|
|
type Handler interface {
|
|
|
|
ServeHTTP(http.ResponseWriter, *http.Request) error
|
|
|
|
}
|
|
|
|
|
|
|
|
// HandlerFunc is a convenience type like http.HandlerFunc.
|
|
|
|
type HandlerFunc func(http.ResponseWriter, *http.Request) error
|
|
|
|
|
|
|
|
// ServeHTTP implements the Handler interface.
|
|
|
|
func (f HandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request) error {
|
|
|
|
return f(w, r)
|
|
|
|
}
|
|
|
|
|
2019-04-11 21:42:55 -05:00
|
|
|
// emptyHandler is used as a no-op handler, which is
|
|
|
|
// sometimes better than a nil Handler pointer.
|
|
|
|
var emptyHandler HandlerFunc = func(w http.ResponseWriter, r *http.Request) error { return nil }
|
|
|
|
|
2019-03-31 21:41:29 -05:00
|
|
|
func parseListenAddr(a string) (network string, addrs []string, err error) {
|
|
|
|
network = "tcp"
|
2019-03-26 20:42:52 -05:00
|
|
|
if idx := strings.Index(a, "/"); idx >= 0 {
|
2019-03-31 21:41:29 -05:00
|
|
|
network = strings.ToLower(strings.TrimSpace(a[:idx]))
|
2019-03-26 20:42:52 -05:00
|
|
|
a = a[idx+1:]
|
2019-03-26 16:45:51 -05:00
|
|
|
}
|
|
|
|
var host, port string
|
|
|
|
host, port, err = net.SplitHostPort(a)
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
ports := strings.SplitN(port, "-", 2)
|
|
|
|
if len(ports) == 1 {
|
|
|
|
ports = append(ports, ports[0])
|
|
|
|
}
|
|
|
|
var start, end int
|
|
|
|
start, err = strconv.Atoi(ports[0])
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
end, err = strconv.Atoi(ports[1])
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if end < start {
|
|
|
|
err = fmt.Errorf("end port must be greater than start port")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
for p := start; p <= end; p++ {
|
|
|
|
addrs = append(addrs, net.JoinHostPort(host, fmt.Sprintf("%d", p)))
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-03-31 21:41:29 -05:00
|
|
|
type middlewareResponseWriter struct {
|
|
|
|
*ResponseWriterWrapper
|
|
|
|
allowWrites bool
|
2019-03-26 13:00:54 -05:00
|
|
|
}
|
2019-03-31 21:41:29 -05:00
|
|
|
|
|
|
|
func (mrw middlewareResponseWriter) WriteHeader(statusCode int) {
|
|
|
|
if !mrw.allowWrites {
|
|
|
|
panic("WriteHeader: middleware cannot write to the response")
|
|
|
|
}
|
|
|
|
mrw.ResponseWriterWrapper.WriteHeader(statusCode)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (mrw middlewareResponseWriter) Write(b []byte) (int, error) {
|
|
|
|
if !mrw.allowWrites {
|
|
|
|
panic("Write: middleware cannot write to the response")
|
|
|
|
}
|
|
|
|
return mrw.ResponseWriterWrapper.Write(b)
|
|
|
|
}
|
|
|
|
|
2019-05-04 14:21:20 -05:00
|
|
|
const ReplacerCtxKey caddy2.CtxKey = "replacer"
|
|
|
|
|
2019-03-31 21:41:29 -05:00
|
|
|
// Interface guards
|
|
|
|
var _ HTTPInterfaces = middlewareResponseWriter{}
|