2019-07-01 01:07:58 +03:00
|
|
|
// Copyright 2015 Matthew Holt and The Caddy Authors
|
|
|
|
//
|
|
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
// you may not use this file except in compliance with the License.
|
|
|
|
// You may obtain a copy of the License at
|
|
|
|
//
|
|
|
|
// http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
//
|
|
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
// See the License for the specific language governing permissions and
|
|
|
|
// limitations under the License.
|
|
|
|
|
2019-04-12 05:42:55 +03:00
|
|
|
package caddyhttp
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
|
2019-07-02 21:37:06 +03:00
|
|
|
"github.com/caddyserver/caddy/v2"
|
2019-04-12 05:42:55 +03:00
|
|
|
)
|
|
|
|
|
2019-05-14 23:14:05 +03:00
|
|
|
// ServerRoute represents a set of matching rules,
|
|
|
|
// middlewares, and a responder for handling HTTP
|
|
|
|
// requests.
|
|
|
|
type ServerRoute struct {
|
2019-05-22 22:13:39 +03:00
|
|
|
Group string `json:"group,omitempty"`
|
|
|
|
MatcherSets []map[string]json.RawMessage `json:"match,omitempty"`
|
|
|
|
Apply []json.RawMessage `json:"apply,omitempty"`
|
|
|
|
Respond json.RawMessage `json:"respond,omitempty"`
|
2019-04-12 05:42:55 +03:00
|
|
|
|
2019-05-22 21:32:36 +03:00
|
|
|
Terminal bool `json:"terminal,omitempty"`
|
2019-04-12 05:42:55 +03:00
|
|
|
|
|
|
|
// decoded values
|
2019-05-22 22:13:39 +03:00
|
|
|
matcherSets []MatcherSet
|
|
|
|
middleware []MiddlewareHandler
|
|
|
|
responder Handler
|
|
|
|
}
|
|
|
|
|
2019-07-05 22:59:30 +03:00
|
|
|
// Empty returns true if the route has all zero/default values.
|
|
|
|
func (sr ServerRoute) Empty() bool {
|
|
|
|
return len(sr.MatcherSets) == 0 &&
|
|
|
|
len(sr.Apply) == 0 &&
|
|
|
|
len(sr.Respond) == 0 &&
|
|
|
|
len(sr.matcherSets) == 0 &&
|
|
|
|
len(sr.middleware) == 0 &&
|
|
|
|
sr.responder == nil &&
|
|
|
|
!sr.Terminal &&
|
|
|
|
sr.Group == ""
|
|
|
|
}
|
|
|
|
|
2019-05-22 22:13:39 +03:00
|
|
|
func (sr ServerRoute) anyMatcherSetMatches(r *http.Request) bool {
|
|
|
|
for _, ms := range sr.matcherSets {
|
|
|
|
if ms.Match(r) {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
2019-05-23 23:42:14 +03:00
|
|
|
// if no matchers, always match
|
|
|
|
return len(sr.matcherSets) == 0
|
2019-05-22 22:13:39 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// MatcherSet is a set of matchers which
|
|
|
|
// must all match in order for the request
|
|
|
|
// to be matched successfully.
|
|
|
|
type MatcherSet []RequestMatcher
|
|
|
|
|
|
|
|
// Match returns true if the request matches all
|
|
|
|
// matchers in mset.
|
|
|
|
func (mset MatcherSet) Match(r *http.Request) bool {
|
|
|
|
for _, m := range mset {
|
|
|
|
if !m.Match(r) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return true
|
2019-04-12 05:42:55 +03:00
|
|
|
}
|
|
|
|
|
2019-05-14 23:14:05 +03:00
|
|
|
// RouteList is a list of server routes that can
|
|
|
|
// create a middleware chain.
|
|
|
|
type RouteList []ServerRoute
|
2019-04-12 05:42:55 +03:00
|
|
|
|
2019-05-14 23:14:05 +03:00
|
|
|
// Provision sets up all the routes by loading the modules.
|
2019-06-14 20:58:28 +03:00
|
|
|
func (routes RouteList) Provision(ctx caddy.Context) error {
|
2019-05-14 23:14:05 +03:00
|
|
|
for i, route := range routes {
|
|
|
|
// matchers
|
2019-05-22 22:13:39 +03:00
|
|
|
for _, matcherSet := range route.MatcherSets {
|
|
|
|
var matchers MatcherSet
|
|
|
|
for modName, rawMsg := range matcherSet {
|
|
|
|
val, err := ctx.LoadModule("http.matchers."+modName, rawMsg)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("loading matcher module '%s': %v", modName, err)
|
|
|
|
}
|
|
|
|
matchers = append(matchers, val.(RequestMatcher))
|
2019-05-14 23:14:05 +03:00
|
|
|
}
|
2019-05-22 22:13:39 +03:00
|
|
|
routes[i].matcherSets = append(routes[i].matcherSets, matchers)
|
2019-05-14 23:14:05 +03:00
|
|
|
}
|
2019-05-22 22:13:39 +03:00
|
|
|
routes[i].MatcherSets = nil // allow GC to deallocate - TODO: Does this help?
|
2019-05-14 23:14:05 +03:00
|
|
|
|
|
|
|
// middleware
|
|
|
|
for j, rawMsg := range route.Apply {
|
2019-05-17 01:05:38 +03:00
|
|
|
mid, err := ctx.LoadModuleInline("middleware", "http.middleware", rawMsg)
|
2019-05-14 23:14:05 +03:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("loading middleware module in position %d: %v", j, err)
|
|
|
|
}
|
|
|
|
routes[i].middleware = append(routes[i].middleware, mid.(MiddlewareHandler))
|
|
|
|
}
|
|
|
|
routes[i].Apply = nil // allow GC to deallocate - TODO: Does this help?
|
|
|
|
|
|
|
|
// responder
|
|
|
|
if route.Respond != nil {
|
2019-05-17 01:05:38 +03:00
|
|
|
resp, err := ctx.LoadModuleInline("responder", "http.responders", route.Respond)
|
2019-05-14 23:14:05 +03:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("loading responder module: %v", err)
|
|
|
|
}
|
|
|
|
routes[i].responder = resp.(Handler)
|
|
|
|
}
|
|
|
|
routes[i].Respond = nil // allow GC to deallocate - TODO: Does this help?
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2019-05-21 08:48:43 +03:00
|
|
|
// BuildCompositeRoute creates a chain of handlers by applying all the matching
|
|
|
|
// routes. The returned ResponseWriter should be used instead of rw.
|
|
|
|
func (routes RouteList) BuildCompositeRoute(rw http.ResponseWriter, req *http.Request) (Handler, http.ResponseWriter) {
|
|
|
|
mrw := &middlewareResponseWriter{ResponseWriterWrapper: &ResponseWriterWrapper{rw}}
|
|
|
|
|
2019-04-12 05:42:55 +03:00
|
|
|
if len(routes) == 0 {
|
2019-05-21 08:48:43 +03:00
|
|
|
return emptyHandler, mrw
|
2019-04-12 05:42:55 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
var mid []Middleware
|
|
|
|
var responder Handler
|
2019-05-20 19:59:20 +03:00
|
|
|
groups := make(map[string]struct{})
|
2019-04-12 05:42:55 +03:00
|
|
|
|
|
|
|
for _, route := range routes {
|
2019-05-22 22:13:39 +03:00
|
|
|
// route must match at least one of the matcher sets
|
|
|
|
if !route.anyMatcherSetMatches(req) {
|
|
|
|
continue
|
2019-04-12 05:42:55 +03:00
|
|
|
}
|
2019-05-20 19:59:20 +03:00
|
|
|
|
|
|
|
// if route is part of a group, ensure only
|
|
|
|
// the first matching route in the group is
|
|
|
|
// applied
|
|
|
|
if route.Group != "" {
|
|
|
|
_, ok := groups[route.Group]
|
|
|
|
if ok {
|
|
|
|
// this group has already been satisfied
|
|
|
|
// by a matching route
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
// this matching route satisfies the group
|
|
|
|
groups[route.Group] = struct{}{}
|
|
|
|
}
|
|
|
|
|
|
|
|
// apply the rest of the route
|
2019-04-12 05:42:55 +03:00
|
|
|
for _, m := range route.middleware {
|
2019-05-21 08:48:43 +03:00
|
|
|
// we have to be sure to wrap m outside
|
|
|
|
// of our current scope so that the
|
|
|
|
// reference to this m isn't overwritten
|
|
|
|
// on the next iteration, leaving only
|
|
|
|
// the last middleware in the chain as
|
|
|
|
// the ONLY middleware in the chain!
|
|
|
|
mid = append(mid, wrapMiddleware(m))
|
2019-04-12 05:42:55 +03:00
|
|
|
}
|
|
|
|
if responder == nil {
|
|
|
|
responder = route.responder
|
|
|
|
}
|
2019-05-11 06:07:02 +03:00
|
|
|
if route.Terminal {
|
2019-04-12 05:42:55 +03:00
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// build the middleware stack, with the responder at the end
|
|
|
|
stack := HandlerFunc(func(w http.ResponseWriter, r *http.Request) error {
|
|
|
|
if responder == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
mrw.allowWrites = true
|
|
|
|
return responder.ServeHTTP(w, r)
|
|
|
|
})
|
|
|
|
for i := len(mid) - 1; i >= 0; i-- {
|
|
|
|
stack = mid[i](stack)
|
|
|
|
}
|
|
|
|
|
2019-05-21 08:48:43 +03:00
|
|
|
return stack, mrw
|
|
|
|
}
|
|
|
|
|
|
|
|
// wrapMiddleware wraps m such that it can be correctly
|
2019-06-27 01:03:29 +03:00
|
|
|
// appended to a list of middleware. This separate closure
|
|
|
|
// is necessary so that only the last middleware in a loop
|
|
|
|
// does not become the only middleware of the stack,
|
|
|
|
// repeatedly executed (i.e. it is necessary to keep a
|
|
|
|
// reference to this m outside of the scope of a loop)!
|
2019-05-21 08:48:43 +03:00
|
|
|
func wrapMiddleware(m MiddlewareHandler) Middleware {
|
|
|
|
return func(next HandlerFunc) HandlerFunc {
|
|
|
|
return func(w http.ResponseWriter, r *http.Request) error {
|
|
|
|
// TODO: This is where request tracing could be implemented; also
|
|
|
|
// see below to trace the responder as well
|
|
|
|
// TODO: Trace a diff of the request, would be cool too! see what changed since the last middleware (host, headers, URI...)
|
|
|
|
// TODO: see what the std lib gives us in terms of stack tracing too
|
|
|
|
return m.ServeHTTP(w, r, next)
|
|
|
|
}
|
|
|
|
}
|
2019-04-12 05:42:55 +03:00
|
|
|
}
|
2019-05-20 19:59:20 +03:00
|
|
|
|
|
|
|
type middlewareResponseWriter struct {
|
|
|
|
*ResponseWriterWrapper
|
|
|
|
allowWrites bool
|
|
|
|
}
|
|
|
|
|
|
|
|
func (mrw middlewareResponseWriter) WriteHeader(statusCode int) {
|
|
|
|
if !mrw.allowWrites {
|
2019-06-18 20:13:12 +03:00
|
|
|
// technically, this is not true: middleware can write headers,
|
|
|
|
// but only after the responder handler has returned; either the
|
|
|
|
// responder did nothing with the response (sad face), or the
|
|
|
|
// middleware wrapped the response and deferred the write
|
|
|
|
panic("WriteHeader: middleware cannot write response headers")
|
2019-05-20 19:59:20 +03:00
|
|
|
}
|
|
|
|
mrw.ResponseWriterWrapper.WriteHeader(statusCode)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (mrw middlewareResponseWriter) Write(b []byte) (int, error) {
|
|
|
|
if !mrw.allowWrites {
|
2019-06-18 20:13:12 +03:00
|
|
|
panic("Write: middleware cannot write to the response before responder")
|
2019-05-20 19:59:20 +03:00
|
|
|
}
|
|
|
|
return mrw.ResponseWriterWrapper.Write(b)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Interface guard
|
2019-06-18 20:13:12 +03:00
|
|
|
var _ HTTPInterfaces = (*middlewareResponseWriter)(nil)
|