2019-08-21 19:46:35 +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.
|
|
|
|
|
|
|
|
package httpcaddyfile
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
2020-04-02 23:20:30 +03:00
|
|
|
"net"
|
2024-09-25 23:30:56 +03:00
|
|
|
"slices"
|
2020-01-15 23:51:12 +03:00
|
|
|
"sort"
|
2020-04-02 23:20:30 +03:00
|
|
|
"strconv"
|
2020-02-26 07:56:43 +03:00
|
|
|
"strings"
|
2019-08-21 19:46:35 +03:00
|
|
|
|
|
|
|
"github.com/caddyserver/caddy/v2"
|
|
|
|
"github.com/caddyserver/caddy/v2/caddyconfig"
|
|
|
|
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
|
|
|
|
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
|
|
|
|
)
|
|
|
|
|
2024-03-06 22:41:45 +03:00
|
|
|
// defaultDirectiveOrder specifies the default order
|
|
|
|
// to apply directives in HTTP routes. This must only
|
|
|
|
// consist of directives that are included in Caddy's
|
|
|
|
// standard distribution.
|
2020-03-29 04:07:51 +03:00
|
|
|
//
|
2024-03-06 22:41:45 +03:00
|
|
|
// e.g. The 'root' directive goes near the start in
|
|
|
|
// case rewrites or redirects depend on existence of
|
|
|
|
// files, i.e. the file matcher, which must know the
|
|
|
|
// root first.
|
2020-03-29 04:07:51 +03:00
|
|
|
//
|
2024-03-06 22:41:45 +03:00
|
|
|
// e.g. The 'header' directive goes before 'redir' so
|
|
|
|
// that headers can be manipulated before doing redirects.
|
|
|
|
//
|
|
|
|
// e.g. The 'respond' directive is near the end because it
|
|
|
|
// writes a response and terminates the middleware chain.
|
|
|
|
var defaultDirectiveOrder = []string{
|
2022-03-08 22:18:32 +03:00
|
|
|
"tracing",
|
|
|
|
|
2024-03-06 22:41:45 +03:00
|
|
|
// set variables that may be used by other directives
|
2020-06-27 00:12:37 +03:00
|
|
|
"map",
|
2022-03-22 19:47:21 +03:00
|
|
|
"vars",
|
2024-01-13 23:12:43 +03:00
|
|
|
"fs",
|
2020-03-29 04:07:51 +03:00
|
|
|
"root",
|
2024-03-06 03:03:59 +03:00
|
|
|
"log_append",
|
2024-03-07 22:34:01 +03:00
|
|
|
"skip_log", // TODO: deprecated, renamed to log_skip
|
2024-03-06 03:03:59 +03:00
|
|
|
"log_skip",
|
2024-05-11 16:31:44 +03:00
|
|
|
"log_name",
|
2020-03-29 04:07:51 +03:00
|
|
|
|
2020-03-22 18:04:40 +03:00
|
|
|
"header",
|
2022-03-13 09:38:11 +03:00
|
|
|
"copy_response_headers", // only in reverse_proxy's handle_response
|
2020-11-16 21:43:39 +03:00
|
|
|
"request_body",
|
2020-03-22 18:04:40 +03:00
|
|
|
|
2020-01-17 21:38:49 +03:00
|
|
|
"redir",
|
2020-01-17 03:08:52 +03:00
|
|
|
|
2022-01-18 22:17:35 +03:00
|
|
|
// incoming request manipulation
|
|
|
|
"method",
|
2021-08-26 23:31:55 +03:00
|
|
|
"rewrite",
|
2020-03-19 20:51:28 +03:00
|
|
|
"uri",
|
2019-08-21 19:46:35 +03:00
|
|
|
"try_files",
|
2020-01-17 21:38:49 +03:00
|
|
|
|
2020-03-22 18:04:40 +03:00
|
|
|
// middleware handlers; some wrap responses
|
2024-02-12 20:34:23 +03:00
|
|
|
"basicauth", // TODO: deprecated, renamed to basic_auth
|
|
|
|
"basic_auth",
|
2022-05-06 17:50:26 +03:00
|
|
|
"forward_auth",
|
2019-09-12 03:48:37 +03:00
|
|
|
"request_header",
|
2019-08-21 19:46:35 +03:00
|
|
|
"encode",
|
2021-08-26 23:31:55 +03:00
|
|
|
"push",
|
2024-05-13 20:38:18 +03:00
|
|
|
"intercept",
|
2019-08-21 19:46:35 +03:00
|
|
|
"templates",
|
2020-01-17 03:08:52 +03:00
|
|
|
|
2020-07-20 21:28:40 +03:00
|
|
|
// special routing & dispatching directives
|
2023-05-16 18:27:52 +03:00
|
|
|
"invoke",
|
2020-01-17 03:08:52 +03:00
|
|
|
"handle",
|
2020-05-27 00:27:51 +03:00
|
|
|
"handle_path",
|
2020-06-03 18:59:36 +03:00
|
|
|
"route",
|
2020-01-17 03:08:52 +03:00
|
|
|
|
2020-02-17 08:24:20 +03:00
|
|
|
// handlers that typically respond to requests
|
2021-08-26 23:31:55 +03:00
|
|
|
"abort",
|
|
|
|
"error",
|
2022-03-13 09:38:11 +03:00
|
|
|
"copy_response", // only in reverse_proxy's handle_response
|
2019-09-16 20:04:18 +03:00
|
|
|
"respond",
|
2020-09-17 21:01:20 +03:00
|
|
|
"metrics",
|
2019-08-21 19:46:35 +03:00
|
|
|
"reverse_proxy",
|
2019-09-11 21:02:35 +03:00
|
|
|
"php_fastcgi",
|
2019-08-21 19:46:35 +03:00
|
|
|
"file_server",
|
2020-06-03 18:59:36 +03:00
|
|
|
"acme_server",
|
2019-08-21 19:46:35 +03:00
|
|
|
}
|
|
|
|
|
2024-03-06 22:41:45 +03:00
|
|
|
// directiveOrder specifies the order to apply directives
|
|
|
|
// in HTTP routes, after being modified by either the
|
|
|
|
// plugins or by the user via the "order" global option.
|
|
|
|
var directiveOrder = defaultDirectiveOrder
|
|
|
|
|
2019-08-21 19:46:35 +03:00
|
|
|
// RegisterDirective registers a unique directive dir with an
|
|
|
|
// associated unmarshaling (setup) function. When directive dir
|
|
|
|
// is encountered in a Caddyfile, setupFunc will be called to
|
|
|
|
// unmarshal its tokens.
|
|
|
|
func RegisterDirective(dir string, setupFunc UnmarshalFunc) {
|
|
|
|
if _, ok := registeredDirectives[dir]; ok {
|
|
|
|
panic("directive " + dir + " already registered")
|
|
|
|
}
|
|
|
|
registeredDirectives[dir] = setupFunc
|
|
|
|
}
|
|
|
|
|
|
|
|
// RegisterHandlerDirective is like RegisterDirective, but for
|
|
|
|
// directives which specifically output only an HTTP handler.
|
2019-12-13 01:27:09 +03:00
|
|
|
// Directives registered with this function will always have
|
|
|
|
// an optional matcher token as the first argument.
|
2019-08-21 19:46:35 +03:00
|
|
|
func RegisterHandlerDirective(dir string, setupFunc UnmarshalHandlerFunc) {
|
|
|
|
RegisterDirective(dir, func(h Helper) ([]ConfigValue, error) {
|
|
|
|
if !h.Next() {
|
|
|
|
return nil, h.ArgErr()
|
|
|
|
}
|
|
|
|
|
2020-11-20 22:38:16 +03:00
|
|
|
matcherSet, err := h.ExtractMatcherSet()
|
2019-08-21 19:46:35 +03:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
val, err := setupFunc(h)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return h.NewRoute(matcherSet, val), nil
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2024-03-06 22:41:45 +03:00
|
|
|
// RegisterDirectiveOrder registers the default order for a
|
|
|
|
// directive from a plugin.
|
|
|
|
//
|
|
|
|
// This is useful when a plugin has a well-understood place
|
|
|
|
// it should run in the middleware pipeline, and it allows
|
|
|
|
// users to avoid having to define the order themselves.
|
|
|
|
//
|
|
|
|
// The directive dir may be placed in the position relative
|
|
|
|
// to ('before' or 'after') a directive included in Caddy's
|
|
|
|
// standard distribution. It cannot be relative to another
|
|
|
|
// plugin's directive.
|
|
|
|
//
|
|
|
|
// EXPERIMENTAL: This API may change or be removed.
|
|
|
|
func RegisterDirectiveOrder(dir string, position Positional, standardDir string) {
|
|
|
|
// check if directive was already ordered
|
2024-09-25 23:30:56 +03:00
|
|
|
if slices.Contains(directiveOrder, dir) {
|
2024-03-06 22:41:45 +03:00
|
|
|
panic("directive '" + dir + "' already ordered")
|
|
|
|
}
|
|
|
|
|
|
|
|
if position != Before && position != After {
|
|
|
|
panic("the 2nd argument must be either 'before' or 'after', got '" + position + "'")
|
|
|
|
}
|
|
|
|
|
|
|
|
// check if directive exists in standard distribution, since
|
|
|
|
// we can't allow plugins to depend on one another; we can't
|
|
|
|
// guarantee the order that plugins are loaded in.
|
2024-09-25 23:30:56 +03:00
|
|
|
foundStandardDir := slices.Contains(defaultDirectiveOrder, standardDir)
|
2024-03-06 22:41:45 +03:00
|
|
|
if !foundStandardDir {
|
|
|
|
panic("the 3rd argument '" + standardDir + "' must be a directive that exists in the standard distribution of Caddy")
|
|
|
|
}
|
|
|
|
|
|
|
|
// insert directive into proper position
|
|
|
|
newOrder := directiveOrder
|
|
|
|
for i, d := range newOrder {
|
|
|
|
if d != standardDir {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
if position == Before {
|
|
|
|
newOrder = append(newOrder[:i], append([]string{dir}, newOrder[i:]...)...)
|
|
|
|
} else if position == After {
|
|
|
|
newOrder = append(newOrder[:i+1], append([]string{dir}, newOrder[i+1:]...)...)
|
|
|
|
}
|
|
|
|
break
|
|
|
|
}
|
|
|
|
directiveOrder = newOrder
|
|
|
|
}
|
|
|
|
|
2020-05-12 00:00:35 +03:00
|
|
|
// RegisterGlobalOption registers a unique global option opt with
|
|
|
|
// an associated unmarshaling (setup) function. When the global
|
|
|
|
// option opt is encountered in a Caddyfile, setupFunc will be
|
|
|
|
// called to unmarshal its tokens.
|
|
|
|
func RegisterGlobalOption(opt string, setupFunc UnmarshalGlobalFunc) {
|
|
|
|
if _, ok := registeredGlobalOptions[opt]; ok {
|
|
|
|
panic("global option " + opt + " already registered")
|
|
|
|
}
|
|
|
|
registeredGlobalOptions[opt] = setupFunc
|
|
|
|
}
|
|
|
|
|
2019-08-21 19:46:35 +03:00
|
|
|
// Helper is a type which helps setup a value from
|
|
|
|
// Caddyfile tokens.
|
|
|
|
type Helper struct {
|
|
|
|
*caddyfile.Dispenser
|
2020-03-04 19:58:49 +03:00
|
|
|
// State stores intermediate variables during caddyfile adaptation.
|
2022-08-02 23:39:09 +03:00
|
|
|
State map[string]any
|
|
|
|
options map[string]any
|
2020-01-16 21:29:20 +03:00
|
|
|
warnings *[]caddyconfig.Warning
|
|
|
|
matcherDefs map[string]caddy.ModuleMap
|
|
|
|
parentBlock caddyfile.ServerBlock
|
2020-01-17 03:08:52 +03:00
|
|
|
groupCounter counter
|
2019-08-22 00:50:02 +03:00
|
|
|
}
|
|
|
|
|
2019-09-30 18:11:30 +03:00
|
|
|
// Option gets the option keyed by name.
|
2022-08-02 23:39:09 +03:00
|
|
|
func (h Helper) Option(name string) any {
|
2019-09-30 18:11:30 +03:00
|
|
|
return h.options[name]
|
|
|
|
}
|
|
|
|
|
2019-08-22 00:50:02 +03:00
|
|
|
// Caddyfiles returns the list of config files from
|
|
|
|
// which tokens in the current server block were loaded.
|
|
|
|
func (h Helper) Caddyfiles() []string {
|
|
|
|
// first obtain set of names of files involved
|
|
|
|
// in this server block, without duplicates
|
|
|
|
files := make(map[string]struct{})
|
|
|
|
for _, segment := range h.parentBlock.Segments {
|
|
|
|
for _, token := range segment {
|
|
|
|
files[token.File] = struct{}{}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// then convert the set into a slice
|
|
|
|
filesSlice := make([]string, 0, len(files))
|
|
|
|
for file := range files {
|
|
|
|
filesSlice = append(filesSlice, file)
|
|
|
|
}
|
2023-05-17 22:50:32 +03:00
|
|
|
sort.Strings(filesSlice)
|
2019-08-22 00:50:02 +03:00
|
|
|
return filesSlice
|
2019-08-21 19:46:35 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// JSON converts val into JSON. Any errors are added to warnings.
|
2022-08-02 23:39:09 +03:00
|
|
|
func (h Helper) JSON(val any) json.RawMessage {
|
2019-08-21 19:46:35 +03:00
|
|
|
return caddyconfig.JSON(val, h.warnings)
|
|
|
|
}
|
|
|
|
|
2020-01-17 03:08:52 +03:00
|
|
|
// MatcherToken assumes the next argument token is (possibly) a matcher,
|
|
|
|
// and if so, returns the matcher set along with a true value. If the next
|
2019-08-21 19:46:35 +03:00
|
|
|
// token is not a matcher, nil and false is returned. Note that a true
|
|
|
|
// value may be returned with a nil matcher set if it is a catch-all.
|
2019-12-10 23:36:46 +03:00
|
|
|
func (h Helper) MatcherToken() (caddy.ModuleMap, bool, error) {
|
2019-08-21 19:46:35 +03:00
|
|
|
if !h.NextArg() {
|
|
|
|
return nil, false, nil
|
|
|
|
}
|
|
|
|
return matcherSetFromMatcherToken(h.Dispenser.Token(), h.matcherDefs, h.warnings)
|
|
|
|
}
|
|
|
|
|
2020-02-28 07:03:45 +03:00
|
|
|
// ExtractMatcherSet is like MatcherToken, except this is a higher-level
|
|
|
|
// method that returns the matcher set described by the matcher token,
|
|
|
|
// or nil if there is none, and deletes the matcher token from the
|
|
|
|
// dispenser and resets it as if this look-ahead never happened. Useful
|
|
|
|
// when wrapping a route (one or more handlers) in a user-defined matcher.
|
|
|
|
func (h Helper) ExtractMatcherSet() (caddy.ModuleMap, error) {
|
|
|
|
matcherSet, hasMatcher, err := h.MatcherToken()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
if hasMatcher {
|
2020-11-20 22:38:16 +03:00
|
|
|
// strip matcher token; we don't need to
|
|
|
|
// use the return value here because a
|
|
|
|
// new dispenser should have been made
|
|
|
|
// solely for this directive's tokens,
|
|
|
|
// with no other uses of same slice
|
|
|
|
h.Dispenser.Delete()
|
2020-02-28 07:03:45 +03:00
|
|
|
}
|
|
|
|
h.Dispenser.Reset() // pretend this lookahead never happened
|
|
|
|
return matcherSet, nil
|
|
|
|
}
|
|
|
|
|
2019-08-21 19:46:35 +03:00
|
|
|
// NewRoute returns config values relevant to creating a new HTTP route.
|
2019-12-10 23:36:46 +03:00
|
|
|
func (h Helper) NewRoute(matcherSet caddy.ModuleMap,
|
2023-08-07 22:40:31 +03:00
|
|
|
handler caddyhttp.MiddlewareHandler,
|
|
|
|
) []ConfigValue {
|
2019-12-13 01:27:09 +03:00
|
|
|
mod, err := caddy.GetModule(caddy.GetModuleID(handler))
|
2019-08-21 19:46:35 +03:00
|
|
|
if err != nil {
|
2019-12-13 01:27:09 +03:00
|
|
|
*h.warnings = append(*h.warnings, caddyconfig.Warning{
|
|
|
|
File: h.File(),
|
|
|
|
Line: h.Line(),
|
|
|
|
Message: err.Error(),
|
|
|
|
})
|
|
|
|
return nil
|
2019-08-21 19:46:35 +03:00
|
|
|
}
|
2019-12-10 23:36:46 +03:00
|
|
|
var matcherSetsRaw []caddy.ModuleMap
|
2019-08-21 19:46:35 +03:00
|
|
|
if matcherSet != nil {
|
|
|
|
matcherSetsRaw = append(matcherSetsRaw, matcherSet)
|
|
|
|
}
|
|
|
|
return []ConfigValue{
|
|
|
|
{
|
|
|
|
Class: "route",
|
|
|
|
Value: caddyhttp.Route{
|
|
|
|
MatcherSetsRaw: matcherSetsRaw,
|
2019-12-10 23:36:46 +03:00
|
|
|
HandlersRaw: []json.RawMessage{caddyconfig.JSONModuleObject(handler, "handler", mod.ID.Name(), h.warnings)},
|
2019-08-21 19:46:35 +03:00
|
|
|
},
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-01-16 22:09:54 +03:00
|
|
|
// GroupRoutes adds the routes (caddyhttp.Route type) in vals to the
|
|
|
|
// same group, if there is more than one route in vals.
|
2020-01-16 21:29:20 +03:00
|
|
|
func (h Helper) GroupRoutes(vals []ConfigValue) {
|
|
|
|
// ensure there's at least two routes; group of one is pointless
|
|
|
|
var count int
|
|
|
|
for _, v := range vals {
|
|
|
|
if _, ok := v.Value.(caddyhttp.Route); ok {
|
|
|
|
count++
|
|
|
|
if count > 1 {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if count < 2 {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// now that we know the group will have some effect, do it
|
2020-01-17 03:08:52 +03:00
|
|
|
groupName := h.groupCounter.nextGroup()
|
2020-01-16 22:09:54 +03:00
|
|
|
for i := range vals {
|
2020-01-16 21:29:20 +03:00
|
|
|
if route, ok := vals[i].Value.(caddyhttp.Route); ok {
|
2020-01-17 03:08:52 +03:00
|
|
|
route.Group = groupName
|
2020-01-16 21:29:20 +03:00
|
|
|
vals[i].Value = route
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-05-02 21:39:06 +03:00
|
|
|
// WithDispenser returns a new instance based on d. All others Helper
|
|
|
|
// fields are copied, so typically maps are shared with this new instance.
|
|
|
|
func (h Helper) WithDispenser(d *caddyfile.Dispenser) Helper {
|
|
|
|
h.Dispenser = d
|
|
|
|
return h
|
|
|
|
}
|
|
|
|
|
2020-05-27 00:27:51 +03:00
|
|
|
// ParseSegmentAsSubroute parses the segment such that its subdirectives
|
|
|
|
// are themselves treated as directives, from which a subroute is built
|
|
|
|
// and returned.
|
|
|
|
func ParseSegmentAsSubroute(h Helper) (caddyhttp.MiddlewareHandler, error) {
|
2020-08-05 22:42:29 +03:00
|
|
|
allResults, err := parseSegmentAsConfig(h)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2023-01-19 00:04:41 +03:00
|
|
|
return buildSubroute(allResults, h.groupCounter, true)
|
2020-08-05 22:42:29 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// parseSegmentAsConfig parses the segment such that its subdirectives
|
|
|
|
// are themselves treated as directives, including named matcher definitions,
|
|
|
|
// and the raw Config structs are returned.
|
|
|
|
func parseSegmentAsConfig(h Helper) ([]ConfigValue, error) {
|
2020-05-27 00:27:51 +03:00
|
|
|
var allResults []ConfigValue
|
|
|
|
|
|
|
|
for h.Next() {
|
2020-09-21 22:44:41 +03:00
|
|
|
// don't allow non-matcher args on the first line
|
|
|
|
if h.NextArg() {
|
|
|
|
return nil, h.ArgErr()
|
|
|
|
}
|
|
|
|
|
2020-05-27 00:27:51 +03:00
|
|
|
// slice the linear list of tokens into top-level segments
|
|
|
|
var segments []caddyfile.Segment
|
|
|
|
for nesting := h.Nesting(); h.NextBlock(nesting); {
|
|
|
|
segments = append(segments, h.NextSegment())
|
|
|
|
}
|
|
|
|
|
|
|
|
// copy existing matcher definitions so we can augment
|
|
|
|
// new ones that are defined only in this scope
|
|
|
|
matcherDefs := make(map[string]caddy.ModuleMap, len(h.matcherDefs))
|
|
|
|
for key, val := range h.matcherDefs {
|
|
|
|
matcherDefs[key] = val
|
|
|
|
}
|
|
|
|
|
|
|
|
// find and extract any embedded matcher definitions in this scope
|
2020-09-23 02:37:15 +03:00
|
|
|
for i := 0; i < len(segments); i++ {
|
|
|
|
seg := segments[i]
|
2020-05-27 00:27:51 +03:00
|
|
|
if strings.HasPrefix(seg.Directive(), matcherPrefix) {
|
2020-09-23 02:37:15 +03:00
|
|
|
// parse, then add the matcher to matcherDefs
|
2020-05-27 00:27:51 +03:00
|
|
|
err := parseMatcherDefinitions(caddyfile.NewDispenser(seg), matcherDefs)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2020-09-23 02:37:15 +03:00
|
|
|
// remove the matcher segment (consumed), then step back the loop
|
2020-05-27 00:27:51 +03:00
|
|
|
segments = append(segments[:i], segments[i+1:]...)
|
2020-09-23 02:37:15 +03:00
|
|
|
i--
|
2020-05-27 00:27:51 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// with matchers ready to go, evaluate each directive's segment
|
|
|
|
for _, seg := range segments {
|
|
|
|
dir := seg.Directive()
|
|
|
|
dirFunc, ok := registeredDirectives[dir]
|
|
|
|
if !ok {
|
2021-08-19 00:32:35 +03:00
|
|
|
return nil, h.Errf("unrecognized directive: %s - are you sure your Caddyfile structure (nesting and braces) is correct?", dir)
|
2020-05-27 00:27:51 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
subHelper := h
|
|
|
|
subHelper.Dispenser = caddyfile.NewDispenser(seg)
|
|
|
|
subHelper.matcherDefs = matcherDefs
|
|
|
|
|
|
|
|
results, err := dirFunc(subHelper)
|
|
|
|
if err != nil {
|
|
|
|
return nil, h.Errf("parsing caddyfile tokens for '%s': %v", dir, err)
|
|
|
|
}
|
2021-12-13 21:42:08 +03:00
|
|
|
|
|
|
|
dir = normalizeDirectiveName(dir)
|
|
|
|
|
2020-05-27 00:27:51 +03:00
|
|
|
for _, result := range results {
|
|
|
|
result.directive = dir
|
|
|
|
allResults = append(allResults, result)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-08-05 22:42:29 +03:00
|
|
|
return allResults, nil
|
2020-05-27 00:27:51 +03:00
|
|
|
}
|
|
|
|
|
2019-08-21 19:46:35 +03:00
|
|
|
// ConfigValue represents a value to be added to the final
|
|
|
|
// configuration, or a value to be consulted when building
|
|
|
|
// the final configuration.
|
|
|
|
type ConfigValue struct {
|
|
|
|
// The kind of value this is. As the config is
|
|
|
|
// being built, the adapter will look in the
|
|
|
|
// "pile" for values belonging to a certain
|
|
|
|
// class when it is setting up a certain part
|
|
|
|
// of the config. The associated value will be
|
|
|
|
// type-asserted and placed accordingly.
|
|
|
|
Class string
|
|
|
|
|
|
|
|
// The value to be used when building the config.
|
|
|
|
// Generally its type is associated with the
|
|
|
|
// name of the Class.
|
2022-08-02 23:39:09 +03:00
|
|
|
Value any
|
2019-08-21 19:46:35 +03:00
|
|
|
|
|
|
|
directive string
|
|
|
|
}
|
|
|
|
|
2020-01-17 03:08:52 +03:00
|
|
|
func sortRoutes(routes []ConfigValue) {
|
2020-01-16 22:09:54 +03:00
|
|
|
dirPositions := make(map[string]int)
|
|
|
|
for i, dir := range directiveOrder {
|
|
|
|
dirPositions[dir] = i
|
|
|
|
}
|
|
|
|
|
2020-01-17 03:08:52 +03:00
|
|
|
sort.SliceStable(routes, func(i, j int) bool {
|
2020-05-07 04:41:37 +03:00
|
|
|
// if the directives are different, just use the established directive order
|
2020-01-17 03:08:52 +03:00
|
|
|
iDir, jDir := routes[i].directive, routes[j].directive
|
2020-05-07 04:41:37 +03:00
|
|
|
if iDir != jDir {
|
|
|
|
return dirPositions[iDir] < dirPositions[jDir]
|
|
|
|
}
|
2020-01-15 23:51:12 +03:00
|
|
|
|
2020-05-07 04:41:37 +03:00
|
|
|
// directives are the same; sub-sort by path matcher length if there's
|
|
|
|
// only one matcher set and one path (this is a very common case and
|
|
|
|
// usually -- but not always -- helpful/expected, oh well; user can
|
|
|
|
// always take manual control of order using handler or route blocks)
|
|
|
|
iRoute, ok := routes[i].Value.(caddyhttp.Route)
|
|
|
|
if !ok {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
jRoute, ok := routes[j].Value.(caddyhttp.Route)
|
|
|
|
if !ok {
|
|
|
|
return false
|
|
|
|
}
|
2020-02-28 23:38:12 +03:00
|
|
|
|
2022-09-13 22:43:21 +03:00
|
|
|
// decode the path matchers if there is just one matcher set
|
2020-05-07 04:41:37 +03:00
|
|
|
var iPM, jPM caddyhttp.MatchPath
|
|
|
|
if len(iRoute.MatcherSetsRaw) == 1 {
|
|
|
|
_ = json.Unmarshal(iRoute.MatcherSetsRaw[0]["path"], &iPM)
|
|
|
|
}
|
|
|
|
if len(jRoute.MatcherSetsRaw) == 1 {
|
|
|
|
_ = json.Unmarshal(jRoute.MatcherSetsRaw[0]["path"], &jPM)
|
2020-01-15 23:51:12 +03:00
|
|
|
}
|
|
|
|
|
2022-09-13 22:43:21 +03:00
|
|
|
// if there is only one path in the path matcher, sort by longer path
|
|
|
|
// (more specific) first; missing path matchers or multi-matchers are
|
|
|
|
// treated as zero-length paths
|
2020-05-07 04:41:37 +03:00
|
|
|
var iPathLen, jPathLen int
|
2022-09-13 22:43:21 +03:00
|
|
|
if len(iPM) == 1 {
|
2020-05-07 04:41:37 +03:00
|
|
|
iPathLen = len(iPM[0])
|
|
|
|
}
|
2022-09-13 22:43:21 +03:00
|
|
|
if len(jPM) == 1 {
|
2020-05-07 04:41:37 +03:00
|
|
|
jPathLen = len(jPM[0])
|
|
|
|
}
|
2020-08-18 01:15:51 +03:00
|
|
|
|
2023-03-27 22:43:44 +03:00
|
|
|
sortByPath := func() bool {
|
2022-09-13 22:43:21 +03:00
|
|
|
// we can only confidently compare path lengths if both
|
|
|
|
// directives have a single path to match (issue #5037)
|
|
|
|
if iPathLen > 0 && jPathLen > 0 {
|
2023-03-27 22:43:44 +03:00
|
|
|
// if both paths are the same except for a trailing wildcard,
|
|
|
|
// sort by the shorter path first (which is more specific)
|
|
|
|
if strings.TrimSuffix(iPM[0], "*") == strings.TrimSuffix(jPM[0], "*") {
|
|
|
|
return iPathLen < jPathLen
|
|
|
|
}
|
2020-08-18 01:15:51 +03:00
|
|
|
|
2022-09-13 22:43:21 +03:00
|
|
|
// sort most-specific (longest) path first
|
|
|
|
return iPathLen > jPathLen
|
2022-04-25 19:47:12 +03:00
|
|
|
}
|
|
|
|
|
2022-09-13 22:43:21 +03:00
|
|
|
// if both directives don't have a single path to compare,
|
|
|
|
// sort whichever one has a matcher first; if both have
|
|
|
|
// a matcher, sort equally (stable sort preserves order)
|
|
|
|
return len(iRoute.MatcherSetsRaw) > 0 && len(jRoute.MatcherSetsRaw) == 0
|
2023-03-27 22:43:44 +03:00
|
|
|
}()
|
|
|
|
|
|
|
|
// some directives involve setting values which can overwrite
|
|
|
|
// each other, so it makes most sense to reverse the order so
|
|
|
|
// that the least-specific matcher is first, allowing the last
|
|
|
|
// matching one to win
|
|
|
|
if iDir == "vars" {
|
|
|
|
return !sortByPath
|
2022-04-25 19:47:12 +03:00
|
|
|
}
|
2023-03-27 22:43:44 +03:00
|
|
|
|
|
|
|
// everything else is most-specific matcher first
|
|
|
|
return sortByPath
|
2020-01-15 23:51:12 +03:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2020-04-02 23:20:30 +03:00
|
|
|
// serverBlock pairs a Caddyfile server block with
|
|
|
|
// a "pile" of config values, keyed by class name,
|
|
|
|
// as well as its parsed keys for convenience.
|
2019-08-21 19:46:35 +03:00
|
|
|
type serverBlock struct {
|
2024-09-30 19:55:03 +03:00
|
|
|
block caddyfile.ServerBlock
|
|
|
|
pile map[string][]ConfigValue // config values obtained from directives
|
|
|
|
parsedKeys []Address
|
2020-04-02 23:20:30 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// hostsFromKeys returns a list of all the non-empty hostnames found in
|
httpcaddyfile, caddytls: Multiple edge case fixes; add tests
- Create two default automation policies; if the TLS app is used in
isolation with the 'automate' certificate loader, it will now use
an internal issuer for internal-only names, and an ACME issuer for
all other names by default.
- If the HTTP Caddyfile adds an 'automate' loader, it now also adds an
automation policy for any names in that loader that do not qualify
for public certificates so that they will be issued internally. (It
might be nice if this wasn't necessary, but the alternative is to
either make auto-HTTPS logic way more complex by scanning the names in
the 'automate' loader, or to have an automation policy without an
issuer switch between default issuer based on the name being issued
a certificate - I think I like the latter option better, right now we
do something kind of like that but at a level above each individual
automation policies, we do that switch only when no automation
policies match, rather than when a policy without an issuer does
match.)
- Set the default LoggerName rather than a LoggerNames with an empty
host value, which is now taken literally rather than as a catch-all.
- hostsFromKeys, the function that gets a list of hosts from server
block keys, no longer returns an empty string in its resulting slice,
ever.
2020-04-08 23:46:44 +03:00
|
|
|
// the keys of the server block sb. If logger mode is false, a key with
|
|
|
|
// an empty hostname portion will return an empty slice, since that
|
|
|
|
// server block is interpreted to effectively match all hosts. An empty
|
|
|
|
// string is never added to the slice.
|
|
|
|
//
|
|
|
|
// If loggerMode is true, then the non-standard ports of keys will be
|
|
|
|
// joined to the hostnames. This is to effectively match the Host
|
|
|
|
// header of requests that come in for that key.
|
|
|
|
//
|
|
|
|
// The resulting slice is not sorted but will never have duplicates.
|
|
|
|
func (sb serverBlock) hostsFromKeys(loggerMode bool) []string {
|
|
|
|
// ensure each entry in our list is unique
|
2020-04-02 23:20:30 +03:00
|
|
|
hostMap := make(map[string]struct{})
|
2024-09-30 19:55:03 +03:00
|
|
|
for _, addr := range sb.parsedKeys {
|
httpcaddyfile, caddytls: Multiple edge case fixes; add tests
- Create two default automation policies; if the TLS app is used in
isolation with the 'automate' certificate loader, it will now use
an internal issuer for internal-only names, and an ACME issuer for
all other names by default.
- If the HTTP Caddyfile adds an 'automate' loader, it now also adds an
automation policy for any names in that loader that do not qualify
for public certificates so that they will be issued internally. (It
might be nice if this wasn't necessary, but the alternative is to
either make auto-HTTPS logic way more complex by scanning the names in
the 'automate' loader, or to have an automation policy without an
issuer switch between default issuer based on the name being issued
a certificate - I think I like the latter option better, right now we
do something kind of like that but at a level above each individual
automation policies, we do that switch only when no automation
policies match, rather than when a policy without an issuer does
match.)
- Set the default LoggerName rather than a LoggerNames with an empty
host value, which is now taken literally rather than as a catch-all.
- hostsFromKeys, the function that gets a list of hosts from server
block keys, no longer returns an empty string in its resulting slice,
ever.
2020-04-08 23:46:44 +03:00
|
|
|
if addr.Host == "" {
|
|
|
|
if !loggerMode {
|
|
|
|
// server block contains a key like ":443", i.e. the host portion
|
|
|
|
// is empty / catch-all, which means to match all hosts
|
|
|
|
return []string{}
|
|
|
|
}
|
|
|
|
// never append an empty string
|
|
|
|
continue
|
2020-04-02 23:20:30 +03:00
|
|
|
}
|
httpcaddyfile, caddytls: Multiple edge case fixes; add tests
- Create two default automation policies; if the TLS app is used in
isolation with the 'automate' certificate loader, it will now use
an internal issuer for internal-only names, and an ACME issuer for
all other names by default.
- If the HTTP Caddyfile adds an 'automate' loader, it now also adds an
automation policy for any names in that loader that do not qualify
for public certificates so that they will be issued internally. (It
might be nice if this wasn't necessary, but the alternative is to
either make auto-HTTPS logic way more complex by scanning the names in
the 'automate' loader, or to have an automation policy without an
issuer switch between default issuer based on the name being issued
a certificate - I think I like the latter option better, right now we
do something kind of like that but at a level above each individual
automation policies, we do that switch only when no automation
policies match, rather than when a policy without an issuer does
match.)
- Set the default LoggerName rather than a LoggerNames with an empty
host value, which is now taken literally rather than as a catch-all.
- hostsFromKeys, the function that gets a list of hosts from server
block keys, no longer returns an empty string in its resulting slice,
ever.
2020-04-08 23:46:44 +03:00
|
|
|
if loggerMode &&
|
2020-04-02 23:20:30 +03:00
|
|
|
addr.Port != "" &&
|
|
|
|
addr.Port != strconv.Itoa(caddyhttp.DefaultHTTPPort) &&
|
|
|
|
addr.Port != strconv.Itoa(caddyhttp.DefaultHTTPSPort) {
|
|
|
|
hostMap[net.JoinHostPort(addr.Host, addr.Port)] = struct{}{}
|
|
|
|
} else {
|
|
|
|
hostMap[addr.Host] = struct{}{}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// convert map to slice
|
|
|
|
sblockHosts := make([]string, 0, len(hostMap))
|
|
|
|
for host := range hostMap {
|
|
|
|
sblockHosts = append(sblockHosts, host)
|
|
|
|
}
|
|
|
|
|
|
|
|
return sblockHosts
|
2019-08-21 19:46:35 +03:00
|
|
|
}
|
|
|
|
|
2021-06-09 23:34:59 +03:00
|
|
|
func (sb serverBlock) hostsFromKeysNotHTTP(httpPort string) []string {
|
|
|
|
// ensure each entry in our list is unique
|
|
|
|
hostMap := make(map[string]struct{})
|
2024-09-30 19:55:03 +03:00
|
|
|
for _, addr := range sb.parsedKeys {
|
2021-06-09 23:34:59 +03:00
|
|
|
if addr.Host == "" {
|
|
|
|
continue
|
|
|
|
}
|
2022-03-25 07:54:03 +03:00
|
|
|
if addr.Scheme != "http" && addr.Port != httpPort {
|
2021-06-09 23:34:59 +03:00
|
|
|
hostMap[addr.Host] = struct{}{}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// convert map to slice
|
|
|
|
sblockHosts := make([]string, 0, len(hostMap))
|
|
|
|
for host := range hostMap {
|
|
|
|
sblockHosts = append(sblockHosts, host)
|
|
|
|
}
|
|
|
|
|
|
|
|
return sblockHosts
|
|
|
|
}
|
|
|
|
|
httpcaddyfile, caddytls: Multiple edge case fixes; add tests
- Create two default automation policies; if the TLS app is used in
isolation with the 'automate' certificate loader, it will now use
an internal issuer for internal-only names, and an ACME issuer for
all other names by default.
- If the HTTP Caddyfile adds an 'automate' loader, it now also adds an
automation policy for any names in that loader that do not qualify
for public certificates so that they will be issued internally. (It
might be nice if this wasn't necessary, but the alternative is to
either make auto-HTTPS logic way more complex by scanning the names in
the 'automate' loader, or to have an automation policy without an
issuer switch between default issuer based on the name being issued
a certificate - I think I like the latter option better, right now we
do something kind of like that but at a level above each individual
automation policies, we do that switch only when no automation
policies match, rather than when a policy without an issuer does
match.)
- Set the default LoggerName rather than a LoggerNames with an empty
host value, which is now taken literally rather than as a catch-all.
- hostsFromKeys, the function that gets a list of hosts from server
block keys, no longer returns an empty string in its resulting slice,
ever.
2020-04-08 23:46:44 +03:00
|
|
|
// hasHostCatchAllKey returns true if sb has a key that
|
|
|
|
// omits a host portion, i.e. it "catches all" hosts.
|
|
|
|
func (sb serverBlock) hasHostCatchAllKey() bool {
|
2024-09-30 19:55:03 +03:00
|
|
|
return slices.ContainsFunc(sb.parsedKeys, func(addr Address) bool {
|
2024-09-25 23:30:56 +03:00
|
|
|
return addr.Host == ""
|
|
|
|
})
|
httpcaddyfile, caddytls: Multiple edge case fixes; add tests
- Create two default automation policies; if the TLS app is used in
isolation with the 'automate' certificate loader, it will now use
an internal issuer for internal-only names, and an ACME issuer for
all other names by default.
- If the HTTP Caddyfile adds an 'automate' loader, it now also adds an
automation policy for any names in that loader that do not qualify
for public certificates so that they will be issued internally. (It
might be nice if this wasn't necessary, but the alternative is to
either make auto-HTTPS logic way more complex by scanning the names in
the 'automate' loader, or to have an automation policy without an
issuer switch between default issuer based on the name being issued
a certificate - I think I like the latter option better, right now we
do something kind of like that but at a level above each individual
automation policies, we do that switch only when no automation
policies match, rather than when a policy without an issuer does
match.)
- Set the default LoggerName rather than a LoggerNames with an empty
host value, which is now taken literally rather than as a catch-all.
- hostsFromKeys, the function that gets a list of hosts from server
block keys, no longer returns an empty string in its resulting slice,
ever.
2020-04-08 23:46:44 +03:00
|
|
|
}
|
|
|
|
|
2022-03-25 07:54:03 +03:00
|
|
|
// isAllHTTP returns true if all sb keys explicitly specify
|
|
|
|
// the http:// scheme
|
|
|
|
func (sb serverBlock) isAllHTTP() bool {
|
2024-09-30 19:55:03 +03:00
|
|
|
return !slices.ContainsFunc(sb.parsedKeys, func(addr Address) bool {
|
2024-09-25 23:30:56 +03:00
|
|
|
return addr.Scheme != "http"
|
|
|
|
})
|
2022-03-25 07:54:03 +03:00
|
|
|
}
|
|
|
|
|
2024-03-06 22:41:45 +03:00
|
|
|
// Positional are the supported modes for ordering directives.
|
|
|
|
type Positional string
|
|
|
|
|
|
|
|
const (
|
|
|
|
Before Positional = "before"
|
|
|
|
After Positional = "after"
|
|
|
|
First Positional = "first"
|
|
|
|
Last Positional = "last"
|
|
|
|
)
|
|
|
|
|
2019-08-21 19:46:35 +03:00
|
|
|
type (
|
|
|
|
// UnmarshalFunc is a function which can unmarshal Caddyfile
|
|
|
|
// tokens into zero or more config values using a Helper type.
|
|
|
|
// These are passed in a call to RegisterDirective.
|
|
|
|
UnmarshalFunc func(h Helper) ([]ConfigValue, error)
|
|
|
|
|
|
|
|
// UnmarshalHandlerFunc is like UnmarshalFunc, except the
|
|
|
|
// output of the unmarshaling is an HTTP handler. This
|
|
|
|
// function does not need to deal with HTTP request matching
|
|
|
|
// which is abstracted away. Since writing HTTP handlers
|
|
|
|
// with Caddyfile support is very common, this is a more
|
|
|
|
// convenient way to add a handler to the chain since a lot
|
|
|
|
// of the details common to HTTP handlers are taken care of
|
|
|
|
// for you. These are passed to a call to
|
|
|
|
// RegisterHandlerDirective.
|
|
|
|
UnmarshalHandlerFunc func(h Helper) (caddyhttp.MiddlewareHandler, error)
|
2020-05-12 00:00:35 +03:00
|
|
|
|
|
|
|
// UnmarshalGlobalFunc is a function which can unmarshal Caddyfile
|
2021-01-07 21:01:58 +03:00
|
|
|
// tokens from a global option. It is passed the tokens to parse and
|
|
|
|
// existing value from the previous instance of this global option
|
|
|
|
// (if any). It returns the value to associate with this global option.
|
2022-08-02 23:39:09 +03:00
|
|
|
UnmarshalGlobalFunc func(d *caddyfile.Dispenser, existingVal any) (any, error)
|
2019-08-21 19:46:35 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
var registeredDirectives = make(map[string]UnmarshalFunc)
|
2020-05-12 00:00:35 +03:00
|
|
|
|
|
|
|
var registeredGlobalOptions = make(map[string]UnmarshalGlobalFunc)
|