xref: /lighttpd1.4/src/mod_rewrite.c (revision f2e4e83a)
1 #include "first.h"
2 
3 #include "base.h"
4 #include "keyvalue.h"
5 #include "log.h"
6 #include "buffer.h"
7 #include "burl.h"
8 
9 #include "plugin.h"
10 #include "stat_cache.h"
11 
12 #include <stdlib.h>
13 #include <string.h>
14 
15 typedef struct {
16     pcre_keyvalue_buffer *rewrite;
17     pcre_keyvalue_buffer *rewrite_NF;
18 } plugin_config;
19 
20 enum { REWRITE_STATE_REWRITTEN = 1024, REWRITE_STATE_FINISHED = 2048}; /*flags*/
21 
22 typedef struct {
23     PLUGIN_DATA;
24     plugin_config defaults;
25     plugin_config conf;
26 } plugin_data;
27 
28 INIT_FUNC(mod_rewrite_init) {
29     return calloc(1, sizeof(plugin_data));
30 }
31 
32 FREE_FUNC(mod_rewrite_free) {
33     plugin_data * const p = p_d;
34     if (NULL == p->cvlist) return;
35     /* (init i to 0 if global context; to 1 to skip empty global context) */
36     for (int i = !p->cvlist[0].v.u2[1], used = p->nconfig; i < used; ++i) {
37         config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0];
38         /* kvb value might be copied in multiple directives; free only once */
39         pcre_keyvalue_buffer *kvb = NULL, *kvb_NF = NULL;
40         for (; -1 != cpv->k_id; ++cpv) {
41             switch (cpv->k_id) {
42               case 0: /* url.rewrite-once */
43               case 1: /* url.rewrite-final */
44               case 2: /* url.rewrite */
45               case 3: /* url.rewrite-repeat */
46                 if (cpv->vtype == T_CONFIG_LOCAL)
47                     kvb = cpv->v.v;
48                 break;
49               case 4: /* url.rewrite-if-not-file */
50               case 5: /* url.rewrite-repeat-if-not-file */
51                 if (cpv->vtype == T_CONFIG_LOCAL)
52                     kvb_NF = cpv->v.v;
53               default:
54                 break;
55             }
56         }
57         if (kvb)    pcre_keyvalue_buffer_free(kvb);
58         if (kvb_NF) pcre_keyvalue_buffer_free(kvb_NF);
59     }
60 }
61 
62 static void mod_rewrite_merge_config_cpv(plugin_config * const pconf, const config_plugin_value_t * const cpv) {
63     switch (cpv->k_id) { /* index into static config_plugin_keys_t cpk[] */
64       case 0: /* url.rewrite-once */
65       case 1: /* url.rewrite-final */
66       case 2: /* url.rewrite */
67       case 3: /* url.rewrite-repeat */
68         /*if (cpv->vtype == T_CONFIG_LOCAL)*//*always true here in mod_rewrite*/
69             pconf->rewrite = cpv->v.v;
70         break;
71       case 4: /* url.rewrite-if-not-file */
72       case 5: /* url.rewrite-repeat-if-not-file */
73         /*if (cpv->vtype == T_CONFIG_LOCAL)*//*always true here in mod_rewrite*/
74             pconf->rewrite_NF = cpv->v.v;
75         break;
76       default:/* should not happen */
77         return;
78     }
79 }
80 
81 static void mod_rewrite_merge_config(plugin_config * const pconf, const config_plugin_value_t *cpv) {
82     do {
83         mod_rewrite_merge_config_cpv(pconf, cpv);
84     } while ((++cpv)->k_id != -1);
85 }
86 
87 static void mod_rewrite_patch_config(request_st * const r, plugin_data * const p) {
88     p->conf = p->defaults; /* copy small struct instead of memcpy() */
89     /*memcpy(&p->conf, &p->defaults, sizeof(plugin_config));*/
90     for (int i = 1, used = p->nconfig; i < used; ++i) {
91         if (config_check_cond(r, (uint32_t)p->cvlist[i].k_id))
92             mod_rewrite_merge_config(&p->conf, p->cvlist+p->cvlist[i].v.u2[0]);
93     }
94 }
95 
96 static pcre_keyvalue_buffer * mod_rewrite_parse_list(server *srv, const array *a, pcre_keyvalue_buffer *kvb, const int condidx) {
97     int allocated = 0;
98     if (NULL == kvb) {
99         allocated = 1;
100         kvb = pcre_keyvalue_buffer_init();
101         kvb->x0 = (unsigned short)condidx;
102     }
103 
104     buffer * const tb = srv->tmp_buf;
105     for (uint32_t j = 0; j < a->used; ++j) {
106         data_string *ds = (data_string *)a->data[j];
107         if (srv->srvconf.http_url_normalize) {
108             pcre_keyvalue_burl_normalize_key(&ds->key, tb);
109             pcre_keyvalue_burl_normalize_value(&ds->value, tb);
110         }
111         if (!pcre_keyvalue_buffer_append(srv->errh, kvb, &ds->key, &ds->value)){
112             log_error(srv->errh, __FILE__, __LINE__,
113               "pcre-compile failed for %s", ds->key.ptr);
114             if (allocated) pcre_keyvalue_buffer_free(kvb);
115             return NULL;
116         }
117     }
118 
119     return kvb;
120 }
121 
122 SETDEFAULTS_FUNC(mod_rewrite_set_defaults) {
123     static const config_plugin_keys_t cpk[] = {
124       { CONST_STR_LEN("url.rewrite-once"),
125         T_CONFIG_ARRAY_KVSTRING,
126         T_CONFIG_SCOPE_CONNECTION }
127      ,{ CONST_STR_LEN("url.rewrite-final"),  /* old name => url.rewrite-once */
128         T_CONFIG_ARRAY_KVSTRING,
129         T_CONFIG_SCOPE_CONNECTION }
130      ,{ CONST_STR_LEN("url.rewrite"),        /* old name => url.rewrite-once */
131         T_CONFIG_ARRAY_KVSTRING,
132         T_CONFIG_SCOPE_CONNECTION }
133      ,{ CONST_STR_LEN("url.rewrite-repeat"),
134         T_CONFIG_ARRAY_KVSTRING,
135         T_CONFIG_SCOPE_CONNECTION }
136      ,{ CONST_STR_LEN("url.rewrite-if-not-file"), /* rewrite-once if ENOENT */
137         T_CONFIG_ARRAY_KVSTRING,
138         T_CONFIG_SCOPE_CONNECTION }
139      ,{ CONST_STR_LEN("url.rewrite-repeat-if-not-file"), /* repeat if ENOENT */
140         T_CONFIG_ARRAY_KVSTRING,
141         T_CONFIG_SCOPE_CONNECTION }
142      ,{ NULL, 0,
143         T_CONFIG_UNSET,
144         T_CONFIG_SCOPE_UNSET }
145     };
146 
147     plugin_data * const p = p_d;
148     if (!config_plugin_values_init(srv, p, cpk, "mod_rewrite"))
149         return HANDLER_ERROR;
150 
151     /* process and validate config directives
152      * (init i to 0 if global context; to 1 to skip empty global context) */
153     for (int i = !p->cvlist[0].v.u2[1]; i < p->nconfig; ++i) {
154         config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0];
155         /* parse directives in specific order to encode repeat_idx in kvb->x1 */
156         config_plugin_value_t *rewrite_once = NULL, *rewrite_repeat = NULL,
157                               *rewrite_NF = NULL,   *rewrite_repeat_NF = NULL,
158                               *rewrite = NULL,      *rewrite_final = NULL;
159         for (; -1 != cpv->k_id; ++cpv) {
160             switch (cpv->k_id) {
161               case 0: /* url.rewrite-once */
162                 rewrite_once = cpv;
163                 break;
164               case 1: /* url.rewrite-final */
165                 rewrite_final = cpv;
166                 break;
167               case 2: /* url.rewrite */
168                 rewrite = cpv;
169                 break;
170               case 3: /* url.rewrite-repeat */
171                 rewrite_repeat = cpv;
172                 break;
173               case 4: /* url.rewrite-if-not-file */
174                 rewrite_NF = cpv;
175                 break;
176               case 5: /* url.rewrite-repeat-if-not-file */
177                 rewrite_repeat_NF = cpv;
178                 break;
179               default:/* should not happen */
180                 break;
181             }
182         }
183 
184         const int condidx = p->cvlist[i].k_id;
185         pcre_keyvalue_buffer *kvb = NULL, *kvb_NF = NULL;
186 
187         if ((cpv = rewrite_once)) {
188             cpv->v.v = mod_rewrite_parse_list(srv, cpv->v.a, kvb, condidx);
189             if (NULL == cpv->v.v) return HANDLER_ERROR;
190             cpv->vtype = T_CONFIG_LOCAL;
191             kvb = cpv->v.v;
192         }
193 
194         if ((cpv = rewrite_final)) {
195             cpv->v.v = mod_rewrite_parse_list(srv, cpv->v.a, kvb, condidx);
196             if (NULL == cpv->v.v) return HANDLER_ERROR;
197             cpv->vtype = T_CONFIG_LOCAL;
198             kvb = cpv->v.v;
199         }
200 
201         if ((cpv = rewrite)) {
202             cpv->v.v = mod_rewrite_parse_list(srv, cpv->v.a, kvb, condidx);
203             if (NULL == cpv->v.v) return HANDLER_ERROR;
204             cpv->vtype = T_CONFIG_LOCAL;
205             kvb = cpv->v.v;
206         }
207 
208         if (kvb) kvb->x1 = (unsigned short)kvb->used; /* repeat_idx */
209 
210         if ((cpv = rewrite_repeat)) {
211             cpv->v.v = mod_rewrite_parse_list(srv, cpv->v.a, kvb, condidx);
212             if (NULL == cpv->v.v) return HANDLER_ERROR;
213             cpv->vtype = T_CONFIG_LOCAL;
214             /*kvb = cpv->v.v;*/
215         }
216 
217         if ((cpv = rewrite_NF)) {
218             cpv->v.v = mod_rewrite_parse_list(srv, cpv->v.a, kvb_NF, condidx);
219             if (NULL == cpv->v.v) return HANDLER_ERROR;
220             cpv->vtype = T_CONFIG_LOCAL;
221             kvb_NF = cpv->v.v;
222         }
223 
224         if (kvb_NF) kvb_NF->x1 = (unsigned short)kvb_NF->used; /* repeat_idx */
225 
226         if ((cpv = rewrite_repeat_NF)) {
227             cpv->v.v = mod_rewrite_parse_list(srv, cpv->v.a, kvb_NF, condidx);
228             if (NULL == cpv->v.v) return HANDLER_ERROR;
229             cpv->vtype = T_CONFIG_LOCAL;
230             /*kvb_NF = cpv->v.v;*/
231         }
232     }
233 
234     /* initialize p->defaults from global config context */
235     if (p->nconfig > 0 && p->cvlist->v.u2[1]) {
236         const config_plugin_value_t *cpv = p->cvlist + p->cvlist->v.u2[0];
237         if (-1 != cpv->k_id)
238             mod_rewrite_merge_config(&p->defaults, cpv);
239     }
240 
241     return HANDLER_GO_ON;
242 }
243 
244 URIHANDLER_FUNC(mod_rewrite_con_reset) {
245     r->plugin_ctx[((plugin_data *)p_d)->id] = NULL;
246     return HANDLER_GO_ON;
247 }
248 
249 static handler_t process_rewrite_rules(request_st * const r, plugin_data *p, const pcre_keyvalue_buffer *kvb) {
250 	struct burl_parts_t burl;
251 	pcre_keyvalue_ctx ctx;
252 	handler_t rc;
253 
254 	if (r->plugin_ctx[p->id]) {
255 		uintptr_t * const hctx = (uintptr_t *)(r->plugin_ctx + p->id);
256 
257 		if (((++*hctx) & 0x1FF) > 100) {
258 			if (0 != kvb->x0) {
259 				config_cond_info cfginfo;
260 				config_get_config_cond_info(&cfginfo, kvb->x0);
261 				log_error(r->conf.errh, __FILE__, __LINE__,
262 				  "ENDLESS LOOP IN rewrite-rule DETECTED ... aborting request, "
263 				  "perhaps you want to use url.rewrite-once instead of "
264 				  "url.rewrite-repeat ($%s %s \"%s\")", cfginfo.comp_key->ptr,
265 				  cfginfo.op, cfginfo.string->ptr);
266 				return HANDLER_ERROR;
267 			}
268 
269 			log_error(r->conf.errh, __FILE__, __LINE__,
270 			  "ENDLESS LOOP IN rewrite-rule DETECTED ... aborting request");
271 			return HANDLER_ERROR;
272 		}
273 
274 		if (*hctx & REWRITE_STATE_FINISHED) return HANDLER_GO_ON;
275 	}
276 
277 	ctx.cache = NULL;
278 	if (kvb->x0) { /*(kvb->x0 is context_idx)*/
279 		ctx.cond_match_count =
280 		  r->cond_cache[kvb->x0].patterncount;
281 		ctx.cache = r->cond_match + kvb->x0;
282         }
283 	ctx.burl = &burl;
284 	burl.scheme    = &r->uri.scheme;
285 	burl.authority = &r->uri.authority;
286 	burl.port      = sock_addr_get_port(&r->con->srv_socket->addr);
287 	burl.path      = &r->target; /*(uri-encoded and includes query-part)*/
288 	burl.query     = &r->uri.query;
289 	if (buffer_string_is_empty(burl.authority))
290 		burl.authority = r->server_name;
291 
292 	buffer * const tb = r->tmp_buf;
293 	rc = pcre_keyvalue_buffer_process(kvb, &ctx, &r->target, tb);
294 	if (HANDLER_FINISHED == rc && !buffer_is_empty(tb) && tb->ptr[0] == '/') {
295 		buffer_copy_buffer(&r->target, tb);
296 		uintptr_t * const hctx = (uintptr_t *)(r->plugin_ctx + p->id);
297 		*hctx |= REWRITE_STATE_REWRITTEN;
298 		/*(kvb->x1 is repeat_idx)*/
299 		if (ctx.m < kvb->x1) *hctx |= REWRITE_STATE_FINISHED;
300 		buffer_reset(&r->physical.path);
301 		rc = HANDLER_COMEBACK;
302 	}
303 	else if (HANDLER_FINISHED == rc) {
304 		rc = HANDLER_ERROR;
305 		log_error(r->conf.errh, __FILE__, __LINE__,
306 		  "mod_rewrite invalid result (not beginning with '/') "
307 		  "while processing uri: %s", r->target.ptr);
308 	}
309 	else if (HANDLER_ERROR == rc) {
310 		log_error(r->conf.errh, __FILE__, __LINE__,
311 		  "pcre_exec() error "
312 		  "while processing uri: %s", r->target.ptr);
313 	}
314 	return rc;
315 }
316 
317 URIHANDLER_FUNC(mod_rewrite_physical) {
318     plugin_data * const p = p_d;
319 
320     if (NULL != r->handler_module) return HANDLER_GO_ON;
321 
322     mod_rewrite_patch_config(r, p);
323     if (!p->conf.rewrite_NF || !p->conf.rewrite_NF->used) return HANDLER_GO_ON;
324 
325     /* skip if physical.path is a regular file */
326     stat_cache_entry *sce = stat_cache_get_entry(&r->physical.path);
327     if (sce && S_ISREG(sce->st.st_mode)) return HANDLER_GO_ON;
328 
329     return process_rewrite_rules(r, p, p->conf.rewrite_NF);
330 }
331 
332 URIHANDLER_FUNC(mod_rewrite_uri_handler) {
333     plugin_data *p = p_d;
334 
335     mod_rewrite_patch_config(r, p);
336     if (!p->conf.rewrite || !p->conf.rewrite->used) return HANDLER_GO_ON;
337 
338     return process_rewrite_rules(r, p, p->conf.rewrite);
339 }
340 
341 int mod_rewrite_plugin_init(plugin *p);
342 int mod_rewrite_plugin_init(plugin *p) {
343 	p->version     = LIGHTTPD_VERSION_ID;
344 	p->name        = "rewrite";
345 
346 	p->init        = mod_rewrite_init;
347 	/* it has to stay _raw as we are matching on uri + querystring
348 	 */
349 
350 	p->handle_uri_raw = mod_rewrite_uri_handler;
351 	p->handle_physical = mod_rewrite_physical;
352 	p->cleanup     = mod_rewrite_free;
353 	p->handle_request_reset = mod_rewrite_con_reset;
354 	p->set_defaults = mod_rewrite_set_defaults;
355 
356 	return 0;
357 }
358