[mod_magnet] expose server addr (local IP) to lua
[lighttpd.git] / src / mod_magnet.c
blob70d380e083eeda82a144a9a70c136bacb1159893
1 #include "first.h"
3 #include "base.h"
4 #include "log.h"
5 #include "buffer.h"
6 #include "http_chunk.h"
7 #include "http_header.h"
9 #include "plugin.h"
11 #include "mod_magnet_cache.h"
12 #include "sock_addr.h"
13 #include "stat_cache.h"
14 #include "status_counter.h"
15 #include "etag.h"
17 #include <stdlib.h>
18 #include <string.h>
19 #include <setjmp.h>
21 #include <lua.h>
22 #include <lauxlib.h>
24 #define LUA_RIDX_LIGHTTPD_SERVER "lighty.srv"
25 #define LUA_RIDX_LIGHTTPD_CONNECTION "lighty.con"
27 #define MAGNET_CONFIG_RAW_URL "magnet.attract-raw-url-to"
28 #define MAGNET_CONFIG_PHYSICAL_PATH "magnet.attract-physical-path-to"
29 #define MAGNET_RESTART_REQUEST 99
31 /* plugin config for all request/connections */
33 static jmp_buf exceptionjmp;
35 typedef struct {
36 array *url_raw;
37 array *physical_path;
38 } plugin_config;
40 typedef struct {
41 PLUGIN_DATA;
43 script_cache *cache;
45 plugin_config **config_storage;
47 plugin_config conf;
48 } plugin_data;
50 /* init the plugin data */
51 INIT_FUNC(mod_magnet_init) {
52 plugin_data *p;
54 p = calloc(1, sizeof(*p));
56 p->cache = script_cache_init();
58 return p;
61 /* detroy the plugin data */
62 FREE_FUNC(mod_magnet_free) {
63 plugin_data *p = p_d;
65 UNUSED(srv);
67 if (!p) return HANDLER_GO_ON;
69 if (p->config_storage) {
70 size_t i;
72 for (i = 0; i < srv->config_context->used; i++) {
73 plugin_config *s = p->config_storage[i];
75 if (NULL == s) continue;
77 array_free(s->url_raw);
78 array_free(s->physical_path);
80 free(s);
82 free(p->config_storage);
85 script_cache_free(p->cache);
87 free(p);
89 return HANDLER_GO_ON;
92 /* handle plugin config and check values */
94 SETDEFAULTS_FUNC(mod_magnet_set_defaults) {
95 plugin_data *p = p_d;
96 size_t i = 0;
98 config_values_t cv[] = {
99 { MAGNET_CONFIG_RAW_URL, NULL, T_CONFIG_ARRAY, T_CONFIG_SCOPE_CONNECTION }, /* 0 */
100 { MAGNET_CONFIG_PHYSICAL_PATH, NULL, T_CONFIG_ARRAY, T_CONFIG_SCOPE_CONNECTION }, /* 1 */
101 { NULL, NULL, T_CONFIG_UNSET, T_CONFIG_SCOPE_UNSET }
104 if (!p) return HANDLER_ERROR;
106 p->config_storage = calloc(srv->config_context->used, sizeof(plugin_config *));
108 for (i = 0; i < srv->config_context->used; i++) {
109 data_config const* config = (data_config const*)srv->config_context->data[i];
110 plugin_config *s;
112 s = calloc(1, sizeof(plugin_config));
113 s->url_raw = array_init();
114 s->physical_path = array_init();
116 cv[0].destination = s->url_raw;
117 cv[1].destination = s->physical_path;
119 p->config_storage[i] = s;
121 if (0 != config_insert_values_global(srv, config->value, cv, i == 0 ? T_CONFIG_SCOPE_SERVER : T_CONFIG_SCOPE_CONNECTION)) {
122 return HANDLER_ERROR;
125 if (!array_is_vlist(s->url_raw)) {
126 log_error_write(srv, __FILE__, __LINE__, "s",
127 "unexpected value for magnet.attract-raw-url-to; expected list of \"scriptpath\"");
128 return HANDLER_ERROR;
131 if (!array_is_vlist(s->physical_path)) {
132 log_error_write(srv, __FILE__, __LINE__, "s",
133 "unexpected value for magnet.attract-physical-path-to; expected list \"scriptpath\"");
134 return HANDLER_ERROR;
138 return HANDLER_GO_ON;
141 #define PATCH(x) \
142 p->conf.x = s->x;
143 static int mod_magnet_patch_connection(server *srv, connection *con, plugin_data *p) {
144 size_t i, j;
145 plugin_config *s = p->config_storage[0];
147 PATCH(url_raw);
148 PATCH(physical_path);
150 /* skip the first, the global context */
151 for (i = 1; i < srv->config_context->used; i++) {
152 data_config *dc = (data_config *)srv->config_context->data[i];
153 s = p->config_storage[i];
155 /* condition didn't match */
156 if (!config_check_cond(srv, con, dc)) continue;
158 /* merge config */
159 for (j = 0; j < dc->value->used; j++) {
160 data_unset *du = dc->value->data[j];
162 if (buffer_is_equal_string(du->key, CONST_STR_LEN(MAGNET_CONFIG_RAW_URL))) {
163 PATCH(url_raw);
164 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN(MAGNET_CONFIG_PHYSICAL_PATH))) {
165 PATCH(physical_path);
170 return 0;
172 #undef PATCH
174 #if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 502
175 /* lua5.1 backward compat definition */
176 static void lua_pushglobaltable(lua_State *L) { /* (-0, +1, -) */
177 lua_pushvalue(L, LUA_GLOBALSINDEX);
179 #endif
181 static void magnet_setfenv_mainfn(lua_State *L, int funcIndex) { /* (-1, 0, -) */
182 #if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 502
183 /* set "_ENV" upvalue, which should be the first upvalue of a "main" lua
184 * function if it uses any global names
187 const char* first_upvalue_name = lua_getupvalue(L, funcIndex, 1);
188 if (NULL == first_upvalue_name) return; /* doesn't have any upvalues */
189 lua_pop(L, 1); /* only need the name of the upvalue, not the value */
191 if (0 != strcmp(first_upvalue_name, "_ENV")) return;
193 if (NULL == lua_setupvalue(L, funcIndex, 1)) {
194 /* pop value if lua_setupvalue didn't set the (not existing) upvalue */
195 lua_pop(L, 1);
197 #else
198 lua_setfenv(L, funcIndex);
199 #endif
202 #if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 502
203 /* lua 5.2 already supports __pairs */
205 /* See http://lua-users.org/wiki/GeneralizedPairsAndIpairs for implementation details.
206 * Override the default pairs() function to allow us to use a __pairs metakey
208 static int magnet_pairs(lua_State *L) {
209 luaL_checkany(L, 1); /* "self" */
211 if (luaL_getmetafield(L, 1, "__pairs")) {
212 /* call __pairs(self) */
213 lua_pushvalue(L, 1);
214 lua_call(L, 1, 3);
215 } else {
216 /* call <original-pairs-method>(self) */
217 lua_pushvalue(L, lua_upvalueindex(1));
218 lua_pushvalue(L, 1);
219 lua_call(L, 1, 3);
221 return 3;
223 #endif
225 static void magnet_push_buffer(lua_State *L, const buffer *b) {
226 if (!buffer_is_empty(b))
227 lua_pushlstring(L, CONST_BUF_LEN(b));
228 else
229 lua_pushnil(L);
232 #if 0
233 static int magnet_array_get_element(lua_State *L, const array *a) {
234 /* __index: param 1 is the (empty) table the value was not found in */
235 size_t klen;
236 const char * const k = luaL_checklstring(L, 2, &klen);
237 data_string * const ds = (data_string *)array_get_element_klen(a, k, klen);
238 magnet_push_buffer(L, NULL != ds ? ds->value : NULL);
239 return 1;
241 #endif
243 /* Define a function that will iterate over an array* (in upval 1) using current position (upval 2) */
244 static int magnet_array_next(lua_State *L) {
245 data_unset *du;
246 data_string *ds;
247 data_integer *di;
249 size_t pos = lua_tointeger(L, lua_upvalueindex(1));
250 array *a = lua_touserdata(L, lua_upvalueindex(2));
252 lua_settop(L, 0);
254 if (pos >= a->used) return 0;
255 if (NULL != (du = a->data[pos])) {
256 lua_pushlstring(L, CONST_BUF_LEN(du->key));
257 switch (du->type) {
258 case TYPE_STRING:
259 ds = (data_string *)du;
260 magnet_push_buffer(L, ds->value);
261 break;
262 case TYPE_INTEGER:
263 di = (data_integer *)du;
264 lua_pushinteger(L, di->value);
265 break;
266 default:
267 lua_pushnil(L);
268 break;
271 /* Update our positional upval to reflect our new current position */
272 pos++;
273 lua_pushinteger(L, pos);
274 lua_replace(L, lua_upvalueindex(1));
276 /* Returning 2 items on the stack (key, value) */
277 return 2;
279 return 0;
282 /* Create the closure necessary to iterate over the array *a with the above function */
283 static int magnet_array_pairs(lua_State *L, array *a) {
284 lua_pushinteger(L, 0); /* Push our current pos (the start) into upval 1 */
285 lua_pushlightuserdata(L, a); /* Push our array *a into upval 2 */
286 lua_pushcclosure(L, magnet_array_next, 2); /* Push our new closure with 2 upvals */
287 return 1;
290 static server* magnet_get_server(lua_State *L) {
291 server *srv;
293 lua_getfield(L, LUA_REGISTRYINDEX, LUA_RIDX_LIGHTTPD_SERVER);
294 srv = lua_touserdata(L, -1);
295 lua_pop(L, 1);
297 return srv;
300 static connection* magnet_get_connection(lua_State *L) {
301 connection *con;
303 lua_getfield(L, LUA_REGISTRYINDEX, LUA_RIDX_LIGHTTPD_CONNECTION);
304 con = lua_touserdata(L, -1);
305 lua_pop(L, 1);
307 return con;
310 typedef struct {
311 const char *ptr;
312 size_t len;
313 } const_buffer;
315 static const_buffer magnet_checkconstbuffer(lua_State *L, int index) {
316 const_buffer cb;
317 cb.ptr = luaL_checklstring(L, index, &cb.len);
318 return cb;
321 static buffer* magnet_checkbuffer(lua_State *L, int index) {
322 const_buffer cb = magnet_checkconstbuffer(L, index);
323 buffer *b = buffer_init();
324 buffer_copy_string_len(b, cb.ptr, cb.len);
325 return b;
328 static int magnet_print(lua_State *L) {
329 const_buffer cb = magnet_checkconstbuffer(L, 1);
330 log_error_write(magnet_get_server(L), __FILE__, __LINE__, "ss",
331 "(lua-print)", cb.ptr);
332 return 0;
335 static int magnet_stat(lua_State *L) {
336 server *srv = magnet_get_server(L);
337 connection *con = magnet_get_connection(L);
338 stat_cache_entry *sce = NULL;
340 buffer *sb = magnet_checkbuffer(L, 1);
341 handler_t res;
343 res = stat_cache_get_entry(srv, con, sb, &sce);
345 if (HANDLER_GO_ON != res) {
346 buffer_free(sb);
347 lua_pushnil(L);
348 return 1;
351 stat_cache_content_type_get(srv, con, sb, sce);
352 buffer_free(sb);
355 lua_newtable(L); // return value
357 lua_pushboolean(L, S_ISREG(sce->st.st_mode));
358 lua_setfield(L, -2, "is_file");
360 lua_pushboolean(L, S_ISDIR(sce->st.st_mode));
361 lua_setfield(L, -2, "is_dir");
363 lua_pushboolean(L, S_ISCHR(sce->st.st_mode));
364 lua_setfield(L, -2, "is_char");
366 lua_pushboolean(L, S_ISBLK(sce->st.st_mode));
367 lua_setfield(L, -2, "is_block");
369 lua_pushboolean(L, S_ISSOCK(sce->st.st_mode));
370 lua_setfield(L, -2, "is_socket");
372 lua_pushboolean(L, S_ISLNK(sce->st.st_mode));
373 lua_setfield(L, -2, "is_link");
375 lua_pushboolean(L, S_ISFIFO(sce->st.st_mode));
376 lua_setfield(L, -2, "is_fifo");
378 lua_pushinteger(L, sce->st.st_mtime);
379 lua_setfield(L, -2, "st_mtime");
381 lua_pushinteger(L, sce->st.st_ctime);
382 lua_setfield(L, -2, "st_ctime");
384 lua_pushinteger(L, sce->st.st_atime);
385 lua_setfield(L, -2, "st_atime");
387 lua_pushinteger(L, sce->st.st_uid);
388 lua_setfield(L, -2, "st_uid");
390 lua_pushinteger(L, sce->st.st_gid);
391 lua_setfield(L, -2, "st_gid");
393 lua_pushinteger(L, sce->st.st_size);
394 lua_setfield(L, -2, "st_size");
396 lua_pushinteger(L, sce->st.st_ino);
397 lua_setfield(L, -2, "st_ino");
399 if (!buffer_string_is_empty(stat_cache_etag_get(sce, con->etag_flags))) {
400 /* we have to mutate the etag */
401 etag_mutate(srv->tmp_buf, sce->etag);
402 lua_pushlstring(L, CONST_BUF_LEN(srv->tmp_buf));
403 } else {
404 lua_pushnil(L);
406 lua_setfield(L, -2, "etag");
408 if (!buffer_string_is_empty(sce->content_type)) {
409 lua_pushlstring(L, CONST_BUF_LEN(sce->content_type));
410 } else {
411 lua_pushnil(L);
413 lua_setfield(L, -2, "content-type");
415 return 1;
419 static int magnet_atpanic(lua_State *L) {
420 const_buffer cb = magnet_checkconstbuffer(L, 1);
421 log_error_write(magnet_get_server(L), __FILE__, __LINE__, "ss",
422 "(lua-atpanic)", cb.ptr);
423 longjmp(exceptionjmp, 1);
426 static int magnet_reqhdr_get(lua_State *L) {
427 /* __index: param 1 is the (empty) table the value was not found in */
428 connection *con = magnet_get_connection(L);
429 size_t klen;
430 const char * const k = luaL_checklstring(L, 2, &klen);
431 buffer * const vb =
432 http_header_request_get(con, HTTP_HEADER_UNSPECIFIED, k, klen);
433 magnet_push_buffer(L, NULL != vb ? vb : NULL);
434 return 1;
437 static int magnet_reqhdr_pairs(lua_State *L) {
438 connection *con = magnet_get_connection(L);
439 return magnet_array_pairs(L, con->request.headers);
442 static int magnet_status_get(lua_State *L) {
443 int *i;
444 server *srv = magnet_get_server(L);
446 /* __index: param 1 is the (empty) table the value was not found in */
447 const_buffer key = magnet_checkconstbuffer(L, 2);
448 i = status_counter_get_counter(srv, key.ptr, key.len);
449 lua_pushinteger(L, (lua_Integer)*i);
451 return 1;
454 static int magnet_status_set(lua_State *L) {
455 server *srv = magnet_get_server(L);
457 /* __newindex: param 1 is the (empty) table the value is supposed to be set in */
458 const_buffer key = magnet_checkconstbuffer(L, 2);
459 int counter = (int) luaL_checkinteger(L, 3);
461 status_counter_set(srv, key.ptr, key.len, counter);
463 return 0;
466 static int magnet_status_pairs(lua_State *L) {
467 server *srv = magnet_get_server(L);
469 return magnet_array_pairs(L, srv->status);
472 typedef struct {
473 const char *name;
474 enum {
475 MAGNET_ENV_UNSET,
477 MAGNET_ENV_PHYICAL_PATH,
478 MAGNET_ENV_PHYICAL_REL_PATH,
479 MAGNET_ENV_PHYICAL_DOC_ROOT,
480 MAGNET_ENV_PHYICAL_BASEDIR,
482 MAGNET_ENV_URI_PATH,
483 MAGNET_ENV_URI_PATH_RAW,
484 MAGNET_ENV_URI_SCHEME,
485 MAGNET_ENV_URI_AUTHORITY,
486 MAGNET_ENV_URI_QUERY,
488 MAGNET_ENV_REQUEST_METHOD,
489 MAGNET_ENV_REQUEST_URI,
490 MAGNET_ENV_REQUEST_ORIG_URI,
491 MAGNET_ENV_REQUEST_PATH_INFO,
492 MAGNET_ENV_REQUEST_REMOTE_IP,
493 MAGNET_ENV_REQUEST_SERVER_ADDR,
494 MAGNET_ENV_REQUEST_PROTOCOL
495 } type;
496 } magnet_env_t;
498 static const magnet_env_t magnet_env[] = {
499 { "physical.path", MAGNET_ENV_PHYICAL_PATH },
500 { "physical.rel-path", MAGNET_ENV_PHYICAL_REL_PATH },
501 { "physical.doc-root", MAGNET_ENV_PHYICAL_DOC_ROOT },
502 { "physical.basedir", MAGNET_ENV_PHYICAL_BASEDIR },
504 { "uri.path", MAGNET_ENV_URI_PATH },
505 { "uri.path-raw", MAGNET_ENV_URI_PATH_RAW },
506 { "uri.scheme", MAGNET_ENV_URI_SCHEME },
507 { "uri.authority", MAGNET_ENV_URI_AUTHORITY },
508 { "uri.query", MAGNET_ENV_URI_QUERY },
510 { "request.method", MAGNET_ENV_REQUEST_METHOD },
511 { "request.uri", MAGNET_ENV_REQUEST_URI },
512 { "request.orig-uri", MAGNET_ENV_REQUEST_ORIG_URI },
513 { "request.path-info", MAGNET_ENV_REQUEST_PATH_INFO },
514 { "request.remote-ip", MAGNET_ENV_REQUEST_REMOTE_IP },
515 { "request.remote-addr", MAGNET_ENV_REQUEST_REMOTE_IP },
516 { "request.server-addr", MAGNET_ENV_REQUEST_SERVER_ADDR },
517 { "request.protocol", MAGNET_ENV_REQUEST_PROTOCOL },
519 { NULL, MAGNET_ENV_UNSET }
522 static buffer *magnet_env_get_buffer_by_id(server *srv, connection *con, int id) {
523 buffer *dest = NULL;
525 UNUSED(srv);
528 * map all internal variables to lua
532 switch (id) {
533 case MAGNET_ENV_PHYICAL_PATH: dest = con->physical.path; break;
534 case MAGNET_ENV_PHYICAL_REL_PATH: dest = con->physical.rel_path; break;
535 case MAGNET_ENV_PHYICAL_DOC_ROOT: dest = con->physical.doc_root; break;
536 case MAGNET_ENV_PHYICAL_BASEDIR: dest = con->physical.basedir; break;
538 case MAGNET_ENV_URI_PATH: dest = con->uri.path; break;
539 case MAGNET_ENV_URI_PATH_RAW: dest = con->uri.path_raw; break;
540 case MAGNET_ENV_URI_SCHEME: dest = con->uri.scheme; break;
541 case MAGNET_ENV_URI_AUTHORITY: dest = con->uri.authority; break;
542 case MAGNET_ENV_URI_QUERY: dest = con->uri.query; break;
544 case MAGNET_ENV_REQUEST_METHOD:
545 buffer_clear(srv->tmp_buf);
546 http_method_append(srv->tmp_buf, con->request.http_method);
547 dest = srv->tmp_buf;
548 break;
549 case MAGNET_ENV_REQUEST_URI: dest = con->request.uri; break;
550 case MAGNET_ENV_REQUEST_ORIG_URI: dest = con->request.orig_uri; break;
551 case MAGNET_ENV_REQUEST_PATH_INFO: dest = con->request.pathinfo; break;
552 case MAGNET_ENV_REQUEST_REMOTE_IP: dest = con->dst_addr_buf; break;
553 case MAGNET_ENV_REQUEST_SERVER_ADDR:
554 dest = srv->tmp_buf;
555 buffer_clear(dest);
556 switch (con->srv_socket->addr.plain.sa_family) {
557 case AF_INET:
558 case AF_INET6:
559 if (sock_addr_is_addr_wildcard(&con->srv_socket->addr)) {
560 sock_addr addrbuf;
561 socklen_t addrlen = sizeof(addrbuf);
562 if (0 == getsockname(con->fd,(struct sockaddr *)&addrbuf,&addrlen)){
563 char buf[INET6_ADDRSTRLEN + 1];
564 const char *s = sock_addr_inet_ntop(&addrbuf, buf, sizeof(buf)-1);
565 if (NULL != s)
566 buffer_copy_string_len(dest, s, strlen(s));
569 else {
570 buffer_copy_buffer(dest, con->srv_socket->srv_token);
571 if (dest->ptr[0] != '[' || dest->ptr[buffer_string_length(dest)-1] != ']') {
572 char *s = strrchr(dest->ptr, ':');
573 if (s != NULL) /* local IP without port */
574 buffer_string_set_length(dest, s - dest->ptr);
577 break;
578 default:
579 break;
581 break;
582 case MAGNET_ENV_REQUEST_PROTOCOL:
583 buffer_copy_string(srv->tmp_buf, get_http_version_name(con->request.http_version));
584 dest = srv->tmp_buf;
585 break;
587 case MAGNET_ENV_UNSET: break;
590 return dest;
593 static buffer *magnet_env_get_buffer(server *srv, connection *con, const char *key) {
594 size_t i;
596 for (i = 0; magnet_env[i].name; i++) {
597 if (0 == strcmp(key, magnet_env[i].name)) break;
600 return magnet_env_get_buffer_by_id(srv, con, magnet_env[i].type);
603 static int magnet_env_get(lua_State *L) {
604 server *srv = magnet_get_server(L);
605 connection *con = magnet_get_connection(L);
607 /* __index: param 1 is the (empty) table the value was not found in */
608 const char *key = luaL_checkstring(L, 2);
609 magnet_push_buffer(L, magnet_env_get_buffer(srv, con, key));
610 return 1;
613 static int magnet_env_set(lua_State *L) {
614 server *srv = magnet_get_server(L);
615 connection *con = magnet_get_connection(L);
617 /* __newindex: param 1 is the (empty) table the value is supposed to be set in */
618 const char *key = luaL_checkstring(L, 2);
619 buffer *dest = NULL;
621 luaL_checkany(L, 3); /* nil or a string */
623 if (NULL != (dest = magnet_env_get_buffer(srv, con, key))) {
624 if (lua_isnil(L, 3)) {
625 buffer_reset(dest);
626 } else {
627 const_buffer val = magnet_checkconstbuffer(L, 3);
628 buffer_copy_string_len(dest, val.ptr, val.len);
630 } else {
631 /* couldn't save */
633 return luaL_error(L, "couldn't store '%s' in lighty.env[]", key);
636 return 0;
639 static int magnet_env_next(lua_State *L) {
640 server *srv = magnet_get_server(L);
641 connection *con = magnet_get_connection(L);
642 const int pos = lua_tointeger(L, lua_upvalueindex(1));
644 /* ignore previous key: use upvalue for current pos */
645 lua_settop(L, 0);
647 if (NULL == magnet_env[pos].name) return 0; /* end of list */
648 /* Update our positional upval to reflect our new current position */
649 lua_pushinteger(L, pos + 1);
650 lua_replace(L, lua_upvalueindex(1));
652 /* key to return */
653 lua_pushstring(L, magnet_env[pos].name);
655 /* get value */
656 magnet_push_buffer(L, magnet_env_get_buffer_by_id(srv, con, magnet_env[pos].type));
658 /* return 2 items on the stack (key, value) */
659 return 2;
662 static int magnet_env_pairs(lua_State *L) {
663 lua_pushinteger(L, 0); /* Push our current pos (the start) into upval 1 */
664 lua_pushcclosure(L, magnet_env_next, 1); /* Push our new closure with 1 upvals */
665 return 1;
668 static int magnet_cgi_get(lua_State *L) {
669 /* __index: param 1 is the (empty) table the value was not found in */
670 connection *con = magnet_get_connection(L);
671 size_t klen;
672 const char * const k = luaL_checklstring(L, 2, &klen);
673 buffer * const vb = http_header_env_get(con, k, klen);
674 magnet_push_buffer(L, NULL != vb ? vb : NULL);
675 return 1;
678 static int magnet_cgi_set(lua_State *L) {
679 /* __newindex: param 1 is the (empty) table the value is supposed to be set in */
680 connection *con = magnet_get_connection(L);
681 const_buffer key = magnet_checkconstbuffer(L, 2);
682 const_buffer val = magnet_checkconstbuffer(L, 3);
683 http_header_env_set(con, key.ptr, key.len, val.ptr, val.len);
684 return 0;
687 static int magnet_cgi_pairs(lua_State *L) {
688 connection *con = magnet_get_connection(L);
690 return magnet_array_pairs(L, con->environment);
694 static int magnet_copy_response_header(connection *con, lua_State *L, int lighty_table_ndx) {
695 force_assert(lua_istable(L, lighty_table_ndx));
697 lua_getfield(L, lighty_table_ndx, "header"); /* lighty.header */
698 if (lua_istable(L, -1)) {
699 /* header is found, and is a table */
701 lua_pushnil(L);
702 while (lua_next(L, -2) != 0) {
703 if (lua_isstring(L, -1) && lua_isstring(L, -2)) {
704 const_buffer key = magnet_checkconstbuffer(L, -2);
705 const_buffer val = magnet_checkconstbuffer(L, -1);
706 enum http_header_e id = http_header_hkey_get(key.ptr, key.len);
708 val.len
709 ? http_header_response_set(con, id, key.ptr, key.len, val.ptr, val.len)
710 : http_header_response_unset(con, id, key.ptr, key.len);
713 lua_pop(L, 1);
716 lua_pop(L, 1); /* pop lighty.header */
718 return 0;
722 * walk through the content array
724 * content = { "<pre>", { file = "/content" } , "</pre>" }
726 * header["Content-Type"] = "text/html"
728 * return 200
730 static int magnet_attach_content(server *srv, connection *con, lua_State *L, int lighty_table_ndx) {
731 force_assert(lua_istable(L, lighty_table_ndx));
733 lua_getfield(L, lighty_table_ndx, "content"); /* lighty.content */
734 if (lua_istable(L, -1)) {
735 int i;
736 /* content is found, and is a table */
738 for (i = 1; ; i++) {
739 lua_rawgeti(L, -1, i);
741 /* -1 is the value and should be the value ... aka a table */
742 if (lua_isstring(L, -1)) {
743 const_buffer data = magnet_checkconstbuffer(L, -1);
745 chunkqueue_append_mem(con->write_queue, data.ptr, data.len);
746 } else if (lua_istable(L, -1)) {
747 lua_getfield(L, -1, "filename");
748 lua_getfield(L, -2, "length"); /* (0-based) end of range (not actually "length") */
749 lua_getfield(L, -3, "offset"); /* (0-based) start of range */
751 if (lua_isstring(L, -3)) { /* filename has to be a string */
752 off_t off = (off_t) luaL_optinteger(L, -1, 0);
753 off_t len = (off_t) luaL_optinteger(L, -2, -1); /*(-1 to http_chunk_append_file_range() uses file size minus offset)*/
754 if (off < 0) {
755 return luaL_error(L, "offset for '%s' is negative", lua_tostring(L, -3));
758 if (len >= off) {
759 len -= off;
760 } else if (-1 != len) {
761 return luaL_error(L, "offset > length for '%s'", lua_tostring(L, -3));
764 if (0 != len) {
765 buffer *fn = magnet_checkbuffer(L, -3);
766 int rc = http_chunk_append_file_range(srv, con, fn, off, len);
767 buffer_free(fn);
768 if (0 != rc) {
769 return luaL_error(L, "error opening file content '%s' at offset %lld", lua_tostring(L, -3), (long long)off);
772 } else {
773 return luaL_error(L, "content[%d] is a table and requires the field \"filename\"", i);
776 lua_pop(L, 3);
777 } else if (lua_isnil(L, -1)) {
778 /* end of list */
780 lua_pop(L, 1);
782 break;
783 } else {
784 return luaL_error(L, "content[%d] is neither a string nor a table: ", i);
787 lua_pop(L, 1); /* pop the content[...] entry value */
789 } else {
790 return luaL_error(L, "lighty.content has to be a table");
792 lua_pop(L, 1); /* pop lighty.content */
794 return 0;
797 static int traceback(lua_State *L) {
798 if (!lua_isstring(L, 1)) /* 'message' not a string? */
799 return 1; /* keep it intact */
800 lua_getglobal(L, "debug");
801 if (!lua_istable(L, -1)) {
802 lua_pop(L, 1);
803 return 1;
805 lua_getfield(L, -1, "traceback");
806 if (!lua_isfunction(L, -1)) {
807 lua_pop(L, 2);
808 return 1;
810 lua_pushvalue(L, 1); /* pass error message */
811 lua_pushinteger(L, 2); /* skip this function and traceback */
812 lua_call(L, 2, 1); /* call debug.traceback */
813 return 1;
816 /* push traceback function before calling lua_pcall after narg arguments
817 * have been pushed (inserts it before the arguments). returns index for
818 * traceback function ("msgh" in lua_pcall)
820 static int push_traceback(lua_State *L, int narg) {
821 int base = lua_gettop(L) - narg; /* function index */
822 lua_pushcfunction(L, traceback);
823 lua_insert(L, base);
824 return base;
827 static handler_t magnet_attract(server *srv, connection *con, plugin_data *p, buffer *name) {
828 lua_State *L;
829 int lua_return_value;
830 const int func_ndx = 1;
831 const int lighty_table_ndx = 2;
833 /* get the script-context */
834 L = script_cache_get_script(srv, con, p->cache, name);
836 if (lua_isstring(L, -1)) {
837 log_error_write(srv, __FILE__, __LINE__,
838 "sbss",
839 "loading script",
840 name,
841 "failed:",
842 lua_tostring(L, -1));
844 lua_pop(L, 1);
846 force_assert(lua_gettop(L) == 0); /* only the error should have been on the stack */
848 con->http_status = 500;
849 con->mode = DIRECT;
851 return HANDLER_FINISHED;
854 force_assert(lua_gettop(L) == 1);
855 force_assert(lua_isfunction(L, func_ndx));
857 lua_pushlightuserdata(L, srv);
858 lua_setfield(L, LUA_REGISTRYINDEX, LUA_RIDX_LIGHTTPD_SERVER);
860 lua_pushlightuserdata(L, con);
861 lua_setfield(L, LUA_REGISTRYINDEX, LUA_RIDX_LIGHTTPD_CONNECTION);
863 lua_atpanic(L, magnet_atpanic);
866 * we want to create empty environment for our script
868 * setmetatable({}, {__index = _G})
870 * if a function symbol is not defined in our env, __index will lookup
871 * in the global env.
873 * all variables created in the script-env will be thrown
874 * away at the end of the script run.
876 lua_newtable(L); /* my empty environment aka {} (sp += 1) */
878 /* we have to overwrite the print function */
879 lua_pushcfunction(L, magnet_print); /* (sp += 1) */
880 lua_setfield(L, -2, "print"); /* -1 is the env we want to set(sp -= 1) */
883 * lighty.request[] (ro) has the HTTP-request headers
884 * lighty.env[] (rw) has various url/physical file paths and
885 * request meta data; might contain nil values
886 * lighty.req_env[] (ro) has the cgi environment
887 * lighty.status[] (ro) has the status counters
888 * lighty.content[] (rw) is a table of string/file
889 * lighty.header[] (rw) is a array to set response headers
892 lua_newtable(L); /* lighty.* (sp += 1) */
894 lua_newtable(L); /* {} (sp += 1) */
895 lua_newtable(L); /* the meta-table for the request-table (sp += 1) */
896 lua_pushcfunction(L, magnet_reqhdr_get); /* (sp += 1) */
897 lua_setfield(L, -2, "__index"); /* (sp -= 1) */
898 lua_pushcfunction(L, magnet_reqhdr_pairs); /* (sp += 1) */
899 lua_setfield(L, -2, "__pairs"); /* (sp -= 1) */
900 lua_setmetatable(L, -2); /* tie the metatable to request (sp -= 1) */
901 lua_setfield(L, -2, "request"); /* content = {} (sp -= 1) */
903 lua_newtable(L); /* {} (sp += 1) */
904 lua_newtable(L); /* the meta-table for the env-table (sp += 1) */
905 lua_pushcfunction(L, magnet_env_get); /* (sp += 1) */
906 lua_setfield(L, -2, "__index"); /* (sp -= 1) */
907 lua_pushcfunction(L, magnet_env_set); /* (sp += 1) */
908 lua_setfield(L, -2, "__newindex"); /* (sp -= 1) */
909 lua_pushcfunction(L, magnet_env_pairs); /* (sp += 1) */
910 lua_setfield(L, -2, "__pairs"); /* (sp -= 1) */
911 lua_setmetatable(L, -2); /* tie the metatable to env (sp -= 1) */
912 lua_setfield(L, -2, "env"); /* content = {} (sp -= 1) */
914 lua_newtable(L); /* {} (sp += 1) */
915 lua_newtable(L); /* the meta-table for the req_env-table (sp += 1) */
916 lua_pushcfunction(L, magnet_cgi_get); /* (sp += 1) */
917 lua_setfield(L, -2, "__index"); /* (sp -= 1) */
918 lua_pushcfunction(L, magnet_cgi_set); /* (sp += 1) */
919 lua_setfield(L, -2, "__newindex"); /* (sp -= 1) */
920 lua_pushcfunction(L, magnet_cgi_pairs); /* (sp += 1) */
921 lua_setfield(L, -2, "__pairs"); /* (sp -= 1) */
922 lua_setmetatable(L, -2); /* tie the metatable to req_env (sp -= 1) */
923 lua_setfield(L, -2, "req_env"); /* content = {} (sp -= 1) */
925 lua_newtable(L); /* {} (sp += 1) */
926 lua_newtable(L); /* the meta-table for the status-table (sp += 1) */
927 lua_pushcfunction(L, magnet_status_get); /* (sp += 1) */
928 lua_setfield(L, -2, "__index"); /* (sp -= 1) */
929 lua_pushcfunction(L, magnet_status_set); /* (sp += 1) */
930 lua_setfield(L, -2, "__newindex"); /* (sp -= 1) */
931 lua_pushcfunction(L, magnet_status_pairs); /* (sp += 1) */
932 lua_setfield(L, -2, "__pairs"); /* (sp -= 1) */
933 lua_setmetatable(L, -2); /* tie the metatable to statzs (sp -= 1) */
934 lua_setfield(L, -2, "status"); /* content = {} (sp -= 1) */
936 /* add empty 'content' and 'header' tables */
937 lua_newtable(L); /* {} (sp += 1) */
938 lua_setfield(L, -2, "content"); /* content = {} (sp -= 1) */
940 lua_newtable(L); /* {} (sp += 1) */
941 lua_setfield(L, -2, "header"); /* header = {} (sp -= 1) */
943 lua_pushinteger(L, MAGNET_RESTART_REQUEST);
944 lua_setfield(L, -2, "RESTART_REQUEST");
946 lua_pushcfunction(L, magnet_stat); /* (sp += 1) */
947 lua_setfield(L, -2, "stat"); /* -1 is the env we want to set (sp -= 1) */
949 /* insert lighty table at index 2 */
950 lua_pushvalue(L, -1);
951 lua_insert(L, lighty_table_ndx);
953 lua_setfield(L, -2, "lighty"); /* lighty.* (sp -= 1) */
955 #if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 502
956 /* override the default pairs() function to our __pairs capable version;
957 * not needed for lua 5.2+
959 lua_getglobal(L, "pairs"); /* push original pairs() (sp += 1) */
960 lua_pushcclosure(L, magnet_pairs, 1);
961 lua_setfield(L, -2, "pairs"); /* (sp -= 1) */
962 #endif
964 lua_newtable(L); /* the meta-table for the new env (sp += 1) */
965 lua_pushglobaltable(L); /* (sp += 1) */
966 lua_setfield(L, -2, "__index"); /* { __index = _G } (sp -= 1) */
967 lua_setmetatable(L, -2); /* setmetatable({}, {__index = _G}) (sp -= 1) */
969 magnet_setfenv_mainfn(L, 1); /* (sp -= 1) */
971 /* pcall will destroy the func value, duplicate it */ /* (sp += 1) */
972 lua_pushvalue(L, func_ndx);
974 int errfunc = push_traceback(L, 0);
975 int ret = lua_pcall(L, 0, 1, errfunc);
976 lua_remove(L, errfunc);
978 /* reset environment */
979 lua_pushglobaltable(L); /* (sp += 1) */
980 magnet_setfenv_mainfn(L, 1); /* (sp -= 1) */
982 if (0 != ret) {
983 log_error_write(srv, __FILE__, __LINE__,
984 "ss",
985 "lua_pcall():",
986 lua_tostring(L, -1));
987 lua_pop(L, 2); /* remove the error-msg and the lighty table at index 2 */
989 force_assert(lua_gettop(L) == 1); /* only the function should be on the stack */
991 con->http_status = 500;
992 con->mode = DIRECT;
994 return HANDLER_FINISHED;
998 /* we should have the function, the lighty table and the return value on the stack */
999 force_assert(lua_gettop(L) == 3);
1001 switch (lua_type(L, -1)) {
1002 case LUA_TNUMBER:
1003 case LUA_TNIL:
1004 lua_return_value = (int) luaL_optinteger(L, -1, -1);
1005 break;
1006 default:
1007 log_error_write(srv, __FILE__, __LINE__, "sss",
1008 "lua_pcall():",
1009 "unexpected return type:",
1010 luaL_typename(L, -1));
1011 lua_return_value = -1;
1012 break;
1015 lua_pop(L, 1); /* pop return value */
1017 magnet_copy_response_header(con, L, lighty_table_ndx);
1020 handler_t result = HANDLER_GO_ON;
1022 if (lua_return_value > 99) {
1023 con->http_status = lua_return_value;
1024 con->file_finished = 1;
1026 /* try { ...*/
1027 if (0 == setjmp(exceptionjmp)) {
1028 magnet_attach_content(srv, con, L, lighty_table_ndx);
1029 if (!chunkqueue_is_empty(con->write_queue)) {
1030 con->mode = p->id;
1032 } else {
1033 lua_settop(L, 2); /* remove all but function and lighty table */
1034 /* } catch () { */
1035 con->http_status = 500;
1036 con->mode = DIRECT;
1039 result = HANDLER_FINISHED;
1040 } else if (MAGNET_RESTART_REQUEST == lua_return_value) {
1041 result = HANDLER_COMEBACK;
1044 lua_pop(L, 1); /* pop the lighty table */
1045 force_assert(lua_gettop(L) == 1); /* only the function should remain on the stack */
1047 return result;
1051 static handler_t magnet_attract_array(server *srv, connection *con, plugin_data *p, array *files) {
1052 size_t i;
1053 handler_t ret = HANDLER_GO_ON;
1055 /* no filename set */
1056 if (files->used == 0) return HANDLER_GO_ON;
1058 srv->request_env(srv, con);
1061 * execute all files and jump out on the first !HANDLER_GO_ON
1063 for (i = 0; i < files->used && ret == HANDLER_GO_ON; i++) {
1064 data_string *ds = (data_string *)files->data[i];
1066 if (buffer_string_is_empty(ds->value)) continue;
1068 ret = magnet_attract(srv, con, p, ds->value);
1071 if (con->error_handler_saved_status) {
1072 /* retrieve (possibly modified) REDIRECT_STATUS and store as number */
1073 unsigned long x;
1074 buffer * const vb = http_header_env_get(con, CONST_STR_LEN("REDIRECT_STATUS"));
1075 if (vb && (x = strtoul(vb->ptr, NULL, 10)) < 1000)
1076 /*(simplified validity check x < 1000)*/
1077 con->error_handler_saved_status =
1078 con->error_handler_saved_status > 0 ? (int)x : -(int)x;
1081 return ret;
1084 URIHANDLER_FUNC(mod_magnet_uri_handler) {
1085 plugin_data *p = p_d;
1087 mod_magnet_patch_connection(srv, con, p);
1089 return magnet_attract_array(srv, con, p, p->conf.url_raw);
1092 URIHANDLER_FUNC(mod_magnet_physical) {
1093 plugin_data *p = p_d;
1095 mod_magnet_patch_connection(srv, con, p);
1097 return magnet_attract_array(srv, con, p, p->conf.physical_path);
1101 /* this function is called at dlopen() time and inits the callbacks */
1103 int mod_magnet_plugin_init(plugin *p);
1104 int mod_magnet_plugin_init(plugin *p) {
1105 p->version = LIGHTTPD_VERSION_ID;
1106 p->name = buffer_init_string("magnet");
1108 p->init = mod_magnet_init;
1109 p->handle_uri_clean = mod_magnet_uri_handler;
1110 p->handle_physical = mod_magnet_physical;
1111 p->set_defaults = mod_magnet_set_defaults;
1112 p->cleanup = mod_magnet_free;
1114 p->data = NULL;
1116 return 0;