2019-06-30 17:07:58 -05: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-03-26 13:00:54 -05:00
|
|
|
package caddyhttp
|
|
|
|
|
|
|
|
import (
|
2019-08-09 13:05:47 -05:00
|
|
|
"bytes"
|
|
|
|
"encoding/json"
|
|
|
|
"io"
|
2019-05-20 16:46:34 -05:00
|
|
|
weakrand "math/rand"
|
2019-03-26 16:45:51 -05:00
|
|
|
"net"
|
|
|
|
"net/http"
|
|
|
|
"strconv"
|
|
|
|
"time"
|
2019-03-26 13:00:54 -05:00
|
|
|
|
2019-07-02 13:37:06 -05:00
|
|
|
"github.com/caddyserver/caddy/v2"
|
2019-03-26 13:00:54 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
func init() {
|
2019-05-20 16:46:34 -05:00
|
|
|
weakrand.Seed(time.Now().UnixNano())
|
2019-04-25 14:54:48 -05:00
|
|
|
|
2020-03-15 22:28:42 -05:00
|
|
|
err := caddy.RegisterModule(tlsPlaceholderWrapper{})
|
2019-03-26 13:00:54 -05:00
|
|
|
if err != nil {
|
2019-10-28 15:39:37 -05:00
|
|
|
caddy.Log().Fatal(err.Error())
|
2019-03-26 13:00:54 -05:00
|
|
|
}
|
2019-05-07 10:56:13 -05:00
|
|
|
}
|
|
|
|
|
2019-05-20 11:59:20 -05:00
|
|
|
// RequestMatcher is a type that can match to a request.
|
2019-07-09 13:58:39 -05:00
|
|
|
// A route matcher MUST NOT modify the request, with the
|
|
|
|
// only exception being its context.
|
2019-05-20 11:59:20 -05:00
|
|
|
type RequestMatcher interface {
|
2019-03-31 21:41:29 -05:00
|
|
|
Match(*http.Request) bool
|
|
|
|
}
|
|
|
|
|
|
|
|
// Handler is like http.Handler except ServeHTTP may return an error.
|
|
|
|
//
|
|
|
|
// If any handler encounters an error, it should be returned for proper
|
|
|
|
// handling. Return values should be propagated down the middleware chain
|
2019-07-09 13:58:39 -05:00
|
|
|
// by returning it unchanged. Returned errors should not be re-wrapped
|
|
|
|
// if they are already HandlerError values.
|
2019-03-31 21:41:29 -05:00
|
|
|
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-07-09 13:58:39 -05:00
|
|
|
// Middleware chains one Handler to the next by being passed
|
|
|
|
// the next Handler in the chain.
|
http: Change routes to sequential matcher evaluation (#2967)
Previously, all matchers in a route would be evaluated before any
handlers were executed, and a composite route of the matching routes
would be created. This made rewrites especially tricky, since the only
way to defer later matchers' evaluation was to wrap them in a subroute,
or to invoke a "rehandle" which often caused bugs.
Instead, this new sequential design evaluates each route's matchers then
its handlers in lock-step; matcher-handlers-matcher-handlers...
If the first matching route consists of a rewrite, then the second route
will be evaluated against the rewritten request, rather than the original
one, and so on.
This should do away with any need for rehandling.
I've also taken this opportunity to avoid adding new values to the
request context in the handler chain, as this creates a copy of the
Request struct, which may possibly lead to bugs like it has in the past
(see PR #1542, PR #1481, and maybe issue #2463). We now add all the
expected context values in the top-level handler at the server, then
any new values can be added to the variable table via the VarsCtxKey
context key, or just the GetVar/SetVar functions. In particular, we are
using this facility to convey dial information in the reverse proxy.
Had to be careful in one place as the middleware compilation logic has
changed, and moved a bit. We no longer compile a middleware chain per-
request; instead, we can compile it at provision-time, and defer only the
evaluation of matchers to request-time, which should slightly improve
performance. Doing this, however, we take advantage of multiple function
closures, and we also changed the use of HandlerFunc (function pointer)
to Handler (interface)... this led to a situation where, if we aren't
careful, allows one request routed a certain way to permanently change
the "next" handler for all/most other requests! We avoid this by making
a copy of the interface value (which is a lightweight pointer copy) and
using exclusively that within our wrapped handlers. This way, the
original stack frame is preserved in a "read-only" fashion. The comments
in the code describe this phenomenon.
This may very well be a breaking change for some configurations, however
I do not expect it to impact many people. I will make it clear in the
release notes that this change has occurred.
2020-01-09 12:00:13 -05:00
|
|
|
type Middleware func(Handler) Handler
|
2019-07-09 13:58:39 -05:00
|
|
|
|
|
|
|
// MiddlewareHandler is like Handler except it takes as a third
|
|
|
|
// argument the next handler in the chain. The next handler will
|
|
|
|
// never be nil, but may be a no-op handler if this is the last
|
|
|
|
// handler in the chain. Handlers which act as middleware should
|
|
|
|
// call the next handler's ServeHTTP method so as to propagate
|
|
|
|
// the request down the chain properly. Handlers which act as
|
|
|
|
// responders (content origins) need not invoke the next handler,
|
|
|
|
// since the last handler in the chain should be the first to
|
|
|
|
// write the response.
|
|
|
|
type MiddlewareHandler interface {
|
|
|
|
ServeHTTP(http.ResponseWriter, *http.Request, Handler) error
|
|
|
|
}
|
|
|
|
|
|
|
|
// emptyHandler is used as a no-op handler.
|
http: Change routes to sequential matcher evaluation (#2967)
Previously, all matchers in a route would be evaluated before any
handlers were executed, and a composite route of the matching routes
would be created. This made rewrites especially tricky, since the only
way to defer later matchers' evaluation was to wrap them in a subroute,
or to invoke a "rehandle" which often caused bugs.
Instead, this new sequential design evaluates each route's matchers then
its handlers in lock-step; matcher-handlers-matcher-handlers...
If the first matching route consists of a rewrite, then the second route
will be evaluated against the rewritten request, rather than the original
one, and so on.
This should do away with any need for rehandling.
I've also taken this opportunity to avoid adding new values to the
request context in the handler chain, as this creates a copy of the
Request struct, which may possibly lead to bugs like it has in the past
(see PR #1542, PR #1481, and maybe issue #2463). We now add all the
expected context values in the top-level handler at the server, then
any new values can be added to the variable table via the VarsCtxKey
context key, or just the GetVar/SetVar functions. In particular, we are
using this facility to convey dial information in the reverse proxy.
Had to be careful in one place as the middleware compilation logic has
changed, and moved a bit. We no longer compile a middleware chain per-
request; instead, we can compile it at provision-time, and defer only the
evaluation of matchers to request-time, which should slightly improve
performance. Doing this, however, we take advantage of multiple function
closures, and we also changed the use of HandlerFunc (function pointer)
to Handler (interface)... this led to a situation where, if we aren't
careful, allows one request routed a certain way to permanently change
the "next" handler for all/most other requests! We avoid this by making
a copy of the interface value (which is a lightweight pointer copy) and
using exclusively that within our wrapped handlers. This way, the
original stack frame is preserved in a "read-only" fashion. The comments
in the code describe this phenomenon.
This may very well be a breaking change for some configurations, however
I do not expect it to impact many people. I will make it clear in the
release notes that this change has occurred.
2020-01-09 12:00:13 -05:00
|
|
|
var emptyHandler Handler = HandlerFunc(func(http.ResponseWriter, *http.Request) error { return nil })
|
2019-04-11 21:42:55 -05:00
|
|
|
|
2020-02-20 17:00:30 -05:00
|
|
|
// An implicit suffix middleware that, if reached, sets the StatusCode to the
|
|
|
|
// error stored in the ErrorCtxKey. This is to prevent situations where the
|
|
|
|
// Error chain does not actually handle the error (for instance, it matches only
|
|
|
|
// on some errors). See #3053
|
|
|
|
var errorEmptyHandler Handler = HandlerFunc(func(w http.ResponseWriter, r *http.Request) error {
|
|
|
|
httpError := r.Context().Value(ErrorCtxKey)
|
|
|
|
if handlerError, ok := httpError.(HandlerError); ok {
|
|
|
|
w.WriteHeader(handlerError.StatusCode)
|
|
|
|
} else {
|
|
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
})
|
|
|
|
|
2019-08-09 13:05:47 -05:00
|
|
|
// WeakString is a type that unmarshals any JSON value
|
|
|
|
// as a string literal, with the following exceptions:
|
2019-12-10 15:36:46 -05:00
|
|
|
//
|
|
|
|
// 1. actual string values are decoded as strings; and
|
|
|
|
// 2. null is decoded as empty string;
|
|
|
|
//
|
2019-08-09 13:05:47 -05:00
|
|
|
// and provides methods for getting the value as various
|
|
|
|
// primitive types. However, using this type removes any
|
|
|
|
// type safety as far as deserializing JSON is concerned.
|
|
|
|
type WeakString string
|
|
|
|
|
|
|
|
// UnmarshalJSON satisfies json.Unmarshaler according to
|
|
|
|
// this type's documentation.
|
|
|
|
func (ws *WeakString) UnmarshalJSON(b []byte) error {
|
|
|
|
if len(b) == 0 {
|
|
|
|
return io.EOF
|
|
|
|
}
|
|
|
|
if b[0] == byte('"') && b[len(b)-1] == byte('"') {
|
|
|
|
var s string
|
|
|
|
err := json.Unmarshal(b, &s)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
*ws = WeakString(s)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
if bytes.Equal(b, []byte("null")) {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
*ws = WeakString(b)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// MarshalJSON marshals was a boolean if true or false,
|
|
|
|
// a number if an integer, or a string otherwise.
|
|
|
|
func (ws WeakString) MarshalJSON() ([]byte, error) {
|
|
|
|
if ws == "true" {
|
|
|
|
return []byte("true"), nil
|
|
|
|
}
|
|
|
|
if ws == "false" {
|
|
|
|
return []byte("false"), nil
|
|
|
|
}
|
|
|
|
if num, err := strconv.Atoi(string(ws)); err == nil {
|
|
|
|
return json.Marshal(num)
|
|
|
|
}
|
|
|
|
return json.Marshal(string(ws))
|
|
|
|
}
|
|
|
|
|
|
|
|
// Int returns ws as an integer. If ws is not an
|
|
|
|
// integer, 0 is returned.
|
|
|
|
func (ws WeakString) Int() int {
|
|
|
|
num, _ := strconv.Atoi(string(ws))
|
|
|
|
return num
|
|
|
|
}
|
|
|
|
|
|
|
|
// Float64 returns ws as a float64. If ws is not a
|
|
|
|
// float value, the zero value is returned.
|
|
|
|
func (ws WeakString) Float64() float64 {
|
|
|
|
num, _ := strconv.ParseFloat(string(ws), 64)
|
|
|
|
return num
|
|
|
|
}
|
|
|
|
|
|
|
|
// Bool returns ws as a boolean. If ws is not a
|
|
|
|
// boolean, false is returned.
|
|
|
|
func (ws WeakString) Bool() bool {
|
|
|
|
return string(ws) == "true"
|
|
|
|
}
|
|
|
|
|
|
|
|
// String returns ws as a string.
|
|
|
|
func (ws WeakString) String() string {
|
|
|
|
return string(ws)
|
|
|
|
}
|
|
|
|
|
2019-10-15 15:07:10 -05:00
|
|
|
// CopyHeader copies HTTP headers by completely
|
|
|
|
// replacing dest with src. (This allows deletions
|
|
|
|
// to be propagated, assuming src started as a
|
|
|
|
// consistent copy of dest.)
|
|
|
|
func CopyHeader(dest, src http.Header) {
|
|
|
|
for field := range dest {
|
|
|
|
delete(dest, field)
|
|
|
|
}
|
|
|
|
for field, val := range src {
|
|
|
|
dest[field] = val
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-09-02 23:01:02 -05:00
|
|
|
// StatusCodeMatches returns true if a real HTTP status code matches
|
|
|
|
// the configured status code, which may be either a real HTTP status
|
|
|
|
// code or an integer representing a class of codes (e.g. 4 for all
|
|
|
|
// 4xx statuses).
|
|
|
|
func StatusCodeMatches(actual, configured int) bool {
|
|
|
|
if actual == configured {
|
|
|
|
return true
|
|
|
|
}
|
2020-01-13 18:16:20 -05:00
|
|
|
if configured < 100 &&
|
|
|
|
actual >= configured*100 &&
|
|
|
|
actual < (configured+1)*100 {
|
2019-09-02 23:01:02 -05:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2020-03-15 22:26:17 -05:00
|
|
|
// tlsPlaceholderWrapper is a no-op listener wrapper that marks
|
|
|
|
// where the TLS listener should be in a chain of listener wrappers.
|
|
|
|
type tlsPlaceholderWrapper struct{}
|
|
|
|
|
|
|
|
func (tlsPlaceholderWrapper) CaddyModule() caddy.ModuleInfo {
|
|
|
|
return caddy.ModuleInfo{
|
|
|
|
ID: "caddy.listeners.tls",
|
|
|
|
New: func() caddy.Module { return new(tlsPlaceholderWrapper) },
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (tlsPlaceholderWrapper) WrapListener(ln net.Listener) net.Listener { return ln }
|
|
|
|
|
2019-05-07 10:56:13 -05:00
|
|
|
const (
|
|
|
|
// DefaultHTTPPort is the default port for HTTP.
|
|
|
|
DefaultHTTPPort = 80
|
|
|
|
|
|
|
|
// DefaultHTTPSPort is the default port for HTTPS.
|
|
|
|
DefaultHTTPSPort = 443
|
|
|
|
)
|
|
|
|
|
2020-03-15 22:28:42 -05:00
|
|
|
// Interface guard
|
|
|
|
var _ caddy.ListenerWrapper = (*tlsPlaceholderWrapper)(nil)
|