summaryrefslogtreecommitdiff
path: root/src/mod_rewrite.c
blob: 058e756954f5d96bfb77c60c4b966d8a6599915b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
#include "base.h"
#include "log.h"
#include "buffer.h"

#include "plugin.h"
#include "stat_cache.h"

#include <ctype.h>
#include <stdlib.h>
#include <string.h>

#ifdef HAVE_PCRE_H
typedef struct {
	pcre *key;

	buffer *value;

	int once;
} rewrite_rule;

typedef struct {
	rewrite_rule **ptr;

	size_t used;
	size_t size;
} rewrite_rule_buffer;

typedef struct {
	rewrite_rule_buffer *rewrite;
	rewrite_rule_buffer *rewrite_NF;
	data_config *context, *context_NF; /* to which apply me */
} plugin_config;

typedef struct {
	enum { REWRITE_STATE_UNSET, REWRITE_STATE_FINISHED} state;
	int loops;
} handler_ctx;

typedef struct {
	PLUGIN_DATA;
	buffer *match_buf;

	plugin_config **config_storage;

	plugin_config conf;
} plugin_data;

static handler_ctx * handler_ctx_init() {
	handler_ctx * hctx;

	hctx = calloc(1, sizeof(*hctx));

	hctx->state = REWRITE_STATE_UNSET;
	hctx->loops = 0;

	return hctx;
}

static void handler_ctx_free(handler_ctx *hctx) {
	free(hctx);
}

static rewrite_rule_buffer *rewrite_rule_buffer_init(void) {
	rewrite_rule_buffer *kvb;

	kvb = calloc(1, sizeof(*kvb));

	return kvb;
}

static int rewrite_rule_buffer_append(rewrite_rule_buffer *kvb, buffer *key, buffer *value, int once) {
	size_t i;
	const char *errptr;
	int erroff;

	if (!key) return -1;

	if (kvb->size == 0) {
		kvb->size = 4;
		kvb->used = 0;

		kvb->ptr = malloc(kvb->size * sizeof(*kvb->ptr));

		for(i = 0; i < kvb->size; i++) {
			kvb->ptr[i] = calloc(1, sizeof(**kvb->ptr));
		}
	} else if (kvb->used == kvb->size) {
		kvb->size += 4;

		kvb->ptr = realloc(kvb->ptr, kvb->size * sizeof(*kvb->ptr));

		for(i = kvb->used; i < kvb->size; i++) {
			kvb->ptr[i] = calloc(1, sizeof(**kvb->ptr));
		}
	}

	if (NULL == (kvb->ptr[kvb->used]->key = pcre_compile(key->ptr,
							    0, &errptr, &erroff, NULL))) {

		return -1;
	}

	kvb->ptr[kvb->used]->value = buffer_init();
	buffer_copy_string_buffer(kvb->ptr[kvb->used]->value, value);
	kvb->ptr[kvb->used]->once = once;

	kvb->used++;

	return 0;
}

static void rewrite_rule_buffer_free(rewrite_rule_buffer *kvb) {
	size_t i;

	for (i = 0; i < kvb->size; i++) {
		if (kvb->ptr[i]->key) pcre_free(kvb->ptr[i]->key);
		if (kvb->ptr[i]->value) buffer_free(kvb->ptr[i]->value);
		free(kvb->ptr[i]);
	}

	if (kvb->ptr) free(kvb->ptr);

	free(kvb);
}


INIT_FUNC(mod_rewrite_init) {
	plugin_data *p;

	p = calloc(1, sizeof(*p));

	p->match_buf = buffer_init();

	return p;
}

FREE_FUNC(mod_rewrite_free) {
	plugin_data *p = p_d;

	UNUSED(srv);

	if (!p) return HANDLER_GO_ON;

	buffer_free(p->match_buf);
	if (p->config_storage) {
		size_t i;
		for (i = 0; i < srv->config_context->used; i++) {
			plugin_config *s = p->config_storage[i];
			rewrite_rule_buffer_free(s->rewrite);
			rewrite_rule_buffer_free(s->rewrite_NF);

			free(s);
		}
		free(p->config_storage);
	}

	free(p);

	return HANDLER_GO_ON;
}

static int parse_config_entry(server *srv, array *ca, rewrite_rule_buffer *kvb, const char *option, int once) {
	data_unset *du;

	if (NULL != (du = array_get_element(ca, option))) {
		data_array *da;
		size_t j;

		if (du->type != TYPE_ARRAY) {
			log_error_write(srv, __FILE__, __LINE__, "sss",
					"unexpected type for key: ", option, "array of strings");

			return HANDLER_ERROR;
		}

		da = (data_array *)du;

		for (j = 0; j < da->value->used; j++) {
			if (da->value->data[j]->type != TYPE_STRING) {
				log_error_write(srv, __FILE__, __LINE__, "sssbs",
						"unexpected type for key: ",
						option,
						"[", da->value->data[j]->key, "](string)");

				return HANDLER_ERROR;
			}

			if (0 != rewrite_rule_buffer_append(kvb,
							    ((data_string *)(da->value->data[j]))->key,
							    ((data_string *)(da->value->data[j]))->value,
							    once)) {
				log_error_write(srv, __FILE__, __LINE__, "sb",
						"pcre-compile failed for", da->value->data[j]->key);
			}
		}
	}

	return 0;
}
#else
static int parse_config_entry(server *srv, array *ca, const char *option) {
	static int logged_message = 0;
	if (logged_message) return 0;
	if (NULL != array_get_element(ca, option)) {
		logged_message = 1;
		log_error_write(srv, __FILE__, __LINE__, "s",
			"pcre support is missing, please install libpcre and the headers");
	}
	return 0;
}
#endif

SETDEFAULTS_FUNC(mod_rewrite_set_defaults) {
	size_t i = 0;
	config_values_t cv[] = {
		{ "url.rewrite-repeat",        NULL, T_CONFIG_LOCAL, T_CONFIG_SCOPE_CONNECTION }, /* 0 */
		{ "url.rewrite-once",          NULL, T_CONFIG_LOCAL, T_CONFIG_SCOPE_CONNECTION }, /* 1 */

		/* these functions only rewrite if the target is not already in the filestore
		 *
		 * url.rewrite-repeat-if-not-file is the equivalent of url.rewrite-repeat
		 * url.rewrite-if-not-file is the equivalent of url.rewrite-once
		 *
		 */
		{ "url.rewrite-repeat-if-not-file", NULL, T_CONFIG_LOCAL, T_CONFIG_SCOPE_CONNECTION }, /* 2 */
		{ "url.rewrite-if-not-file",        NULL, T_CONFIG_LOCAL, T_CONFIG_SCOPE_CONNECTION }, /* 3 */

		/* old names, still supported
		 *
		 * url.rewrite remapped to url.rewrite-once
		 * url.rewrite-final    is url.rewrite-once
		 *
		 */
		{ "url.rewrite",               NULL, T_CONFIG_LOCAL, T_CONFIG_SCOPE_CONNECTION }, /* 4 */
		{ "url.rewrite-final",         NULL, T_CONFIG_LOCAL, T_CONFIG_SCOPE_CONNECTION }, /* 5 */
		{ NULL,                        NULL, T_CONFIG_UNSET, T_CONFIG_SCOPE_UNSET }
	};

#ifdef HAVE_PCRE_H
	plugin_data *p = p_d;

	if (!p) return HANDLER_ERROR;

	/* 0 */
	p->config_storage = calloc(1, srv->config_context->used * sizeof(specific_config *));
#else
	UNUSED(p_d);
#endif

	for (i = 0; i < srv->config_context->used; i++) {
		array *ca;
#ifdef HAVE_PCRE_H
		plugin_config *s;

		s = calloc(1, sizeof(plugin_config));
		s->rewrite = rewrite_rule_buffer_init();
		s->rewrite_NF = rewrite_rule_buffer_init();
		p->config_storage[i] = s;
#endif

		ca = ((data_config *)srv->config_context->data[i])->value;

		if (0 != config_insert_values_global(srv, ca, cv)) {
			return HANDLER_ERROR;
		}

#ifndef HAVE_PCRE_H
# define parse_config_entry(srv, ca, x, option, y) parse_config_entry(srv, ca, option)
#endif
		parse_config_entry(srv, ca, s->rewrite, "url.rewrite-once",      1);
		parse_config_entry(srv, ca, s->rewrite, "url.rewrite-final",     1);
		parse_config_entry(srv, ca, s->rewrite_NF, "url.rewrite-if-not-file",   1);
		parse_config_entry(srv, ca, s->rewrite_NF, "url.rewrite-repeat-if-not-file", 0);
		parse_config_entry(srv, ca, s->rewrite, "url.rewrite",           1);
		parse_config_entry(srv, ca, s->rewrite, "url.rewrite-repeat",    0);
	}

	return HANDLER_GO_ON;
}

#ifdef HAVE_PCRE_H

#define PATCH(x) \
	p->conf.x = s->x;
static int mod_rewrite_patch_connection(server *srv, connection *con, plugin_data *p) {
	size_t i, j;
	plugin_config *s = p->config_storage[0];

	PATCH(rewrite);
	PATCH(rewrite_NF);
	p->conf.context = NULL;
	p->conf.context_NF = NULL;

	/* skip the first, the global context */
	for (i = 1; i < srv->config_context->used; i++) {
		data_config *dc = (data_config *)srv->config_context->data[i];
		s = p->config_storage[i];

		if (COMP_HTTP_URL == dc->comp) continue;

		/* condition didn't match */
		if (!config_check_cond(srv, con, dc)) continue;

		/* merge config */
		for (j = 0; j < dc->value->used; j++) {
			data_unset *du = dc->value->data[j];

			if (buffer_is_equal_string(du->key, CONST_STR_LEN("url.rewrite"))) {
				PATCH(rewrite);
				p->conf.context = dc;
			} else if (buffer_is_equal_string(du->key, CONST_STR_LEN("url.rewrite-once"))) {
				PATCH(rewrite);
				p->conf.context = dc;
			} else if (buffer_is_equal_string(du->key, CONST_STR_LEN("url.rewrite-repeat"))) {
				PATCH(rewrite);
				p->conf.context = dc;
			} else if (buffer_is_equal_string(du->key, CONST_STR_LEN("url.rewrite-if-not-file"))) {
				PATCH(rewrite_NF);
				p->conf.context_NF = dc;
			} else if (buffer_is_equal_string(du->key, CONST_STR_LEN("url.rewrite-repeat-if-not-file"))) {
				PATCH(rewrite_NF);
				p->conf.context_NF = dc;
			} else if (buffer_is_equal_string(du->key, CONST_STR_LEN("url.rewrite-final"))) {
				PATCH(rewrite);
				p->conf.context = dc;
			}
		}
	}

	return 0;
}

URIHANDLER_FUNC(mod_rewrite_con_reset) {
	plugin_data *p = p_d;

	UNUSED(srv);

	if (con->plugin_ctx[p->id]) {
		handler_ctx_free(con->plugin_ctx[p->id]);
		con->plugin_ctx[p->id] = NULL;
	}

	return HANDLER_GO_ON;
}

static int process_rewrite_rules(server *srv, connection *con, plugin_data *p, rewrite_rule_buffer *kvb) {
	size_t i;
	handler_ctx *hctx;

	if (con->plugin_ctx[p->id]) {
		hctx = con->plugin_ctx[p->id];

		if (hctx->loops++ > 100) {
			log_error_write(srv, __FILE__, __LINE__,  "s",
					"ENDLESS LOOP IN rewrite-rule DETECTED ... aborting request, perhaps you want to use url.rewrite-once instead of url.rewrite-repeat");

			return HANDLER_ERROR;
		}

		if (hctx->state == REWRITE_STATE_FINISHED) return HANDLER_GO_ON;
	}

	buffer_copy_string_buffer(p->match_buf, con->request.uri);

	for (i = 0; i < kvb->used; i++) {
		pcre *match;
		const char *pattern;
		size_t pattern_len;
		int n;
		rewrite_rule *rule = kvb->ptr[i];
# define N 10
		int ovec[N * 3];

		match       = rule->key;
		pattern     = rule->value->ptr;
		pattern_len = rule->value->used - 1;

		if ((n = pcre_exec(match, NULL, p->match_buf->ptr, p->match_buf->used - 1, 0, 0, ovec, 3 * N)) < 0) {
			if (n != PCRE_ERROR_NOMATCH) {
				log_error_write(srv, __FILE__, __LINE__, "sd",
						"execution error while matching: ", n);
				return HANDLER_ERROR;
			}
		} else {
			const char **list;
			size_t start;
			size_t k;

			/* it matched */
			pcre_get_substring_list(p->match_buf->ptr, ovec, n, &list);

			/* search for $[0-9] */

			buffer_reset(con->request.uri);

			start = 0;
			for (k = 0; k+1 < pattern_len; k++) {
				if (pattern[k] == '$' || pattern[k] == '%') {
					/* got one */

					size_t num = pattern[k + 1] - '0';

					buffer_append_string_len(con->request.uri, pattern + start, k - start);

					if (!isdigit((unsigned char)pattern[k + 1])) {
						/* enable escape: "%%" => "%", "%a" => "%a", "$$" => "$" */
						buffer_append_string_len(con->request.uri, pattern+k, pattern[k] == pattern[k+1] ? 1 : 2);
					} else if (pattern[k] == '$') {
						/* n is always > 0 */
						if (num < (size_t)n) {
							buffer_append_string(con->request.uri, list[num]);
						}
					} else if (p->conf.context == NULL) {
						/* we have no context, we are global */
						log_error_write(srv, __FILE__, __LINE__, "sb",
								"used a redirect containing a %[0-9]+ in the global scope, ignored:",
								rule->value);

					} else {
						config_append_cond_match_buffer(con, p->conf.context, con->request.uri, num);
					}

					k++;
					start = k + 1;
				}
			}

			buffer_append_string_len(con->request.uri, pattern + start, pattern_len - start);

			pcre_free(list);

			if (con->plugin_ctx[p->id] == NULL) {
				hctx = handler_ctx_init();
				con->plugin_ctx[p->id] = hctx;
			} else {
				hctx = con->plugin_ctx[p->id];
			}

			if (rule->once) hctx->state = REWRITE_STATE_FINISHED;

			return HANDLER_COMEBACK;
		}
#undef N
	}

	return HANDLER_GO_ON;
}

URIHANDLER_FUNC(mod_rewrite_physical) {
	plugin_data *p = p_d;
	handler_t r;
	stat_cache_entry *sce;

	if (con->mode != DIRECT) return HANDLER_GO_ON;

	mod_rewrite_patch_connection(srv, con, p);
	p->conf.context = p->conf.context_NF;

	if (!p->conf.rewrite_NF) return HANDLER_GO_ON;

	/* skip if physical.path is a regular file */
	sce = NULL;
	if (HANDLER_ERROR != stat_cache_get_entry(srv, con, con->physical.path, &sce)) {
		if (S_ISREG(sce->st.st_mode)) return HANDLER_GO_ON;
	}

	switch(r = process_rewrite_rules(srv, con, p, p->conf.rewrite_NF)) {
	case HANDLER_COMEBACK:
		buffer_reset(con->physical.path);
	default:
		return r;
	}

	return HANDLER_GO_ON;
}

URIHANDLER_FUNC(mod_rewrite_uri_handler) {
	plugin_data *p = p_d;

	mod_rewrite_patch_connection(srv, con, p);

	if (!p->conf.rewrite) return HANDLER_GO_ON;

	return process_rewrite_rules(srv, con, p, p->conf.rewrite);

	return HANDLER_GO_ON;
}
#endif

int mod_rewrite_plugin_init(plugin *p);
int mod_rewrite_plugin_init(plugin *p) {
	p->version     = LIGHTTPD_VERSION_ID;
	p->name        = buffer_init_string("rewrite");

#ifdef HAVE_PCRE_H
	p->init        = mod_rewrite_init;
	/* it has to stay _raw as we are matching on uri + querystring
	 */

	p->handle_uri_raw = mod_rewrite_uri_handler;
	p->handle_physical = mod_rewrite_physical;
	p->cleanup     = mod_rewrite_free;
	p->connection_reset = mod_rewrite_con_reset;
#endif
	p->set_defaults = mod_rewrite_set_defaults;

	p->data        = NULL;

	return 0;
}