| 1 | // Copyright 2015 Matthew Holt and The Caddy Authors |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | package headers |
| 16 | |
| 17 | import ( |
| 18 | "fmt" |
| 19 | "net/http" |
| 20 | "reflect" |
| 21 | "strings" |
| 22 | |
| 23 | "github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile" |
| 24 | "github.com/caddyserver/caddy/v2/modules/caddyhttp" |
| 25 | ) |
| 26 | |
| 27 | func init() { |
| 28 | httpcaddyfile.RegisterDirective("header", parseCaddyfile) |
| 29 | httpcaddyfile.RegisterDirective("request_header", parseReqHdrCaddyfile) |
| 30 | } |
| 31 | |
| 32 | // parseCaddyfile sets up the handler for response headers from |
| 33 | // Caddyfile tokens. Syntax: |
| 34 | // |
| 35 | // header [<matcher>] [[+|-|?|>]<field> [<value|regexp>] [<replacement>]] { |
| 36 | // [+]<field> [<value|regexp> [<replacement>]] |
| 37 | // ?<field> <default_value> |
| 38 | // -<field> |
| 39 | // ><field> |
| 40 | // [defer] |
| 41 | // } |
| 42 | // |
| 43 | // Either a block can be opened or a single header field can be configured |
| 44 | // in the first line, but not both in the same directive. Header operations |
| 45 | // are deferred to write-time if any headers are being deleted or if the |
| 46 | // 'defer' subdirective is used. + appends a header value, - deletes a field, |
| 47 | // ? conditionally sets a value only if the header field is not already set, |
| 48 | // and > sets a field with defer enabled. |
| 49 | func parseCaddyfile(h httpcaddyfile.Helper) ([]httpcaddyfile.ConfigValue, error) { |
| 50 | h.Next() // consume directive name |
| 51 | matcherSet, err := h.ExtractMatcherSet() |
| 52 | if err != nil { |
| 53 | return nil, err |
| 54 | } |
| 55 | h.Next() // consume the directive name again (matcher parsing resets) |
| 56 | |
| 57 | makeHandler := func() Handler { |
| 58 | return Handler{ |
| 59 | Response: &RespHeaderOps{ |
| 60 | HeaderOps: &HeaderOps{}, |
| 61 | }, |
| 62 | } |
| 63 | } |
| 64 | handler, handlerWithRequire := makeHandler(), makeHandler() |
| 65 | |
| 66 | // first see if headers are in the initial line |
| 67 | var hasArgs bool |
| 68 | if h.NextArg() { |
| 69 | hasArgs = true |
| 70 | field := h.Val() |
| 71 | var value string |
| 72 | var replacement *string |
| 73 | if h.NextArg() { |
| 74 | value = h.Val() |
| 75 | } |
| 76 | if h.NextArg() { |
| 77 | arg := h.Val() |
| 78 | replacement = &arg |
| 79 | } |
| 80 | err := applyHeaderOp( |
| 81 | handler.Response.HeaderOps, |
| 82 | handler.Response, |
| 83 | field, |
| 84 | value, |
| 85 | replacement, |
| 86 | ) |
| 87 | if err != nil { |
| 88 | return nil, h.Err(err.Error()) |
| 89 | } |
| 90 | if len(handler.Response.HeaderOps.Delete) > 0 { |
| 91 | handler.Response.Deferred = true |
| 92 | } |
| 93 | } |
| 94 | |
| 95 | // if not, they should be in a block |
| 96 | for h.NextBlock(0) { |
| 97 | field := h.Val() |
| 98 | if field == "defer" { |
| 99 | handler.Response.Deferred = true |
| 100 | continue |
| 101 | } |
| 102 | if field == "match" { |
| 103 | responseMatchers := make(map[string]caddyhttp.ResponseMatcher) |
| 104 | err := caddyhttp.ParseNamedResponseMatcher(h.NewFromNextSegment(), responseMatchers) |
| 105 | if err != nil { |
| 106 | return nil, err |
| 107 | } |
| 108 | matcher := responseMatchers["match"] |
| 109 | handler.Response.Require = &matcher |
| 110 | continue |
| 111 | } |
| 112 | if hasArgs { |
| 113 | return nil, h.Err("cannot specify headers in both arguments and block") // because it would be weird |
| 114 | } |
| 115 | |
| 116 | // sometimes it is habitual for users to suffix a field name with a colon, |
| 117 | // as if they were writing a curl command or something; see |
| 118 | // https://caddy.community/t/v2-reverse-proxy-please-add-cors-example-to-the-docs/7349/19 |
| 119 | field = strings.TrimSuffix(field, ":") |
| 120 | |
| 121 | var value string |
| 122 | var replacement *string |
| 123 | if h.NextArg() { |
| 124 | value = h.Val() |
| 125 | } |
| 126 | if h.NextArg() { |
| 127 | arg := h.Val() |
| 128 | replacement = &arg |
| 129 | } |
| 130 | |
| 131 | handlerToUse := handler |
| 132 | if strings.HasPrefix(field, "?") { |
| 133 | handlerToUse = handlerWithRequire |
| 134 | } |
| 135 | |
| 136 | err := applyHeaderOp( |
| 137 | handlerToUse.Response.HeaderOps, |
| 138 | handlerToUse.Response, |
| 139 | field, |
| 140 | value, |
| 141 | replacement, |
| 142 | ) |
| 143 | if err != nil { |
| 144 | return nil, h.Err(err.Error()) |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | var configValues []httpcaddyfile.ConfigValue |
| 149 | if !reflect.DeepEqual(handler, makeHandler()) { |
| 150 | configValues = append(configValues, h.NewRoute(matcherSet, handler)...) |
| 151 | } |
| 152 | if !reflect.DeepEqual(handlerWithRequire, makeHandler()) { |
| 153 | configValues = append(configValues, h.NewRoute(matcherSet, handlerWithRequire)...) |
| 154 | } |
| 155 | |
| 156 | return configValues, nil |
| 157 | } |
| 158 | |
| 159 | // parseReqHdrCaddyfile sets up the handler for request headers |
| 160 | // from Caddyfile tokens. Syntax: |
| 161 | // |
| 162 | // request_header [<matcher>] [[+|-]<field> [<value|regexp>] [<replacement>]] |
| 163 | func parseReqHdrCaddyfile(h httpcaddyfile.Helper) ([]httpcaddyfile.ConfigValue, error) { |
| 164 | h.Next() // consume directive name |
| 165 | matcherSet, err := h.ExtractMatcherSet() |
| 166 | if err != nil { |
| 167 | return nil, err |
| 168 | } |
| 169 | h.Next() // consume the directive name again (matcher parsing resets) |
| 170 | |
| 171 | if !h.NextArg() { |
| 172 | return nil, h.ArgErr() |
| 173 | } |
| 174 | field := h.Val() |
| 175 | |
| 176 | hdr := Handler{ |
| 177 | Request: &HeaderOps{}, |
| 178 | } |
| 179 | |
| 180 | // sometimes it is habitual for users to suffix a field name with a colon, |
| 181 | // as if they were writing a curl command or something; see |
| 182 | // https://caddy.community/t/v2-reverse-proxy-please-add-cors-example-to-the-docs/7349/19 |
| 183 | field = strings.TrimSuffix(field, ":") |
| 184 | |
| 185 | var value string |
| 186 | var replacement *string |
| 187 | if h.NextArg() { |
| 188 | value = h.Val() |
| 189 | } |
| 190 | if h.NextArg() { |
| 191 | arg := h.Val() |
| 192 | replacement = &arg |
| 193 | if h.NextArg() { |
| 194 | return nil, h.ArgErr() |
| 195 | } |
| 196 | } |
| 197 | |
| 198 | if hdr.Request == nil { |
| 199 | hdr.Request = new(HeaderOps) |
| 200 | } |
| 201 | if err := CaddyfileHeaderOp(hdr.Request, field, value, replacement); err != nil { |
| 202 | return nil, h.Err(err.Error()) |
| 203 | } |
| 204 | |
| 205 | configValues := h.NewRoute(matcherSet, hdr) |
| 206 | |
| 207 | if h.NextArg() { |
| 208 | return nil, h.ArgErr() |
| 209 | } |
| 210 | return configValues, nil |
| 211 | } |
| 212 | |
| 213 | // CaddyfileHeaderOp applies a new header operation according to |
| 214 | // field, value, and replacement. The field can be prefixed with |
| 215 | // "+" or "-" to specify adding or removing; otherwise, the value |
| 216 | // will be set (overriding any previous value). If replacement is |
| 217 | // non-nil, value will be treated as a regular expression which |
| 218 | // will be used to search and then replacement will be used to |
| 219 | // complete the substring replacement; in that case, any + or - |
| 220 | // prefix to field will be ignored. |
| 221 | func CaddyfileHeaderOp(ops *HeaderOps, field, value string, replacement *string) error { |
| 222 | return applyHeaderOp(ops, nil, field, value, replacement) |
| 223 | } |
| 224 | |
| 225 | func applyHeaderOp(ops *HeaderOps, respHeaderOps *RespHeaderOps, field, value string, replacement *string) error { |
| 226 | switch { |
| 227 | case strings.HasPrefix(field, "+"): // append |
| 228 | if ops.Add == nil { |
| 229 | ops.Add = make(http.Header) |
| 230 | } |
| 231 | ops.Add.Add(field[1:], value) |
| 232 | |
| 233 | case strings.HasPrefix(field, "-"): // delete |
| 234 | ops.Delete = append(ops.Delete, field[1:]) |
| 235 | if respHeaderOps != nil { |
| 236 | respHeaderOps.Deferred = true |
| 237 | } |
| 238 | |
| 239 | case strings.HasPrefix(field, "?"): // default (conditional on not existing) - response headers only |
| 240 | if respHeaderOps == nil { |
| 241 | return fmt.Errorf("%v: the default header modifier ('?') can only be used on response headers; for conditional manipulation of request headers, use matchers", field) |
| 242 | } |
| 243 | if respHeaderOps.Require == nil { |
| 244 | respHeaderOps.Require = &caddyhttp.ResponseMatcher{ |
| 245 | Headers: make(http.Header), |
| 246 | } |
| 247 | } |
| 248 | field = strings.TrimPrefix(field, "?") |
| 249 | respHeaderOps.Require.Headers[field] = nil |
| 250 | if respHeaderOps.Set == nil { |
| 251 | respHeaderOps.Set = make(http.Header) |
| 252 | } |
| 253 | respHeaderOps.Set.Set(field, value) |
| 254 | |
| 255 | case replacement != nil: // replace |
| 256 | // allow defer shortcut for replace syntax |
| 257 | if strings.HasPrefix(field, ">") && respHeaderOps != nil { |
| 258 | respHeaderOps.Deferred = true |
| 259 | } |
| 260 | if ops.Replace == nil { |
| 261 | ops.Replace = make(map[string][]Replacement) |
| 262 | } |
| 263 | field = strings.TrimLeft(field, "+-?>") |
| 264 | ops.Replace[field] = append( |
| 265 | ops.Replace[field], |
| 266 | Replacement{ |
| 267 | SearchRegexp: value, |
| 268 | Replace: *replacement, |
| 269 | }, |
| 270 | ) |
| 271 | |
| 272 | case strings.HasPrefix(field, ">"): // set (overwrite) with defer |
| 273 | if ops.Set == nil { |
| 274 | ops.Set = make(http.Header) |
| 275 | } |
| 276 | ops.Set.Set(field[1:], value) |
| 277 | if respHeaderOps != nil { |
| 278 | respHeaderOps.Deferred = true |
| 279 | } |
| 280 | |
| 281 | default: // set (overwrite) |
| 282 | if ops.Set == nil { |
| 283 | ops.Set = make(http.Header) |
| 284 | } |
| 285 | ops.Set.Set(field, value) |
| 286 | } |
| 287 | |
| 288 | return nil |
| 289 | } |