1 /* Copyright 1999-2004 The Apache Software Foundation
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
7 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 * mod_headers.c: Add/append/remove HTTP response headers
18 * Written by Paul Sutton, paul@ukweb.com, 1 Oct 1996
20 * The Header directive can be used to add/replace/remove HTTP headers
21 * within the response message. The RequestHeader directive can be used
22 * to add/replace/remove HTTP headers before a request message is processed.
23 * Valid in both per-server and per-dir configurations.
27 * Header action header value
28 * RequestHeader action header value
30 * Where action is one of:
31 * set - set this header, replacing any old value
32 * add - add this header, possible resulting in two or more
33 * headers with the same name
34 * append - append this text onto any existing header of this same
35 * unset - remove this header
37 * Where action is unset, the third argument (value) should not be given.
38 * The header name can include the colon, or not.
40 * The Header and RequestHeader directives can only be used where allowed
41 * by the FileInfo override.
43 * When the request is processed, the header directives are processed in
44 * this order: firstly, the main server, then the virtual server handling
45 * this request (if any), then any <Directory> sections (working downwards
46 * from the root dir), then an <Location> sections (working down from
47 * shortest URL component), the any <File> sections. This order is
48 * important if any 'set' or 'unset' actions are used. For example,
49 * the following two directives have different effect if applied in
52 * Header append Author "John P. Doe"
57 * To set the "Author" header, use
58 * Header add Author "John P. Doe"
67 #include "apr_strings.h"
68 #include "apr_buckets.h"
71 #define APR_WANT_STRFUNC
75 #include "http_config.h"
76 #include "http_request.h"
78 #include "util_filter.h"
79 #include "http_protocol.h"
81 #include "mod_ssl.h" /* for the ssl_var_lookup optional function defn */
83 /* format_tag_hash is initialized during pre-config */
84 static apr_hash_t *format_tag_hash;
87 hdr_add = 'a', /* add header (could mean multiple hdrs) */
88 hdr_set = 's', /* set (replace old value) */
89 hdr_append = 'm', /* append (merge into any old value) */
90 hdr_unset = 'u', /* unset header */
91 hdr_echo = 'e' /* echo headers from request to response */
95 * magic cmd->info values
97 static char hdr_in = '0'; /* RequestHeader */
98 static char hdr_out = '1'; /* Header onsuccess */
99 static char hdr_err = '2'; /* Header always */
102 * There is an array of struct format_tag per Header/RequestHeader
106 const char* (*func)(request_rec *r,char *arg);
110 /* 'Magic' condition_var value to run action in post_read_request */
111 static const char* condition_early = "early";
113 * There is one "header_entry" per Header/RequestHeader config directive
118 apr_array_header_t *ta; /* Array of format_tag structs */
120 const char *condition_var;
123 /* echo_do is used for Header echo to iterate through the request headers*/
130 * headers_conf is our per-module configuration. This is used as both
131 * a per-dir and per-server config
134 apr_array_header_t *fixup_in;
135 apr_array_header_t *fixup_out;
136 apr_array_header_t *fixup_err;
139 module AP_MODULE_DECLARE_DATA headers_module;
141 /* Pointer to ssl_var_lookup, if available. */
142 static APR_OPTIONAL_FN_TYPE(ssl_var_lookup) *header_ssl_lookup = NULL;
145 * Tag formatting functions
147 static const char *constant_item(request_rec *r, char *stuff)
151 static const char *header_request_duration(request_rec *r, char *a)
153 return apr_psprintf(r->pool, "D=%" APR_TIME_T_FMT,
154 (apr_time_now() - r->request_time));
156 static const char *header_request_time(request_rec *r, char *a)
158 return apr_psprintf(r->pool, "t=%" APR_TIME_T_FMT, r->request_time);
161 /* unwrap_header returns HDR with any newlines converted into
162 * whitespace if necessary. */
163 static const char *unwrap_header(apr_pool_t *p, const char *hdr)
165 if (ap_strchr_c(hdr, APR_ASCII_LF) || ap_strchr_c(hdr, APR_ASCII_CR)) {
168 hdr = ptr = apr_pstrdup(p, hdr);
171 if (*ptr == APR_ASCII_LF || *ptr == APR_ASCII_CR)
172 *ptr = APR_ASCII_BLANK;
178 static const char *header_request_env_var(request_rec *r, char *a)
180 const char *s = apr_table_get(r->subprocess_env,a);
183 return unwrap_header(r->pool, s);
188 static const char *header_request_ssl_var(request_rec *r, char *name)
190 if (header_ssl_lookup) {
191 const char *val = header_ssl_lookup(r->pool, r->server,
192 r->connection, r, name);
194 return unwrap_header(r->pool, val);
207 static void *create_headers_dir_config(apr_pool_t *p, char *d)
209 headers_conf *conf = apr_pcalloc(p, sizeof(*conf));
211 conf->fixup_in = apr_array_make(p, 2, sizeof(header_entry));
212 conf->fixup_out = apr_array_make(p, 2, sizeof(header_entry));
213 conf->fixup_err = apr_array_make(p, 2, sizeof(header_entry));
218 static void *merge_headers_config(apr_pool_t *p, void *basev, void *overridesv)
220 headers_conf *newconf = apr_pcalloc(p, sizeof(*newconf));
221 headers_conf *base = basev;
222 headers_conf *overrides = overridesv;
224 newconf->fixup_in = apr_array_append(p, base->fixup_in,
225 overrides->fixup_in);
226 newconf->fixup_out = apr_array_append(p, base->fixup_out,
227 overrides->fixup_out);
228 newconf->fixup_err = apr_array_append(p, base->fixup_err,
229 overrides->fixup_err);
234 static char *parse_misc_string(apr_pool_t *p, format_tag *tag, const char **sa)
239 tag->func = constant_item;
242 while (*s && *s != '%') {
246 * This might allocate a few chars extra if there's a backslash
247 * escape in the format string.
249 tag->arg = apr_palloc(p, s - *sa + 1);
253 while (*s && *s != '%') {
280 * Allow the loop to deal with this *s in the normal
281 * fashion so that it handles end of string etc.
294 static char *parse_format_tag(apr_pool_t *p, format_tag *tag, const char **sa)
297 const char * (*tag_handler)(request_rec *,char *);
299 /* Handle string literal/conditionals */
301 return parse_misc_string(p, tag, sa);
303 s++; /* skip the % */
305 /* Pass through %% as % */
307 tag->func = constant_item;
314 /* grab the argument if there is one */
317 tag->arg = ap_getword(p,&s,'}');
320 tag_handler = (const char * (*)(request_rec *,char *))apr_hash_get(format_tag_hash, s++, 1);
326 return apr_pstrcat(p, "Unrecognized header format %", dummy, NULL);
328 tag->func = tag_handler;
335 * A format string consists of white space, text and optional format
336 * tags in any order. E.g.,
338 * Header add MyHeader "Free form text %D %t more text"
340 * Decompose the format string into its tags. Each tag (struct format_tag)
341 * contains a pointer to the function used to format the tag. Then save each
342 * tag in the tag array anchored in the header_entry.
344 static char *parse_format_string(apr_pool_t *p, header_entry *hdr, const char *s)
348 /* No string to parse with unset and echo commands */
349 if (hdr->action == hdr_unset ||
350 hdr->action == hdr_echo) {
354 hdr->ta = apr_array_make(p, 10, sizeof(format_tag));
357 if ((res = parse_format_tag(p, (format_tag *) apr_array_push(hdr->ta), &s))) {
364 /* handle RequestHeader and Header directive */
365 static APR_INLINE const char *header_inout_cmd(cmd_parms *cmd,
370 const char* envclause)
372 headers_conf *dirconf = indirconf;
373 const char *condition_var = NULL;
377 apr_array_header_t *fixup = (cmd->info == &hdr_in)
378 ? dirconf->fixup_in : (cmd->info == &hdr_err)
380 : dirconf->fixup_out;
382 new = (header_entry *) apr_array_push(fixup);
384 if (!strcasecmp(action, "set"))
385 new->action = hdr_set;
386 else if (!strcasecmp(action, "add"))
387 new->action = hdr_add;
388 else if (!strcasecmp(action, "append"))
389 new->action = hdr_append;
390 else if (!strcasecmp(action, "unset"))
391 new->action = hdr_unset;
392 else if (!strcasecmp(action, "echo"))
393 new->action = hdr_echo;
395 return "first argument must be 'add', 'set', 'append', 'unset' or "
398 if (new->action == hdr_unset) {
401 return "header unset takes two arguments";
407 else if (new->action == hdr_echo) {
412 return "Header echo takes two arguments";
417 if (cmd->info != &hdr_out && cmd->info != &hdr_err)
418 return "Header echo only valid on Header "
421 regex = ap_pregcomp(cmd->pool, hdr, REG_EXTENDED | REG_NOSUB);
423 return "Header echo regex could not be compiled";
429 return "Header requires three arguments";
431 /* Handle the envclause on Header */
432 if (envclause != NULL) {
433 if (strcasecmp(envclause, "early") == 0) {
434 condition_var = condition_early;
437 if (strncasecmp(envclause, "env=", 4) != 0) {
438 return "error: envclause should be in the form env=envar";
440 if ((envclause[4] == '\0')
441 || ((envclause[4] == '!') && (envclause[5] == '\0'))) {
442 return "error: missing environment variable name. "
443 "envclause should be in the form env=envar ";
445 condition_var = envclause + 4;
449 if ((colon = ap_strchr_c(hdr, ':'))) {
450 hdr = apr_pstrmemdup(cmd->pool, hdr, colon-hdr);
454 new->condition_var = condition_var;
456 return parse_format_string(cmd->pool, new, value);
459 /* Handle all (xxx)Header directives */
460 static const char *header_cmd(cmd_parms *cmd, void *indirconf,
466 const char *envclause;
468 action = ap_getword_conf(cmd->pool, &args);
469 if (cmd->info == &hdr_out) {
470 if (!strcasecmp(action, "always")) {
471 cmd->info = &hdr_err;
472 action = ap_getword_conf(cmd->pool, &args);
474 else if (!strcasecmp(action, "onsuccess")) {
475 action = ap_getword_conf(cmd->pool, &args);
478 hdr = ap_getword_conf(cmd->pool, &args);
479 val = *args ? ap_getword_conf(cmd->pool, &args) : NULL;
480 envclause = *args ? ap_getword_conf(cmd->pool, &args) : NULL;
483 return apr_pstrcat(cmd->pool, cmd->cmd->name,
484 " has too many arguments", NULL);
487 return header_inout_cmd(cmd, indirconf, action, hdr, val, envclause);
491 * Process the tags in the format string. Tags may be format specifiers
492 * (%D, %t, etc.), whitespace or text strings. For each tag, run the handler
493 * (formatter) specific to the tag. Handlers return text strings.
494 * Concatenate the return from each handler into one string that is
495 * returned from this call.
497 static char* process_tags(header_entry *hdr, request_rec *r)
503 format_tag *tag = (format_tag*) hdr->ta->elts;
505 for (i = 0; i < hdr->ta->nelts; i++) {
506 s = tag[i].func(r, tag[i].arg);
508 str = apr_pstrdup(r->pool, s);
510 str = apr_pstrcat(r->pool, str, s, NULL);
512 return str ? str : "";
515 static int echo_header(echo_do *v, const char *key, const char *val)
517 /* If the input header (key) matches the regex, echo it intact to
520 if (!ap_regexec(v->hdr->regex, key, 0, NULL, 0)) {
521 apr_table_add(v->r->headers_out, key, val);
527 static void do_headers_fixup(request_rec *r, apr_table_t *headers,
528 apr_array_header_t *fixup, int early)
532 for (i = 0; i < fixup->nelts; ++i) {
533 header_entry *hdr = &((header_entry *) (fixup->elts))[i];
534 const char *envar = hdr->condition_var;
536 /* ignore early headers in late calls */
537 if (!early && (envar == condition_early)) {
540 /* ignore late headers in early calls */
541 else if (early && (envar != condition_early)) {
544 /* Have any conditional envar-controlled Header processing to do? */
545 else if (envar && !early) {
547 if (apr_table_get(r->subprocess_env, envar) == NULL)
551 if (apr_table_get(r->subprocess_env, &envar[1]) != NULL)
556 switch (hdr->action) {
558 apr_table_addn(headers, hdr->header, process_tags(hdr, r));
561 apr_table_mergen(headers, hdr->header, process_tags(hdr, r));
564 apr_table_setn(headers, hdr->header, process_tags(hdr, r));
567 apr_table_unset(headers, hdr->header);
574 apr_table_do((int (*) (void *, const char *, const char *))
575 echo_header, (void *) &v, r->headers_in, NULL);
582 static void ap_headers_insert_output_filter(request_rec *r)
584 headers_conf *dirconf = ap_get_module_config(r->per_dir_config,
587 if (dirconf->fixup_out->nelts || dirconf->fixup_err->nelts) {
588 ap_add_output_filter("FIXUP_HEADERS_OUT", NULL, r, r->connection);
593 * Make sure our error-path filter is in place.
595 static void ap_headers_insert_error_filter(request_rec *r)
597 headers_conf *dirconf = ap_get_module_config(r->per_dir_config,
600 if (dirconf->fixup_err->nelts) {
601 ap_add_output_filter("FIXUP_HEADERS_ERR", NULL, r, r->connection);
605 static apr_status_t ap_headers_output_filter(ap_filter_t *f,
606 apr_bucket_brigade *in)
608 headers_conf *dirconf = ap_get_module_config(f->r->per_dir_config,
611 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, f->r->server,
612 "headers: ap_headers_output_filter()");
615 do_headers_fixup(f->r, f->r->err_headers_out, dirconf->fixup_err, 0);
616 do_headers_fixup(f->r, f->r->headers_out, dirconf->fixup_out, 0);
618 /* remove ourselves from the filter chain */
619 ap_remove_output_filter(f);
621 /* send the data up the stack */
622 return ap_pass_brigade(f->next,in);
626 * Make sure we propagate any "Header always" settings on the error
627 * path through http_protocol.c.
629 static apr_status_t ap_headers_error_filter(ap_filter_t *f,
630 apr_bucket_brigade *in)
632 headers_conf *dirconf;
634 dirconf = ap_get_module_config(f->r->per_dir_config,
636 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, f->r->server,
637 "headers: ap_headers_error_filter()");
640 * Add any header fields defined by "Header always" to r->err_headers_out.
641 * Server-wide first, then per-directory to allow overriding.
643 do_headers_fixup(f->r, f->r->err_headers_out, dirconf->fixup_err, 0);
646 * We've done our bit; remove ourself from the filter chain so there's
647 * no possibility we'll be called again.
649 ap_remove_output_filter(f);
652 * Pass the buck. (euro?)
654 return ap_pass_brigade(f->next, in);
657 static apr_status_t ap_headers_fixup(request_rec *r)
659 headers_conf *dirconf = ap_get_module_config(r->per_dir_config,
663 if (dirconf->fixup_in->nelts) {
664 do_headers_fixup(r, r->headers_in, dirconf->fixup_in, 0);
669 static apr_status_t ap_headers_early(request_rec *r)
671 headers_conf *dirconf = ap_get_module_config(r->per_dir_config,
675 if (dirconf->fixup_in->nelts) {
676 do_headers_fixup(r, r->headers_in, dirconf->fixup_in, 1);
678 if (dirconf->fixup_err->nelts) {
679 do_headers_fixup(r, r->err_headers_out, dirconf->fixup_err, 1);
681 if (dirconf->fixup_out->nelts) {
682 do_headers_fixup(r, r->headers_out, dirconf->fixup_out, 1);
688 static const command_rec headers_cmds[] =
690 AP_INIT_RAW_ARGS("Header", header_cmd, &hdr_out, OR_FILEINFO,
691 "an optional condition, an action, header and value "
692 "followed by optional env clause"),
693 AP_INIT_RAW_ARGS("RequestHeader", header_cmd, &hdr_in, OR_FILEINFO,
694 "an action, header and value followed by optional env "
699 static void register_format_tag_handler(const char *tag,
700 const void *tag_handler)
702 apr_hash_set(format_tag_hash, tag, 1, tag_handler);
705 static int header_pre_config(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp)
707 format_tag_hash = apr_hash_make(p);
708 register_format_tag_handler("D", (const void *)header_request_duration);
709 register_format_tag_handler("t", (const void *)header_request_time);
710 register_format_tag_handler("e", (const void *)header_request_env_var);
711 register_format_tag_handler("s", (const void *)header_request_ssl_var);
716 static int header_post_config(apr_pool_t *pconf, apr_pool_t *plog,
717 apr_pool_t *ptemp, server_rec *s)
719 header_ssl_lookup = APR_RETRIEVE_OPTIONAL_FN(ssl_var_lookup);
723 static void register_hooks(apr_pool_t *p)
725 ap_register_output_filter("FIXUP_HEADERS_OUT", ap_headers_output_filter,
726 NULL, AP_FTYPE_CONTENT_SET);
727 ap_register_output_filter("FIXUP_HEADERS_ERR", ap_headers_error_filter,
728 NULL, AP_FTYPE_CONTENT_SET);
729 ap_hook_pre_config(header_pre_config,NULL,NULL,APR_HOOK_MIDDLE);
730 ap_hook_post_config(header_post_config,NULL,NULL,APR_HOOK_MIDDLE);
731 ap_hook_insert_filter(ap_headers_insert_output_filter, NULL, NULL, APR_HOOK_LAST);
732 ap_hook_insert_error_filter(ap_headers_insert_error_filter,
733 NULL, NULL, APR_HOOK_LAST);
734 ap_hook_fixups(ap_headers_fixup, NULL, NULL, APR_HOOK_LAST);
735 ap_hook_post_read_request(ap_headers_early, NULL, NULL, APR_HOOK_FIRST);
738 module AP_MODULE_DECLARE_DATA headers_module =
740 STANDARD20_MODULE_STUFF,
741 create_headers_dir_config, /* dir config creater */
742 merge_headers_config, /* dir merger --- default is to override */
743 NULL, /* server config */
744 NULL, /* merge server configs */
745 headers_cmds, /* command apr_table_t */
746 register_hooks /* register hooks */