xref: /lighttpd1.4/src/mod_magnet.c (revision 49e9f0ac)
1 #include "first.h"
2 
3 #include "base.h"
4 #include "log.h"
5 #include "buffer.h"
6 #include "http_chunk.h"
7 #include "http_header.h"
8 
9 #include "plugin.h"
10 
11 #include "mod_magnet_cache.h"
12 #include "stat_cache.h"
13 #include "status_counter.h"
14 #include "etag.h"
15 
16 #include <stdlib.h>
17 #include <string.h>
18 #include <setjmp.h>
19 
20 #include <lua.h>
21 #include <lauxlib.h>
22 
23 #define LUA_RIDX_LIGHTTPD_SERVER     "lighty.srv"
24 #define LUA_RIDX_LIGHTTPD_CONNECTION "lighty.con"
25 
26 #define MAGNET_CONFIG_RAW_URL       "magnet.attract-raw-url-to"
27 #define MAGNET_CONFIG_PHYSICAL_PATH "magnet.attract-physical-path-to"
28 #define MAGNET_RESTART_REQUEST      99
29 
30 /* plugin config for all request/connections */
31 
32 static jmp_buf exceptionjmp;
33 
34 typedef struct {
35 	array *url_raw;
36 	array *physical_path;
37 } plugin_config;
38 
39 typedef struct {
40 	PLUGIN_DATA;
41 
42 	script_cache *cache;
43 
44 	plugin_config **config_storage;
45 
46 	plugin_config conf;
47 } plugin_data;
48 
49 /* init the plugin data */
50 INIT_FUNC(mod_magnet_init) {
51 	plugin_data *p;
52 
53 	p = calloc(1, sizeof(*p));
54 
55 	p->cache = script_cache_init();
56 
57 	return p;
58 }
59 
60 /* detroy the plugin data */
61 FREE_FUNC(mod_magnet_free) {
62 	plugin_data *p = p_d;
63 
64 	UNUSED(srv);
65 
66 	if (!p) return HANDLER_GO_ON;
67 
68 	if (p->config_storage) {
69 		size_t i;
70 
71 		for (i = 0; i < srv->config_context->used; i++) {
72 			plugin_config *s = p->config_storage[i];
73 
74 			if (NULL == s) continue;
75 
76 			array_free(s->url_raw);
77 			array_free(s->physical_path);
78 
79 			free(s);
80 		}
81 		free(p->config_storage);
82 	}
83 
84 	script_cache_free(p->cache);
85 
86 	free(p);
87 
88 	return HANDLER_GO_ON;
89 }
90 
91 /* handle plugin config and check values */
92 
93 SETDEFAULTS_FUNC(mod_magnet_set_defaults) {
94 	plugin_data *p = p_d;
95 	size_t i = 0;
96 
97 	config_values_t cv[] = {
98 		{ MAGNET_CONFIG_RAW_URL,       NULL, T_CONFIG_ARRAY, T_CONFIG_SCOPE_CONNECTION },       /* 0 */
99 		{ MAGNET_CONFIG_PHYSICAL_PATH, NULL, T_CONFIG_ARRAY, T_CONFIG_SCOPE_CONNECTION },       /* 1 */
100 		{ NULL,                           NULL, T_CONFIG_UNSET, T_CONFIG_SCOPE_UNSET }
101 	};
102 
103 	if (!p) return HANDLER_ERROR;
104 
105 	p->config_storage = calloc(srv->config_context->used, sizeof(plugin_config *));
106 
107 	for (i = 0; i < srv->config_context->used; i++) {
108 		data_config const* config = (data_config const*)srv->config_context->data[i];
109 		plugin_config *s;
110 
111 		s = calloc(1, sizeof(plugin_config));
112 		s->url_raw  = array_init();
113 		s->physical_path = array_init();
114 
115 		cv[0].destination = s->url_raw;
116 		cv[1].destination = s->physical_path;
117 
118 		p->config_storage[i] = s;
119 
120 		if (0 != config_insert_values_global(srv, config->value, cv, i == 0 ? T_CONFIG_SCOPE_SERVER : T_CONFIG_SCOPE_CONNECTION)) {
121 			return HANDLER_ERROR;
122 		}
123 
124 		if (!array_is_vlist(s->url_raw)) {
125 			log_error_write(srv, __FILE__, __LINE__, "s",
126 					"unexpected value for magnet.attract-raw-url-to; expected list of \"scriptpath\"");
127 			return HANDLER_ERROR;
128 		}
129 
130 		if (!array_is_vlist(s->physical_path)) {
131 			log_error_write(srv, __FILE__, __LINE__, "s",
132 					"unexpected value for magnet.attract-physical-path-to; expected list \"scriptpath\"");
133 			return HANDLER_ERROR;
134 		}
135 	}
136 
137 	return HANDLER_GO_ON;
138 }
139 
140 #define PATCH(x) \
141 	p->conf.x = s->x;
142 static int mod_magnet_patch_connection(server *srv, connection *con, plugin_data *p) {
143 	size_t i, j;
144 	plugin_config *s = p->config_storage[0];
145 
146 	PATCH(url_raw);
147 	PATCH(physical_path);
148 
149 	/* skip the first, the global context */
150 	for (i = 1; i < srv->config_context->used; i++) {
151 		data_config *dc = (data_config *)srv->config_context->data[i];
152 		s = p->config_storage[i];
153 
154 		/* condition didn't match */
155 		if (!config_check_cond(srv, con, dc)) continue;
156 
157 		/* merge config */
158 		for (j = 0; j < dc->value->used; j++) {
159 			data_unset *du = dc->value->data[j];
160 
161 			if (buffer_is_equal_string(du->key, CONST_STR_LEN(MAGNET_CONFIG_RAW_URL))) {
162 				PATCH(url_raw);
163 			} else if (buffer_is_equal_string(du->key, CONST_STR_LEN(MAGNET_CONFIG_PHYSICAL_PATH))) {
164 				PATCH(physical_path);
165 			}
166 		}
167 	}
168 
169 	return 0;
170 }
171 #undef PATCH
172 
173 #if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 502
174 /* lua5.1 backward compat definition */
175 static void lua_pushglobaltable(lua_State *L) { /* (-0, +1, -) */
176 	lua_pushvalue(L, LUA_GLOBALSINDEX);
177 }
178 #endif
179 
180 static void magnet_setfenv_mainfn(lua_State *L, int funcIndex) { /* (-1, 0, -) */
181 #if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 502
182 	/* set "_ENV" upvalue, which should be the first upvalue of a "main" lua
183 	 * function if it uses any global names
184 	 */
185 
186 	const char* first_upvalue_name = lua_getupvalue(L, funcIndex, 1);
187 	if (NULL == first_upvalue_name) return; /* doesn't have any upvalues */
188 	lua_pop(L, 1); /* only need the name of the upvalue, not the value */
189 
190 	if (0 != strcmp(first_upvalue_name, "_ENV")) return;
191 
192 	if (NULL == lua_setupvalue(L, funcIndex, 1)) {
193 		/* pop value if lua_setupvalue didn't set the (not existing) upvalue */
194 		lua_pop(L, 1);
195 	}
196 #else
197 	lua_setfenv(L, funcIndex);
198 #endif
199 }
200 
201 #if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 502
202 /* lua 5.2 already supports __pairs */
203 
204 /* See http://lua-users.org/wiki/GeneralizedPairsAndIpairs for implementation details.
205  * Override the default pairs() function to allow us to use a __pairs metakey
206  */
207 static int magnet_pairs(lua_State *L) {
208 	luaL_checkany(L, 1); /* "self" */
209 
210 	if (luaL_getmetafield(L, 1, "__pairs")) {
211 		/* call __pairs(self) */
212 		lua_pushvalue(L, 1);
213 		lua_call(L, 1, 3);
214 	} else {
215 		/* call <original-pairs-method>(self) */
216 		lua_pushvalue(L, lua_upvalueindex(1));
217 		lua_pushvalue(L, 1);
218 		lua_call(L, 1, 3);
219 	}
220 	return 3;
221 }
222 #endif
223 
224 static void magnet_push_buffer(lua_State *L, const buffer *b) {
225     if (!buffer_is_empty(b))
226         lua_pushlstring(L, CONST_BUF_LEN(b));
227     else
228         lua_pushnil(L);
229 }
230 
231 #if 0
232 static int magnet_array_get_element(lua_State *L, const array *a) {
233     /* __index: param 1 is the (empty) table the value was not found in */
234     size_t klen;
235     const char * const k = luaL_checklstring(L, 2, &klen);
236     data_string * const ds = (data_string *)array_get_element_klen(a, k, klen);
237     magnet_push_buffer(L, NULL != ds ? ds->value : NULL);
238     return 1;
239 }
240 #endif
241 
242 /* Define a function that will iterate over an array* (in upval 1) using current position (upval 2) */
243 static int magnet_array_next(lua_State *L) {
244 	data_unset *du;
245 	data_string *ds;
246 	data_integer *di;
247 
248 	size_t pos = lua_tointeger(L, lua_upvalueindex(1));
249 	array *a = lua_touserdata(L, lua_upvalueindex(2));
250 
251 	lua_settop(L, 0);
252 
253 	if (pos >= a->used) return 0;
254 	if (NULL != (du = a->data[pos])) {
255 		lua_pushlstring(L, CONST_BUF_LEN(du->key));
256 		switch (du->type) {
257 			case TYPE_STRING:
258 				ds = (data_string *)du;
259 				magnet_push_buffer(L, ds->value);
260 				break;
261 			case TYPE_INTEGER:
262 				di = (data_integer *)du;
263 				lua_pushinteger(L, di->value);
264 				break;
265 			default:
266 				lua_pushnil(L);
267 				break;
268 		}
269 
270 		/* Update our positional upval to reflect our new current position */
271 		pos++;
272 		lua_pushinteger(L, pos);
273 		lua_replace(L, lua_upvalueindex(1));
274 
275 		/* Returning 2 items on the stack (key, value) */
276 		return 2;
277 	}
278 	return 0;
279 }
280 
281 /* Create the closure necessary to iterate over the array *a with the above function */
282 static int magnet_array_pairs(lua_State *L, array *a) {
283 	lua_pushinteger(L, 0); /* Push our current pos (the start) into upval 1 */
284 	lua_pushlightuserdata(L, a); /* Push our array *a into upval 2 */
285 	lua_pushcclosure(L, magnet_array_next, 2); /* Push our new closure with 2 upvals */
286 	return 1;
287 }
288 
289 static server* magnet_get_server(lua_State *L) {
290 	server *srv;
291 
292 	lua_getfield(L, LUA_REGISTRYINDEX, LUA_RIDX_LIGHTTPD_SERVER);
293 	srv = lua_touserdata(L, -1);
294 	lua_pop(L, 1);
295 
296 	return srv;
297 }
298 
299 static connection* magnet_get_connection(lua_State *L) {
300 	connection *con;
301 
302 	lua_getfield(L, LUA_REGISTRYINDEX, LUA_RIDX_LIGHTTPD_CONNECTION);
303 	con = lua_touserdata(L, -1);
304 	lua_pop(L, 1);
305 
306 	return con;
307 }
308 
309 typedef struct {
310 	const char *ptr;
311 	size_t len;
312 } const_buffer;
313 
314 static const_buffer magnet_checkconstbuffer(lua_State *L, int index) {
315 	const_buffer cb;
316 	cb.ptr = luaL_checklstring(L, index, &cb.len);
317 	return cb;
318 }
319 
320 static buffer* magnet_checkbuffer(lua_State *L, int index) {
321 	const_buffer cb = magnet_checkconstbuffer(L, index);
322 	buffer *b = buffer_init();
323 	buffer_copy_string_len(b, cb.ptr, cb.len);
324 	return b;
325 }
326 
327 static int magnet_print(lua_State *L) {
328 	const_buffer cb = magnet_checkconstbuffer(L, 1);
329 	log_error_write(magnet_get_server(L), __FILE__, __LINE__, "ss",
330 			"(lua-print)", cb.ptr);
331 	return 0;
332 }
333 
334 static int magnet_stat(lua_State *L) {
335 	server *srv = magnet_get_server(L);
336 	connection *con = magnet_get_connection(L);
337 	stat_cache_entry *sce = NULL;
338     {
339 	buffer *sb = magnet_checkbuffer(L, 1);
340 	handler_t res;
341 
342 	res = stat_cache_get_entry(srv, con, sb, &sce);
343 
344 	if (HANDLER_GO_ON != res) {
345 		buffer_free(sb);
346 		lua_pushnil(L);
347 		return 1;
348 	}
349 
350 	stat_cache_content_type_get(srv, con, sb, sce);
351 	buffer_free(sb);
352     }
353 
354 	lua_newtable(L); // return value
355 
356 	lua_pushboolean(L, S_ISREG(sce->st.st_mode));
357 	lua_setfield(L, -2, "is_file");
358 
359 	lua_pushboolean(L, S_ISDIR(sce->st.st_mode));
360 	lua_setfield(L, -2, "is_dir");
361 
362 	lua_pushboolean(L, S_ISCHR(sce->st.st_mode));
363 	lua_setfield(L, -2, "is_char");
364 
365 	lua_pushboolean(L, S_ISBLK(sce->st.st_mode));
366 	lua_setfield(L, -2, "is_block");
367 
368 	lua_pushboolean(L, S_ISSOCK(sce->st.st_mode));
369 	lua_setfield(L, -2, "is_socket");
370 
371 	lua_pushboolean(L, S_ISLNK(sce->st.st_mode));
372 	lua_setfield(L, -2, "is_link");
373 
374 	lua_pushboolean(L, S_ISFIFO(sce->st.st_mode));
375 	lua_setfield(L, -2, "is_fifo");
376 
377 	lua_pushinteger(L, sce->st.st_mtime);
378 	lua_setfield(L, -2, "st_mtime");
379 
380 	lua_pushinteger(L, sce->st.st_ctime);
381 	lua_setfield(L, -2, "st_ctime");
382 
383 	lua_pushinteger(L, sce->st.st_atime);
384 	lua_setfield(L, -2, "st_atime");
385 
386 	lua_pushinteger(L, sce->st.st_uid);
387 	lua_setfield(L, -2, "st_uid");
388 
389 	lua_pushinteger(L, sce->st.st_gid);
390 	lua_setfield(L, -2, "st_gid");
391 
392 	lua_pushinteger(L, sce->st.st_size);
393 	lua_setfield(L, -2, "st_size");
394 
395 	lua_pushinteger(L, sce->st.st_ino);
396 	lua_setfield(L, -2, "st_ino");
397 
398 	if (!buffer_string_is_empty(stat_cache_etag_get(sce, con->etag_flags))) {
399 		/* we have to mutate the etag */
400 		etag_mutate(srv->tmp_buf, sce->etag);
401 		lua_pushlstring(L, CONST_BUF_LEN(srv->tmp_buf));
402 	} else {
403 		lua_pushnil(L);
404 	}
405 	lua_setfield(L, -2, "etag");
406 
407 	if (!buffer_string_is_empty(sce->content_type)) {
408 		lua_pushlstring(L, CONST_BUF_LEN(sce->content_type));
409 	} else {
410 		lua_pushnil(L);
411 	}
412 	lua_setfield(L, -2, "content-type");
413 
414 	return 1;
415 }
416 
417 
418 static int magnet_atpanic(lua_State *L) {
419 	const_buffer cb = magnet_checkconstbuffer(L, 1);
420 	log_error_write(magnet_get_server(L), __FILE__, __LINE__, "ss",
421 			"(lua-atpanic)", cb.ptr);
422 	longjmp(exceptionjmp, 1);
423 }
424 
425 static int magnet_reqhdr_get(lua_State *L) {
426     /* __index: param 1 is the (empty) table the value was not found in */
427     connection *con = magnet_get_connection(L);
428     size_t klen;
429     const char * const k = luaL_checklstring(L, 2, &klen);
430     buffer * const vb =
431       http_header_request_get(con, HTTP_HEADER_UNSPECIFIED, k, klen);
432     magnet_push_buffer(L, NULL != vb ? vb : NULL);
433     return 1;
434 }
435 
436 static int magnet_reqhdr_pairs(lua_State *L) {
437 	connection *con = magnet_get_connection(L);
438 	return magnet_array_pairs(L, con->request.headers);
439 }
440 
441 static int magnet_status_get(lua_State *L) {
442 	int *i;
443 	server *srv = magnet_get_server(L);
444 
445 	/* __index: param 1 is the (empty) table the value was not found in */
446 	const_buffer key = magnet_checkconstbuffer(L, 2);
447 	i = status_counter_get_counter(srv, key.ptr, key.len);
448 	lua_pushinteger(L, (lua_Integer)*i);
449 
450 	return 1;
451 }
452 
453 static int magnet_status_set(lua_State *L) {
454 	server *srv = magnet_get_server(L);
455 
456 	/* __newindex: param 1 is the (empty) table the value is supposed to be set in */
457 	const_buffer key = magnet_checkconstbuffer(L, 2);
458 	int counter = (int) luaL_checkinteger(L, 3);
459 
460 	status_counter_set(srv, key.ptr, key.len, counter);
461 
462 	return 0;
463 }
464 
465 static int magnet_status_pairs(lua_State *L) {
466 	server *srv = magnet_get_server(L);
467 
468 	return magnet_array_pairs(L, srv->status);
469 }
470 
471 typedef struct {
472 	const char *name;
473 	enum {
474 		MAGNET_ENV_UNSET,
475 
476 		MAGNET_ENV_PHYICAL_PATH,
477 		MAGNET_ENV_PHYICAL_REL_PATH,
478 		MAGNET_ENV_PHYICAL_DOC_ROOT,
479 		MAGNET_ENV_PHYICAL_BASEDIR,
480 
481 		MAGNET_ENV_URI_PATH,
482 		MAGNET_ENV_URI_PATH_RAW,
483 		MAGNET_ENV_URI_SCHEME,
484 		MAGNET_ENV_URI_AUTHORITY,
485 		MAGNET_ENV_URI_QUERY,
486 
487 		MAGNET_ENV_REQUEST_METHOD,
488 		MAGNET_ENV_REQUEST_URI,
489 		MAGNET_ENV_REQUEST_ORIG_URI,
490 		MAGNET_ENV_REQUEST_PATH_INFO,
491 		MAGNET_ENV_REQUEST_REMOTE_IP,
492 		MAGNET_ENV_REQUEST_PROTOCOL
493 	} type;
494 } magnet_env_t;
495 
496 static const magnet_env_t magnet_env[] = {
497 	{ "physical.path", MAGNET_ENV_PHYICAL_PATH },
498 	{ "physical.rel-path", MAGNET_ENV_PHYICAL_REL_PATH },
499 	{ "physical.doc-root", MAGNET_ENV_PHYICAL_DOC_ROOT },
500 	{ "physical.basedir", MAGNET_ENV_PHYICAL_BASEDIR },
501 
502 	{ "uri.path", MAGNET_ENV_URI_PATH },
503 	{ "uri.path-raw", MAGNET_ENV_URI_PATH_RAW },
504 	{ "uri.scheme", MAGNET_ENV_URI_SCHEME },
505 	{ "uri.authority", MAGNET_ENV_URI_AUTHORITY },
506 	{ "uri.query", MAGNET_ENV_URI_QUERY },
507 
508 	{ "request.method", MAGNET_ENV_REQUEST_METHOD },
509 	{ "request.uri", MAGNET_ENV_REQUEST_URI },
510 	{ "request.orig-uri", MAGNET_ENV_REQUEST_ORIG_URI },
511 	{ "request.path-info", MAGNET_ENV_REQUEST_PATH_INFO },
512 	{ "request.remote-ip", MAGNET_ENV_REQUEST_REMOTE_IP },
513 	{ "request.protocol", MAGNET_ENV_REQUEST_PROTOCOL },
514 
515 	{ NULL, MAGNET_ENV_UNSET }
516 };
517 
518 static buffer *magnet_env_get_buffer_by_id(server *srv, connection *con, int id) {
519 	buffer *dest = NULL;
520 
521 	UNUSED(srv);
522 
523 	/**
524 	 * map all internal variables to lua
525 	 *
526 	 */
527 
528 	switch (id) {
529 	case MAGNET_ENV_PHYICAL_PATH: dest = con->physical.path; break;
530 	case MAGNET_ENV_PHYICAL_REL_PATH: dest = con->physical.rel_path; break;
531 	case MAGNET_ENV_PHYICAL_DOC_ROOT: dest = con->physical.doc_root; break;
532 	case MAGNET_ENV_PHYICAL_BASEDIR: dest = con->physical.basedir; break;
533 
534 	case MAGNET_ENV_URI_PATH: dest = con->uri.path; break;
535 	case MAGNET_ENV_URI_PATH_RAW: dest = con->uri.path_raw; break;
536 	case MAGNET_ENV_URI_SCHEME: dest = con->uri.scheme; break;
537 	case MAGNET_ENV_URI_AUTHORITY: dest = con->uri.authority; break;
538 	case MAGNET_ENV_URI_QUERY: dest = con->uri.query; break;
539 
540 	case MAGNET_ENV_REQUEST_METHOD:
541 		buffer_clear(srv->tmp_buf);
542 		http_method_append(srv->tmp_buf, con->request.http_method);
543 		dest = srv->tmp_buf;
544 		break;
545 	case MAGNET_ENV_REQUEST_URI:      dest = con->request.uri; break;
546 	case MAGNET_ENV_REQUEST_ORIG_URI: dest = con->request.orig_uri; break;
547 	case MAGNET_ENV_REQUEST_PATH_INFO: dest = con->request.pathinfo; break;
548 	case MAGNET_ENV_REQUEST_REMOTE_IP: dest = con->dst_addr_buf; break;
549 	case MAGNET_ENV_REQUEST_PROTOCOL:
550 		buffer_copy_string(srv->tmp_buf, get_http_version_name(con->request.http_version));
551 		dest = srv->tmp_buf;
552 		break;
553 
554 	case MAGNET_ENV_UNSET: break;
555 	}
556 
557 	return dest;
558 }
559 
560 static buffer *magnet_env_get_buffer(server *srv, connection *con, const char *key) {
561 	size_t i;
562 
563 	for (i = 0; magnet_env[i].name; i++) {
564 		if (0 == strcmp(key, magnet_env[i].name)) break;
565 	}
566 
567 	return magnet_env_get_buffer_by_id(srv, con, magnet_env[i].type);
568 }
569 
570 static int magnet_env_get(lua_State *L) {
571 	server *srv = magnet_get_server(L);
572 	connection *con = magnet_get_connection(L);
573 
574 	/* __index: param 1 is the (empty) table the value was not found in */
575 	const char *key = luaL_checkstring(L, 2);
576 	magnet_push_buffer(L, magnet_env_get_buffer(srv, con, key));
577 	return 1;
578 }
579 
580 static int magnet_env_set(lua_State *L) {
581 	server *srv = magnet_get_server(L);
582 	connection *con = magnet_get_connection(L);
583 
584 	/* __newindex: param 1 is the (empty) table the value is supposed to be set in */
585 	const char *key = luaL_checkstring(L, 2);
586 	buffer *dest = NULL;
587 
588 	luaL_checkany(L, 3); /* nil or a string */
589 
590 	if (NULL != (dest = magnet_env_get_buffer(srv, con, key))) {
591 		if (lua_isnil(L, 3)) {
592 			buffer_reset(dest);
593 		} else {
594 			const_buffer val = magnet_checkconstbuffer(L, 3);
595 			buffer_copy_string_len(dest, val.ptr, val.len);
596 		}
597 	} else {
598 		/* couldn't save */
599 
600 		return luaL_error(L, "couldn't store '%s' in lighty.env[]", key);
601 	}
602 
603 	return 0;
604 }
605 
606 static int magnet_env_next(lua_State *L) {
607 	server *srv = magnet_get_server(L);
608 	connection *con = magnet_get_connection(L);
609 	const int pos = lua_tointeger(L, lua_upvalueindex(1));
610 
611 	/* ignore previous key: use upvalue for current pos */
612 	lua_settop(L, 0);
613 
614 	if (NULL == magnet_env[pos].name) return 0; /* end of list */
615 	/* Update our positional upval to reflect our new current position */
616 	lua_pushinteger(L, pos + 1);
617 	lua_replace(L, lua_upvalueindex(1));
618 
619 	/* key to return */
620 	lua_pushstring(L, magnet_env[pos].name);
621 
622 	/* get value */
623 	magnet_push_buffer(L, magnet_env_get_buffer_by_id(srv, con, magnet_env[pos].type));
624 
625 	/* return 2 items on the stack (key, value) */
626 	return 2;
627 }
628 
629 static int magnet_env_pairs(lua_State *L) {
630 	lua_pushinteger(L, 0); /* Push our current pos (the start) into upval 1 */
631 	lua_pushcclosure(L, magnet_env_next, 1); /* Push our new closure with 1 upvals */
632 	return 1;
633 }
634 
635 static int magnet_cgi_get(lua_State *L) {
636     /* __index: param 1 is the (empty) table the value was not found in */
637     connection *con = magnet_get_connection(L);
638     size_t klen;
639     const char * const k = luaL_checklstring(L, 2, &klen);
640     buffer * const vb = http_header_env_get(con, k, klen);
641     magnet_push_buffer(L, NULL != vb ? vb : NULL);
642     return 1;
643 }
644 
645 static int magnet_cgi_set(lua_State *L) {
646     /* __newindex: param 1 is the (empty) table the value is supposed to be set in */
647     connection *con = magnet_get_connection(L);
648     const_buffer key = magnet_checkconstbuffer(L, 2);
649     const_buffer val = magnet_checkconstbuffer(L, 3);
650     http_header_env_set(con, key.ptr, key.len, val.ptr, val.len);
651     return 0;
652 }
653 
654 static int magnet_cgi_pairs(lua_State *L) {
655 	connection *con = magnet_get_connection(L);
656 
657 	return magnet_array_pairs(L, con->environment);
658 }
659 
660 
661 static int magnet_copy_response_header(connection *con, lua_State *L, int lighty_table_ndx) {
662 	force_assert(lua_istable(L, lighty_table_ndx));
663 
664 	lua_getfield(L, lighty_table_ndx, "header"); /* lighty.header */
665 	if (lua_istable(L, -1)) {
666 		/* header is found, and is a table */
667 
668 		lua_pushnil(L);
669 		while (lua_next(L, -2) != 0) {
670 			if (lua_isstring(L, -1) && lua_isstring(L, -2)) {
671 				const_buffer key = magnet_checkconstbuffer(L, -2);
672 				const_buffer val = magnet_checkconstbuffer(L, -1);
673 				enum http_header_e id = http_header_hkey_get(key.ptr, key.len);
674 
675 				val.len
676 				  ? http_header_response_set(con, id, key.ptr, key.len, val.ptr, val.len)
677 				  : http_header_response_unset(con, id, key.ptr, key.len);
678 			}
679 
680 			lua_pop(L, 1);
681 		}
682 	}
683 	lua_pop(L, 1); /* pop lighty.header */
684 
685 	return 0;
686 }
687 
688 /**
689  * walk through the content array
690  *
691  * content = { "<pre>", { file = "/content" } , "</pre>" }
692  *
693  * header["Content-Type"] = "text/html"
694  *
695  * return 200
696  */
697 static int magnet_attach_content(server *srv, connection *con, lua_State *L, int lighty_table_ndx) {
698 	force_assert(lua_istable(L, lighty_table_ndx));
699 
700 	lua_getfield(L, lighty_table_ndx, "content"); /* lighty.content */
701 	if (lua_istable(L, -1)) {
702 		int i;
703 		/* content is found, and is a table */
704 
705 		for (i = 1; ; i++) {
706 			lua_rawgeti(L, -1, i);
707 
708 			/* -1 is the value and should be the value ... aka a table */
709 			if (lua_isstring(L, -1)) {
710 				const_buffer data = magnet_checkconstbuffer(L, -1);
711 
712 				chunkqueue_append_mem(con->write_queue, data.ptr, data.len);
713 			} else if (lua_istable(L, -1)) {
714 				lua_getfield(L, -1, "filename");
715 				lua_getfield(L, -2, "length"); /* (0-based) end of range (not actually "length") */
716 				lua_getfield(L, -3, "offset"); /* (0-based) start of range */
717 
718 				if (lua_isstring(L, -3)) { /* filename has to be a string */
719 					off_t off = (off_t) luaL_optinteger(L, -1, 0);
720 					off_t len = (off_t) luaL_optinteger(L, -2, -1); /*(-1 to http_chunk_append_file_range() uses file size minus offset)*/
721 					if (off < 0) {
722 						return luaL_error(L, "offset for '%s' is negative", lua_tostring(L, -3));
723 					}
724 
725 					if (len >= off) {
726 						len -= off;
727 					} else if (-1 != len) {
728 						return luaL_error(L, "offset > length for '%s'", lua_tostring(L, -3));
729 					}
730 
731 					if (0 != len) {
732 						buffer *fn = magnet_checkbuffer(L, -3);
733 						int rc = http_chunk_append_file_range(srv, con, fn, off, len);
734 						buffer_free(fn);
735 						if (0 != rc) {
736 							return luaL_error(L, "error opening file content '%s' at offset %lld", lua_tostring(L, -3), (long long)off);
737 						}
738 					}
739 				} else {
740 					return luaL_error(L, "content[%d] is a table and requires the field \"filename\"", i);
741 				}
742 
743 				lua_pop(L, 3);
744 			} else if (lua_isnil(L, -1)) {
745 				/* end of list */
746 
747 				lua_pop(L, 1);
748 
749 				break;
750 			} else {
751 				return luaL_error(L, "content[%d] is neither a string nor a table: ", i);
752 			}
753 
754 			lua_pop(L, 1); /* pop the content[...] entry value */
755 		}
756 	} else {
757 		return luaL_error(L, "lighty.content has to be a table");
758 	}
759 	lua_pop(L, 1); /* pop lighty.content */
760 
761 	return 0;
762 }
763 
764 static int traceback(lua_State *L) {
765 	if (!lua_isstring(L, 1))  /* 'message' not a string? */
766 		return 1;  /* keep it intact */
767 	lua_getglobal(L, "debug");
768 	if (!lua_istable(L, -1)) {
769 		lua_pop(L, 1);
770 		return 1;
771 	}
772 	lua_getfield(L, -1, "traceback");
773 	if (!lua_isfunction(L, -1)) {
774 		lua_pop(L, 2);
775 		return 1;
776 	}
777 	lua_pushvalue(L, 1);  /* pass error message */
778 	lua_pushinteger(L, 2);  /* skip this function and traceback */
779 	lua_call(L, 2, 1);  /* call debug.traceback */
780 	return 1;
781 }
782 
783 /* push traceback function before calling lua_pcall after narg arguments
784  * have been pushed (inserts it before the arguments). returns index for
785  * traceback function ("msgh" in lua_pcall)
786  */
787 static int push_traceback(lua_State *L, int narg) {
788 	int base = lua_gettop(L) - narg;  /* function index */
789 	lua_pushcfunction(L, traceback);
790 	lua_insert(L, base);
791 	return base;
792 }
793 
794 static handler_t magnet_attract(server *srv, connection *con, plugin_data *p, buffer *name) {
795 	lua_State *L;
796 	int lua_return_value;
797 	const int func_ndx = 1;
798 	const int lighty_table_ndx = 2;
799 
800 	/* get the script-context */
801 	L = script_cache_get_script(srv, con, p->cache, name);
802 
803 	if (lua_isstring(L, -1)) {
804 		log_error_write(srv, __FILE__, __LINE__,
805 				"sbss",
806 				"loading script",
807 				name,
808 				"failed:",
809 				lua_tostring(L, -1));
810 
811 		lua_pop(L, 1);
812 
813 		force_assert(lua_gettop(L) == 0); /* only the error should have been on the stack */
814 
815 		con->http_status = 500;
816 		con->mode = DIRECT;
817 
818 		return HANDLER_FINISHED;
819 	}
820 
821 	force_assert(lua_gettop(L) == 1);
822 	force_assert(lua_isfunction(L, func_ndx));
823 
824 	lua_pushlightuserdata(L, srv);
825 	lua_setfield(L, LUA_REGISTRYINDEX, LUA_RIDX_LIGHTTPD_SERVER);
826 
827 	lua_pushlightuserdata(L, con);
828 	lua_setfield(L, LUA_REGISTRYINDEX, LUA_RIDX_LIGHTTPD_CONNECTION);
829 
830 	lua_atpanic(L, magnet_atpanic);
831 
832 	/**
833 	 * we want to create empty environment for our script
834 	 *
835 	 * setmetatable({}, {__index = _G})
836 	 *
837 	 * if a function symbol is not defined in our env, __index will lookup
838 	 * in the global env.
839 	 *
840 	 * all variables created in the script-env will be thrown
841 	 * away at the end of the script run.
842 	 */
843 	lua_newtable(L); /* my empty environment aka {}              (sp += 1) */
844 
845 	/* we have to overwrite the print function */
846 	lua_pushcfunction(L, magnet_print);                       /* (sp += 1) */
847 	lua_setfield(L, -2, "print"); /* -1 is the env we want to set(sp -= 1) */
848 
849 	/**
850 	 * lighty.request[] (ro) has the HTTP-request headers
851 	 * lighty.env[] (rw) has various url/physical file paths and
852 	 *                   request meta data; might contain nil values
853 	 * lighty.req_env[] (ro) has the cgi environment
854 	 * lighty.status[] (ro) has the status counters
855 	 * lighty.content[] (rw) is a table of string/file
856 	 * lighty.header[] (rw) is a array to set response headers
857 	 */
858 
859 	lua_newtable(L); /* lighty.*                                 (sp += 1) */
860 
861 	lua_newtable(L); /*  {}                                      (sp += 1) */
862 	lua_newtable(L); /* the meta-table for the request-table     (sp += 1) */
863 	lua_pushcfunction(L, magnet_reqhdr_get);                  /* (sp += 1) */
864 	lua_setfield(L, -2, "__index");                           /* (sp -= 1) */
865 	lua_pushcfunction(L, magnet_reqhdr_pairs);                /* (sp += 1) */
866 	lua_setfield(L, -2, "__pairs");                           /* (sp -= 1) */
867 	lua_setmetatable(L, -2); /* tie the metatable to request     (sp -= 1) */
868 	lua_setfield(L, -2, "request"); /* content = {}              (sp -= 1) */
869 
870 	lua_newtable(L); /*  {}                                      (sp += 1) */
871 	lua_newtable(L); /* the meta-table for the env-table         (sp += 1) */
872 	lua_pushcfunction(L, magnet_env_get);                     /* (sp += 1) */
873 	lua_setfield(L, -2, "__index");                           /* (sp -= 1) */
874 	lua_pushcfunction(L, magnet_env_set);                     /* (sp += 1) */
875 	lua_setfield(L, -2, "__newindex");                        /* (sp -= 1) */
876 	lua_pushcfunction(L, magnet_env_pairs);                   /* (sp += 1) */
877 	lua_setfield(L, -2, "__pairs");                           /* (sp -= 1) */
878 	lua_setmetatable(L, -2); /* tie the metatable to env         (sp -= 1) */
879 	lua_setfield(L, -2, "env"); /* content = {}                  (sp -= 1) */
880 
881 	lua_newtable(L); /*  {}                                      (sp += 1) */
882 	lua_newtable(L); /* the meta-table for the req_env-table     (sp += 1) */
883 	lua_pushcfunction(L, magnet_cgi_get);                     /* (sp += 1) */
884 	lua_setfield(L, -2, "__index");                           /* (sp -= 1) */
885 	lua_pushcfunction(L, magnet_cgi_set);                     /* (sp += 1) */
886 	lua_setfield(L, -2, "__newindex");                        /* (sp -= 1) */
887 	lua_pushcfunction(L, magnet_cgi_pairs);                   /* (sp += 1) */
888 	lua_setfield(L, -2, "__pairs");                           /* (sp -= 1) */
889 	lua_setmetatable(L, -2); /* tie the metatable to req_env     (sp -= 1) */
890 	lua_setfield(L, -2, "req_env"); /* content = {}              (sp -= 1) */
891 
892 	lua_newtable(L); /*  {}                                      (sp += 1) */
893 	lua_newtable(L); /* the meta-table for the status-table      (sp += 1) */
894 	lua_pushcfunction(L, magnet_status_get);                  /* (sp += 1) */
895 	lua_setfield(L, -2, "__index");                           /* (sp -= 1) */
896 	lua_pushcfunction(L, magnet_status_set);                  /* (sp += 1) */
897 	lua_setfield(L, -2, "__newindex");                        /* (sp -= 1) */
898 	lua_pushcfunction(L, magnet_status_pairs);                /* (sp += 1) */
899 	lua_setfield(L, -2, "__pairs");                           /* (sp -= 1) */
900 	lua_setmetatable(L, -2); /* tie the metatable to statzs      (sp -= 1) */
901 	lua_setfield(L, -2, "status"); /* content = {}               (sp -= 1) */
902 
903 	/* add empty 'content' and 'header' tables */
904 	lua_newtable(L); /*  {}                                      (sp += 1) */
905 	lua_setfield(L, -2, "content"); /* content = {}              (sp -= 1) */
906 
907 	lua_newtable(L); /*  {}                                      (sp += 1) */
908 	lua_setfield(L, -2, "header"); /* header = {}                (sp -= 1) */
909 
910 	lua_pushinteger(L, MAGNET_RESTART_REQUEST);
911 	lua_setfield(L, -2, "RESTART_REQUEST");
912 
913 	lua_pushcfunction(L, magnet_stat);                        /* (sp += 1) */
914 	lua_setfield(L, -2, "stat"); /* -1 is the env we want to set (sp -= 1) */
915 
916 	/* insert lighty table at index 2 */
917 	lua_pushvalue(L, -1);
918 	lua_insert(L, lighty_table_ndx);
919 
920 	lua_setfield(L, -2, "lighty"); /* lighty.*                   (sp -= 1) */
921 
922 #if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 502
923 	/* override the default pairs() function to our __pairs capable version;
924 	 * not needed for lua 5.2+
925 	 */
926 	lua_getglobal(L, "pairs"); /* push original pairs()          (sp += 1) */
927 	lua_pushcclosure(L, magnet_pairs, 1);
928 	lua_setfield(L, -2, "pairs");                             /* (sp -= 1) */
929 #endif
930 
931 	lua_newtable(L); /* the meta-table for the new env           (sp += 1) */
932 	lua_pushglobaltable(L);                                   /* (sp += 1) */
933 	lua_setfield(L, -2, "__index"); /* { __index = _G }          (sp -= 1) */
934 	lua_setmetatable(L, -2); /* setmetatable({}, {__index = _G}) (sp -= 1) */
935 
936 	magnet_setfenv_mainfn(L, 1);                              /* (sp -= 1) */
937 
938 	/* pcall will destroy the func value, duplicate it */     /* (sp += 1) */
939 	lua_pushvalue(L, func_ndx);
940 	{
941 		int errfunc = push_traceback(L, 0);
942 		int ret = lua_pcall(L, 0, 1, errfunc);
943 		lua_remove(L, errfunc);
944 
945 		/* reset environment */
946 		lua_pushglobaltable(L);                               /* (sp += 1) */
947 		magnet_setfenv_mainfn(L, 1);                          /* (sp -= 1) */
948 
949 		if (0 != ret) {
950 			log_error_write(srv, __FILE__, __LINE__,
951 				"ss",
952 				"lua_pcall():",
953 				lua_tostring(L, -1));
954 			lua_pop(L, 2); /* remove the error-msg and the lighty table at index 2 */
955 
956 			force_assert(lua_gettop(L) == 1); /* only the function should be on the stack */
957 
958 			con->http_status = 500;
959 			con->mode = DIRECT;
960 
961 			return HANDLER_FINISHED;
962 		}
963 	}
964 
965 	/* we should have the function, the lighty table and the return value on the stack */
966 	force_assert(lua_gettop(L) == 3);
967 
968 	switch (lua_type(L, -1)) {
969 	case LUA_TNUMBER:
970 	case LUA_TNIL:
971 		lua_return_value = (int) luaL_optinteger(L, -1, -1);
972 		break;
973 	default:
974 		log_error_write(srv, __FILE__, __LINE__, "sss",
975 				"lua_pcall():",
976 				"unexpected return type:",
977 				luaL_typename(L, -1));
978 		lua_return_value = -1;
979 		break;
980 	}
981 
982 	lua_pop(L, 1); /* pop return value */
983 
984 	magnet_copy_response_header(con, L, lighty_table_ndx);
985 
986 	{
987 		handler_t result = HANDLER_GO_ON;
988 
989 		if (lua_return_value > 99) {
990 			con->http_status = lua_return_value;
991 			con->file_finished = 1;
992 
993 			/* try { ...*/
994 			if (0 == setjmp(exceptionjmp)) {
995 				magnet_attach_content(srv, con, L, lighty_table_ndx);
996 				if (!chunkqueue_is_empty(con->write_queue)) {
997 					con->mode = p->id;
998 				}
999 			} else {
1000 				lua_settop(L, 2); /* remove all but function and lighty table */
1001 				/* } catch () { */
1002 				con->http_status = 500;
1003 				con->mode = DIRECT;
1004 			}
1005 
1006 			result = HANDLER_FINISHED;
1007 		} else if (MAGNET_RESTART_REQUEST == lua_return_value) {
1008 			result = HANDLER_COMEBACK;
1009 		}
1010 
1011 		lua_pop(L, 1); /* pop the lighty table */
1012 		force_assert(lua_gettop(L) == 1); /* only the function should remain on the stack */
1013 
1014 		return result;
1015 	}
1016 }
1017 
1018 static handler_t magnet_attract_array(server *srv, connection *con, plugin_data *p, array *files) {
1019 	size_t i;
1020 	handler_t ret = HANDLER_GO_ON;
1021 
1022 	/* no filename set */
1023 	if (files->used == 0) return HANDLER_GO_ON;
1024 
1025 	srv->request_env(srv, con);
1026 
1027 	/**
1028 	 * execute all files and jump out on the first !HANDLER_GO_ON
1029 	 */
1030 	for (i = 0; i < files->used && ret == HANDLER_GO_ON; i++) {
1031 		data_string *ds = (data_string *)files->data[i];
1032 
1033 		if (buffer_string_is_empty(ds->value)) continue;
1034 
1035 		ret = magnet_attract(srv, con, p, ds->value);
1036 	}
1037 
1038 	if (con->error_handler_saved_status) {
1039 		/* retrieve (possibly modified) REDIRECT_STATUS and store as number */
1040 		unsigned long x;
1041 		buffer * const vb = http_header_env_get(con, CONST_STR_LEN("REDIRECT_STATUS"));
1042 		if (vb && (x = strtoul(vb->ptr, NULL, 10)) < 1000)
1043 			/*(simplified validity check x < 1000)*/
1044 			con->error_handler_saved_status =
1045 			  con->error_handler_saved_status > 0 ? (int)x : -(int)x;
1046 	}
1047 
1048 	return ret;
1049 }
1050 
1051 URIHANDLER_FUNC(mod_magnet_uri_handler) {
1052 	plugin_data *p = p_d;
1053 
1054 	mod_magnet_patch_connection(srv, con, p);
1055 
1056 	return magnet_attract_array(srv, con, p, p->conf.url_raw);
1057 }
1058 
1059 URIHANDLER_FUNC(mod_magnet_physical) {
1060 	plugin_data *p = p_d;
1061 
1062 	mod_magnet_patch_connection(srv, con, p);
1063 
1064 	return magnet_attract_array(srv, con, p, p->conf.physical_path);
1065 }
1066 
1067 
1068 /* this function is called at dlopen() time and inits the callbacks */
1069 
1070 int mod_magnet_plugin_init(plugin *p);
1071 int mod_magnet_plugin_init(plugin *p) {
1072 	p->version     = LIGHTTPD_VERSION_ID;
1073 	p->name        = buffer_init_string("magnet");
1074 
1075 	p->init        = mod_magnet_init;
1076 	p->handle_uri_clean  = mod_magnet_uri_handler;
1077 	p->handle_physical   = mod_magnet_physical;
1078 	p->set_defaults  = mod_magnet_set_defaults;
1079 	p->cleanup     = mod_magnet_free;
1080 
1081 	p->data        = NULL;
1082 
1083 	return 0;
1084 }
1085