1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 * _ __ ___ ___ __| | _ __ _____ ___ __(_) |_ ___
19 * | '_ ` _ \ / _ \ / _` | | '__/ _ \ \ /\ / / '__| | __/ _ \
20 * | | | | | | (_) | (_| | | | | __/\ V V /| | | | || __/
21 * |_| |_| |_|\___/ \__,_|___|_| \___| \_/\_/ |_| |_|\__\___|
24 * URL Rewriting Module
26 * This module uses a rule-based rewriting engine (based on a
27 * regular-expression parser) to rewrite requested URLs on the fly.
29 * It supports an unlimited number of additional rule conditions (which can
30 * operate on a lot of variables, even on HTTP headers) for granular
31 * matching and even external database lookups (either via plain text
32 * tables, DBM hash files or even external processes) for advanced URL
35 * It operates on the full URLs (including the PATH_INFO part) both in
36 * per-server context (httpd.conf) and per-dir context (.htaccess) and even
37 * can generate QUERY_STRING parts on result. The rewriting result finally
38 * can lead to internal subprocessing, external request redirection or even
39 * to internal proxy throughput.
41 * This module was originally written in April 1996 and
42 * gifted exclusively to the The Apache Software Foundation in July 1997 by
50 #include "apr_strings.h"
54 #include "apr_signal.h"
55 #include "apr_global_mutex.h"
61 #include "apr_thread_mutex.h"
64 #define APR_WANT_MEMFUNC
65 #define APR_WANT_STRFUNC
66 #define APR_WANT_IOVEC
69 /* XXX: Do we really need these headers? */
73 #if APR_HAVE_SYS_TYPES_H
74 #include <sys/types.h>
86 #include "ap_config.h"
88 #include "http_config.h"
89 #include "http_request.h"
90 #include "http_core.h"
92 #include "http_protocol.h"
93 #include "http_vhost.h"
97 #include "mod_rewrite.h"
99 #ifdef AP_NEED_SET_MUTEX_PERMS
103 static ap_dbd_t *(*dbd_acquire)(request_rec*) = NULL;
104 static void (*dbd_prepare)(server_rec*, const char*, const char*) = NULL;
107 * in order to improve performance on running production systems, you
108 * may strip all rewritelog code entirely from mod_rewrite by using the
109 * -DREWRITELOG_DISABLED compiler option.
111 * DO NOT USE THIS OPTION FOR PUBLIC BINARY RELEASES. Otherwise YOU are
112 * responsible for answering all the mod_rewrite questions out there.
114 #ifndef REWRITELOG_DISABLED
116 #define rewritelog(x) do_rewritelog x
117 #define REWRITELOG_MODE ( APR_UREAD | APR_UWRITE | APR_GREAD | APR_WREAD )
118 #define REWRITELOG_FLAGS ( APR_WRITE | APR_APPEND | APR_CREATE )
120 #else /* !REWRITELOG_DISABLED */
122 #define rewritelog(x)
124 #endif /* REWRITELOG_DISABLED */
126 /* remembered mime-type for [T=...] */
127 #define REWRITE_FORCED_MIMETYPE_NOTEVAR "rewrite-forced-mimetype"
128 #define REWRITE_FORCED_HANDLER_NOTEVAR "rewrite-forced-handler"
130 #define ENVVAR_SCRIPT_URL "SCRIPT_URL"
131 #define REDIRECT_ENVVAR_SCRIPT_URL "REDIRECT_" ENVVAR_SCRIPT_URL
132 #define ENVVAR_SCRIPT_URI "SCRIPT_URI"
134 #define CONDFLAG_NONE 1<<0
135 #define CONDFLAG_NOCASE 1<<1
136 #define CONDFLAG_NOTMATCH 1<<2
137 #define CONDFLAG_ORNEXT 1<<3
138 #define CONDFLAG_NOVARY 1<<4
140 #define RULEFLAG_NONE 1<<0
141 #define RULEFLAG_FORCEREDIRECT 1<<1
142 #define RULEFLAG_LASTRULE 1<<2
143 #define RULEFLAG_NEWROUND 1<<3
144 #define RULEFLAG_CHAIN 1<<4
145 #define RULEFLAG_IGNOREONSUBREQ 1<<5
146 #define RULEFLAG_NOTMATCH 1<<6
147 #define RULEFLAG_PROXY 1<<7
148 #define RULEFLAG_PASSTHROUGH 1<<8
149 #define RULEFLAG_QSAPPEND 1<<9
150 #define RULEFLAG_NOCASE 1<<10
151 #define RULEFLAG_NOESCAPE 1<<11
152 #define RULEFLAG_NOSUB 1<<12
153 #define RULEFLAG_STATUS 1<<13
154 #define RULEFLAG_ESCAPEBACKREF 1<<14
156 /* return code of the rewrite rule
157 * the result may be escaped - or not
159 #define ACTION_NORMAL 1<<0
160 #define ACTION_NOESCAPE 1<<1
161 #define ACTION_STATUS 1<<2
164 #define MAPTYPE_TXT 1<<0
165 #define MAPTYPE_DBM 1<<1
166 #define MAPTYPE_PRG 1<<2
167 #define MAPTYPE_INT 1<<3
168 #define MAPTYPE_RND 1<<4
169 #define MAPTYPE_DBD 1<<5
170 #define MAPTYPE_DBD_CACHE 1<<6
172 #define ENGINE_DISABLED 1<<0
173 #define ENGINE_ENABLED 1<<1
175 #define OPTION_NONE 1<<0
176 #define OPTION_INHERIT 1<<1
179 #define RAND_MAX 32767
182 /* max cookie size in rfc 2109 */
183 /* XXX: not used at all. We should do a check somewhere and/or cut the cookie */
184 #define MAX_COOKIE_LEN 4096
186 /* max line length (incl.\n) in text rewrite maps */
187 #ifndef REWRITE_MAX_TXT_MAP_LINE
188 #define REWRITE_MAX_TXT_MAP_LINE 1024
191 /* buffer length for prg rewrite maps */
192 #ifndef REWRITE_PRG_MAP_BUF
193 #define REWRITE_PRG_MAP_BUF 1024
196 /* for better readbility */
197 #define LEFT_CURLY '{'
198 #define RIGHT_CURLY '}'
201 * expansion result items on the stack to save some cycles
203 * (5 == about 2 variables like "foo%{var}bar%{var}baz")
205 #define SMALL_EXPANSION 5
208 * check that a subrequest won't cause infinite recursion
210 * either not in a subrequest, or in a subrequest
211 * and URIs aren't NULL and sub/main URIs differ
213 #define subreq_ok(r) (!r->main || \
214 (r->main->uri && r->uri && strcmp(r->main->uri, r->uri)))
218 * +-------------------------------------------------------+
220 * | Types and Structures
222 * +-------------------------------------------------------+
226 const char *datafile; /* filename for map data files */
227 const char *dbmtype; /* dbm type for dbm map data files */
228 const char *checkfile; /* filename to check for map existence */
229 const char *cachename; /* for cached maps (txt/rnd/dbm) */
230 int type; /* the type of the map */
231 apr_file_t *fpin; /* in file pointer for program maps */
232 apr_file_t *fpout; /* out file pointer for program maps */
233 apr_file_t *fperr; /* err file pointer for program maps */
234 char *(*func)(request_rec *, /* function pointer for internal maps */
236 char **argv; /* argv of the external rewrite map */
237 const char *dbdq; /* SQL SELECT statement for rewritemap */
238 const char *checkfile2; /* filename to check for map existence
239 NULL if only one file */
242 /* special pattern types for RewriteCond */
258 char *input; /* Input string of RewriteCond */
259 char *pattern; /* the RegExp pattern string */
260 ap_regex_t *regexp; /* the precompiled regexp */
261 int flags; /* Flags which control the match */
262 pattern_type ptype; /* pattern type */
265 /* single linked list for env vars and cookies */
266 typedef struct data_item {
267 struct data_item *next;
272 apr_array_header_t *rewriteconds;/* the corresponding RewriteCond entries */
273 char *pattern; /* the RegExp pattern string */
274 ap_regex_t *regexp; /* the RegExp pattern compilation */
275 char *output; /* the Substitution string */
276 int flags; /* Flags which control the substitution */
277 char *forced_mimetype; /* forced MIME type of substitution */
278 char *forced_handler; /* forced content handler of subst. */
279 int forced_responsecode; /* forced HTTP response status */
280 data_item *env; /* added environment variables */
281 data_item *cookie; /* added cookies */
282 int skip; /* number of next rules to skip */
286 int state; /* the RewriteEngine state */
287 int options; /* the RewriteOption state */
288 #ifndef REWRITELOG_DISABLED
289 const char *rewritelogfile; /* the RewriteLog filename */
290 apr_file_t *rewritelogfp; /* the RewriteLog open filepointer */
291 int rewriteloglevel; /* the RewriteLog level of verbosity */
293 apr_hash_t *rewritemaps; /* the RewriteMap entries */
294 apr_array_header_t *rewriteconds; /* the RewriteCond entries (temp.) */
295 apr_array_header_t *rewriterules; /* the RewriteRule entries */
296 server_rec *server; /* the corresponding server indicator */
297 } rewrite_server_conf;
300 int state; /* the RewriteEngine state */
301 int options; /* the RewriteOption state */
302 apr_array_header_t *rewriteconds; /* the RewriteCond entries (temp.) */
303 apr_array_header_t *rewriterules; /* the RewriteRule entries */
304 char *directory; /* the directory where it applies */
305 const char *baseurl; /* the base-URL where it applies */
306 } rewrite_perdir_conf;
308 /* the (per-child) cache structures.
310 typedef struct cache {
314 apr_thread_mutex_t *lock;
318 /* cached maps contain an mtime for the whole map and live in a subpool
319 * of the cachep->pool. That makes it easy to forget them if necessary.
327 /* the regex structure for the
328 * substitution of backreferences
330 typedef struct backrefinfo {
333 ap_regmatch_t regmatch[AP_MAX_REG_MATCH];
336 /* single linked list used for
339 typedef struct result_list {
340 struct result_list *next;
345 /* context structure for variable lookup and expansion
350 const char *vary_this;
358 * +-------------------------------------------------------+
360 * | static module data
362 * +-------------------------------------------------------+
365 /* the global module structure */
366 module AP_MODULE_DECLARE_DATA rewrite_module;
368 /* rewritemap int: handler function registry */
369 static apr_hash_t *mapfunc_hash;
372 static cache *cachep;
374 /* whether proxy module is available or not */
375 static int proxy_available;
377 /* whether random seed can be reaped */
378 static int rewrite_rand_init_done = 0;
381 static const char *lockname;
382 static apr_global_mutex_t *rewrite_mapr_lock_acquire = NULL;
384 #ifndef REWRITELOG_DISABLED
385 static apr_global_mutex_t *rewrite_log_lock = NULL;
388 /* Optional functions imported from mod_ssl when loaded: */
389 static APR_OPTIONAL_FN_TYPE(ssl_var_lookup) *rewrite_ssl_lookup = NULL;
390 static APR_OPTIONAL_FN_TYPE(ssl_is_https) *rewrite_is_https = NULL;
393 * +-------------------------------------------------------+
395 * | rewriting logfile support
397 * +-------------------------------------------------------+
400 #ifndef REWRITELOG_DISABLED
401 static char *current_logtime(request_rec *r)
407 apr_time_exp_lt(&t, apr_time_now());
409 apr_strftime(tstr, &len, sizeof(tstr), "[%d/%b/%Y:%H:%M:%S ", &t);
410 apr_snprintf(tstr+len, sizeof(tstr)-len, "%c%.2d%.2d]",
411 t.tm_gmtoff < 0 ? '-' : '+',
412 t.tm_gmtoff / (60*60), t.tm_gmtoff % (60*60));
414 return apr_pstrdup(r->pool, tstr);
417 static int open_rewritelog(server_rec *s, apr_pool_t *p)
419 rewrite_server_conf *conf;
422 conf = ap_get_module_config(s->module_config, &rewrite_module);
424 /* - no logfile configured
425 * - logfilename empty
426 * - virtual log shared w/ main server
428 if (!conf->rewritelogfile || !*conf->rewritelogfile || conf->rewritelogfp) {
432 if (*conf->rewritelogfile == '|') {
435 fname = ap_server_root_relative(p, conf->rewritelogfile+1);
437 ap_log_error(APLOG_MARK, APLOG_ERR, APR_EBADPATH, s,
438 "mod_rewrite: Invalid RewriteLog "
439 "path %s", conf->rewritelogfile+1);
443 if ((pl = ap_open_piped_log(p, fname)) == NULL) {
444 ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
445 "mod_rewrite: could not open reliable pipe "
446 "to RewriteLog filter %s", fname);
449 conf->rewritelogfp = ap_piped_log_write_fd(pl);
454 fname = ap_server_root_relative(p, conf->rewritelogfile);
456 ap_log_error(APLOG_MARK, APLOG_ERR, APR_EBADPATH, s,
457 "mod_rewrite: Invalid RewriteLog "
458 "path %s", conf->rewritelogfile);
462 if ((rc = apr_file_open(&conf->rewritelogfp, fname,
463 REWRITELOG_FLAGS, REWRITELOG_MODE, p))
465 ap_log_error(APLOG_MARK, APLOG_ERR, rc, s,
466 "mod_rewrite: could not open RewriteLog "
475 static void do_rewritelog(request_rec *r, int level, char *perdir,
476 const char *fmt, ...)
478 rewrite_server_conf *conf;
479 char *logline, *text;
480 const char *rhost, *rname;
487 conf = ap_get_module_config(r->server->module_config, &rewrite_module);
489 if (!conf->rewritelogfp || level > conf->rewriteloglevel) {
493 rhost = ap_get_remote_host(r->connection, r->per_dir_config,
494 REMOTE_NOLOOKUP, NULL);
495 rname = ap_get_remote_logname(r);
497 for (redir=0, req=r; req->prev; req = req->prev) {
502 text = apr_pvsprintf(r->pool, fmt, ap);
505 logline = apr_psprintf(r->pool, "%s %s %s %s [%s/sid#%pp][rid#%pp/%s%s%s] "
506 "(%d) %s%s%s%s" APR_EOL_STR,
507 rhost ? rhost : "UNKNOWN-HOST",
509 r->user ? (*r->user ? r->user : "\"\"") : "-",
511 ap_get_server_name(r),
514 r->main ? "subreq" : "initial",
515 redir ? "/redir#" : "",
516 redir ? apr_itoa(r->pool, redir) : "",
518 perdir ? "[perdir " : "",
519 perdir ? perdir : "",
523 rv = apr_global_mutex_lock(rewrite_log_lock);
524 if (rv != APR_SUCCESS) {
525 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
526 "apr_global_mutex_lock(rewrite_log_lock) failed");
527 /* XXX: Maybe this should be fatal? */
530 nbytes = strlen(logline);
531 apr_file_write(conf->rewritelogfp, logline, &nbytes);
533 rv = apr_global_mutex_unlock(rewrite_log_lock);
534 if (rv != APR_SUCCESS) {
535 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
536 "apr_global_mutex_unlock(rewrite_log_lock) failed");
537 /* XXX: Maybe this should be fatal? */
542 #endif /* !REWRITELOG_DISABLED */
546 * +-------------------------------------------------------+
548 * | URI and path functions
550 * +-------------------------------------------------------+
553 /* return number of chars of the scheme (incl. '://')
554 * if the URI is absolute (includes a scheme etc.)
557 * NOTE: If you add new schemes here, please have a
558 * look at escape_absolute_uri and splitout_queryargs.
559 * Not every scheme takes query strings and some schemes
560 * may be handled in a special way.
562 * XXX: we may consider a scheme registry, perhaps with
563 * appropriate escape callbacks to allow other modules
564 * to extend mod_rewrite at runtime.
566 static unsigned is_absolute_uri(char *uri)
569 if (*uri == '/' || strlen(uri) <= 5) {
576 if (!strncasecmp(uri, "jp://", 5)) { /* ajp:// */
583 if (!strncasecmp(uri, "alancer://", 10)) { /* balancer:// */
590 if (!strncasecmp(uri, "tp://", 5)) { /* ftp:// */
593 if (!strncasecmp(uri, "cgi://", 6)) { /* fcgi:// */
600 if (!strncasecmp(uri, "opher://", 8)) { /* gopher:// */
607 if (!strncasecmp(uri, "ttp://", 6)) { /* http:// */
610 else if (!strncasecmp(uri, "ttps://", 7)) { /* https:// */
617 if (!strncasecmp(uri, "dap://", 6)) { /* ldap:// */
624 if (!strncasecmp(uri, "ailto:", 6)) { /* mailto: */
631 if (!strncasecmp(uri, "ews:", 4)) { /* news: */
634 else if (!strncasecmp(uri, "ntp://", 6)) { /* nntp:// */
644 * escape absolute uri, which may or may not be path oriented.
645 * So let's handle them differently.
647 static char *escape_absolute_uri(apr_pool_t *p, char *uri, unsigned scheme)
652 * NULL should indicate elsewhere, that something's wrong
654 if (!scheme || strlen(uri) < scheme) {
660 /* scheme with authority part? */
663 while (*cp && *cp != '/') {
667 /* nothing after the hostpart. ready! */
668 if (!*cp || !*++cp) {
669 return apr_pstrdup(p, uri);
672 /* remember the hostname stuff */
675 /* special thing for ldap.
676 * The parts are separated by question marks. From RFC 2255:
677 * ldapurl = scheme "://" [hostport] ["/"
678 * [dn ["?" [attributes] ["?" [scope]
679 * ["?" [filter] ["?" extensions]]]]]]
681 if (!strncasecmp(uri, "ldap", 4)) {
685 token[0] = cp = apr_pstrdup(p, cp);
686 while (*cp && c < 4) {
694 return apr_pstrcat(p, apr_pstrndup(p, uri, scheme),
695 ap_escape_uri(p, token[0]),
696 (c >= 1) ? "?" : NULL,
697 (c >= 1) ? ap_escape_uri(p, token[1]) : NULL,
698 (c >= 2) ? "?" : NULL,
699 (c >= 2) ? ap_escape_uri(p, token[2]) : NULL,
700 (c >= 3) ? "?" : NULL,
701 (c >= 3) ? ap_escape_uri(p, token[3]) : NULL,
702 (c >= 4) ? "?" : NULL,
703 (c >= 4) ? ap_escape_uri(p, token[4]) : NULL,
708 /* Nothing special here. Apply normal escaping. */
709 return apr_pstrcat(p, apr_pstrndup(p, uri, scheme),
710 ap_escape_uri(p, cp), NULL);
714 * split out a QUERY_STRING part from
715 * the current URI string
717 static void splitout_queryargs(request_rec *r, int qsappend)
721 /* don't touch, unless it's an http or mailto URL.
722 * See RFC 1738 and RFC 2368.
724 if (is_absolute_uri(r->filename)
725 && strncasecmp(r->filename, "ajp", 3)
726 && strncasecmp(r->filename, "balancer", 8)
727 && strncasecmp(r->filename, "http", 4)
728 && strncasecmp(r->filename, "mailto", 6)) {
729 r->args = NULL; /* forget the query that's still flying around */
733 q = ap_strchr(r->filename, '?');
738 olduri = apr_pstrdup(r->pool, r->filename);
741 r->args = apr_pstrcat(r->pool, q, "&", r->args, NULL);
744 r->args = apr_pstrdup(r->pool, q);
747 len = strlen(r->args);
751 else if (r->args[len-1] == '&') {
752 r->args[len-1] = '\0';
755 rewritelog((r, 3, NULL, "split uri=%s -> uri=%s, args=%s", olduri,
756 r->filename, r->args ? r->args : "<none>"));
763 * strip 'http[s]://ourhost/' from URI
765 static void reduce_uri(request_rec *r)
770 cp = (char *)ap_http_scheme(r);
772 if ( strlen(r->filename) > l+3
773 && strncasecmp(r->filename, cp, l) == 0
774 && r->filename[l] == ':'
775 && r->filename[l+1] == '/'
776 && r->filename[l+2] == '/' ) {
779 char *portp, *host, *url, *scratch;
781 scratch = apr_pstrdup(r->pool, r->filename); /* our scratchpad */
783 /* cut the hostname and port out of the URI */
784 cp = host = scratch + l + 3; /* 3 == strlen("://") */
785 while (*cp && *cp != '/' && *cp != ':') {
789 if (*cp == ':') { /* additional port given */
792 while (*cp && *cp != '/') {
798 url = r->filename + (cp - scratch);
803 else if (*cp == '/') { /* default port */
806 port = ap_default_port(r);
807 url = r->filename + (cp - scratch);
810 port = ap_default_port(r);
814 /* now check whether we could reduce it to a local path... */
815 if (ap_matches_request_vhost(r, host, port)) {
816 rewritelog((r, 3, NULL, "reduce %s -> %s", r->filename, url));
817 r->filename = apr_pstrdup(r->pool, url);
825 * add 'http[s]://ourhost[:ourport]/' to URI
826 * if URI is still not fully qualified
828 static void fully_qualify_uri(request_rec *r)
830 if (!is_absolute_uri(r->filename)) {
831 const char *thisserver;
835 thisserver = ap_get_server_name(r);
836 port = ap_get_server_port(r);
837 thisport = ap_is_default_port(port, r)
839 : apr_psprintf(r->pool, ":%u", port);
841 r->filename = apr_psprintf(r->pool, "%s://%s%s%s%s",
842 ap_http_scheme(r), thisserver, thisport,
843 (*r->filename == '/') ? "" : "/",
851 * stat() only the first segment of a path
853 static int prefix_stat(const char *path, apr_pool_t *pool)
855 const char *curpath = path;
861 rv = apr_filepath_root(&root, &curpath, APR_FILEPATH_TRUENAME, pool);
863 if (rv != APR_SUCCESS) {
867 /* let's recognize slashes only, the mod_rewrite semantics are opaque
870 if ((slash = ap_strchr_c(curpath, '/')) != NULL) {
871 rv = apr_filepath_merge(&statpath, root,
872 apr_pstrndup(pool, curpath,
873 (apr_size_t)(slash - curpath)),
874 APR_FILEPATH_NOTABOVEROOT |
875 APR_FILEPATH_NOTRELATIVE, pool);
878 rv = apr_filepath_merge(&statpath, root, curpath,
879 APR_FILEPATH_NOTABOVEROOT |
880 APR_FILEPATH_NOTRELATIVE, pool);
883 if (rv == APR_SUCCESS) {
886 if (apr_stat(&sb, statpath, APR_FINFO_MIN, pool) == APR_SUCCESS) {
895 * substitute the prefix path 'match' in 'input' with 'subst' (RewriteBase)
897 static char *subst_prefix_path(request_rec *r, char *input, char *match,
900 apr_size_t len = strlen(match);
902 if (len && match[len - 1] == '/') {
906 if (!strncmp(input, match, len) && input[len++] == '/') {
907 apr_size_t slen, outlen;
910 rewritelog((r, 5, NULL, "strip matching prefix: %s -> %s", input,
913 slen = strlen(subst);
914 if (slen && subst[slen - 1] != '/') {
918 outlen = strlen(input) + slen - len;
919 output = apr_palloc(r->pool, outlen + 1); /* don't forget the \0 */
921 memcpy(output, subst, slen);
922 if (slen && !output[slen-1]) {
923 output[slen-1] = '/';
925 memcpy(output+slen, input+len, outlen - slen);
926 output[outlen] = '\0';
928 rewritelog((r, 4, NULL, "add subst prefix: %s -> %s", input+len,
934 /* prefix didn't match */
940 * +-------------------------------------------------------+
944 * +-------------------------------------------------------+
947 static void set_cache_value(const char *name, apr_time_t t, char *key,
954 apr_thread_mutex_lock(cachep->lock);
956 map = apr_hash_get(cachep->maps, name, APR_HASH_KEY_STRING);
961 if (apr_pool_create(&p, cachep->pool) != APR_SUCCESS) {
963 apr_thread_mutex_unlock(cachep->lock);
968 map = apr_palloc(cachep->pool, sizeof(cachedmap));
970 map->entries = apr_hash_make(map->pool);
973 apr_hash_set(cachep->maps, name, APR_HASH_KEY_STRING, map);
975 else if (map->mtime != t) {
976 apr_pool_clear(map->pool);
977 map->entries = apr_hash_make(map->pool);
981 /* Now we should have a valid map->entries hash, where we
982 * can store our value.
984 * We need to copy the key and the value into OUR pool,
985 * so that we don't leave it during the r->pool cleanup.
987 apr_hash_set(map->entries,
988 apr_pstrdup(map->pool, key), APR_HASH_KEY_STRING,
989 apr_pstrdup(map->pool, val));
992 apr_thread_mutex_unlock(cachep->lock);
999 static char *get_cache_value(const char *name, apr_time_t t, char *key,
1007 apr_thread_mutex_lock(cachep->lock);
1009 map = apr_hash_get(cachep->maps, name, APR_HASH_KEY_STRING);
1012 /* if this map is outdated, forget it. */
1013 if (map->mtime != t) {
1014 apr_pool_clear(map->pool);
1015 map->entries = apr_hash_make(map->pool);
1019 val = apr_hash_get(map->entries, key, APR_HASH_KEY_STRING);
1021 /* copy the cached value into the supplied pool,
1022 * where it belongs (r->pool usually)
1024 val = apr_pstrdup(p, val);
1030 apr_thread_mutex_unlock(cachep->lock);
1037 static int init_cache(apr_pool_t *p)
1039 cachep = apr_palloc(p, sizeof(cache));
1040 if (apr_pool_create(&cachep->pool, p) != APR_SUCCESS) {
1041 cachep = NULL; /* turns off cache */
1045 cachep->maps = apr_hash_make(cachep->pool);
1047 (void)apr_thread_mutex_create(&(cachep->lock), APR_THREAD_MUTEX_DEFAULT, p);
1055 * +-------------------------------------------------------+
1059 * +-------------------------------------------------------+
1063 * General Note: key is already a fresh string, created (expanded) just
1064 * for the purpose to be passed in here. So one can modify key itself.
1067 static char *rewrite_mapfunc_toupper(request_rec *r, char *key)
1071 for (p = key; *p; ++p) {
1072 *p = apr_toupper(*p);
1078 static char *rewrite_mapfunc_tolower(request_rec *r, char *key)
1080 ap_str_tolower(key);
1085 static char *rewrite_mapfunc_escape(request_rec *r, char *key)
1087 return ap_escape_uri(r->pool, key);
1090 static char *rewrite_mapfunc_unescape(request_rec *r, char *key)
1092 ap_unescape_url(key);
1097 static char *select_random_value_part(request_rec *r, char *value)
1102 /* count number of distinct values */
1103 while ((p = ap_strchr(p, '|')) != NULL) {
1109 /* initialize random generator
1111 * XXX: Probably this should be wrapped into a thread mutex,
1112 * shouldn't it? Is it worth the effort?
1114 if (!rewrite_rand_init_done) {
1115 srand((unsigned)(getpid()));
1116 rewrite_rand_init_done = 1;
1119 /* select a random subvalue */
1120 n = (int)(((double)(rand() % RAND_MAX) / RAND_MAX) * n + 1);
1122 /* extract it from the whole string */
1123 while (--n && (value = ap_strchr(value, '|')) != NULL) {
1127 if (value) { /* should not be NULL, but ... */
1128 p = ap_strchr(value, '|');
1138 /* child process code */
1139 static void rewrite_child_errfn(apr_pool_t *p, apr_status_t err,
1142 ap_log_error(APLOG_MARK, APLOG_ERR, err, NULL, "%s", desc);
1145 static apr_status_t rewritemap_program_child(apr_pool_t *p,
1146 const char *progname, char **argv,
1151 apr_procattr_t *procattr;
1152 apr_proc_t *procnew;
1154 if ( APR_SUCCESS == (rc=apr_procattr_create(&procattr, p))
1155 && APR_SUCCESS == (rc=apr_procattr_io_set(procattr, APR_FULL_BLOCK,
1156 APR_FULL_BLOCK, APR_NO_PIPE))
1157 && APR_SUCCESS == (rc=apr_procattr_dir_set(procattr,
1158 ap_make_dirstr_parent(p, argv[0])))
1159 && APR_SUCCESS == (rc=apr_procattr_cmdtype_set(procattr, APR_PROGRAM))
1160 && APR_SUCCESS == (rc=apr_procattr_child_errfn_set(procattr,
1161 rewrite_child_errfn))
1162 && APR_SUCCESS == (rc=apr_procattr_error_check_set(procattr, 1))) {
1164 procnew = apr_pcalloc(p, sizeof(*procnew));
1165 rc = apr_proc_create(procnew, argv[0], (const char **)argv, NULL,
1168 if (rc == APR_SUCCESS) {
1169 apr_pool_note_subprocess(p, procnew, APR_KILL_AFTER_TIMEOUT);
1172 (*fpin) = procnew->in;
1176 (*fpout) = procnew->out;
1184 static apr_status_t run_rewritemap_programs(server_rec *s, apr_pool_t *p)
1186 rewrite_server_conf *conf;
1187 apr_hash_index_t *hi;
1189 int lock_warning_issued = 0;
1191 conf = ap_get_module_config(s->module_config, &rewrite_module);
1193 /* If the engine isn't turned on,
1194 * don't even try to do anything.
1196 if (conf->state == ENGINE_DISABLED) {
1200 for (hi = apr_hash_first(p, conf->rewritemaps); hi; hi = apr_hash_next(hi)){
1201 apr_file_t *fpin = NULL;
1202 apr_file_t *fpout = NULL;
1203 rewritemap_entry *map;
1206 apr_hash_this(hi, NULL, NULL, &val);
1209 if (map->type != MAPTYPE_PRG) {
1212 if (!(map->argv[0]) || !*(map->argv[0]) || map->fpin || map->fpout) {
1216 if (!lock_warning_issued && (!lockname || !*lockname)) {
1217 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
1218 "mod_rewrite: Running external rewrite maps "
1219 "without defining a RewriteLock is DANGEROUS!");
1220 ++lock_warning_issued;
1223 rc = rewritemap_program_child(p, map->argv[0], map->argv,
1225 if (rc != APR_SUCCESS || fpin == NULL || fpout == NULL) {
1226 ap_log_error(APLOG_MARK, APLOG_ERR, rc, s,
1227 "mod_rewrite: could not start RewriteMap "
1228 "program %s", map->checkfile);
1240 * +-------------------------------------------------------+
1242 * | Lookup functions
1244 * +-------------------------------------------------------+
1247 static char *lookup_map_txtfile(request_rec *r, const char *file, char *key)
1249 apr_file_t *fp = NULL;
1250 char line[REWRITE_MAX_TXT_MAP_LINE + 1]; /* +1 for \0 */
1251 char *value, *keylast;
1253 if (apr_file_open(&fp, file, APR_READ|APR_BUFFERED, APR_OS_DEFAULT,
1254 r->pool) != APR_SUCCESS) {
1258 keylast = key + strlen(key);
1260 while (apr_file_gets(line, sizeof(line), fp) == APR_SUCCESS) {
1263 /* ignore comments and lines starting with whitespaces */
1264 if (*line == '#' || apr_isspace(*line)) {
1270 while (c < keylast && *p == *c && !apr_isspace(*p)) {
1275 /* key doesn't match - ignore. */
1276 if (c != keylast || !apr_isspace(*p)) {
1280 /* jump to the value */
1281 while (*p && apr_isspace(*p)) {
1285 /* no value? ignore */
1290 /* extract the value and return. */
1292 while (*p && !apr_isspace(*p)) {
1295 value = apr_pstrmemdup(r->pool, c, p - c);
1303 static char *lookup_map_dbmfile(request_rec *r, const char *file,
1304 const char *dbmtype, char *key)
1306 apr_dbm_t *dbmfp = NULL;
1311 if (apr_dbm_open_ex(&dbmfp, dbmtype, file, APR_DBM_READONLY, APR_OS_DEFAULT,
1312 r->pool) != APR_SUCCESS) {
1317 dbmkey.dsize = strlen(key);
1319 if (apr_dbm_fetch(dbmfp, dbmkey, &dbmval) == APR_SUCCESS && dbmval.dptr) {
1320 value = apr_pstrmemdup(r->pool, dbmval.dptr, dbmval.dsize);
1326 apr_dbm_close(dbmfp);
1330 static char *lookup_map_dbd(request_rec *r, char *key, const char *label)
1333 apr_dbd_prepared_t *stmt;
1335 apr_dbd_results_t *res = NULL;
1336 apr_dbd_row_t *row = NULL;
1337 const char *ret = NULL;
1339 ap_dbd_t *db = dbd_acquire(r);
1341 stmt = apr_hash_get(db->prepared, label, APR_HASH_KEY_STRING);
1343 rv = apr_dbd_pvselect(db->driver, r->pool, db->handle, &res,
1344 stmt, 0, key, NULL);
1346 errmsg = apr_dbd_error(db->driver, db->handle, rv);
1347 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1348 "rewritemap: error %s querying for %s", errmsg, key);
1351 while (rv = apr_dbd_get_row(db->driver, r->pool, res, &row, -1), rv == 0) {
1354 ret = apr_dbd_get_entry(db->driver, row, 0);
1357 /* randomise crudely amongst multiple results */
1358 if ((double)rand() < (double)RAND_MAX/(double)n) {
1359 ret = apr_dbd_get_entry(db->driver, row, 0);
1364 errmsg = apr_dbd_error(db->driver, db->handle, rv);
1365 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1366 "rewritemap: error %s looking up %s", errmsg, key);
1372 return apr_pstrdup(r->pool, ret);
1374 /* what's a fair rewritelog level for this? */
1375 rewritelog((r, 3, NULL, "Multiple values found for %s", key));
1376 return apr_pstrdup(r->pool, ret);
1380 static char *lookup_map_program(request_rec *r, apr_file_t *fpin,
1381 apr_file_t *fpout, char *key)
1385 apr_size_t i, nbytes, combined_len = 0;
1387 const char *eol = APR_EOL_STR;
1388 apr_size_t eolc = 0;
1390 result_list *buflist = NULL, *curbuf = NULL;
1393 struct iovec iova[2];
1397 /* when `RewriteEngine off' was used in the per-server
1398 * context then the rewritemap-programs were not spawned.
1399 * In this case using such a map (usually in per-dir context)
1400 * is useless because it is not available.
1402 * newlines in the key leave bytes in the pipe and cause
1403 * bad things to happen (next map lookup will use the chars
1404 * after the \n instead of the new key etc etc - in other words,
1405 * the Rewritemap falls out of sync with the requests).
1407 if (fpin == NULL || fpout == NULL || ap_strchr(key, '\n')) {
1412 if (rewrite_mapr_lock_acquire) {
1413 rv = apr_global_mutex_lock(rewrite_mapr_lock_acquire);
1414 if (rv != APR_SUCCESS) {
1415 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1416 "apr_global_mutex_lock(rewrite_mapr_lock_acquire) "
1418 return NULL; /* Maybe this should be fatal? */
1422 /* write out the request key */
1424 nbytes = strlen(key);
1425 apr_file_write(fpin, key, &nbytes);
1427 apr_file_write(fpin, "\n", &nbytes);
1429 iova[0].iov_base = key;
1430 iova[0].iov_len = strlen(key);
1431 iova[1].iov_base = "\n";
1432 iova[1].iov_len = 1;
1435 apr_file_writev(fpin, iova, niov, &nbytes);
1438 buf = apr_palloc(r->pool, REWRITE_PRG_MAP_BUF + 1);
1440 /* read in the response value */
1442 apr_file_read(fpout, &c, &nbytes);
1445 while (nbytes == 1 && (i < REWRITE_PRG_MAP_BUF)) {
1446 if (c == eol[eolc]) {
1448 /* remove eol from the buffer */
1451 curbuf->len -= eolc-i;
1462 /* only partial (invalid) eol sequence -> reset the counter */
1467 /* catch binary mode, e.g. on Win32 */
1468 else if (c == '\n') {
1474 apr_file_read(fpout, &c, &nbytes);
1477 /* well, if there wasn't a newline yet, we need to read further */
1478 if (buflist || (nbytes == 1 && !found_nl)) {
1480 curbuf = buflist = apr_palloc(r->pool, sizeof(*buflist));
1483 curbuf->next = apr_palloc(r->pool, sizeof(*buflist));
1484 curbuf = curbuf->next;
1487 curbuf->next = NULL;
1490 curbuf->string = buf;
1493 buf = apr_palloc(r->pool, REWRITE_PRG_MAP_BUF);
1496 if (nbytes == 1 && !found_nl) {
1505 /* concat the stuff */
1509 p = buf = apr_palloc(r->pool, combined_len + 1); /* \0 */
1512 memcpy(p, buflist->string, buflist->len);
1515 buflist = buflist->next;
1524 /* give the lock back */
1525 if (rewrite_mapr_lock_acquire) {
1526 rv = apr_global_mutex_unlock(rewrite_mapr_lock_acquire);
1527 if (rv != APR_SUCCESS) {
1528 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1529 "apr_global_mutex_unlock(rewrite_mapr_lock_acquire) "
1531 return NULL; /* Maybe this should be fatal? */
1535 /* catch the "failed" case */
1536 if (i == 4 && !strcasecmp(buf, "NULL")) {
1544 * generic map lookup
1546 static char *lookup_map(request_rec *r, char *name, char *key)
1548 rewrite_server_conf *conf;
1549 rewritemap_entry *s;
1554 /* get map configuration */
1555 conf = ap_get_module_config(r->server->module_config, &rewrite_module);
1556 s = apr_hash_get(conf->rewritemaps, name, APR_HASH_KEY_STRING);
1558 /* map doesn't exist */
1565 * Text file map (perhaps random)
1569 rv = apr_stat(&st, s->checkfile, APR_FINFO_MIN, r->pool);
1570 if (rv != APR_SUCCESS) {
1571 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1572 "mod_rewrite: can't access text RewriteMap file %s",
1574 rewritelog((r, 1, NULL,
1575 "can't open RewriteMap file, see error log"));
1579 value = get_cache_value(s->cachename, st.mtime, key, r->pool);
1581 rewritelog((r, 6, NULL,
1582 "cache lookup FAILED, forcing new map lookup"));
1584 value = lookup_map_txtfile(r, s->datafile, key);
1586 rewritelog((r, 5, NULL, "map lookup FAILED: map=%s[txt] key=%s",
1588 set_cache_value(s->cachename, st.mtime, key, "");
1592 rewritelog((r, 5, NULL,"map lookup OK: map=%s[txt] key=%s -> val=%s",
1594 set_cache_value(s->cachename, st.mtime, key, value);
1597 rewritelog((r,5,NULL,"cache lookup OK: map=%s[txt] key=%s -> val=%s",
1601 if (s->type == MAPTYPE_RND && *value) {
1602 value = select_random_value_part(r, value);
1603 rewritelog((r, 5, NULL, "randomly chosen the subvalue `%s'",value));
1606 return *value ? value : NULL;
1612 rv = apr_stat(&st, s->checkfile, APR_FINFO_MIN, r->pool);
1613 if (rv != APR_SUCCESS) {
1614 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1615 "mod_rewrite: can't access DBM RewriteMap file %s",
1618 else if(s->checkfile2 != NULL) {
1621 rv = apr_stat(&st2, s->checkfile2, APR_FINFO_MIN, r->pool);
1622 if (rv != APR_SUCCESS) {
1623 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1624 "mod_rewrite: can't access DBM RewriteMap "
1625 "file %s", s->checkfile2);
1627 else if(st2.mtime > st.mtime) {
1628 st.mtime = st2.mtime;
1631 if(rv != APR_SUCCESS) {
1632 rewritelog((r, 1, NULL,
1633 "can't open DBM RewriteMap file, see error log"));
1637 value = get_cache_value(s->cachename, st.mtime, key, r->pool);
1639 rewritelog((r, 6, NULL,
1640 "cache lookup FAILED, forcing new map lookup"));
1642 value = lookup_map_dbmfile(r, s->datafile, s->dbmtype, key);
1644 rewritelog((r, 5, NULL, "map lookup FAILED: map=%s[dbm] key=%s",
1646 set_cache_value(s->cachename, st.mtime, key, "");
1650 rewritelog((r, 5, NULL, "map lookup OK: map=%s[dbm] key=%s -> "
1651 "val=%s", name, key, value));
1653 set_cache_value(s->cachename, st.mtime, key, value);
1657 rewritelog((r, 5, NULL, "cache lookup OK: map=%s[dbm] key=%s -> val=%s",
1659 return *value ? value : NULL;
1662 * SQL map without cache
1665 value = lookup_map_dbd(r, key, s->dbdq);
1667 rewritelog((r, 5, NULL, "SQL map lookup FAILED: map %s key=%s",
1672 rewritelog((r, 5, NULL, "SQL map lookup OK: map %s key=%s, val=%s",
1678 * SQL map with cache
1680 case MAPTYPE_DBD_CACHE:
1681 value = get_cache_value(s->cachename, 0, key, r->pool);
1683 rewritelog((r, 6, NULL,
1684 "cache lookup FAILED, forcing new map lookup"));
1686 value = lookup_map_dbd(r, key, s->dbdq);
1688 rewritelog((r, 5, NULL, "SQL map lookup FAILED: map %s key=%s",
1690 set_cache_value(s->cachename, 0, key, "");
1694 rewritelog((r, 5, NULL, "SQL map lookup OK: map %s key=%s, val=%s",
1697 set_cache_value(s->cachename, 0, key, value);
1701 rewritelog((r, 5, NULL, "cache lookup OK: map=%s[SQL] key=%s, val=%s",
1703 return *value ? value : NULL;
1709 value = lookup_map_program(r, s->fpin, s->fpout, key);
1711 rewritelog((r, 5,NULL,"map lookup FAILED: map=%s key=%s", name,
1716 rewritelog((r, 5, NULL, "map lookup OK: map=%s key=%s -> val=%s",
1724 value = s->func(r, key);
1726 rewritelog((r, 5,NULL,"map lookup FAILED: map=%s key=%s", name,
1731 rewritelog((r, 5, NULL, "map lookup OK: map=%s key=%s -> val=%s",
1740 * lookup a HTTP header and set VARY note
1742 static const char *lookup_header(const char *name, rewrite_ctx *ctx)
1744 const char *val = apr_table_get(ctx->r->headers_in, name);
1747 ctx->vary_this = ctx->vary_this
1748 ? apr_pstrcat(ctx->r->pool, ctx->vary_this, ", ",
1750 : apr_pstrdup(ctx->r->pool, name);
1757 * lookahead helper function
1758 * Determine the correct URI path in perdir context
1760 static APR_INLINE const char *la_u(rewrite_ctx *ctx)
1762 rewrite_perdir_conf *conf;
1764 if (*ctx->uri == '/') {
1768 conf = ap_get_module_config(ctx->r->per_dir_config, &rewrite_module);
1770 return apr_pstrcat(ctx->r->pool, conf->baseurl
1771 ? conf->baseurl : conf->directory,
1776 * generic variable lookup
1778 static char *lookup_variable(char *var, rewrite_ctx *ctx)
1781 request_rec *r = ctx->r;
1782 apr_size_t varlen = strlen(var);
1786 return apr_pstrdup(r->pool, "");
1791 /* fast tests for variable length variables (sic) first */
1792 if (var[3] == ':') {
1793 if (var[4] && !strncasecmp(var, "ENV", 3)) {
1795 result = apr_table_get(r->notes, var);
1798 result = apr_table_get(r->subprocess_env, var);
1801 result = getenv(var);
1804 else if (var[4] && !strncasecmp(var, "SSL", 3) && rewrite_ssl_lookup) {
1805 result = rewrite_ssl_lookup(r->pool, r->server, r->connection, r,
1809 else if (var[4] == ':') {
1814 if (!strncasecmp(var, "HTTP", 4)) {
1815 result = lookup_header(var+5, ctx);
1817 else if (!strncasecmp(var, "LA-U", 4)) {
1818 if (ctx->uri && subreq_ok(r)) {
1819 path = ctx->perdir ? la_u(ctx) : ctx->uri;
1820 rr = ap_sub_req_lookup_uri(path, r, NULL);
1822 result = apr_pstrdup(r->pool, lookup_variable(var+5, ctx));
1824 ap_destroy_sub_req(rr);
1826 rewritelog((r, 5, ctx->perdir, "lookahead: path=%s var=%s "
1827 "-> val=%s", path, var+5, result));
1829 return (char *)result;
1832 else if (!strncasecmp(var, "LA-F", 4)) {
1833 if (ctx->uri && subreq_ok(r)) {
1835 if (ctx->perdir && *path == '/') {
1836 /* sigh, the user wants a file based subrequest, but
1837 * we can't do one, since we don't know what the file
1838 * path is! In this case behave like LA-U.
1840 rr = ap_sub_req_lookup_uri(path, r, NULL);
1844 rewrite_perdir_conf *conf;
1846 conf = ap_get_module_config(r->per_dir_config,
1849 path = apr_pstrcat(r->pool, conf->directory, path,
1853 rr = ap_sub_req_lookup_file(path, r, NULL);
1857 result = apr_pstrdup(r->pool, lookup_variable(var+5, ctx));
1859 ap_destroy_sub_req(rr);
1861 rewritelog((r, 5, ctx->perdir, "lookahead: path=%s var=%s "
1862 "-> val=%s", path, var+5, result));
1864 return (char *)result;
1870 /* well, do it the hard way */
1875 /* can't do this above, because of the getenv call */
1876 for (p = var; *p; ++p) {
1877 *p = apr_toupper(*p);
1882 if (!strcmp(var, "TIME")) {
1883 apr_time_exp_lt(&tm, apr_time_now());
1884 result = apr_psprintf(r->pool, "%04d%02d%02d%02d%02d%02d",
1885 tm.tm_year+1900, tm.tm_mon+1, tm.tm_mday,
1886 tm.tm_hour, tm.tm_min, tm.tm_sec);
1887 rewritelog((r, 1, ctx->perdir, "RESULT='%s'", result));
1888 return (char *)result;
1893 if (!strcmp(var, "HTTPS")) {
1894 int flag = rewrite_is_https && rewrite_is_https(r->connection);
1895 return apr_pstrdup(r->pool, flag ? "on" : "off");
1902 if (!strcmp(var, "TIME_DAY")) {
1903 apr_time_exp_lt(&tm, apr_time_now());
1904 return apr_psprintf(r->pool, "%02d", tm.tm_mday);
1909 if (!strcmp(var, "TIME_SEC")) {
1910 apr_time_exp_lt(&tm, apr_time_now());
1911 return apr_psprintf(r->pool, "%02d", tm.tm_sec);
1916 if (!strcmp(var, "TIME_MIN")) {
1917 apr_time_exp_lt(&tm, apr_time_now());
1918 return apr_psprintf(r->pool, "%02d", tm.tm_min);
1923 if (!strcmp(var, "TIME_MON")) {
1924 apr_time_exp_lt(&tm, apr_time_now());
1925 return apr_psprintf(r->pool, "%02d", tm.tm_mon+1);
1934 if (var[8] == 'Y' && !strcmp(var, "TIME_WDAY")) {
1935 apr_time_exp_lt(&tm, apr_time_now());
1936 return apr_psprintf(r->pool, "%d", tm.tm_wday);
1938 else if (!strcmp(var, "TIME_YEAR")) {
1939 apr_time_exp_lt(&tm, apr_time_now());
1940 return apr_psprintf(r->pool, "%04d", tm.tm_year+1900);
1945 if (!strcmp(var, "IS_SUBREQ")) {
1946 result = (r->main ? "true" : "false");
1951 if (!strcmp(var, "PATH_INFO")) {
1952 result = r->path_info;
1957 if (!strcmp(var, "AUTH_TYPE")) {
1958 result = r->ap_auth_type;
1963 if (!strcmp(var, "HTTP_HOST")) {
1964 result = lookup_header("Host", ctx);
1969 if (!strcmp(var, "TIME_HOUR")) {
1970 apr_time_exp_lt(&tm, apr_time_now());
1971 return apr_psprintf(r->pool, "%02d", tm.tm_hour);
1980 if (!strcmp(var, "SERVER_NAME")) {
1981 result = ap_get_server_name(r);
1986 if (*var == 'R' && !strcmp(var, "REMOTE_ADDR")) {
1987 result = r->connection->remote_ip;
1989 else if (!strcmp(var, "SERVER_ADDR")) {
1990 result = r->connection->local_ip;
1995 if (*var == 'H' && !strcmp(var, "HTTP_ACCEPT")) {
1996 result = lookup_header("Accept", ctx);
1998 else if (!strcmp(var, "THE_REQUEST")) {
1999 result = r->the_request;
2004 if (!strcmp(var, "API_VERSION")) {
2005 return apr_psprintf(r->pool, "%d:%d",
2006 MODULE_MAGIC_NUMBER_MAJOR,
2007 MODULE_MAGIC_NUMBER_MINOR);
2012 if (!strcmp(var, "HTTP_COOKIE")) {
2013 result = lookup_header("Cookie", ctx);
2018 if (*var == 'S' && !strcmp(var, "SERVER_PORT")) {
2019 return apr_psprintf(r->pool, "%u", ap_get_server_port(r));
2021 else if (var[7] == 'H' && !strcmp(var, "REMOTE_HOST")) {
2022 result = ap_get_remote_host(r->connection,r->per_dir_config,
2025 else if (!strcmp(var, "REMOTE_PORT")) {
2026 return apr_itoa(r->pool, r->connection->remote_addr->port);
2031 if (*var == 'R' && !strcmp(var, "REMOTE_USER")) {
2034 else if (!strcmp(var, "SCRIPT_USER")) {
2035 result = "<unknown>";
2036 if (r->finfo.valid & APR_FINFO_USER) {
2037 apr_uid_name_get((char **)&result, r->finfo.user,
2044 if (!strcmp(var, "REQUEST_URI")) {
2054 if (!strcmp(var, "SCRIPT_GROUP")) {
2055 result = "<unknown>";
2056 if (r->finfo.valid & APR_FINFO_GROUP) {
2057 apr_gid_name_get((char **)&result, r->finfo.group,
2064 if (!strcmp(var, "REMOTE_IDENT")) {
2065 result = ap_get_remote_logname(r);
2070 if (!strcmp(var, "HTTP_REFERER")) {
2071 result = lookup_header("Referer", ctx);
2076 if (!strcmp(var, "QUERY_STRING")) {
2082 if (!strcmp(var, "SERVER_ADMIN")) {
2083 result = r->server->server_admin;
2090 if (!strcmp(var, "DOCUMENT_ROOT")) {
2091 result = ap_document_root(r);
2096 if (*var == 'H' && !strcmp(var, "HTTP_FORWARDED")) {
2097 result = lookup_header("Forwarded", ctx);
2099 else if (!strcmp(var, "REQUEST_METHOD")) {
2107 if (!strcmp(var, "HTTP_USER_AGENT")) {
2108 result = lookup_header("User-Agent", ctx);
2113 if (!strcmp(var, "SCRIPT_FILENAME")) {
2114 result = r->filename; /* same as request_filename (16) */
2119 if (!strcmp(var, "SERVER_PROTOCOL")) {
2120 result = r->protocol;
2125 if (!strcmp(var, "SERVER_SOFTWARE")) {
2126 result = ap_get_server_banner();
2133 if (!strcmp(var, "REQUEST_FILENAME")) {
2134 result = r->filename; /* same as script_filename (15) */
2139 if (!strcmp(var, "HTTP_PROXY_CONNECTION")) {
2140 result = lookup_header("Proxy-Connection", ctx);
2146 return apr_pstrdup(r->pool, result ? result : "");
2151 * +-------------------------------------------------------+
2153 * | Expansion functions
2155 * +-------------------------------------------------------+
2159 * Bracketed expression handling
2160 * s points after the opening bracket
2162 static APR_INLINE char *find_closing_curly(char *s)
2166 for (depth = 1; *s; ++s) {
2167 if (*s == RIGHT_CURLY && --depth == 0) {
2170 else if (*s == LEFT_CURLY) {
2178 static APR_INLINE char *find_char_in_curlies(char *s, int c)
2182 for (depth = 1; *s; ++s) {
2183 if (*s == c && depth == 1) {
2186 else if (*s == RIGHT_CURLY && --depth == 0) {
2189 else if (*s == LEFT_CURLY) {
2197 /* perform all the expansions on the input string
2198 * putting the result into a new string
2200 * for security reasons this expansion must be performed in a
2201 * single pass, otherwise an attacker can arrange for the result
2202 * of an earlier expansion to include expansion specifiers that
2203 * are interpreted by a later expansion, producing results that
2204 * were not intended by the administrator.
2206 static char *do_expand(char *input, rewrite_ctx *ctx, rewriterule_entry *entry)
2208 result_list *result, *current;
2209 result_list sresult[SMALL_EXPANSION];
2211 apr_size_t span, inputlen, outlen;
2213 apr_pool_t *pool = ctx->r->pool;
2215 span = strcspn(input, "\\$%");
2216 inputlen = strlen(input);
2219 if (inputlen == span) {
2220 return apr_pstrdup(pool, input);
2223 /* well, actually something to do */
2224 result = current = &(sresult[spc++]);
2227 current->next = NULL;
2228 current->string = input;
2229 current->len = span;
2232 /* loop for specials */
2234 /* prepare next entry */
2236 current->next = (spc < SMALL_EXPANSION)
2238 : (result_list *)apr_palloc(pool,
2239 sizeof(result_list));
2240 current = current->next;
2241 current->next = NULL;
2245 /* escaped character */
2250 current->string = p;
2254 current->string = ++p;
2259 /* variable or map lookup */
2260 else if (p[1] == '{') {
2263 endp = find_closing_curly(p+2);
2266 current->string = p;
2271 /* variable lookup */
2272 else if (*p == '%') {
2273 p = lookup_variable(apr_pstrmemdup(pool, p+2, endp-p-2), ctx);
2276 current->len = span;
2277 current->string = p;
2283 else { /* *p == '$' */
2287 * To make rewrite maps useful, the lookup key and
2288 * default values must be expanded, so we make
2289 * recursive calls to do the work. For security
2290 * reasons we must never expand a string that includes
2291 * verbatim data from the network. The recursion here
2292 * isn't a problem because the result of expansion is
2293 * only passed to lookup_map() so it cannot be
2294 * re-expanded, only re-looked-up. Another way of
2295 * looking at it is that the recursion is entirely
2296 * driven by the syntax of the nested curly brackets.
2299 key = find_char_in_curlies(p+2, ':');
2302 current->string = p;
2309 map = apr_pstrmemdup(pool, p+2, endp-p-2);
2310 key = map + (key-p-2);
2312 dflt = find_char_in_curlies(key, '|');
2317 /* reuse of key variable as result */
2318 key = lookup_map(ctx->r, map, do_expand(key, ctx, entry));
2320 if (!key && dflt && *dflt) {
2321 key = do_expand(dflt, ctx, entry);
2326 current->len = span;
2327 current->string = key;
2337 else if (apr_isdigit(p[1])) {
2339 backrefinfo *bri = (*p == '$') ? &ctx->briRR : &ctx->briRC;
2341 /* see ap_pregsub() in server/util.c */
2342 if (bri->source && n < AP_MAX_REG_MATCH
2343 && bri->regmatch[n].rm_eo > bri->regmatch[n].rm_so) {
2344 span = bri->regmatch[n].rm_eo - bri->regmatch[n].rm_so;
2345 if (entry && (entry->flags & RULEFLAG_ESCAPEBACKREF)) {
2346 /* escape the backreference */
2348 tmp = apr_pstrndup(pool, bri->source + bri->regmatch[n].rm_so, span);
2349 tmp2 = ap_escape_path_segment(pool, tmp);
2350 rewritelog((ctx->r, 5, ctx->perdir, "escaping backreference '%s' to '%s'",
2353 current->len = span = strlen(tmp2);
2354 current->string = tmp2;
2357 current->len = span;
2358 current->string = bri->source + bri->regmatch[n].rm_so;
2367 /* not for us, just copy it */
2370 current->string = p++;
2374 /* check the remainder */
2375 if (*p && (span = strcspn(p, "\\$%")) > 0) {
2377 current->next = (spc < SMALL_EXPANSION)
2379 : (result_list *)apr_palloc(pool,
2380 sizeof(result_list));
2381 current = current->next;
2382 current->next = NULL;
2385 current->len = span;
2386 current->string = p;
2391 } while (p < input+inputlen);
2393 /* assemble result */
2394 c = p = apr_palloc(pool, outlen + 1); /* don't forget the \0 */
2397 ap_assert(c+result->len <= p+outlen); /* XXX: can be removed after
2398 * extensive testing and
2401 memcpy(c, result->string, result->len);
2404 result = result->next;
2413 * perform all the expansions on the environment variables
2415 static void do_expand_env(data_item *env, rewrite_ctx *ctx)
2420 name = do_expand(env->data, ctx, NULL);
2421 if ((val = ap_strchr(name, ':')) != NULL) {
2424 apr_table_set(ctx->r->subprocess_env, name, val);
2425 rewritelog((ctx->r, 5, NULL, "setting env variable '%s' to '%s'",
2436 * perform all the expansions on the cookies
2438 * TODO: use cached time similar to how logging does it
2440 static void add_cookie(request_rec *r, char *s)
2451 var = apr_strtok(s, ":", &tok_cntx);
2452 val = apr_strtok(NULL, ":", &tok_cntx);
2453 domain = apr_strtok(NULL, ":", &tok_cntx);
2455 if (var && val && domain) {
2456 request_rec *rmain = r;
2460 while (rmain->main) {
2461 rmain = rmain->main;
2464 notename = apr_pstrcat(rmain->pool, var, "_rewrite", NULL);
2465 apr_pool_userdata_get(&data, notename, rmain->pool);
2467 char *exp_time = NULL;
2469 expires = apr_strtok(NULL, ":", &tok_cntx);
2470 path = expires ? apr_strtok(NULL, ":", &tok_cntx) : NULL;
2474 apr_time_exp_gmt(&tms, r->request_time
2475 + apr_time_from_sec((60 * atol(expires))));
2476 exp_time = apr_psprintf(r->pool, "%s, %.2d-%s-%.4d "
2477 "%.2d:%.2d:%.2d GMT",
2478 apr_day_snames[tms.tm_wday],
2480 apr_month_snames[tms.tm_mon],
2482 tms.tm_hour, tms.tm_min, tms.tm_sec);
2485 cookie = apr_pstrcat(rmain->pool,
2487 "; path=", path ? path : "/",
2488 "; domain=", domain,
2489 expires ? "; expires=" : NULL,
2490 expires ? exp_time : NULL,
2493 apr_table_addn(rmain->err_headers_out, "Set-Cookie", cookie);
2494 apr_pool_userdata_set("set", notename, NULL, rmain->pool);
2495 rewritelog((rmain, 5, NULL, "setting cookie '%s'", cookie));
2498 rewritelog((rmain, 5, NULL, "skipping already set cookie '%s'",
2506 static void do_expand_cookie(data_item *cookie, rewrite_ctx *ctx)
2509 add_cookie(ctx->r, do_expand(cookie->data, ctx, NULL));
2510 cookie = cookie->next;
2518 * Expand tilde-paths (/~user) through Unix /etc/passwd
2519 * database information (or other OS-specific database)
2521 static char *expand_tildepaths(request_rec *r, char *uri)
2523 if (uri && *uri == '/' && uri[1] == '~') {
2527 while (*p && *p != '/') {
2534 user = apr_pstrmemdup(r->pool, user, p-user);
2535 if (apr_uid_homepath_get(&homedir, user, r->pool) == APR_SUCCESS) {
2537 /* reuse of user variable */
2538 user = homedir + strlen(homedir) - 1;
2539 if (user >= homedir && *user == '/') {
2543 return apr_pstrcat(r->pool, homedir, p, NULL);
2554 #endif /* if APR_HAS_USER */
2558 * +-------------------------------------------------------+
2560 * | rewriting lockfile support
2562 * +-------------------------------------------------------+
2565 static apr_status_t rewritelock_create(server_rec *s, apr_pool_t *p)
2569 /* only operate if a lockfile is used */
2570 if (lockname == NULL || *(lockname) == '\0') {
2574 /* create the lockfile */
2575 rc = apr_global_mutex_create(&rewrite_mapr_lock_acquire, lockname,
2576 APR_LOCK_DEFAULT, p);
2577 if (rc != APR_SUCCESS) {
2578 ap_log_error(APLOG_MARK, APLOG_CRIT, rc, s,
2579 "mod_rewrite: Parent could not create RewriteLock "
2580 "file %s", lockname);
2584 #ifdef AP_NEED_SET_MUTEX_PERMS
2585 rc = unixd_set_global_mutex_perms(rewrite_mapr_lock_acquire);
2586 if (rc != APR_SUCCESS) {
2587 ap_log_error(APLOG_MARK, APLOG_CRIT, rc, s,
2588 "mod_rewrite: Parent could not set permissions "
2589 "on RewriteLock; check User and Group directives");
2597 static apr_status_t rewritelock_remove(void *data)
2599 /* only operate if a lockfile is used */
2600 if (lockname == NULL || *(lockname) == '\0') {
2604 /* destroy the rewritelock */
2605 apr_global_mutex_destroy (rewrite_mapr_lock_acquire);
2606 rewrite_mapr_lock_acquire = NULL;
2613 * +-------------------------------------------------------+
2615 * | configuration directive handling
2617 * +-------------------------------------------------------+
2621 * own command line parser for RewriteRule and RewriteCond,
2622 * which doesn't have the '\\' problem.
2623 * (returns true on error)
2625 * XXX: what an inclined parser. Seems we have to leave it so
2626 * for backwards compat. *sigh*
2628 static int parseargline(char *str, char **a1, char **a2, char **a3)
2632 while (apr_isspace(*str)) {
2637 * determine first argument
2639 quote = (*str == '"' || *str == '\'') ? *str++ : '\0';
2642 for (; *str; ++str) {
2643 if ((apr_isspace(*str) && !quote) || (*str == quote)) {
2646 if (*str == '\\' && apr_isspace(str[1])) {
2657 while (apr_isspace(*str)) {
2662 * determine second argument
2664 quote = (*str == '"' || *str == '\'') ? *str++ : '\0';
2667 for (; *str; ++str) {
2668 if ((apr_isspace(*str) && !quote) || (*str == quote)) {
2671 if (*str == '\\' && apr_isspace(str[1])) {
2678 *a3 = NULL; /* 3rd argument is optional */
2683 while (apr_isspace(*str)) {
2688 *a3 = NULL; /* 3rd argument is still optional */
2693 * determine third argument
2695 quote = (*str == '"' || *str == '\'') ? *str++ : '\0';
2697 for (; *str; ++str) {
2698 if ((apr_isspace(*str) && !quote) || (*str == quote)) {
2701 if (*str == '\\' && apr_isspace(str[1])) {
2711 static void *config_server_create(apr_pool_t *p, server_rec *s)
2713 rewrite_server_conf *a;
2715 a = (rewrite_server_conf *)apr_pcalloc(p, sizeof(rewrite_server_conf));
2717 a->state = ENGINE_DISABLED;
2718 a->options = OPTION_NONE;
2719 #ifndef REWRITELOG_DISABLED
2720 a->rewritelogfile = NULL;
2721 a->rewritelogfp = NULL;
2722 a->rewriteloglevel = 0;
2724 a->rewritemaps = apr_hash_make(p);
2725 a->rewriteconds = apr_array_make(p, 2, sizeof(rewritecond_entry));
2726 a->rewriterules = apr_array_make(p, 2, sizeof(rewriterule_entry));
2732 static void *config_server_merge(apr_pool_t *p, void *basev, void *overridesv)
2734 rewrite_server_conf *a, *base, *overrides;
2736 a = (rewrite_server_conf *)apr_pcalloc(p,
2737 sizeof(rewrite_server_conf));
2738 base = (rewrite_server_conf *)basev;
2739 overrides = (rewrite_server_conf *)overridesv;
2741 a->state = overrides->state;
2742 a->options = overrides->options;
2743 a->server = overrides->server;
2745 if (a->options & OPTION_INHERIT) {
2747 * local directives override
2748 * and anything else is inherited
2750 #ifndef REWRITELOG_DISABLED
2751 a->rewriteloglevel = overrides->rewriteloglevel != 0
2752 ? overrides->rewriteloglevel
2753 : base->rewriteloglevel;
2754 a->rewritelogfile = overrides->rewritelogfile != NULL
2755 ? overrides->rewritelogfile
2756 : base->rewritelogfile;
2757 a->rewritelogfp = overrides->rewritelogfp != NULL
2758 ? overrides->rewritelogfp
2759 : base->rewritelogfp;
2761 a->rewritemaps = apr_hash_overlay(p, overrides->rewritemaps,
2763 a->rewriteconds = apr_array_append(p, overrides->rewriteconds,
2764 base->rewriteconds);
2765 a->rewriterules = apr_array_append(p, overrides->rewriterules,
2766 base->rewriterules);
2770 * local directives override
2771 * and anything else gets defaults
2773 #ifndef REWRITELOG_DISABLED
2774 a->rewriteloglevel = overrides->rewriteloglevel;
2775 a->rewritelogfile = overrides->rewritelogfile;
2776 a->rewritelogfp = overrides->rewritelogfp;
2778 a->rewritemaps = overrides->rewritemaps;
2779 a->rewriteconds = overrides->rewriteconds;
2780 a->rewriterules = overrides->rewriterules;
2786 static void *config_perdir_create(apr_pool_t *p, char *path)
2788 rewrite_perdir_conf *a;
2790 a = (rewrite_perdir_conf *)apr_pcalloc(p, sizeof(rewrite_perdir_conf));
2792 a->state = ENGINE_DISABLED;
2793 a->options = OPTION_NONE;
2795 a->rewriteconds = apr_array_make(p, 2, sizeof(rewritecond_entry));
2796 a->rewriterules = apr_array_make(p, 2, sizeof(rewriterule_entry));
2799 a->directory = NULL;
2802 /* make sure it has a trailing slash */
2803 if (path[strlen(path)-1] == '/') {
2804 a->directory = apr_pstrdup(p, path);
2807 a->directory = apr_pstrcat(p, path, "/", NULL);
2814 static void *config_perdir_merge(apr_pool_t *p, void *basev, void *overridesv)
2816 rewrite_perdir_conf *a, *base, *overrides;
2818 a = (rewrite_perdir_conf *)apr_pcalloc(p,
2819 sizeof(rewrite_perdir_conf));
2820 base = (rewrite_perdir_conf *)basev;
2821 overrides = (rewrite_perdir_conf *)overridesv;
2823 a->state = overrides->state;
2824 a->options = overrides->options;
2825 a->directory = overrides->directory;
2826 a->baseurl = overrides->baseurl;
2828 if (a->options & OPTION_INHERIT) {
2829 a->rewriteconds = apr_array_append(p, overrides->rewriteconds,
2830 base->rewriteconds);
2831 a->rewriterules = apr_array_append(p, overrides->rewriterules,
2832 base->rewriterules);
2835 a->rewriteconds = overrides->rewriteconds;
2836 a->rewriterules = overrides->rewriterules;
2842 static const char *cmd_rewriteengine(cmd_parms *cmd,
2843 void *in_dconf, int flag)
2845 rewrite_perdir_conf *dconf = in_dconf;
2846 rewrite_server_conf *sconf;
2848 sconf = ap_get_module_config(cmd->server->module_config, &rewrite_module);
2850 if (cmd->path == NULL) { /* is server command */
2851 sconf->state = (flag ? ENGINE_ENABLED : ENGINE_DISABLED);
2853 else /* is per-directory command */ {
2854 dconf->state = (flag ? ENGINE_ENABLED : ENGINE_DISABLED);
2860 static const char *cmd_rewriteoptions(cmd_parms *cmd,
2861 void *in_dconf, const char *option)
2867 w = ap_getword_conf(cmd->pool, &option);
2869 if (!strcasecmp(w, "inherit")) {
2870 options |= OPTION_INHERIT;
2872 else if (!strncasecmp(w, "MaxRedirects=", 13)) {
2873 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, cmd->server,
2874 "RewriteOptions: MaxRedirects option has been "
2875 "removed in favor of the global "
2876 "LimitInternalRecursion directive and will be "
2880 return apr_pstrcat(cmd->pool, "RewriteOptions: unknown option '",
2885 /* put it into the appropriate config */
2886 if (cmd->path == NULL) { /* is server command */
2887 rewrite_server_conf *conf =
2888 ap_get_module_config(cmd->server->module_config,
2891 conf->options |= options;
2893 else { /* is per-directory command */
2894 rewrite_perdir_conf *conf = in_dconf;
2896 conf->options |= options;
2902 #ifndef REWRITELOG_DISABLED
2903 static const char *cmd_rewritelog(cmd_parms *cmd, void *dconf, const char *a1)
2905 rewrite_server_conf *sconf;
2907 sconf = ap_get_module_config(cmd->server->module_config, &rewrite_module);
2908 sconf->rewritelogfile = a1;
2913 static const char *cmd_rewriteloglevel(cmd_parms *cmd, void *dconf,
2916 rewrite_server_conf *sconf;
2918 sconf = ap_get_module_config(cmd->server->module_config, &rewrite_module);
2919 sconf->rewriteloglevel = atoi(a1);
2923 #endif /* rewritelog */
2925 static const char *cmd_rewritemap(cmd_parms *cmd, void *dconf, const char *a1,
2928 rewrite_server_conf *sconf;
2929 rewritemap_entry *newmap;
2933 sconf = ap_get_module_config(cmd->server->module_config, &rewrite_module);
2935 newmap = apr_palloc(cmd->pool, sizeof(rewritemap_entry));
2936 newmap->func = NULL;
2938 if (strncasecmp(a2, "txt:", 4) == 0) {
2939 if ((fname = ap_server_root_relative(cmd->pool, a2+4)) == NULL) {
2940 return apr_pstrcat(cmd->pool, "RewriteMap: bad path to txt map: ",
2944 newmap->type = MAPTYPE_TXT;
2945 newmap->datafile = fname;
2946 newmap->checkfile = fname;
2947 newmap->checkfile2= NULL;
2948 newmap->cachename = apr_psprintf(cmd->pool, "%pp:%s",
2949 (void *)cmd->server, a1);
2951 else if (strncasecmp(a2, "rnd:", 4) == 0) {
2952 if ((fname = ap_server_root_relative(cmd->pool, a2+4)) == NULL) {
2953 return apr_pstrcat(cmd->pool, "RewriteMap: bad path to rnd map: ",
2957 newmap->type = MAPTYPE_RND;
2958 newmap->datafile = fname;
2959 newmap->checkfile = fname;
2960 newmap->checkfile2= NULL;
2961 newmap->cachename = apr_psprintf(cmd->pool, "%pp:%s",
2962 (void *)cmd->server, a1);
2964 else if (strncasecmp(a2, "dbm", 3) == 0) {
2967 newmap->type = MAPTYPE_DBM;
2969 newmap->cachename = apr_psprintf(cmd->pool, "%pp:%s",
2970 (void *)cmd->server, a1);
2973 newmap->dbmtype = "default";
2976 else if (a2[3] == '=') {
2977 const char *colon = ap_strchr_c(a2 + 4, ':');
2980 newmap->dbmtype = apr_pstrndup(cmd->pool, a2 + 4,
2981 colon - (a2 + 3) - 1);
2987 return apr_pstrcat(cmd->pool, "RewriteMap: bad map:",
2991 if ((newmap->datafile = ap_server_root_relative(cmd->pool,
2993 return apr_pstrcat(cmd->pool, "RewriteMap: bad path to dbm map: ",
2997 rv = apr_dbm_get_usednames_ex(cmd->pool, newmap->dbmtype,
2998 newmap->datafile, &newmap->checkfile,
2999 &newmap->checkfile2);
3000 if (rv != APR_SUCCESS) {
3001 return apr_pstrcat(cmd->pool, "RewriteMap: dbm type ",
3002 newmap->dbmtype, " is invalid", NULL);
3005 else if ((strncasecmp(a2, "dbd:", 4) == 0)
3006 || (strncasecmp(a2, "fastdbd:", 8) == 0)) {
3007 if (dbd_prepare == NULL) {
3008 return "RewriteMap types dbd and fastdbd require mod_dbd!";
3010 if ((a2[0] == 'd') || (a2[0] == 'D')) {
3011 newmap->type = MAPTYPE_DBD;
3015 newmap->type = MAPTYPE_DBD_CACHE;
3017 newmap->cachename = apr_psprintf(cmd->pool, "%pp:%s",
3018 (void *)cmd->server, a1);
3021 dbd_prepare(cmd->server, fname, newmap->dbdq);
3023 else if (strncasecmp(a2, "prg:", 4) == 0) {
3024 apr_tokenize_to_argv(a2 + 4, &newmap->argv, cmd->pool);
3026 fname = newmap->argv[0];
3027 if ((newmap->argv[0] = ap_server_root_relative(cmd->pool,
3029 return apr_pstrcat(cmd->pool, "RewriteMap: bad path to prg map: ",
3033 newmap->type = MAPTYPE_PRG;
3034 newmap->datafile = NULL;
3035 newmap->checkfile = newmap->argv[0];
3036 newmap->checkfile2= NULL;
3037 newmap->cachename = NULL;
3039 else if (strncasecmp(a2, "int:", 4) == 0) {
3040 newmap->type = MAPTYPE_INT;
3041 newmap->datafile = NULL;
3042 newmap->checkfile = NULL;
3043 newmap->checkfile2= NULL;
3044 newmap->cachename = NULL;
3045 newmap->func = (char *(*)(request_rec *,char *))
3046 apr_hash_get(mapfunc_hash, a2+4, strlen(a2+4));
3047 if ((sconf->state == ENGINE_ENABLED) && (newmap->func == NULL)) {
3048 return apr_pstrcat(cmd->pool, "RewriteMap: internal map not found:",
3053 if ((fname = ap_server_root_relative(cmd->pool, a2)) == NULL) {
3054 return apr_pstrcat(cmd->pool, "RewriteMap: bad path to txt map: ",
3058 newmap->type = MAPTYPE_TXT;
3059 newmap->datafile = fname;
3060 newmap->checkfile = fname;
3061 newmap->checkfile2= NULL;
3062 newmap->cachename = apr_psprintf(cmd->pool, "%pp:%s",
3063 (void *)cmd->server, a1);
3065 newmap->fpin = NULL;
3066 newmap->fpout = NULL;
3068 if (newmap->checkfile && (sconf->state == ENGINE_ENABLED)
3069 && (apr_stat(&st, newmap->checkfile, APR_FINFO_MIN,
3070 cmd->pool) != APR_SUCCESS)) {
3071 return apr_pstrcat(cmd->pool,
3072 "RewriteMap: file for map ", a1,
3073 " not found:", newmap->checkfile, NULL);
3076 apr_hash_set(sconf->rewritemaps, a1, APR_HASH_KEY_STRING, newmap);
3081 static const char *cmd_rewritelock(cmd_parms *cmd, void *dconf, const char *a1)
3085 if ((error = ap_check_cmd_context(cmd, GLOBAL_ONLY)) != NULL)
3088 /* fixup the path, especially for rewritelock_remove() */
3089 lockname = ap_server_root_relative(cmd->pool, a1);
3092 return apr_pstrcat(cmd->pool, "Invalid RewriteLock path ", a1);
3098 static const char *cmd_rewritebase(cmd_parms *cmd, void *in_dconf,
3101 rewrite_perdir_conf *dconf = in_dconf;
3103 if (cmd->path == NULL || dconf == NULL) {
3104 return "RewriteBase: only valid in per-directory config files";
3106 if (a1[0] == '\0') {
3107 return "RewriteBase: empty URL not allowed";
3110 return "RewriteBase: argument is not a valid URL";
3113 dconf->baseurl = a1;
3119 * generic lexer for RewriteRule and RewriteCond flags.
3120 * The parser will be passed in as a function pointer
3121 * and called if a flag was found
3123 static const char *cmd_parseflagfield(apr_pool_t *p, void *cfg, char *key,
3124 const char *(*parse)(apr_pool_t *,
3128 char *val, *nextp, *endp;
3131 endp = key + strlen(key) - 1;
3132 if (*key != '[' || *endp != ']') {
3133 return "RewriteCond: bad flag delimiters";
3136 *endp = ','; /* for simpler parsing */
3140 /* skip leading spaces */
3141 while (apr_isspace(*key)) {
3145 if (!*key || (nextp = ap_strchr(key, ',')) == NULL) { /* NULL should not
3151 /* strip trailing spaces */
3153 while (apr_isspace(*endp)) {
3158 /* split key and val */
3159 val = ap_strchr(key, '=');
3167 err = parse(p, cfg, key, val);
3178 static const char *cmd_rewritecond_setflag(apr_pool_t *p, void *_cfg,
3179 char *key, char *val)
3181 rewritecond_entry *cfg = _cfg;
3183 if ( strcasecmp(key, "nocase") == 0
3184 || strcasecmp(key, "NC") == 0 ) {
3185 cfg->flags |= CONDFLAG_NOCASE;
3187 else if ( strcasecmp(key, "ornext") == 0
3188 || strcasecmp(key, "OR") == 0 ) {
3189 cfg->flags |= CONDFLAG_ORNEXT;
3191 else if ( strcasecmp(key, "novary") == 0
3192 || strcasecmp(key, "NV") == 0 ) {
3193 cfg->flags |= CONDFLAG_NOVARY;
3196 return apr_pstrcat(p, "RewriteCond: unknown flag '", key, "'", NULL);
3201 static const char *cmd_rewritecond(cmd_parms *cmd, void *in_dconf,
3204 rewrite_perdir_conf *dconf = in_dconf;
3205 char *str = apr_pstrdup(cmd->pool, in_str);
3206 rewrite_server_conf *sconf;
3207 rewritecond_entry *newcond;
3214 sconf = ap_get_module_config(cmd->server->module_config, &rewrite_module);
3216 /* make a new entry in the internal temporary rewrite rule list */
3217 if (cmd->path == NULL) { /* is server command */
3218 newcond = apr_array_push(sconf->rewriteconds);
3220 else { /* is per-directory command */
3221 newcond = apr_array_push(dconf->rewriteconds);
3224 /* parse the argument line ourself
3225 * a1 .. a3 are substrings of str, which is a fresh copy
3226 * of the argument line. So we can use a1 .. a3 without
3227 * copying them again.
3229 if (parseargline(str, &a1, &a2, &a3)) {
3230 return apr_pstrcat(cmd->pool, "RewriteCond: bad argument line '", str,
3234 /* arg1: the input string */
3235 newcond->input = a1;
3237 /* arg3: optional flags field
3238 * (this has to be parsed first, because we need to
3239 * know if the regex should be compiled with ICASE!)
3241 newcond->flags = CONDFLAG_NONE;
3243 if ((err = cmd_parseflagfield(cmd->pool, newcond, a3,
3244 cmd_rewritecond_setflag)) != NULL) {
3249 /* arg2: the pattern */
3251 newcond->flags |= CONDFLAG_NOTMATCH;
3255 /* determine the pattern type */
3258 if (!a2[2] && *a2 == '-') {
3260 case 'f': newcond->ptype = CONDPAT_FILE_EXISTS; break;
3261 case 's': newcond->ptype = CONDPAT_FILE_SIZE; break;
3262 case 'l': newcond->ptype = CONDPAT_FILE_LINK; break;
3263 case 'd': newcond->ptype = CONDPAT_FILE_DIR; break;
3264 case 'x': newcond->ptype = CONDPAT_FILE_XBIT; break;
3265 case 'U': newcond->ptype = CONDPAT_LU_URL; break;
3266 case 'F': newcond->ptype = CONDPAT_LU_FILE; break;
3271 case '>': newcond->ptype = CONDPAT_STR_GT; break;
3272 case '<': newcond->ptype = CONDPAT_STR_LT; break;
3273 case '=': newcond->ptype = CONDPAT_STR_EQ;
3274 /* "" represents an empty string */
3275 if (*++a2 == '"' && a2[1] == '"' && !a2[2]) {
3283 if (newcond->ptype && newcond->ptype != CONDPAT_STR_EQ &&
3284 (newcond->flags & CONDFLAG_NOCASE)) {
3285 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, cmd->server,
3286 "RewriteCond: NoCase option for non-regex pattern '%s' "
3287 "is not supported and will be ignored.", a2);
3288 newcond->flags &= ~CONDFLAG_NOCASE;
3291 newcond->pattern = a2;
3293 if (!newcond->ptype) {
3294 regexp = ap_pregcomp(cmd->pool, a2,
3295 AP_REG_EXTENDED | ((newcond->flags & CONDFLAG_NOCASE)
3296 ? AP_REG_ICASE : 0));
3298 return apr_pstrcat(cmd->pool, "RewriteCond: cannot compile regular "
3299 "expression '", a2, "'", NULL);
3302 newcond->regexp = regexp;
3308 static const char *cmd_rewriterule_setflag(apr_pool_t *p, void *_cfg,
3309 char *key, char *val)
3311 rewriterule_entry *cfg = _cfg;
3317 if (!*key || !strcasecmp(key, "ackrefescaping")) {
3318 cfg->flags |= RULEFLAG_ESCAPEBACKREF;
3326 if (!*key || !strcasecmp(key, "hain")) { /* chain */
3327 cfg->flags |= RULEFLAG_CHAIN;
3329 else if (((*key == 'O' || *key == 'o') && !key[1])
3330 || !strcasecmp(key, "ookie")) { /* cookie */
3331 data_item *cp = cfg->cookie;
3334 cp = cfg->cookie = apr_palloc(p, sizeof(*cp));
3340 cp->next = apr_palloc(p, sizeof(*cp));
3354 if (!*key || !strcasecmp(key, "nv")) { /* env */
3355 data_item *cp = cfg->env;
3358 cp = cfg->env = apr_palloc(p, sizeof(*cp));
3364 cp->next = apr_palloc(p, sizeof(*cp));
3378 if (!*key || !strcasecmp(key, "orbidden")) { /* forbidden */
3379 cfg->flags |= (RULEFLAG_STATUS | RULEFLAG_NOSUB);
3380 cfg->forced_responsecode = HTTP_FORBIDDEN;
3389 if (!*key || !strcasecmp(key, "one")) { /* gone */
3390 cfg->flags |= (RULEFLAG_STATUS | RULEFLAG_NOSUB);
3391 cfg->forced_responsecode = HTTP_GONE;
3400 if (!*key || !strcasecmp(key, "andler")) { /* handler */
3401 cfg->forced_handler = val;
3410 if (!*key || !strcasecmp(key, "ast")) { /* last */
3411 cfg->flags |= RULEFLAG_LASTRULE;
3420 if (((*key == 'E' || *key == 'e') && !key[1])
3421 || !strcasecmp(key, "oescape")) { /* noescape */
3422 cfg->flags |= RULEFLAG_NOESCAPE;
3424 else if (!*key || !strcasecmp(key, "ext")) { /* next */
3425 cfg->flags |= RULEFLAG_NEWROUND;
3427 else if (((*key == 'S' || *key == 's') && !key[1])
3428 || !strcasecmp(key, "osubreq")) { /* nosubreq */
3429 cfg->flags |= RULEFLAG_IGNOREONSUBREQ;
3431 else if (((*key == 'C' || *key == 'c') && !key[1])
3432 || !strcasecmp(key, "ocase")) { /* nocase */
3433 cfg->flags |= RULEFLAG_NOCASE;
3442 if (!*key || !strcasecmp(key, "roxy")) { /* proxy */
3443 cfg->flags |= RULEFLAG_PROXY;
3445 else if (((*key == 'T' || *key == 't') && !key[1])
3446 || !strcasecmp(key, "assthrough")) { /* passthrough */
3447 cfg->flags |= RULEFLAG_PASSTHROUGH;
3456 if ( !strcasecmp(key, "SA")
3457 || !strcasecmp(key, "sappend")) { /* qsappend */
3458 cfg->flags |= RULEFLAG_QSAPPEND;
3467 if (!*key || !strcasecmp(key, "edirect")) { /* redirect */
3470 cfg->flags |= RULEFLAG_FORCEREDIRECT;
3471 if (strlen(val) > 0) {
3472 if (strcasecmp(val, "permanent") == 0) {
3473 status = HTTP_MOVED_PERMANENTLY;
3475 else if (strcasecmp(val, "temp") == 0) {
3476 status = HTTP_MOVED_TEMPORARILY;
3478 else if (strcasecmp(val, "seeother") == 0) {
3479 status = HTTP_SEE_OTHER;
3481 else if (apr_isdigit(*val)) {
3483 if (status != HTTP_INTERNAL_SERVER_ERROR) {
3485 ap_index_of_response(HTTP_INTERNAL_SERVER_ERROR);
3487 if (ap_index_of_response(status) == idx) {
3488 return apr_psprintf(p, "RewriteRule: invalid HTTP "
3489 "response code '%s' for "
3494 if (!ap_is_HTTP_REDIRECT(status)) {
3495 cfg->flags |= (RULEFLAG_STATUS | RULEFLAG_NOSUB);
3498 cfg->forced_responsecode = status;
3508 if (!*key || !strcasecmp(key, "kip")) { /* skip */
3509 cfg->skip = atoi(val);
3518 if (!*key || !strcasecmp(key, "ype")) { /* type */
3519 cfg->forced_mimetype = val;
3531 return apr_pstrcat(p, "RewriteRule: unknown flag '", --key, "'", NULL);
3537 static const char *cmd_rewriterule(cmd_parms *cmd, void *in_dconf,
3540 rewrite_perdir_conf *dconf = in_dconf;
3541 char *str = apr_pstrdup(cmd->pool, in_str);
3542 rewrite_server_conf *sconf;
3543 rewriterule_entry *newrule;
3550 sconf = ap_get_module_config(cmd->server->module_config, &rewrite_module);
3552 /* make a new entry in the internal rewrite rule list */
3553 if (cmd->path == NULL) { /* is server command */
3554 newrule = apr_array_push(sconf->rewriterules);
3556 else { /* is per-directory command */
3557 newrule = apr_array_push(dconf->rewriterules);
3560 /* parse the argument line ourself */
3561 if (parseargline(str, &a1, &a2, &a3)) {
3562 return apr_pstrcat(cmd->pool, "RewriteRule: bad argument line '", str,
3566 /* arg3: optional flags field */
3567 newrule->forced_mimetype = NULL;
3568 newrule->forced_handler = NULL;
3569 newrule->forced_responsecode = HTTP_MOVED_TEMPORARILY;
3570 newrule->flags = RULEFLAG_NONE;
3571 newrule->env = NULL;
3572 newrule->cookie = NULL;
3575 if ((err = cmd_parseflagfield(cmd->pool, newrule, a3,
3576 cmd_rewriterule_setflag)) != NULL) {
3581 /* arg1: the pattern
3582 * try to compile the regexp to test if is ok
3585 newrule->flags |= RULEFLAG_NOTMATCH;
3589 regexp = ap_pregcomp(cmd->pool, a1, AP_REG_EXTENDED |
3590 ((newrule->flags & RULEFLAG_NOCASE)
3591 ? AP_REG_ICASE : 0));
3593 return apr_pstrcat(cmd->pool,
3594 "RewriteRule: cannot compile regular expression '",
3598 newrule->pattern = a1;
3599 newrule->regexp = regexp;
3601 /* arg2: the output string */
3602 newrule->output = a2;
3603 if (*a2 == '-' && !a2[1]) {
3604 newrule->flags |= RULEFLAG_NOSUB;
3607 /* now, if the server or per-dir config holds an
3608 * array of RewriteCond entries, we take it for us
3609 * and clear the array
3611 if (cmd->path == NULL) { /* is server command */
3612 newrule->rewriteconds = sconf->rewriteconds;
3613 sconf->rewriteconds = apr_array_make(cmd->pool, 2,
3614 sizeof(rewritecond_entry));
3616 else { /* is per-directory command */
3617 newrule->rewriteconds = dconf->rewriteconds;
3618 dconf->rewriteconds = apr_array_make(cmd->pool, 2,
3619 sizeof(rewritecond_entry));
3627 * +-------------------------------------------------------+
3629 * | the rewriting engine
3631 * +-------------------------------------------------------+
3634 /* Lexicographic Compare */
3635 static APR_INLINE int compare_lexicography(char *a, char *b)
3637 apr_size_t i, lena, lenb;
3643 for (i = 0; i < lena; ++i) {
3645 return ((unsigned char)a[i] > (unsigned char)b[i]) ? 1 : -1;
3652 return ((lena > lenb) ? 1 : -1);
3656 * Apply a single rewriteCond
3658 static int apply_rewrite_cond(rewritecond_entry *p, rewrite_ctx *ctx)
3660 char *input = do_expand(p->input, ctx, NULL);
3662 request_rec *rsub, *r = ctx->r;
3663 ap_regmatch_t regmatch[AP_MAX_REG_MATCH];
3667 case CONDPAT_FILE_EXISTS:
3668 if ( apr_stat(&sb, input, APR_FINFO_MIN, r->pool) == APR_SUCCESS
3669 && sb.filetype == APR_REG) {
3674 case CONDPAT_FILE_SIZE:
3675 if ( apr_stat(&sb, input, APR_FINFO_MIN, r->pool) == APR_SUCCESS
3676 && sb.filetype == APR_REG && sb.size > 0) {
3681 case CONDPAT_FILE_LINK:
3683 if ( apr_stat(&sb, input, APR_FINFO_MIN | APR_FINFO_LINK,
3684 r->pool) == APR_SUCCESS
3685 && sb.filetype == APR_LNK) {
3691 case CONDPAT_FILE_DIR:
3692 if ( apr_stat(&sb, input, APR_FINFO_MIN, r->pool) == APR_SUCCESS
3693 && sb.filetype == APR_DIR) {
3698 case CONDPAT_FILE_XBIT:
3699 if ( apr_stat(&sb, input, APR_FINFO_PROT, r->pool) == APR_SUCCESS
3700 && (sb.protection & (APR_UEXECUTE | APR_GEXECUTE | APR_WEXECUTE))) {
3705 case CONDPAT_LU_URL:
3706 if (*input && subreq_ok(r)) {
3707 rsub = ap_sub_req_lookup_uri(input, r, NULL);
3708 if (rsub->status < 400) {
3711 rewritelog((r, 5, NULL, "RewriteCond URI (-U) check: "
3712 "path=%s -> status=%d", input, rsub->status));
3713 ap_destroy_sub_req(rsub);
3717 case CONDPAT_LU_FILE:
3718 if (*input && subreq_ok(r)) {
3719 rsub = ap_sub_req_lookup_file(input, r, NULL);
3720 if (rsub->status < 300 &&
3721 /* double-check that file exists since default result is 200 */
3722 apr_stat(&sb, rsub->filename, APR_FINFO_MIN,
3723 r->pool) == APR_SUCCESS) {
3726 rewritelog((r, 5, NULL, "RewriteCond file (-F) check: path=%s "
3727 "-> file=%s status=%d", input, rsub->filename,
3729 ap_destroy_sub_req(rsub);
3733 case CONDPAT_STR_GT:
3734 rc = (compare_lexicography(input, p->pattern+1) == 1) ? 1 : 0;
3737 case CONDPAT_STR_LT:
3738 rc = (compare_lexicography(input, p->pattern+1) == -1) ? 1 : 0;
3741 case CONDPAT_STR_EQ:
3742 if (p->flags & CONDFLAG_NOCASE) {
3743 rc = !strcasecmp(input, p->pattern);
3746 rc = !strcmp(input, p->pattern);
3751 /* it is really a regexp pattern, so apply it */
3752 rc = !ap_regexec(p->regexp, input, AP_MAX_REG_MATCH, regmatch, 0);
3754 /* update briRC backref info */
3755 if (rc && !(p->flags & CONDFLAG_NOTMATCH)) {
3756 ctx->briRC.source = input;
3757 ctx->briRC.nsub = p->regexp->re_nsub;
3758 memcpy(ctx->briRC.regmatch, regmatch, sizeof(regmatch));
3763 if (p->flags & CONDFLAG_NOTMATCH) {
3767 rewritelog((r, 4, ctx->perdir, "RewriteCond: input='%s' pattern='%s%s%s'%s "
3768 "=> %s", input, (p->flags & CONDFLAG_NOTMATCH) ? "!" : "",
3769 (p->ptype == CONDPAT_STR_EQ) ? "=" : "", p->pattern,
3770 (p->flags & CONDFLAG_NOCASE) ? " [NC]" : "",
3771 rc ? "matched" : "not-matched"));
3776 /* check for forced type and handler */
3777 static APR_INLINE void force_type_handler(rewriterule_entry *p,
3782 if (p->forced_mimetype) {
3783 expanded = do_expand(p->forced_mimetype, ctx, p);
3786 ap_str_tolower(expanded);
3788 rewritelog((ctx->r, 2, ctx->perdir, "remember %s to have MIME-type "
3789 "'%s'", ctx->r->filename, expanded));
3791 apr_table_setn(ctx->r->notes, REWRITE_FORCED_MIMETYPE_NOTEVAR,
3796 if (p->forced_handler) {
3797 expanded = do_expand(p->forced_handler, ctx, p);
3800 ap_str_tolower(expanded);
3802 rewritelog((ctx->r, 2, ctx->perdir, "remember %s to have "
3803 "Content-handler '%s'", ctx->r->filename, expanded));
3805 apr_table_setn(ctx->r->notes, REWRITE_FORCED_HANDLER_NOTEVAR,
3812 * Apply a single RewriteRule
3814 static int apply_rewrite_rule(rewriterule_entry *p, rewrite_ctx *ctx)
3816 ap_regmatch_t regmatch[AP_MAX_REG_MATCH];
3817 apr_array_header_t *rewriteconds;
3818 rewritecond_entry *conds;
3820 char *newuri = NULL;
3821 request_rec *r = ctx->r;
3822 int is_proxyreq = 0;
3824 ctx->uri = r->filename;
3827 apr_size_t dirlen = strlen(ctx->perdir);
3832 is_proxyreq = ( r->proxyreq && r->filename
3833 && !strncmp(r->filename, "proxy:", 6));
3835 /* Since we want to match against the (so called) full URL, we have
3836 * to re-add the PATH_INFO postfix
3838 if (r->path_info && *r->path_info) {
3839 rewritelog((r, 3, ctx->perdir, "add path info postfix: %s -> %s%s",
3840 ctx->uri, ctx->uri, r->path_info));
3841 ctx->uri = apr_pstrcat(r->pool, ctx->uri, r->path_info, NULL);
3844 /* Additionally we strip the physical path from the url to match
3845 * it independent from the underlaying filesystem.
3847 if (!is_proxyreq && strlen(ctx->uri) >= dirlen &&
3848 !strncmp(ctx->uri, ctx->perdir, dirlen)) {
3850 rewritelog((r, 3, ctx->perdir, "strip per-dir prefix: %s -> %s",
3851 ctx->uri, ctx->uri + dirlen));
3852 ctx->uri = ctx->uri + dirlen;
3856 /* Try to match the URI against the RewriteRule pattern
3857 * and exit immediately if it didn't apply.
3859 rewritelog((r, 3, ctx->perdir, "applying pattern '%s' to uri '%s'",
3860 p->pattern, ctx->uri));
3862 rc = !ap_regexec(p->regexp, ctx->uri, AP_MAX_REG_MATCH, regmatch, 0);
3863 if (! (( rc && !(p->flags & RULEFLAG_NOTMATCH)) ||
3864 (!rc && (p->flags & RULEFLAG_NOTMATCH)) ) ) {
3868 /* It matched, wow! Now it's time to prepare the context structure for
3869 * further processing
3871 ctx->vary_this = NULL;
3872 ctx->briRC.source = NULL;
3874 if (p->flags & RULEFLAG_NOTMATCH) {
3875 ctx->briRR.source = NULL;
3878 ctx->briRR.source = apr_pstrdup(r->pool, ctx->uri);
3879 ctx->briRR.nsub = p->regexp->re_nsub;
3880 memcpy(ctx->briRR.regmatch, regmatch, sizeof(regmatch));
3883 /* Ok, we already know the pattern has matched, but we now
3884 * additionally have to check for all existing preconditions
3885 * (RewriteCond) which have to be also true. We do this at
3886 * this very late stage to avoid unnessesary checks which
3887 * would slow down the rewriting engine.
3889 rewriteconds = p->rewriteconds;
3890 conds = (rewritecond_entry *)rewriteconds->elts;
3892 for (i = 0; i < rewriteconds->nelts; ++i) {
3893 rewritecond_entry *c = &conds[i];
3895 rc = apply_rewrite_cond(c, ctx);
3897 * Reset vary_this if the novary flag is set for this condition.
3899 if (c->flags & CONDFLAG_NOVARY) {
3900 ctx->vary_this = NULL;
3902 if (c->flags & CONDFLAG_ORNEXT) {
3904 /* One condition is false, but another can be still true. */
3905 ctx->vary_this = NULL;
3909 /* skip the rest of the chained OR conditions */
3910 while ( i < rewriteconds->nelts
3911 && c->flags & CONDFLAG_ORNEXT) {
3920 /* If some HTTP header was involved in the condition, remember it
3923 if (ctx->vary_this) {
3924 ctx->vary = ctx->vary
3925 ? apr_pstrcat(r->pool, ctx->vary, ", ", ctx->vary_this,
3928 ctx->vary_this = NULL;
3932 /* expand the result */
3933 if (!(p->flags & RULEFLAG_NOSUB)) {
3934 newuri = do_expand(p->output, ctx, p);
3935 rewritelog((r, 2, ctx->perdir, "rewrite '%s' -> '%s'", ctx->uri,
3939 /* expand [E=var:val] and [CO=<cookie>] */
3940 do_expand_env(p->env, ctx);
3941 do_expand_cookie(p->cookie, ctx);
3943 /* non-substitution rules ('RewriteRule <pat> -') end here. */
3944 if (p->flags & RULEFLAG_NOSUB) {
3945 force_type_handler(p, ctx);
3947 if (p->flags & RULEFLAG_STATUS) {
3948 rewritelog((r, 2, ctx->perdir, "forcing responsecode %d for %s",
3949 p->forced_responsecode, r->filename));
3951 r->status = p->forced_responsecode;
3957 /* Now adjust API's knowledge about r->filename and r->args */
3958 r->filename = newuri;
3959 splitout_queryargs(r, p->flags & RULEFLAG_QSAPPEND);
3961 /* Add the previously stripped per-directory location prefix, unless
3962 * (1) it's an absolute URL path and
3963 * (2) it's a full qualified URL
3965 if ( ctx->perdir && !is_proxyreq && *r->filename != '/'
3966 && !is_absolute_uri(r->filename)) {
3967 rewritelog((r, 3, ctx->perdir, "add per-dir prefix: %s -> %s%s",
3968 r->filename, ctx->perdir, r->filename));
3970 r->filename = apr_pstrcat(r->pool, ctx->perdir, r->filename, NULL);
3973 /* If this rule is forced for proxy throughput
3974 * (`RewriteRule ... ... [P]') then emulate mod_proxy's
3975 * URL-to-filename handler to be sure mod_proxy is triggered
3976 * for this URL later in the Apache API. But make sure it is
3977 * a fully-qualified URL. (If not it is qualified with
3980 if (p->flags & RULEFLAG_PROXY) {
3981 /* PR#39746: Escaping things here gets repeated in mod_proxy */
3982 fully_qualify_uri(r);
3984 rewritelog((r, 2, ctx->perdir, "forcing proxy-throughput with %s",
3987 r->filename = apr_pstrcat(r->pool, "proxy:", r->filename, NULL);
3991 /* If this rule is explicitly forced for HTTP redirection
3992 * (`RewriteRule .. .. [R]') then force an external HTTP
3993 * redirect. But make sure it is a fully-qualified URL. (If
3994 * not it is qualified with ourself).
3996 if (p->flags & RULEFLAG_FORCEREDIRECT) {
3997 fully_qualify_uri(r);
3999 rewritelog((r, 2, ctx->perdir, "explicitly forcing redirect with %s",
4002 r->status = p->forced_responsecode;
4006 /* Special Rewriting Feature: Self-Reduction
4007 * We reduce the URL by stripping a possible
4008 * http[s]://<ourhost>[:<port>] prefix, i.e. a prefix which
4009 * corresponds to ourself. This is to simplify rewrite maps
4010 * and to avoid recursion, etc. When this prefix is not a
4011 * coincidence then the user has to use [R] explicitly (see
4016 /* If this rule is still implicitly forced for HTTP
4017 * redirection (`RewriteRule .. <scheme>://...') then
4018 * directly force an external HTTP redirect.
4020 if (is_absolute_uri(r->filename)) {
4021 rewritelog((r, 2, ctx->perdir, "implicitly forcing redirect (rc=%d) "
4022 "with %s", p->forced_responsecode, r->filename));
4024 r->status = p->forced_responsecode;
4028 /* Finally remember the forced mime-type */
4029 force_type_handler(p, ctx);
4031 /* Puuhhhhhhhh... WHAT COMPLICATED STUFF ;_)
4032 * But now we're done for this particular rule.
4038 * Apply a complete rule set,
4039 * i.e. a list of rewrite rules
4041 static int apply_rewrite_list(request_rec *r, apr_array_header_t *rewriterules,
4044 rewriterule_entry *entries;
4045 rewriterule_entry *p;
4052 ctx = apr_palloc(r->pool, sizeof(*ctx));
4053 ctx->perdir = perdir;
4057 * Iterate over all existing rules
4059 entries = (rewriterule_entry *)rewriterules->elts;
4062 for (i = 0; i < rewriterules->nelts; i++) {
4066 * Ignore this rule on subrequests if we are explicitly
4067 * asked to do so or this is a proxy-throughput or a
4068 * forced redirect rule.
4070 if (r->main != NULL &&
4071 (p->flags & RULEFLAG_IGNOREONSUBREQ ||
4072 p->flags & RULEFLAG_FORCEREDIRECT )) {
4077 * Apply the current rule.
4080 rc = apply_rewrite_rule(p, ctx);
4083 /* Regardless of what we do next, we've found a match. Check to see
4084 * if any of the request header fields were involved, and add them
4085 * to the Vary field of the response.
4088 apr_table_merge(r->headers_out, "Vary", ctx->vary);
4092 * The rule sets the response code (implies match-only)
4094 if (p->flags & RULEFLAG_STATUS) {
4095 return ACTION_STATUS;
4099 * Indicate a change if this was not a match-only rule.
4102 changed = ((p->flags & RULEFLAG_NOESCAPE)
4103 ? ACTION_NOESCAPE : ACTION_NORMAL);
4107 * Pass-Through Feature (`RewriteRule .. .. [PT]'):
4108 * Because the Apache 1.x API is very limited we
4109 * need this hack to pass the rewritten URL to other
4110 * modules like mod_alias, mod_userdir, etc.
4112 if (p->flags & RULEFLAG_PASSTHROUGH) {
4113 rewritelog((r, 2, perdir, "forcing '%s' to get passed through "
4114 "to next API URI-to-filename handler", r->filename));
4115 r->filename = apr_pstrcat(r->pool, "passthrough:",
4117 changed = ACTION_NORMAL;
4122 * Stop processing also on proxy pass-through and
4123 * last-rule and new-round flags.
4125 if (p->flags & (RULEFLAG_PROXY | RULEFLAG_LASTRULE)) {
4130 * On "new-round" flag we just start from the top of
4131 * the rewriting ruleset again.
4133 if (p->flags & RULEFLAG_NEWROUND) {
4138 * If we are forced to skip N next rules, do it now.
4142 while ( i < rewriterules->nelts
4152 * If current rule is chained with next rule(s),
4153 * skip all this next rule(s)
4155 while ( i < rewriterules->nelts
4156 && p->flags & RULEFLAG_CHAIN) {
4167 * +-------------------------------------------------------+
4169 * | Module Initialization Hooks
4171 * +-------------------------------------------------------+
4174 static int pre_config(apr_pool_t *pconf,
4178 APR_OPTIONAL_FN_TYPE(ap_register_rewrite_mapfunc) *map_pfn_register;
4180 /* register int: rewritemap handlers */
4181 mapfunc_hash = apr_hash_make(pconf);
4182 map_pfn_register = APR_RETRIEVE_OPTIONAL_FN(ap_register_rewrite_mapfunc);
4183 if (map_pfn_register) {
4184 map_pfn_register("tolower", rewrite_mapfunc_tolower);
4185 map_pfn_register("toupper", rewrite_mapfunc_toupper);
4186 map_pfn_register("escape", rewrite_mapfunc_escape);
4187 map_pfn_register("unescape", rewrite_mapfunc_unescape);
4189 dbd_acquire = APR_RETRIEVE_OPTIONAL_FN(ap_dbd_acquire);
4190 dbd_prepare = APR_RETRIEVE_OPTIONAL_FN(ap_dbd_prepare);
4194 static int post_config(apr_pool_t *p,
4202 const char *userdata_key = "rewrite_init_module";
4204 apr_pool_userdata_get(&data, userdata_key, s->process->pool);
4207 apr_pool_userdata_set((const void *)1, userdata_key,
4208 apr_pool_cleanup_null, s->process->pool);
4211 /* check if proxy module is available */
4212 proxy_available = (ap_find_linked_module("mod_proxy.c") != NULL);
4214 #ifndef REWRITELOG_DISABLED
4215 /* create the rewriting lockfiles in the parent */
4216 if ((rv = apr_global_mutex_create(&rewrite_log_lock, NULL,
4217 APR_LOCK_DEFAULT, p)) != APR_SUCCESS) {
4218 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, s,
4219 "mod_rewrite: could not create rewrite_log_lock");
4220 return HTTP_INTERNAL_SERVER_ERROR;
4223 #ifdef AP_NEED_SET_MUTEX_PERMS
4224 rv = unixd_set_global_mutex_perms(rewrite_log_lock);
4225 if (rv != APR_SUCCESS) {
4226 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, s,
4227 "mod_rewrite: Could not set permissions on "
4228 "rewrite_log_lock; check User and Group directives");
4229 return HTTP_INTERNAL_SERVER_ERROR;
4232 #endif /* rewritelog */
4234 rv = rewritelock_create(s, p);
4235 if (rv != APR_SUCCESS) {
4236 return HTTP_INTERNAL_SERVER_ERROR;
4239 apr_pool_cleanup_register(p, (void *)s, rewritelock_remove,
4240 apr_pool_cleanup_null);
4242 /* step through the servers and
4243 * - open each rewriting logfile
4244 * - open the RewriteMap prg:xxx programs
4246 for (; s; s = s->next) {
4247 #ifndef REWRITELOG_DISABLED
4248 if (!open_rewritelog(s, p)) {
4249 return HTTP_INTERNAL_SERVER_ERROR;
4254 if (run_rewritemap_programs(s, p) != APR_SUCCESS) {
4255 return HTTP_INTERNAL_SERVER_ERROR;
4260 rewrite_ssl_lookup = APR_RETRIEVE_OPTIONAL_FN(ssl_var_lookup);
4261 rewrite_is_https = APR_RETRIEVE_OPTIONAL_FN(ssl_is_https);
4266 static void init_child(apr_pool_t *p, server_rec *s)
4268 apr_status_t rv = 0; /* get a rid of gcc warning (REWRITELOG_DISABLED) */
4270 if (lockname != NULL && *(lockname) != '\0') {
4271 rv = apr_global_mutex_child_init(&rewrite_mapr_lock_acquire,
4273 if (rv != APR_SUCCESS) {
4274 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, s,
4275 "mod_rewrite: could not init rewrite_mapr_lock_acquire"
4280 #ifndef REWRITELOG_DISABLED
4281 rv = apr_global_mutex_child_init(&rewrite_log_lock, NULL, p);
4282 if (rv != APR_SUCCESS) {
4283 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, s,
4284 "mod_rewrite: could not init rewrite log lock in child");
4288 /* create the lookup cache */
4289 if (!init_cache(p)) {
4290 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, s,
4291 "mod_rewrite: could not init map cache in child");
4297 * +-------------------------------------------------------+
4301 * +-------------------------------------------------------+
4305 * URI-to-filename hook
4306 * [deals with RewriteRules in server context]
4308 static int hook_uri2file(request_rec *r)
4310 rewrite_server_conf *conf;
4311 const char *saved_rulestatus;
4313 const char *thisserver;
4315 const char *thisurl;
4320 * retrieve the config structures
4322 conf = ap_get_module_config(r->server->module_config, &rewrite_module);
4325 * only do something under runtime if the engine is really enabled,
4326 * else return immediately!
4328 if (conf->state == ENGINE_DISABLED) {
4333 * check for the ugly API case of a virtual host section where no
4334 * mod_rewrite directives exists. In this situation we became no chance
4335 * by the API to setup our default per-server config so we have to
4336 * on-the-fly assume we have the default config. But because the default
4337 * config has a disabled rewriting engine we are lucky because can
4338 * just stop operating now.
4340 if (conf->server != r->server) {
4345 * add the SCRIPT_URL variable to the env. this is a bit complicated
4346 * due to the fact that apache uses subrequests and internal redirects
4349 if (r->main == NULL) {
4350 var = apr_table_get(r->subprocess_env, REDIRECT_ENVVAR_SCRIPT_URL);
4352 apr_table_setn(r->subprocess_env, ENVVAR_SCRIPT_URL, r->uri);
4355 apr_table_setn(r->subprocess_env, ENVVAR_SCRIPT_URL, var);
4359 var = apr_table_get(r->main->subprocess_env, ENVVAR_SCRIPT_URL);
4360 apr_table_setn(r->subprocess_env, ENVVAR_SCRIPT_URL, var);
4364 * create the SCRIPT_URI variable for the env
4367 /* add the canonical URI of this URL */
4368 thisserver = ap_get_server_name(r);
4369 port = ap_get_server_port(r);
4370 if (ap_is_default_port(port, r)) {
4374 thisport = apr_psprintf(r->pool, ":%u", port);
4376 thisurl = apr_table_get(r->subprocess_env, ENVVAR_SCRIPT_URL);
4378 /* set the variable */
4379 var = apr_pstrcat(r->pool, ap_http_scheme(r), "://", thisserver, thisport,
4381 apr_table_setn(r->subprocess_env, ENVVAR_SCRIPT_URI, var);
4383 if (!(saved_rulestatus = apr_table_get(r->notes,"mod_rewrite_rewritten"))) {
4384 /* if filename was not initially set,
4385 * we start with the requested URI
4387 if (r->filename == NULL) {
4388 r->filename = apr_pstrdup(r->pool, r->uri);
4389 rewritelog((r, 2, NULL, "init rewrite engine with requested uri %s",
4393 rewritelog((r, 2, NULL, "init rewrite engine with passed filename "
4394 "%s. Original uri = %s", r->filename, r->uri));
4398 * now apply the rules ...
4400 rulestatus = apply_rewrite_list(r, conf->rewriterules, NULL);
4401 apr_table_set(r->notes,"mod_rewrite_rewritten",
4402 apr_psprintf(r->pool,"%d",rulestatus));
4405 rewritelog((r, 2, NULL, "uri already rewritten. Status %s, Uri %s, "
4406 "r->filename %s", saved_rulestatus, r->uri, r->filename));
4408 rulestatus = atoi(saved_rulestatus);
4415 if (ACTION_STATUS == rulestatus) {
4418 r->status = HTTP_OK;
4422 flen = r->filename ? strlen(r->filename) : 0;
4423 if (flen > 6 && strncmp(r->filename, "proxy:", 6) == 0) {
4424 /* it should be go on as an internal proxy request */
4426 /* check if the proxy module is enabled, so
4427 * we can actually use it!
4429 if (!proxy_available) {
4430 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
4431 "attempt to make remote request from mod_rewrite "
4432 "without proxy enabled: %s", r->filename);
4433 return HTTP_FORBIDDEN;
4436 if (rulestatus == ACTION_NOESCAPE) {
4437 apr_table_setn(r->notes, "proxy-nocanon", "1");
4440 /* make sure the QUERY_STRING and
4441 * PATH_INFO parts get incorporated
4443 if (r->path_info != NULL) {
4444 r->filename = apr_pstrcat(r->pool, r->filename,
4445 r->path_info, NULL);
4447 if (r->args != NULL &&
4448 r->uri == r->unparsed_uri) {
4449 /* see proxy_http:proxy_http_canon() */
4450 r->filename = apr_pstrcat(r->pool, r->filename,
4451 "?", r->args, NULL);
4454 /* now make sure the request gets handled by the proxy handler */
4455 if (PROXYREQ_NONE == r->proxyreq) {
4456 r->proxyreq = PROXYREQ_REVERSE;
4458 r->handler = "proxy-server";
4460 rewritelog((r, 1, NULL, "go-ahead with proxy request %s [OK]",
4464 else if ((skip = is_absolute_uri(r->filename)) > 0) {
4467 /* it was finally rewritten to a remote URL */
4469 if (rulestatus != ACTION_NOESCAPE) {
4470 rewritelog((r, 1, NULL, "escaping %s for redirect",
4472 r->filename = escape_absolute_uri(r->pool, r->filename, skip);
4475 /* append the QUERY_STRING part */
4477 r->filename = apr_pstrcat(r->pool, r->filename, "?",
4478 (rulestatus == ACTION_NOESCAPE)
4480 : ap_escape_uri(r->pool, r->args),
4484 /* determine HTTP redirect response code */
4485 if (ap_is_HTTP_REDIRECT(r->status)) {
4487 r->status = HTTP_OK; /* make Apache kernel happy */
4490 n = HTTP_MOVED_TEMPORARILY;
4493 /* now do the redirection */
4494 apr_table_setn(r->headers_out, "Location", r->filename);
4495 rewritelog((r, 1, NULL, "redirect to %s [REDIRECT/%d]", r->filename,
4500 else if (flen > 12 && strncmp(r->filename, "passthrough:", 12) == 0) {
4502 * Hack because of underpowered API: passing the current
4503 * rewritten filename through to other URL-to-filename handlers
4504 * just as it were the requested URL. This is to enable
4505 * post-processing by mod_alias, etc. which always act on
4506 * r->uri! The difference here is: We do not try to
4507 * add the document root
4509 r->uri = apr_pstrdup(r->pool, r->filename+12);
4513 /* it was finally rewritten to a local path */
4515 /* expand "/~user" prefix */
4517 r->filename = expand_tildepaths(r, r->filename);
4519 rewritelog((r, 2, NULL, "local path result: %s", r->filename));
4521 /* the filename must be either an absolute local path or an
4522 * absolute local URL.
4524 if ( *r->filename != '/'
4525 && !ap_os_is_path_absolute(r->pool, r->filename)) {
4526 return HTTP_BAD_REQUEST;
4529 /* if there is no valid prefix, we call
4530 * the translator from the core and
4531 * prefix the filename with document_root
4534 * We cannot leave out the prefix_stat because
4535 * - when we always prefix with document_root
4536 * then no absolute path can be created, e.g. via
4537 * emulating a ScriptAlias directive, etc.
4538 * - when we always NOT prefix with document_root
4539 * then the files under document_root have to
4540 * be references directly and document_root
4541 * gets never used and will be a dummy parameter -
4545 * Under real Unix systems this is no problem,
4546 * because we only do stat() on the first directory
4547 * and this gets cached by the kernel for along time!
4549 if (!prefix_stat(r->filename, r->pool)) {
4553 r->uri = r->filename;
4554 res = ap_core_translate(r);
4558 rewritelog((r, 1, NULL, "prefixing with document_root of %s"
4559 " FAILED", r->filename));
4564 rewritelog((r, 2, NULL, "prefixed with document_root to %s",
4568 rewritelog((r, 1, NULL, "go-ahead with %s [OK]", r->filename));
4573 rewritelog((r, 1, NULL, "pass through %s", r->filename));
4580 * [RewriteRules in directory context]
4582 static int hook_fixup(request_rec *r)
4584 rewrite_perdir_conf *dconf;
4594 dconf = (rewrite_perdir_conf *)ap_get_module_config(r->per_dir_config,
4597 /* if there is no per-dir config we return immediately */
4598 if (dconf == NULL) {
4602 /* if there are no real (i.e. no RewriteRule directives!)
4603 per-dir config of us, we return also immediately */
4604 if (dconf->directory == NULL) {
4611 is_proxyreq = ( r->proxyreq && r->filename
4612 && !strncmp(r->filename, "proxy:", 6));
4615 * .htaccess file is called before really entering the directory, i.e.:
4616 * URL: http://localhost/foo and .htaccess is located in foo directory
4617 * Ignore such attempts, since they may lead to undefined behaviour.
4620 l = strlen(dconf->directory) - 1;
4621 if (r->filename && strlen(r->filename) == l &&
4622 (dconf->directory)[l] == '/' &&
4623 !strncmp(r->filename, dconf->directory, l)) {
4629 * only do something under runtime if the engine is really enabled,
4630 * for this directory, else return immediately!
4632 if (dconf->state == ENGINE_DISABLED) {
4637 * Do the Options check after engine check, so
4638 * the user is able to explicitely turn RewriteEngine Off.
4640 if (!(ap_allow_options(r) & (OPT_SYM_LINKS | OPT_SYM_OWNER))) {
4641 /* FollowSymLinks is mandatory! */
4642 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
4643 "Options FollowSymLinks or SymLinksIfOwnerMatch is off "
4644 "which implies that RewriteRule directive is forbidden: "
4646 return HTTP_FORBIDDEN;
4650 * remember the current filename before rewriting for later check
4651 * to prevent deadlooping because of internal redirects
4652 * on final URL/filename which can be equal to the inital one.
4653 * also, we'll restore original r->filename if we decline this
4656 ofilename = r->filename;
4658 if (r->filename == NULL) {
4659 r->filename = apr_pstrdup(r->pool, r->uri);
4660 rewritelog((r, 2, "init rewrite engine with requested uri %s",
4665 * now apply the rules ...
4667 rulestatus = apply_rewrite_list(r, dconf->rewriterules, dconf->directory);
4671 if (ACTION_STATUS == rulestatus) {
4674 r->status = HTTP_OK;
4678 l = strlen(r->filename);
4679 if (l > 6 && strncmp(r->filename, "proxy:", 6) == 0) {
4680 /* it should go on as an internal proxy request */
4682 /* make sure the QUERY_STRING and
4683 * PATH_INFO parts get incorporated
4684 * (r->path_info was already appended by the
4685 * rewriting engine because of the per-dir context!)
4687 if (r->args != NULL) {
4688 r->filename = apr_pstrcat(r->pool, r->filename,
4689 "?", r->args, NULL);
4692 /* now make sure the request gets handled by the proxy handler */
4693 if (PROXYREQ_NONE == r->proxyreq) {
4694 r->proxyreq = PROXYREQ_REVERSE;
4696 r->handler = "proxy-server";
4698 rewritelog((r, 1, dconf->directory, "go-ahead with proxy request "
4699 "%s [OK]", r->filename));
4702 else if ((skip = is_absolute_uri(r->filename)) > 0) {
4703 /* it was finally rewritten to a remote URL */
4705 /* because we are in a per-dir context
4706 * first try to replace the directory with its base-URL
4707 * if there is a base-URL available
4709 if (dconf->baseurl != NULL) {
4710 /* skip 'scheme://' */
4711 cp = r->filename + skip;
4713 if ((cp = ap_strchr(cp, '/')) != NULL && *(++cp)) {
4714 rewritelog((r, 2, dconf->directory,
4715 "trying to replace prefix %s with %s",
4716 dconf->directory, dconf->baseurl));
4718 /* I think, that hack needs an explanation:
4720 * mod_rewrite was written for unix systems, were
4721 * absolute file-system paths start with a slash.
4722 * URL-paths _also_ start with slashes, so they
4723 * can be easily compared with system paths.
4725 * the following assumes, that the actual url-path
4726 * may be prefixed by the current directory path and
4727 * tries to replace the system path with the RewriteBase
4729 * That assumption is true if we use a RewriteRule like
4731 * RewriteRule ^foo bar [R]
4733 * (see apply_rewrite_rule function)
4734 * However on systems that don't have a / as system
4735 * root this will never match, so we skip the / after the
4736 * hostname and compare/substitute only the stuff after it.
4738 * (note that cp was already increased to the right value)
4740 cp2 = subst_prefix_path(r, cp, (*dconf->directory == '/')
4741 ? dconf->directory + 1
4743 dconf->baseurl + 1);
4744 if (strcmp(cp2, cp) != 0) {
4746 r->filename = apr_pstrcat(r->pool, r->filename,
4752 /* now prepare the redirect... */
4753 if (rulestatus != ACTION_NOESCAPE) {
4754 rewritelog((r, 1, dconf->directory, "escaping %s for redirect",
4756 r->filename = escape_absolute_uri(r->pool, r->filename, skip);
4759 /* append the QUERY_STRING part */
4761 r->filename = apr_pstrcat(r->pool, r->filename, "?",
4762 (rulestatus == ACTION_NOESCAPE)
4764 : ap_escape_uri(r->pool, r->args),
4768 /* determine HTTP redirect response code */
4769 if (ap_is_HTTP_REDIRECT(r->status)) {
4771 r->status = HTTP_OK; /* make Apache kernel happy */
4774 n = HTTP_MOVED_TEMPORARILY;
4777 /* now do the redirection */
4778 apr_table_setn(r->headers_out, "Location", r->filename);
4779 rewritelog((r, 1, dconf->directory, "redirect to %s [REDIRECT/%d]",
4784 /* it was finally rewritten to a local path */
4786 /* if someone used the PASSTHROUGH flag in per-dir
4787 * context we just ignore it. It is only useful
4788 * in per-server context
4790 if (l > 12 && strncmp(r->filename, "passthrough:", 12) == 0) {
4791 r->filename = apr_pstrdup(r->pool, r->filename+12);
4794 /* the filename must be either an absolute local path or an
4795 * absolute local URL.
4797 if ( *r->filename != '/'
4798 && !ap_os_is_path_absolute(r->pool, r->filename)) {
4799 return HTTP_BAD_REQUEST;
4802 /* Check for deadlooping:
4803 * At this point we KNOW that at least one rewriting
4804 * rule was applied, but when the resulting URL is
4805 * the same as the initial URL, we are not allowed to
4806 * use the following internal redirection stuff because
4807 * this would lead to a deadloop.
4809 if (ofilename != NULL && strcmp(r->filename, ofilename) == 0) {
4810 rewritelog((r, 1, dconf->directory, "initial URL equal rewritten"
4811 " URL: %s [IGNORING REWRITE]", r->filename));
4815 /* if there is a valid base-URL then substitute
4816 * the per-dir prefix with this base-URL if the
4817 * current filename still is inside this per-dir
4818 * context. If not then treat the result as a
4821 if (dconf->baseurl != NULL) {
4822 rewritelog((r, 2, dconf->directory, "trying to replace prefix "
4823 "%s with %s", dconf->directory, dconf->baseurl));
4825 r->filename = subst_prefix_path(r, r->filename,
4830 /* if no explicit base-URL exists we assume
4831 * that the directory prefix is also a valid URL
4832 * for this webserver and only try to remove the
4833 * document_root if it is prefix
4835 if ((ccp = ap_document_root(r)) != NULL) {
4836 /* strip trailing slash */
4838 if (ccp[l-1] == '/') {
4841 if (!strncmp(r->filename, ccp, l) &&
4842 r->filename[l] == '/') {
4843 rewritelog((r, 2,dconf->directory, "strip document_root"
4844 " prefix: %s -> %s", r->filename,
4847 r->filename = apr_pstrdup(r->pool, r->filename+l);
4852 /* now initiate the internal redirect */
4853 rewritelog((r, 1, dconf->directory, "internal redirect with %s "
4854 "[INTERNAL REDIRECT]", r->filename));
4855 r->filename = apr_pstrcat(r->pool, "redirect:", r->filename, NULL);
4856 r->handler = "redirect-handler";
4861 rewritelog((r, 1, dconf->directory, "pass through %s", r->filename));
4862 r->filename = ofilename;
4869 * [T=...,H=...] execution
4871 static int hook_mimetype(request_rec *r)
4876 t = apr_table_get(r->notes, REWRITE_FORCED_MIMETYPE_NOTEVAR);
4878 rewritelog((r, 1, NULL, "force filename %s to have MIME-type '%s'",
4881 ap_set_content_type(r, t);
4885 t = apr_table_get(r->notes, REWRITE_FORCED_HANDLER_NOTEVAR);
4887 rewritelog((r, 1, NULL, "force filename %s to have the "
4888 "Content-handler '%s'", r->filename, t));
4898 * "content" handler for internal redirects
4900 static int handler_redirect(request_rec *r)
4902 if (strcmp(r->handler, "redirect-handler")) {
4906 /* just make sure that we are really meant! */
4907 if (strncmp(r->filename, "redirect:", 9) != 0) {
4911 /* now do the internal redirect */
4912 ap_internal_redirect(apr_pstrcat(r->pool, r->filename+9,
4913 r->args ? "?" : NULL, r->args, NULL), r);
4915 /* and return gracefully */
4921 * +-------------------------------------------------------+
4923 * | Module paraphernalia
4925 * +-------------------------------------------------------+
4928 #ifdef REWRITELOG_DISABLED
4929 static const char *fake_rewritelog(cmd_parms *cmd, void *dummy, const char *a1)
4931 return "RewriteLog and RewriteLogLevel are not supported by this build "
4932 "of mod_rewrite because it was compiled using the "
4933 "-DREWRITELOG_DISABLED compiler option. You have to recompile "
4934 "mod_rewrite WITHOUT this option in order to use the rewrite log.";
4938 static const command_rec command_table[] = {
4939 AP_INIT_FLAG( "RewriteEngine", cmd_rewriteengine, NULL, OR_FILEINFO,
4940 "On or Off to enable or disable (default) the whole "
4941 "rewriting engine"),
4942 AP_INIT_ITERATE( "RewriteOptions", cmd_rewriteoptions, NULL, OR_FILEINFO,
4943 "List of option strings to set"),
4944 AP_INIT_TAKE1( "RewriteBase", cmd_rewritebase, NULL, OR_FILEINFO,
4945 "the base URL of the per-directory context"),
4946 AP_INIT_RAW_ARGS("RewriteCond", cmd_rewritecond, NULL, OR_FILEINFO,
4947 "an input string and a to be applied regexp-pattern"),
4948 AP_INIT_RAW_ARGS("RewriteRule", cmd_rewriterule, NULL, OR_FILEINFO,
4949 "an URL-applied regexp-pattern and a substitution URL"),
4950 AP_INIT_TAKE2( "RewriteMap", cmd_rewritemap, NULL, RSRC_CONF,
4951 "a mapname and a filename"),
4952 AP_INIT_TAKE1( "RewriteLock", cmd_rewritelock, NULL, RSRC_CONF,
4953 "the filename of a lockfile used for inter-process "
4955 #ifndef REWRITELOG_DISABLED
4956 AP_INIT_TAKE1( "RewriteLog", cmd_rewritelog, NULL, RSRC_CONF,
4957 "the filename of the rewriting logfile"),
4958 AP_INIT_TAKE1( "RewriteLogLevel", cmd_rewriteloglevel, NULL, RSRC_CONF,
4959 "the level of the rewriting logfile verbosity "
4960 "(0=none, 1=std, .., 9=max)"),
4962 AP_INIT_TAKE1( "RewriteLog", fake_rewritelog, NULL, RSRC_CONF,
4963 "[DISABLED] the filename of the rewriting logfile"),
4964 AP_INIT_TAKE1( "RewriteLogLevel", fake_rewritelog, NULL, RSRC_CONF,
4965 "[DISABLED] the level of the rewriting logfile verbosity"),
4970 static void ap_register_rewrite_mapfunc(char *name, rewrite_mapfunc_t *func)
4972 apr_hash_set(mapfunc_hash, name, strlen(name), (const void *)func);
4975 static void register_hooks(apr_pool_t *p)
4977 /* fixup after mod_proxy, so that the proxied url will not
4978 * escaped accidentally by mod_proxy's fixup.
4980 static const char * const aszPre[]={ "mod_proxy.c", NULL };
4982 APR_REGISTER_OPTIONAL_FN(ap_register_rewrite_mapfunc);
4984 ap_hook_handler(handler_redirect, NULL, NULL, APR_HOOK_MIDDLE);
4985 ap_hook_pre_config(pre_config, NULL, NULL, APR_HOOK_MIDDLE);
4986 ap_hook_post_config(post_config, NULL, NULL, APR_HOOK_MIDDLE);
4987 ap_hook_child_init(init_child, NULL, NULL, APR_HOOK_MIDDLE);
4989 ap_hook_fixups(hook_fixup, aszPre, NULL, APR_HOOK_FIRST);
4990 ap_hook_fixups(hook_mimetype, NULL, NULL, APR_HOOK_LAST);
4991 ap_hook_translate_name(hook_uri2file, NULL, NULL, APR_HOOK_FIRST);
4994 /* the main config structure */
4995 module AP_MODULE_DECLARE_DATA rewrite_module = {
4996 STANDARD20_MODULE_STUFF,
4997 config_perdir_create, /* create per-dir config structures */
4998 config_perdir_merge, /* merge per-dir config structures */
4999 config_server_create, /* create per-server config structures */
5000 config_server_merge, /* merge per-server config structures */
5001 command_table, /* table of config file commands */
5002 register_hooks /* register hooks */