xref: /lighttpd1.4/src/mod_magnet.c (revision 3e70494d)
1 #include "first.h"
2 
3 #include "sys-crypto-md.h"
4 #include "algo_hmac.h"
5 #include "base.h"
6 #include "base64.h"
7 #include "burl.h"
8 #include "log.h"
9 #include "buffer.h"
10 #include "chunk.h"
11 #include "ck.h"
12 #include "h2.h"
13 #include "http_chunk.h"
14 #include "http_etag.h"
15 #include "http_header.h"
16 #include "rand.h"
17 #include "response.h"   /* http_response_send_1xx() */
18 
19 #include "plugin.h"
20 
21 #include "mod_magnet_cache.h"
22 #include "sock_addr.h"
23 #include "stat_cache.h"
24 #include "status_counter.h"
25 
26 #include <dirent.h>
27 #include <stdlib.h>
28 #include <string.h>
29 /*#include <setjmp.h>*//*(not currently used)*/
30 
31 #include <lua.h>
32 #include <lauxlib.h>
33 
34 #define MAGNET_RESTART_REQUEST      99
35 
36 /* plugin config for all request/connections */
37 
38 /*static jmp_buf exceptionjmp;*//*(not currently used)*/
39 
40 typedef struct {
41     script * const *url_raw;
42     script * const *physical_path;
43     script * const *response_start;
44     int stage;
45 } plugin_config;
46 
47 typedef struct {
48     PLUGIN_DATA;
49     plugin_config defaults;
50     plugin_config conf;
51 
52     script_cache cache;
53 } plugin_data;
54 
55 INIT_FUNC(mod_magnet_init) {
56     return calloc(1, sizeof(plugin_data));
57 }
58 
59 FREE_FUNC(mod_magnet_free) {
60     plugin_data * const p = p_d;
61     script_cache_free_data(&p->cache);
62     if (NULL == p->cvlist) return;
63     /* (init i to 0 if global context; to 1 to skip empty global context) */
64     for (int i = !p->cvlist[0].v.u2[1], used = p->nconfig; i < used; ++i) {
65         config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0];
66         for (; -1 != cpv->k_id; ++cpv) {
67             if (cpv->vtype != T_CONFIG_LOCAL || NULL == cpv->v.v) continue;
68             switch (cpv->k_id) {
69               case 0: /* magnet.attract-raw-url-to */
70               case 1: /* magnet.attract-physical-path-to */
71               case 2: /* magnet.attract-response-start-to */
72                 free(cpv->v.v);
73                 break;
74               default:
75                 break;
76             }
77         }
78     }
79 }
80 
81 static void mod_magnet_merge_config_cpv(plugin_config * const pconf, const config_plugin_value_t * const cpv) {
82     if (cpv->vtype != T_CONFIG_LOCAL)
83         return;
84     switch (cpv->k_id) { /* index into static config_plugin_keys_t cpk[] */
85       case 0: /* magnet.attract-raw-url-to */
86         pconf->url_raw = cpv->v.v;
87         break;
88       case 1: /* magnet.attract-physical-path-to */
89         pconf->physical_path = cpv->v.v;
90         break;
91       case 2: /* magnet.attract-response-start-to */
92         pconf->response_start = cpv->v.v;
93         break;
94       default:/* should not happen */
95         return;
96     }
97 }
98 
99 static void mod_magnet_merge_config(plugin_config * const pconf, const config_plugin_value_t *cpv) {
100     do {
101         mod_magnet_merge_config_cpv(pconf, cpv);
102     } while ((++cpv)->k_id != -1);
103 }
104 
105 static void mod_magnet_patch_config(request_st * const r, plugin_data * const p) {
106     p->conf = p->defaults; /* copy small struct instead of memcpy() */
107     /*memcpy(&p->conf, &p->defaults, sizeof(plugin_config));*/
108     for (int i = 1, used = p->nconfig; i < used; ++i) {
109         if (config_check_cond(r, (uint32_t)p->cvlist[i].k_id))
110             mod_magnet_merge_config(&p->conf, p->cvlist + p->cvlist[i].v.u2[0]);
111     }
112 }
113 
114 SETDEFAULTS_FUNC(mod_magnet_set_defaults) {
115     static const config_plugin_keys_t cpk[] = {
116       { CONST_STR_LEN("magnet.attract-raw-url-to"),
117         T_CONFIG_ARRAY_VLIST,
118         T_CONFIG_SCOPE_CONNECTION }
119      ,{ CONST_STR_LEN("magnet.attract-physical-path-to"),
120         T_CONFIG_ARRAY_VLIST,
121         T_CONFIG_SCOPE_CONNECTION }
122      ,{ CONST_STR_LEN("magnet.attract-response-start-to"),
123         T_CONFIG_ARRAY_VLIST,
124         T_CONFIG_SCOPE_CONNECTION }
125      ,{ NULL, 0,
126         T_CONFIG_UNSET,
127         T_CONFIG_SCOPE_UNSET }
128     };
129 
130     plugin_data * const p = p_d;
131     if (!config_plugin_values_init(srv, p, cpk, "mod_magnet"))
132         return HANDLER_ERROR;
133 
134     /* process and validate config directives
135      * (init i to 0 if global context; to 1 to skip empty global context) */
136     for (int i = !p->cvlist[0].v.u2[1]; i < p->nconfig; ++i) {
137         config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0];
138         for (; -1 != cpv->k_id; ++cpv) {
139             switch (cpv->k_id) {
140               case 0: /* magnet.attract-raw-url-to */
141               case 1: /* magnet.attract-physical-path-to */
142               case 2: /* magnet.attract-response-start-to */
143                 if (0 == cpv->v.a->used) {
144                     cpv->v.v = NULL;
145                     cpv->vtype = T_CONFIG_LOCAL;
146                 }
147                 else {
148                     script ** const a =
149                       malloc(sizeof(script *)*(cpv->v.a->used+1));
150                     force_assert(a);
151                     for (uint32_t j = 0; j < cpv->v.a->used; ++j) {
152                         data_string *ds = (data_string *)cpv->v.a->data[j];
153                         if (buffer_is_blank(&ds->value)) {
154                             log_error(srv->errh, __FILE__, __LINE__,
155                               "unexpected (blank) value for %s; "
156                               "expected list of \"scriptpath\"", cpk[cpv->k_id].k);
157                             free(a);
158                             return HANDLER_ERROR;
159                         }
160                         a[j] = script_cache_get_script(&p->cache, &ds->value);
161                     }
162                     a[cpv->v.a->used] = NULL;
163                     cpv->v.v = a;
164                     cpv->vtype = T_CONFIG_LOCAL;
165                 }
166                 break;
167               default:/* should not happen */
168                 break;
169             }
170         }
171     }
172 
173     /* initialize p->defaults from global config context */
174     if (p->nconfig > 0 && p->cvlist->v.u2[1]) {
175         const config_plugin_value_t *cpv = p->cvlist + p->cvlist->v.u2[0];
176         if (-1 != cpv->k_id)
177             mod_magnet_merge_config(&p->defaults, cpv);
178     }
179 
180     return HANDLER_GO_ON;
181 }
182 
183 #if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 504
184 #define lua_newuserdata0(L, sz) lua_newuserdata((L),(sz))
185 #else
186 #define lua_newuserdata0(L, sz) lua_newuserdatauv((L),(sz),0)
187 #endif
188 
189 #if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 503
190 #define lua_getfield_and_type(L,idx,k) \
191        (lua_getfield((L),(idx),(k)), lua_type((L),-1))
192 #define lua_getglobal_and_type(L,name) \
193        (lua_getglobal((L),(name)), lua_type((L),-1))
194 #else
195 #define lua_getfield_and_type(L,idx,k) \
196         lua_getfield((L),(idx),(k))
197 #define lua_getglobal_and_type(L,name) \
198         lua_getglobal((L),(name))
199 #endif
200 
201 #if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 502
202 static lua_Integer
203 lua_tointegerx (lua_State * const L, int idx, int *isnum)
204 {
205     /*(caller should check for LUA_TNIL if using a default value is desired)*/
206     /*(note: return 0 for floating point not convertible to integer)*/
207     *isnum = lua_isnumber(L, idx);
208     return *isnum ? lua_tointeger(L, idx) : 0;
209 }
210 #endif
211 
212 #if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 502
213 /* lua5.1 backward compat definition */
214 static void lua_pushglobaltable(lua_State *L) { /* (-0, +1, -) */
215 	lua_pushvalue(L, LUA_GLOBALSINDEX);
216 }
217 #endif
218 
219 static void magnet_setfenv_mainfn(lua_State *L, int funcIndex) { /* (-1, 0, -) */
220 #if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 502
221 	/* set "_ENV" upvalue, which should be the first upvalue of a "main" lua
222 	 * function if it uses any global names
223 	 */
224 
225 	const char* first_upvalue_name = lua_getupvalue(L, funcIndex, 1);
226 	if (NULL == first_upvalue_name) return; /* doesn't have any upvalues */
227 	lua_pop(L, 1); /* only need the name of the upvalue, not the value */
228 
229 	if (0 != strcmp(first_upvalue_name, "_ENV")) return;
230 
231 	if (NULL == lua_setupvalue(L, funcIndex, 1)) {
232 		/* pop value if lua_setupvalue didn't set the (not existing) upvalue */
233 		lua_pop(L, 1);
234 	}
235 #else
236 	lua_setfenv(L, funcIndex);
237 #endif
238 }
239 
240 #if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 502
241 /* lua 5.1 deprecated luaL_getn() for lua_objlen() */
242 /* lua 5.2 renamed lua_objlen() to lua_rawlen() */
243 #define lua_rawlen lua_objlen
244 /* lua 5.2 deprecated luaL_register() for luaL_setfuncs()
245  * (this define is valid only when 0 == nup) */
246 #define luaL_setfuncs(L, l, nup) luaL_register((L), NULL, (l))
247 #endif
248 
249 #if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 502
250 /* lua 5.2 already supports __pairs */
251 
252 /* See http://lua-users.org/wiki/GeneralizedPairsAndIpairs for implementation details.
253  * Override the default pairs() function to allow us to use a __pairs metakey
254  */
255 static int magnet_pairs(lua_State *L) {
256 	luaL_checkany(L, 1); /* "self" */
257 
258 	if (luaL_getmetafield(L, 1, "__pairs")) {
259 		/* call __pairs(self) */
260 		lua_pushvalue(L, 1);
261 		lua_call(L, 1, 3);
262 	} else {
263 		/* call <original-pairs-method>(self) */
264 		lua_pushvalue(L, lua_upvalueindex(1));
265 		lua_pushvalue(L, 1);
266 		lua_call(L, 1, 3);
267 	}
268 	return 3;
269 }
270 #endif
271 
272 
273 /* XXX: mystery why dir walk (readdir) is not already part of lua io liolib.c */
274 
275 #ifndef _D_EXACT_NAMLEN
276 #ifdef _DIRENT_HAVE_D_NAMLEN
277 #define _D_EXACT_NAMLEN(d) ((d)->d_namlen)
278 #else
279 #define _D_EXACT_NAMLEN(d) (strlen ((d)->d_name))
280 #endif
281 #endif
282 
283 static int magnet_readdir_iter(lua_State *L) {
284     DIR ** const d = (DIR **)lua_touserdata(L, lua_upvalueindex(1));
285     if (NULL == *d) return 0;
286 
287     /* readdir() and skip over "." and ".." */
288     struct dirent *de;
289     const char *n;
290     do {
291         de = readdir(*d);
292     } while (de && (n = de->d_name)[0] == '.'
293              && (n[1] == '\0' || (n[1] == '.' && n[2] == '\0')));
294 
295     if (de) {
296         lua_pushlstring(L, de->d_name, _D_EXACT_NAMLEN(de));
297         return 1;
298     }
299     else { /* EOF */
300         closedir(*d);
301         *d = NULL;
302         return 0;
303     }
304 }
305 
306 static int magnet_readdir_gc(lua_State *L) {
307     /*DIR ** const d = ((DIR **)luaL_checkudata(L, 1, "li.DIR"));*/
308     DIR ** const d = lua_touserdata(L, 1);
309     if (*d) closedir(*d);
310     return 0;
311 }
312 
313 static void magnet_readdir_metatable(lua_State * const L) {
314     if (luaL_newmetatable(L, "li.DIR")) {                     /* (sp += 1) */
315         lua_pushcclosure(L, magnet_readdir_gc, 0);            /* (sp += 1) */
316         lua_setfield(L, -2, "__gc");                          /* (sp -= 1) */
317         lua_pushboolean(L, 0);                                /* (sp += 1) */
318         lua_setfield(L, -2, "__metatable"); /* protect metatable (sp -= 1) */
319     }
320 }
321 
322 static int magnet_readdir(lua_State *L) {
323     const char * const s = luaL_checkstring(L, 1);
324     DIR * const d = opendir(s);
325     if (d) {
326         *(DIR **)lua_newuserdata0(L, sizeof(DIR *)) = d;
327         magnet_readdir_metatable(L);
328         lua_setmetatable(L, -2);
329         lua_pushcclosure(L, magnet_readdir_iter, 1);
330     }
331     else
332         lua_pushnil(L);
333     return 1;
334 }
335 
336 
337 __attribute_cold__
338 static int magnet_newindex_readonly(lua_State *L) {
339     lua_pushliteral(L, "lua table is read-only");
340     return lua_error(L);
341 }
342 
343 static void magnet_push_buffer(lua_State *L, const buffer *b) {
344     if (b && !buffer_is_unset(b))
345         lua_pushlstring(L, BUF_PTR_LEN(b));
346     else
347         lua_pushnil(L);
348 }
349 
350 #if 0
351 static int magnet_array_get_element(lua_State *L, const array *a) {
352     /* __index: param 1 is the (empty) table the value was not found in */
353     size_t klen;
354     const char * const k = luaL_checklstring(L, 2, &klen);
355     const data_string * const ds = (const data_string *)
356       array_get_element_klen(a, k, klen);
357     magnet_push_buffer(L, NULL != ds ? &ds->value : NULL);
358     return 1;
359 }
360 #endif
361 
362 /* Define a function that will iterate over an array* (in upval 2) using current position (upval 1) */
363 static int magnet_array_next(lua_State *L) {
364 	lua_settop(L, 0);
365 	const uint32_t pos = lua_tointeger(L, lua_upvalueindex(1));
366 	const array * const a = lua_touserdata(L, lua_upvalueindex(2));
367 	const data_unset * const du = pos < a->used ? a->data[pos] : NULL;
368 	if (NULL == du) return 0;
369 
370 		lua_pushlstring(L, BUF_PTR_LEN(&du->key));
371 		switch (du->type) {
372 			case TYPE_STRING:
373 				magnet_push_buffer(L, &((const data_string *)du)->value);
374 				break;
375 			case TYPE_INTEGER:
376 				lua_pushinteger(L, ((const data_integer *)du)->value);
377 				break;
378 			default:
379 				lua_pushnil(L);
380 				break;
381 		}
382 
383 		/* Update our positional upval to reflect our new current position */
384 		lua_pushinteger(L, pos+1);
385 		lua_replace(L, lua_upvalueindex(1));
386 
387 		/* Returning 2 items on the stack (key, value) */
388 		return 2;
389 }
390 
391 /* Create the closure necessary to iterate over the array *a with the above function */
392 __attribute_noinline__
393 static int magnet_array_pairs(lua_State *L, array *a) {
394 	lua_pushinteger(L, 0); /* Push our current pos (the start) into upval 1 */
395 	lua_pushlightuserdata(L, a); /* Push our array *a into upval 2 */
396 	lua_pushcclosure(L, magnet_array_next, 2); /* Push our new closure with 2 upvals */
397 	return 1;
398 }
399 
400 #if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 503
401 #define LUA_RIDX_LIGHTTPD_REQUEST "li.request"
402 #endif
403 
404 #if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 503
405 __attribute_noinline__
406 #endif
407 static request_st * magnet_get_request(lua_State *L) {
408      #if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 503
409 	lua_getfield(L, LUA_REGISTRYINDEX, LUA_RIDX_LIGHTTPD_REQUEST);
410 	request_st * const r = lua_touserdata(L, -1);
411 	lua_pop(L, 1);
412 	return r;
413      #else
414 	return *(request_st **)lua_getextraspace(L);
415      #endif
416 }
417 
418 static void magnet_set_request(lua_State *L, request_st * const r) {
419      #if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 503
420 	lua_pushlightuserdata(L, r);
421 	lua_setfield(L, LUA_REGISTRYINDEX, LUA_RIDX_LIGHTTPD_REQUEST);
422      #else
423 	*(request_st **)lua_getextraspace(L) = r;
424      #endif
425 }
426 
427 #if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
428 __attribute_noinline__
429 #endif
430 static buffer * magnet_tmpbuf_acquire(lua_State *L)
431 {
432   #if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 503
433     UNUSED(L);
434     return chunk_buffer_acquire();
435   #else
436     request_st * const r = magnet_get_request(L);
437     buffer * const tb = r->tmp_buf;
438     buffer_clear(tb);
439     return tb;
440   #endif
441 }
442 
443 static void magnet_tmpbuf_release(buffer *b)
444 {
445   #if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 503
446     chunk_buffer_release(b);
447   #else
448     UNUSED(b);
449   #endif
450 }
451 
452 typedef struct {
453 	const char *ptr;
454 	size_t len;
455 } const_buffer;
456 
457 __attribute_noinline__
458 static const_buffer magnet_checkconstbuffer(lua_State *L, int idx) {
459 	const_buffer cb;
460 	if (!lua_isnoneornil(L, idx))
461 		cb.ptr = luaL_checklstring(L, idx, &cb.len);
462 	else {
463 		cb.ptr = NULL;
464 		cb.len = 0;
465 	}
466 	return cb;
467 }
468 
469 static const buffer* magnet_checkbuffer(lua_State *L, int idx, buffer *b) {
470 	const_buffer cb = magnet_checkconstbuffer(L, idx);
471 	/* assign result into (buffer *), and return (const buffer *)
472 	 * (note: caller must not free result) */
473 	*(const char **)&b->ptr = cb.ptr ? cb.ptr : "";
474 	b->used = cb.len+1;
475 	b->size = 0;
476 	return b;
477 }
478 
479 
480 static int magnet_return_upvalue2(lua_State *L) {
481     /*(XXX: is there a better way to do this?)*/
482     lua_pushvalue(L, lua_upvalueindex(1));
483     lua_pushvalue(L, lua_upvalueindex(2));
484     return 2;
485 }
486 
487 static int magnet_stat_field(lua_State *L) {
488     if (lua_gettop(L) != 2)
489         return 0; /*(should not happen; __index method in protected metatable)*/
490 
491     stat_cache_entry * const sce = *(stat_cache_entry **)lua_touserdata(L, -2);
492     const_buffer k = magnet_checkconstbuffer(L, -1);
493     switch (k.len ? k.ptr[0] : 0) {
494       case 'c': { /* content-type */
495         if (0 != strcmp(k.ptr, "content-type")) break;
496         request_st * const r = magnet_get_request(L);
497         const buffer *content_type = stat_cache_content_type_get(sce, r);
498         if (content_type && !buffer_is_blank(content_type))
499             lua_pushlstring(L, BUF_PTR_LEN(content_type));
500         else
501             lua_pushnil(L);
502         return 1;
503       }
504       case 'e': { /* etag */
505         if (0 != strcmp(k.ptr, "etag")) break;
506         request_st * const r = magnet_get_request(L);
507         const buffer *etag = stat_cache_etag_get(sce, r->conf.etag_flags);
508         if (etag && !buffer_is_blank(etag))
509             lua_pushlstring(L, BUF_PTR_LEN(etag));
510         else
511             lua_pushnil(L);
512         return 1;
513       }
514       case 'h': { /* http-response-send-file */
515         if (0 != strcmp(k.ptr, "http-response-send-file")) break;
516         request_st * const r = magnet_get_request(L);
517         http_response_send_file(r, &sce->name, sce);
518         lua_pushinteger(L, r->http_status);
519         return 1;
520       }
521       case 'i': /* is_* */
522         if (k.len < 4) break;
523         switch (k.ptr[3]) {
524           case 'b': /* is_block */
525             if (0 == strcmp(k.ptr, "is_block")) {
526                 lua_pushboolean(L, S_ISBLK(sce->st.st_mode));
527                 return 1;
528             }
529             break;
530           case 'c': /* is_char */
531             if (0 == strcmp(k.ptr, "is_char")) {
532                 lua_pushboolean(L, S_ISCHR(sce->st.st_mode));
533                 return 1;
534             }
535             break;
536           case 'd': /* is_dir */
537             if (0 == strcmp(k.ptr, "is_dir")) {
538                 lua_pushboolean(L, S_ISDIR(sce->st.st_mode));
539                 return 1;
540             }
541             break;
542           case 'f': /* is_file is_fifo */
543             if (0 == strcmp(k.ptr, "is_file")) {
544                 lua_pushboolean(L, S_ISREG(sce->st.st_mode));
545                 return 1;
546             }
547             if (0 == strcmp(k.ptr, "is_fifo")) {
548                 lua_pushboolean(L, S_ISFIFO(sce->st.st_mode));
549                 return 1;
550             }
551             break;
552           case 'l': /* is_link */
553             if (0 == strcmp(k.ptr, "is_link")) {
554                 lua_pushboolean(L, S_ISLNK(sce->st.st_mode));
555                 return 1;
556             }
557             break;
558           case 's': /* is_socket */
559             if (0 == strcmp(k.ptr, "is_socket")) {
560                 lua_pushboolean(L, S_ISSOCK(sce->st.st_mode));
561                 return 1;
562             }
563             break;
564           default:
565             break;
566         }
567         break;
568       case 's': /* st_* */
569         if (k.len < 4) break;
570         switch (k.ptr[3]) {
571           case 'a': /* st_atime */
572             if (0 == strcmp(k.ptr, "st_atime")) {
573                 lua_pushinteger(L, TIME64_CAST(sce->st.st_atime));
574                 return 1;
575             }
576             break;
577           case 'c': /* st_ctime */
578             if (0 == strcmp(k.ptr, "st_ctime")) {
579                 lua_pushinteger(L, TIME64_CAST(sce->st.st_ctime));
580                 return 1;
581             }
582             break;
583           case 'i': /* st_ino */
584             if (0 == strcmp(k.ptr, "st_ino")) {
585                 lua_pushinteger(L, sce->st.st_ino);
586                 return 1;
587             }
588             break;
589           case 'm': /* st_mtime st_mode */
590             if (0 == strcmp(k.ptr, "st_mtime")) {
591                 lua_pushinteger(L, TIME64_CAST(sce->st.st_mtime));
592                 return 1;
593             }
594             if (0 == strcmp(k.ptr, "st_mode")) {
595                 lua_pushinteger(L, sce->st.st_mode);
596                 return 1;
597             }
598             break;
599           case 'g': /* st_gid */
600             if (0 == strcmp(k.ptr, "st_gid")) {
601                 lua_pushinteger(L, sce->st.st_gid);
602                 return 1;
603             }
604             break;
605           case 's': /* st_size */
606             if (0 == strcmp(k.ptr, "st_size")) {
607                 lua_pushinteger(L, sce->st.st_size);
608                 return 1;
609             }
610             break;
611           case 'u': /* st_uid */
612             if (0 == strcmp(k.ptr, "st_uid")) {
613                 lua_pushinteger(L, sce->st.st_uid);
614                 return 1;
615             }
616             break;
617           default:
618             break;
619         }
620         break;
621       default:
622         break;
623     }
624 
625     lua_pushliteral(L, "stat[\"field\"] invalid: ");
626     lua_pushvalue(L, -2); /* field */
627     lua_concat(L, 2);
628     lua_error(L);
629     return 0;
630 }
631 
632 
633 __attribute_cold__
634 static int magnet_stat_pairs_noimpl_iter(lua_State *L) {
635     request_st * const r = magnet_get_request(L);
636     log_error(r->conf.errh, __FILE__, __LINE__,
637       "(lua) pairs() not implemented on lighty.stat object; "
638       "returning empty iter");
639     return 0;
640 }
641 
642 
643 __attribute_cold__
644 static int magnet_stat_pairs_noimpl(lua_State *L) {
645     lua_pushcclosure(L, magnet_stat_pairs_noimpl_iter, 0);
646     return 1;
647 }
648 
649 
650 static void magnet_stat_metatable(lua_State *L) {
651     if (luaL_newmetatable(L, "li.stat")) {                      /* (sp += 1) */
652         lua_pushcfunction(L, magnet_stat_field);                /* (sp += 1) */
653         lua_setfield(L, -2, "__index");                         /* (sp -= 1) */
654         lua_pushcfunction(L, magnet_newindex_readonly);         /* (sp += 1) */
655         lua_setfield(L, -2, "__newindex");                      /* (sp -= 1) */
656         lua_pushcfunction(L, magnet_stat_pairs_noimpl);         /* (sp += 1) */
657         lua_setfield(L, -2, "__pairs");                         /* (sp -= 1) */
658         lua_pushboolean(L, 0);                                  /* (sp += 1) */
659         lua_setfield(L, -2, "__metatable"); /* protect metatable   (sp -= 1) */
660     }
661 }
662 
663 
664 static int magnet_stat(lua_State *L) {
665     buffer stor; /*(note: do not free magnet_checkbuffer() result)*/
666     const buffer * const sb = magnet_checkbuffer(L, 1, &stor);
667     stat_cache_entry * const sce = (!buffer_is_blank(sb))
668       ? stat_cache_get_entry(sb)
669       : NULL;
670     if (NULL == sce) {
671         lua_pushnil(L);
672         return 1;
673     }
674 
675     /* note: caching sce valid only for procedural script which does not yield;
676      * (sce might not be valid if script yields and is later resumed)
677      * (script must not cache sce in persistent global state for later use)
678      * (If we did want sce to be persistent, then could increment sce refcnt,
679      *  and set up __gc metatable method to decrement sce refcnt) */
680     stat_cache_entry ** const udata =(struct stat_cache_entry**)/* (sp += 1) */
681       lua_newuserdata0(L, sizeof(stat_cache_entry *));
682     *udata = sce;
683 
684     magnet_stat_metatable(L);                                   /* (sp += 1) */
685     lua_setmetatable(L, -2);                                    /* (sp -= 1) */
686     return 1;
687 }
688 
689 
690 static int magnet_time(lua_State *L) {
691     lua_pushinteger(L, (lua_Integer)log_epoch_secs);
692     return 1;
693 }
694 
695 
696 static int magnet_hrtime(lua_State *L) {
697     unix_timespec64_t ts;
698     if (0 != log_clock_gettime_realtime(&ts))
699         return 0;
700     lua_pushinteger(L, (lua_Integer)ts.tv_sec);
701     lua_pushinteger(L, (lua_Integer)ts.tv_nsec);
702     return 2;
703 }
704 
705 
706 static int magnet_rand(lua_State *L) {
707     lua_pushinteger(L, (lua_Integer)li_rand_pseudo());
708     return 1;
709 }
710 
711 
712 static int magnet_md_once(lua_State *L) {
713     if (lua_gettop(L) != 2) {
714         lua_pushliteral(L,
715           "lighty.c.md(algo, data): incorrect number of arguments");
716         return lua_error(L);
717     }
718     const_buffer algo = magnet_checkconstbuffer(L, -2);
719     const_buffer msg  = magnet_checkconstbuffer(L, -1);
720     uint8_t digest[MD_DIGEST_LENGTH_MAX];
721     uint32_t dlen = 0;
722     switch (algo.len) {
723      #ifdef USE_LIB_CRYPTO
724       case 6:
725        #ifdef USE_LIB_CRYPTO_SHA512
726         if (0 == memcmp(algo.ptr, "sha512", 6)) {
727             SHA512_once(digest, msg.ptr, msg.len);
728             dlen = SHA512_DIGEST_LENGTH;
729             break;
730         }
731        #endif
732        #ifdef USE_LIB_CRYPTO_SHA256
733         if (0 == memcmp(algo.ptr, "sha256", 6)) {
734             SHA256_once(digest, msg.ptr, msg.len);
735             dlen = SHA256_DIGEST_LENGTH;
736             break;
737         }
738        #endif
739         break;
740       case 4:
741        #ifdef USE_LIB_CRYPTO_SHA1
742         if (0 == memcmp(algo.ptr, "sha1", 4)) {
743             SHA1_once(digest, msg.ptr, msg.len);
744             dlen = SHA1_DIGEST_LENGTH;
745             break;
746         }
747        #endif
748         break;
749      #endif
750       case 3:
751         if (0 == memcmp(algo.ptr, "md5", 3)) {
752             MD5_once(digest, msg.ptr, msg.len);
753             dlen = MD5_DIGEST_LENGTH;
754             break;
755         }
756         break;
757       default:
758         break;
759     }
760 
761     if (dlen) {
762         char dighex[MD_DIGEST_LENGTH_MAX*2+1];
763         li_tohex_uc(dighex, sizeof(dighex), (char *)digest, dlen);
764         lua_pushlstring(L, dighex, dlen*2);
765     }
766     else
767         lua_pushnil(L);
768 
769     return 1;
770 }
771 
772 static int magnet_hmac_once(lua_State *L) {
773     if (lua_gettop(L) != 3) {
774         lua_pushliteral(L,
775           "lighty.c.hmac(algo, secret, data): incorrect number of arguments");
776         return lua_error(L);
777     }
778     const_buffer algo   = magnet_checkconstbuffer(L, -3);
779     const_buffer secret = magnet_checkconstbuffer(L, -2);
780     const_buffer msg    = magnet_checkconstbuffer(L, -1);
781     const uint8_t * const msgptr = (uint8_t *)msg.ptr;
782     uint8_t digest[MD_DIGEST_LENGTH_MAX];
783     uint32_t dlen = 0;
784     int rc = 0;
785     switch (algo.len) {
786      #ifdef USE_LIB_CRYPTO
787       case 6:
788        #ifdef USE_LIB_CRYPTO_SHA512
789         if (0 == memcmp(algo.ptr, "sha512", 6)) {
790             rc = li_hmac_sha512(digest,secret.ptr,secret.len,msgptr,msg.len);
791             dlen = SHA512_DIGEST_LENGTH;
792             break;
793         }
794        #endif
795        #ifdef USE_LIB_CRYPTO_SHA256
796         if (0 == memcmp(algo.ptr, "sha256", 6)) {
797             rc = li_hmac_sha256(digest,secret.ptr,secret.len,msgptr,msg.len);
798             dlen = SHA256_DIGEST_LENGTH;
799             break;
800         }
801        #endif
802         break;
803       case 4:
804        #ifdef USE_LIB_CRYPTO_SHA1
805         if (0 == memcmp(algo.ptr, "sha1", 4)) {
806             rc = li_hmac_sha1(digest,secret.ptr,secret.len,msgptr,msg.len);
807             dlen = SHA1_DIGEST_LENGTH;
808             break;
809         }
810        #endif
811         break;
812      #endif
813       case 3:
814         if (0 == memcmp(algo.ptr, "md5", 3)) {
815             rc = li_hmac_md5(digest,secret.ptr,secret.len,msgptr,msg.len);
816             dlen = MD5_DIGEST_LENGTH;
817             break;
818         }
819         break;
820       default:
821         break;
822     }
823 
824     if (rc) {
825         char dighex[MD_DIGEST_LENGTH_MAX*2+1];
826         li_tohex_uc(dighex, sizeof(dighex), (char *)digest, dlen);
827         lua_pushlstring(L, dighex, dlen*2);
828     }
829     else
830         lua_pushnil(L);
831 
832     return 1;
833 }
834 
835 static int magnet_digest_eq(lua_State *L) {
836     if (lua_gettop(L) != 2) {
837         lua_pushliteral(L,
838           "lighty.c.digest_eq(d1, d2): incorrect number of arguments");
839         return lua_error(L);
840     }
841     const_buffer d1 = magnet_checkconstbuffer(L, -2);
842     const_buffer d2 = magnet_checkconstbuffer(L, -1);
843     /* convert hex to binary: validate hex and eliminate hex case comparison */
844     uint8_t b1[MD_DIGEST_LENGTH_MAX];
845     uint8_t b2[MD_DIGEST_LENGTH_MAX];
846     int rc = (d1.len == d2.len)
847           && 0 == li_hex2bin(b1, sizeof(b1), d1.ptr, d1.len)
848           && 0 == li_hex2bin(b2, sizeof(b2), d2.ptr, d2.len)
849           && ck_memeq_const_time_fixed_len(b1, b2, d2.len >> 1);
850     lua_pushboolean(L, rc);
851     return 1;
852 }
853 
854 static int magnet_secret_eq(lua_State *L) {
855     if (lua_gettop(L) != 2) {
856         lua_pushliteral(L,
857           "lighty.c.secret_eq(d1, d2): incorrect number of arguments");
858         return lua_error(L);
859     }
860     const_buffer d1 = magnet_checkconstbuffer(L, -2);
861     const_buffer d2 = magnet_checkconstbuffer(L, -1);
862     lua_pushboolean(L, ck_memeq_const_time(d1.ptr, d1.len, d2.ptr, d2.len));
863     return 1;
864 }
865 
866 static int magnet_b64dec(lua_State *L, base64_charset dict) {
867     if (lua_isnoneornil(L, -1)) {
868         lua_pushlstring(L, "", 0);
869         return 1;
870     }
871     const_buffer s = magnet_checkconstbuffer(L, -1);
872     if (0 == s.len) {
873         lua_pushvalue(L, -1);
874         return 1;
875     }
876     buffer * const b = magnet_tmpbuf_acquire(L);
877     if (buffer_append_base64_decode(b, s.ptr, s.len, dict))
878         lua_pushlstring(L, BUF_PTR_LEN(b));
879     else
880         lua_pushnil(L);
881     magnet_tmpbuf_release(b);
882     return 1;
883 }
884 
885 static int magnet_b64enc(lua_State *L, base64_charset dict) {
886     if (lua_isnoneornil(L, -1)) {
887         lua_pushlstring(L, "", 0);
888         return 1;
889     }
890     const_buffer s = magnet_checkconstbuffer(L, -1);
891     if (0 == s.len) {
892         lua_pushvalue(L, -1);
893         return 1;
894     }
895     buffer * const b = magnet_tmpbuf_acquire(L);
896     buffer_append_base64_encode_no_padding(b, (uint8_t *)s.ptr, s.len, dict);
897     lua_pushlstring(L, BUF_PTR_LEN(b));
898     magnet_tmpbuf_release(b);
899     return 1;
900 }
901 
902 static int magnet_b64urldec(lua_State *L) {
903     return magnet_b64dec(L, BASE64_URL);
904 }
905 
906 static int magnet_b64urlenc(lua_State *L) {
907     return magnet_b64enc(L, BASE64_URL);
908 }
909 
910 static int magnet_b64stddec(lua_State *L) {
911     return magnet_b64dec(L, BASE64_STANDARD);
912 }
913 
914 static int magnet_b64stdenc(lua_State *L) {
915     return magnet_b64enc(L, BASE64_STANDARD);
916 }
917 
918 static int magnet_hexdec(lua_State *L) {
919     if (lua_isnoneornil(L, -1)) {
920         lua_pushlstring(L, "", 0);
921         return 1;
922     }
923     const_buffer s = magnet_checkconstbuffer(L, -1);
924     if (0 == s.len) {
925         lua_pushvalue(L, -1);
926         return 1;
927     }
928     buffer * const b = magnet_tmpbuf_acquire(L);
929     uint8_t * const p = (uint8_t *)buffer_extend(b, s.len >> 1);
930     int rc = li_hex2bin(p, s.len >> 1, s.ptr, s.len);
931     if (0 == rc)
932         lua_pushlstring(L, BUF_PTR_LEN(b));
933     magnet_tmpbuf_release(b);
934     return rc+1; /* 1 on success (pushed string); 0 on failure (no value) */
935 }
936 
937 static int magnet_hexenc(lua_State *L) {
938     if (lua_isnoneornil(L, -1)) {
939         lua_pushlstring(L, "", 0);
940         return 1;
941     }
942     const_buffer s = magnet_checkconstbuffer(L, -1);
943     if (0 == s.len) {
944         lua_pushvalue(L, -1);
945         return 1;
946     }
947     buffer * const b = magnet_tmpbuf_acquire(L);
948     buffer_append_string_encoded_hex_uc(b, s.ptr, s.len);
949     lua_pushlstring(L, BUF_PTR_LEN(b));
950     magnet_tmpbuf_release(b);
951     return 1; /* uppercase hex string; use lua s = s:lower() to lowercase */
952 }
953 
954 static int magnet_quoteddec(lua_State *L) {
955     if (lua_isnoneornil(L, -1)) {
956         lua_pushlstring(L, "", 0);
957         return 1;
958     }
959     const_buffer s = magnet_checkconstbuffer(L, -1);
960     if (0 == s.len || s.ptr[0] != '"') {
961         lua_pushvalue(L, -1);
962         return 1;
963     }
964     buffer * const b = magnet_tmpbuf_acquire(L);
965     char *p = buffer_string_prepare_append(b, s.len);/*(s.len-1 is sufficient)*/
966     size_t i = 1;
967     for (; i < s.len && s.ptr[i] != '"'; ++i) {
968         if (s.ptr[i] == '\\') {
969             if (i+2 < s.len)
970                 ++i;
971             else
972                 break;
973         }
974         *p++ = s.ptr[i];
975     }
976     int rc = (i == s.len-1 && s.ptr[i] == '"');
977     if (rc)
978         lua_pushlstring(L, b->ptr, (size_t)(p - b->ptr));
979     magnet_tmpbuf_release(b);
980     return rc; /* 1 on success (pushed string); 0 on failure (no value) */
981 }
982 
983 static int magnet_quotedenc(lua_State *L) {
984     if (lua_isnoneornil(L, -1)) {
985         lua_pushlstring(L, "", 0);
986         return 1;
987     }
988     const_buffer s = magnet_checkconstbuffer(L, -1);
989     if (0 == s.len) {
990         lua_pushvalue(L, -1);
991         return 1;
992     }
993     buffer * const b = magnet_tmpbuf_acquire(L);
994     char *p = buffer_string_prepare_append(b, 2+(s.len << 1));
995     *p++ = '"';
996     for (size_t i = 0; i < s.len; ++i) {
997         /*(note: not strictly checking for TEXT)*/
998         /*(TEXT: any OCTET except CTLs but including LWS)*/
999         if (s.ptr[i] == '"' || s.ptr[i] == '\\')
1000             *p++ = '\\';
1001         *p++ = s.ptr[i];
1002     }
1003     *p++ = '"';
1004     lua_pushlstring(L, b->ptr, (size_t)(p - b->ptr));
1005     magnet_tmpbuf_release(b);
1006     return 1;
1007 }
1008 
1009 static int magnet_xmlenc(lua_State *L) {
1010     if (lua_isnoneornil(L, -1)) {
1011         lua_pushlstring(L, "", 0);
1012         return 1;
1013     }
1014     const_buffer s = magnet_checkconstbuffer(L, -1);
1015     if (0 == s.len) {
1016         lua_pushvalue(L, -1);
1017         return 1;
1018     }
1019     buffer * const b = magnet_tmpbuf_acquire(L);
1020   #if 1
1021     buffer_append_string_encoded(b, s.ptr, s.len, ENCODING_MINIMAL_XML);
1022   #else
1023     const char *e;
1024     size_t i, n, elen;
1025     for (i = 0, n = 0; i < s.len; ++i) {
1026         switch (s.ptr[i]) {
1027           default: continue;
1028           case '<':  e = "&lt;";   elen = sizeof("&lt;")-1;   break;
1029           case '>':  e = "&gt;";   elen = sizeof("&gt;")-1;   break;
1030           case '&':  e = "&amp;";  elen = sizeof("&amp;")-1;  break;
1031           case '\'': e = "&apos;"; elen = sizeof("&apos;")-1; break;
1032           case '"':  e = "&quot;"; elen = sizeof("&quot;")-1; break;
1033           /*(XXX: would be good idea to add CTRLs, DEL, '`' */
1034         }
1035         buffer_append_str2(b, s.ptr+n, i-n, e, elen);
1036         n = i+1;
1037     }
1038     if (i-n)
1039         buffer_append_string_len(b, s.ptr+n, i-n);
1040   #endif
1041     lua_pushlstring(L, BUF_PTR_LEN(b));
1042     magnet_tmpbuf_release(b);
1043     return 1;
1044 }
1045 
1046 static int magnet_urldec(lua_State *L) {
1047     /* url-decode and replace non-printable chars with '_'
1048      * This function should not be used on query-string unless it is used on
1049      * portions of query-string after splitting on '&', replacing '+' w/ ' ' */
1050     if (lua_isnoneornil(L, -1)) {
1051         lua_pushlstring(L, "", 0);
1052         return 1;
1053     }
1054     const_buffer s = magnet_checkconstbuffer(L, -1);
1055     if (0 == s.len) {
1056         lua_pushvalue(L, -1);
1057         return 1;
1058     }
1059     buffer * const b = magnet_tmpbuf_acquire(L);
1060     buffer_copy_string_len(b, s.ptr, s.len);
1061     buffer_urldecode_path(b);
1062     lua_pushlstring(L, BUF_PTR_LEN(b));
1063     magnet_tmpbuf_release(b);
1064     return 1;
1065 }
1066 
1067 static int magnet_urlenc(lua_State *L) {
1068     /* url-encode path
1069      * ('?' is encoded, if present)
1070      *  caller must split string if '?' is part of query-string)
1071      * ('/' is not encoded; caller must encode if not path separator) */
1072     if (lua_isnoneornil(L, -1)) {
1073         lua_pushlstring(L, "", 0);
1074         return 1;
1075     }
1076     const_buffer s = magnet_checkconstbuffer(L, -1);
1077     if (0 == s.len) {
1078         lua_pushvalue(L, -1);
1079         return 1;
1080     }
1081     buffer * const b = magnet_tmpbuf_acquire(L);
1082     buffer_append_string_encoded(b, s.ptr, s.len, ENCODING_REL_URI);
1083     lua_pushlstring(L, BUF_PTR_LEN(b));
1084     magnet_tmpbuf_release(b);
1085     return 1;
1086 }
1087 
1088 static void magnet_urldec_query_part(buffer * const b, const char *s, const size_t slen) {
1089     buffer_clear(b);
1090     char *p = buffer_extend(b, slen);
1091     for (size_t i = 0; i < slen; ++i)
1092         p[i] = (s[i] != '+') ? s[i] : ' ';
1093     buffer_urldecode_path(b);
1094 }
1095 
1096 static int magnet_urldec_query(lua_State *L) {
1097     /* split on '&' and '=', url-decode and replace non-printable chars w/ '_',
1098      * and store components in table
1099      * (string input should be query-string without leading '?')
1100      * (note: duplicated keys replace earlier values, but this interface returns
1101      *  a table useful for lookups, so this limitation is often acceptable) */
1102     lua_createtable(L, 0, 0);
1103     if (lua_isnoneornil(L, 1)) {
1104         return 1;
1105     }
1106     const_buffer s = magnet_checkconstbuffer(L, 1);
1107     if (0 == s.len) {
1108         return 1;
1109     }
1110     buffer * const b = magnet_tmpbuf_acquire(L);
1111     for (const char *qs = s.ptr, *eq, *amp; *qs; qs = amp+1) {
1112         for (amp = qs, eq = NULL; *amp && *amp != '&'; ++amp) {
1113             if (*amp == '=' && !eq) eq = amp;
1114         }
1115         if (amp != qs) {
1116             if (eq) {
1117                 magnet_urldec_query_part(b, qs, (size_t)(eq - qs));
1118                 lua_pushlstring(L, BUF_PTR_LEN(b));
1119                 magnet_urldec_query_part(b, eq+1, (size_t)(amp - (eq+1)));
1120                 lua_pushlstring(L, BUF_PTR_LEN(b));
1121             }
1122             else {
1123                 magnet_urldec_query_part(b, qs, (size_t)(amp - qs));
1124                 lua_pushlstring(L, BUF_PTR_LEN(b));
1125                 lua_pushlstring(L, "", 0); /*(lua_pushnil() would delete key)*/
1126             }
1127             lua_rawset(L, -3);
1128         }
1129         if (*amp == '\0') break;
1130     }
1131     magnet_tmpbuf_release(b);
1132     return 1;
1133 }
1134 
1135 static void magnet_urlenc_query_part(buffer * const b, const char * const s, const size_t slen, const int iskey) {
1136     /* encode query part (each part is typically much smaller than chunk buffer)
1137      * all required chars plus '&' ';' '+' '\'' (and encode '=' if part of key)
1138      * (burl_append(b,str,len,BURL_ENCODE_ALL) works, but over-encodes) */
1139   #if 0
1140     /* alternative: (over-encodes some, but less than burl_append()) */
1141     UNUSED(iskey);
1142     buffer_append_string_encoded(b, s, slen, ENCODING_REL_URI);
1143   #else
1144     static const char hex_chars_uc[] = "0123456789ABCDEF";
1145     char * const p = buffer_string_prepare_append(b, slen*3);
1146     int j = 0;
1147     for (size_t i = 0; i < slen; ++i, ++j) {
1148         int c = s[i];
1149         if (!light_isalnum(c)) switch (c) {
1150           case ' ':
1151             c = '+';
1152             break;
1153           /*case '\'':*//*(ok in url query-part, but might be misused in HTML)*/
1154           case '!': case '$': case '(': case ')': case '*': case ',': case '-':
1155           case '.': case '/': case ':': case '?': case '@': case '_': case '~':
1156             break;
1157           case '=':
1158             if (!iskey) break;
1159             __attribute_fallthrough__
1160           default:
1161             p[j]   = '%';
1162             p[++j] = hex_chars_uc[(s[i] >> 4) & 0xF];
1163             p[++j] = hex_chars_uc[s[i] & 0xF];
1164             continue;
1165         }
1166         p[j] = c;
1167     }
1168     buffer_commit(b, j);
1169   #endif
1170 }
1171 
1172 static int magnet_urlenc_query(lua_State *L) {
1173     /* encode pairs in lua table into query string
1174      * (caller should add leading '?' or '&' when appending to full URL)
1175      * (caller should skip empty table if appending to existing query-string) */
1176     if (!lua_istable(L, 1)) {
1177         lua_pushlstring(L, "", 0);
1178         return 1;
1179     }
1180     buffer * const b = magnet_tmpbuf_acquire(L);
1181     const_buffer s;
1182     for (lua_pushnil(L); lua_next(L, -2); lua_pop(L, 1)) {
1183         if (lua_isstring(L, -2)) {
1184             if (!buffer_is_blank(b))
1185                 buffer_append_string_len(b, CONST_STR_LEN("&"));
1186             s = magnet_checkconstbuffer(L, -2);
1187             magnet_urlenc_query_part(b, s.ptr, s.len, 1);
1188             if (!lua_isnil(L, -1)) {
1189                 s = magnet_checkconstbuffer(L, -1);
1190                 buffer_append_string_len(b, CONST_STR_LEN("="));
1191                 magnet_urlenc_query_part(b, s.ptr, s.len, 0);
1192             }
1193         }
1194     }
1195     lua_pushlstring(L, BUF_PTR_LEN(b));
1196     magnet_tmpbuf_release(b);
1197     return 1;
1198 }
1199 
1200 static int magnet_urlenc_normalize(lua_State *L) {
1201     /* normalize url-encoding
1202      * url-encode (and url-decode safe chars) to normalize url-path
1203      * ('?' is treated as start of query-string and is not encoded;
1204      *  caller must encode '?' if intended to be part of url-path)
1205      * ('/' is not encoded; caller must encode if not path separator)
1206      * (burl_append() is not exposed here; caller might want to build
1207      *  url with lighty.c.urlenc() and lighty.c.urlenc_query(),
1208      *  then call lighty.c.urlenc_normalize()) */
1209     if (lua_isnoneornil(L, -1)) {
1210         lua_pushlstring(L, "", 0);
1211         return 1;
1212     }
1213     const_buffer s = magnet_checkconstbuffer(L, -1);
1214     if (0 == s.len) {
1215         lua_pushvalue(L, -1);
1216         return 1;
1217     }
1218     buffer * const b = magnet_tmpbuf_acquire(L);
1219     buffer * const t = chunk_buffer_acquire();
1220   #if 0 /*(?maybe have different interface to use config policy?)*/
1221     request_st * const r = magnet_get_request(L);
1222     const int flags = r->conf.http_parseopts;
1223   #else
1224     const int flags = HTTP_PARSEOPT_URL_NORMALIZE
1225                     | HTTP_PARSEOPT_URL_NORMALIZE_UNRESERVED
1226                     | HTTP_PARSEOPT_URL_NORMALIZE_REQUIRED
1227                     | HTTP_PARSEOPT_URL_NORMALIZE_PATH_2F_DECODE
1228                     | HTTP_PARSEOPT_URL_NORMALIZE_PATH_DOTSEG_REMOVE
1229                     | HTTP_PARSEOPT_URL_NORMALIZE_QUERY_20_PLUS;
1230   #endif
1231     buffer_copy_string_len(b, s.ptr, s.len);
1232     burl_normalize(b, t, flags);
1233     lua_pushlstring(L, BUF_PTR_LEN(b));
1234     chunk_buffer_release(t);
1235     magnet_tmpbuf_release(b);
1236     return 1;
1237 }
1238 
1239 static int magnet_fspath_simplify(lua_State *L) {
1240     /* simplify filesystem path */
1241     if (lua_isnoneornil(L, -1)) {
1242         lua_pushlstring(L, "", 0);
1243         return 1;
1244     }
1245     const_buffer s = magnet_checkconstbuffer(L, -1);
1246     if (0 == s.len) {
1247         lua_pushvalue(L, -1);
1248         return 1;
1249     }
1250     buffer * const b = magnet_tmpbuf_acquire(L);
1251     buffer_copy_string_len(b, s.ptr, s.len);
1252     buffer_path_simplify(b);
1253     lua_pushlstring(L, BUF_PTR_LEN(b));
1254     magnet_tmpbuf_release(b);
1255     return 1;
1256 }
1257 
1258 __attribute_pure__
1259 static const char * magnet_scan_quoted_string (const char *s) {
1260     /* scan to end of of quoted-string (with s starting at '"')
1261      * loose parse; non-validating
1262      * - permit missing '"' at end of string (caller should check)
1263      * - stop at stray '\\' at end of string missing closing '"'
1264      * - not rejecting non-WS CTL chars
1265      */
1266     /*force_assert(*s == '"');*/
1267     do { ++s; } while (*s && *s != '"' && (*s != '\\' || (s[1] ? ++s : 0)));
1268     /*do { ++s; } while (*s && *s != '"' && (*s != '\\' || (*++s || (--s, 0))));*/
1269     return s;
1270 }
1271 
1272 static const char * magnet_push_quoted_string_range (lua_State *L, const char *b, const char *s) {
1273     /* quoted-string is unmodified (except for quoted-string end consistency)
1274      * including surrounding double-quotes and with quoted-pair unmodified */
1275     if (__builtin_expect( (*s == '"'), 1))
1276         lua_pushlstring(L, b, (size_t)(++s-b));
1277     else { /*(else invalid quoted-string, but handle anyway)*/
1278         /* append closing '"' for consistency */
1279         lua_pushlstring(L, b, (size_t)(s-b));
1280         if (*s != '\\')
1281             lua_pushlstring(L, "\"", 1);
1282         else { /* unescaped backslash at end of string; escape and close '"' */
1283             lua_pushlstring(L, "\\\\\"", 3);
1284             ++s; /*(now *s == '\0')*/
1285         }
1286         lua_concat(L, 2);
1287     }
1288     return s;
1289 }
1290 
1291 static const char * magnet_push_quoted_string(lua_State *L, const char *s) {
1292     return magnet_push_quoted_string_range(L, s, magnet_scan_quoted_string(s));
1293 }
1294 
1295 static const char * magnet_cookie_param_push_token(lua_State *L, const char *s) {
1296     const char *b = s;
1297     while (*s!='=' /*(note: not strictly rejecting all 'separators')*/
1298             && *s!=';' && *s!=' ' && *s!='\t' && *s!='\r' && *s!='\n' && *s)
1299         ++s;
1300     lua_pushlstring(L, b, (size_t)(s-b));
1301     return s;
1302 }
1303 
1304 static int magnet_cookie_tokens(lua_State *L) {
1305     /*(special-case cookies (';' separator); dup cookie-names overwritten)*/
1306     lua_createtable(L, 0, 0);
1307     if (lua_isnoneornil(L, 1))
1308         return 1;
1309     const char *s = luaL_checkstring(L, 1);
1310     do {
1311         while (*s==';' || *s==' ' || *s=='\t' || *s=='\r' || *s=='\n')
1312             ++s;
1313         if (*s == '\0') break;
1314         s = magnet_cookie_param_push_token(L, s);
1315         while (           *s==' ' || *s=='\t' || *s=='\r' || *s=='\n')
1316             ++s;
1317         if (*s == '=') {
1318             do {
1319                 ++s;
1320             } while (     *s==' ' || *s=='\t' || *s=='\r' || *s=='\n');
1321             if (*s==';' || *s=='\0')
1322                 lua_pushlstring(L, "", 0); /*(lua_pushnil() would delete key)*/
1323             else if (*s != '"')
1324                 s = magnet_cookie_param_push_token(L, s);
1325             else
1326                 s = magnet_push_quoted_string(L, s);
1327         }
1328         else {
1329             lua_pushlstring(L, "", 0); /*(lua_pushnil() would delete key)*/
1330         }
1331         lua_settable(L, -3);
1332         while (*s!=';' && *s!='\0') ++s; /* ignore/skip stray tokens */
1333     } while (*s++);
1334     return 1;
1335 }
1336 
1337 static const char * magnet_push_token(lua_State *L, const char *s) {
1338     const char *b = s;
1339     while (               *s!=' ' && *s!='\t' && *s!='\r' && *s!='\n'
1340            && *s!=',' && *s!=';' && *s!='=' && *s)
1341         ++s;
1342     lua_pushlstring(L, b, (size_t)(s-b));
1343     return s;
1344 }
1345 
1346 static int magnet_header_tokens(lua_State *L) {
1347     /* split into sequence of tokens/words
1348      *   Intermediate table is then more convenient to walk once quoted-string
1349      *   parsed into table entries since quoted-string may contain separators.
1350      *   Each token can be passed to lighty.c.quoteddec()
1351      *     (lighty.c.quoteddec() returns string as-is if not quoted-string)
1352      * (note: non-validating;
1353      *  e.g. existence of '=' token does not mean that next token is value,
1354      *       and '=' in value which is not part of quoted-string will be
1355      *       treated as separate token)
1356      * (note: case is preserved; non-quoted-string tokens are not lower-cased)
1357      * (words separated by whitespace are separate tokens unless quoted-string)
1358      *   (if that format not permitted in a specific header, caller must detect)
1359      * (optional whitespace (OWS) and bad whitespace (BWS) are removed)
1360      * (caller can create lookup table from sequence table, as appropriate) */
1361     lua_createtable(L, 0, 0);
1362     if (lua_isnoneornil(L, 1))
1363         return 1;
1364     const char *s = luaL_checkstring(L, 1);
1365     int i = 0;
1366     do {
1367         while (           *s==' ' || *s=='\t' || *s=='\r' || *s=='\n')
1368             ++s;
1369         if (*s=='\0') break;
1370         if (*s==',' || *s==';' || *s=='=')
1371             lua_pushlstring(L, s++, 1);
1372         else if (*s != '"')
1373             s = magnet_push_token(L, s);
1374         else
1375             s = magnet_push_quoted_string(L, s);
1376         lua_rawseti(L, -2, ++i);
1377     } while (*s);
1378     return 1;
1379 }
1380 
1381 static int magnet_reqhdr_get(lua_State *L) {
1382     size_t klen;
1383     const char * const k = luaL_checklstring(L, 2, &klen);
1384     const request_st * const r = **(request_st ***)lua_touserdata(L, 1);
1385     const int id = http_header_hkey_get(k, (uint32_t)klen);
1386     magnet_push_buffer(L, http_header_request_get(r, id, k, klen));
1387     return 1;
1388 }
1389 
1390 static int magnet_reqhdr_set(lua_State *L) {
1391     const_buffer k = magnet_checkconstbuffer(L, 2);
1392     const_buffer v = magnet_checkconstbuffer(L, 3);
1393 
1394     request_st * const r = **(request_st ***)lua_touserdata(L, 1);
1395     enum http_header_e id = http_header_hkey_get(k.ptr, (uint32_t)k.len);
1396 
1397     switch (id) {
1398       /*case HTTP_HEADER_OTHER:*/
1399       default:
1400         break;
1401 
1402       case HTTP_HEADER_HOST:
1403         /* do not allow Host to be unset, even if HTTP/1.0
1404          * (change Host to something else, if you must */
1405         if (0 == v.len) return 0;
1406 
1407         /*(must set r->http_host if r->http_host was not previously set)*/
1408         /* copied from request.c:http_request_header_set_Host() */
1409         r->http_host = http_header_request_set_ptr(r, HTTP_HEADER_HOST,
1410                                                    CONST_STR_LEN("Host"));
1411         buffer_copy_string_len_lc(r->http_host, v.ptr, v.len);
1412         return 0;
1413 
1414       case HTTP_HEADER_CONTENT_LENGTH:
1415         /* not attempting to handle Content-Length modification; may revisit */
1416         /* future: might permit setting to 0 to force discard of request body
1417          * but would have to check if request body present, and if
1418          * Content-Length was set, or if Transfer-Encoding: chunked,
1419          * and handle resetting internal chunked encoding state,
1420          * as well as making sure that this is handled properly for HTTP/2 */
1421         return 0; /* silently ignore; do not allow modification */
1422 
1423       /* do not permit modification of hop-by-hop (connection) headers */
1424 
1425       case HTTP_HEADER_CONNECTION:
1426         /* do not permit modification of Connection, incl add/remove tokens */
1427         /* future: might provide a different interface to set r->keep_alive = 0,
1428          *         and also handle in context if HTTP/2 */
1429       case HTTP_HEADER_TRANSFER_ENCODING:
1430       case HTTP_HEADER_SET_COOKIE:/*(response hdr;avoid accidental reflection)*/
1431         return 0; /* silently ignore; do not allow modification */
1432      #if 0 /*(eh, if script sets Upgrade, script probably intends this action)*/
1433       case HTTP_HEADER_UPGRADE:
1434         /* note: modifications here do not modify Connection header
1435          *       to add or remove "upgrade" token */
1436         /* future: might allow removal of existing tokens, but not addition */
1437         if (0 != v.len) return 0; /* do not allow Upgrade other than to unset */
1438         break;
1439      #endif
1440      #if 0 /*(eh, if script sets TE, script probably intends this action)*/
1441       case HTTP_HEADER_TE:
1442         if (0 != v.len) return 0; /* do not allow TE other than to unset */
1443         break;
1444      #endif
1445     }
1446 
1447     v.len
1448       ? http_header_request_set(r, id, k.ptr, k.len, v.ptr, v.len)
1449       : http_header_request_unset(r, id, k.ptr, k.len);
1450     return 0;
1451 }
1452 
1453 static int magnet_reqhdr_pairs(lua_State *L) {
1454     request_st * const r = **(request_st ***)lua_touserdata(L, 1);
1455     return magnet_array_pairs(L, &r->rqst_headers);
1456 }
1457 
1458 static int magnet_resphdr_get(lua_State *L) {
1459     /* Note: access to lighttpd r->resp_headers here is *independent* from
1460      * the (pending) changes in the (deprecated) lua lighty.headers[] table */
1461     size_t klen;
1462     const char * const k = luaL_checklstring(L, 2, &klen);
1463     const request_st * const r = **(request_st ***)lua_touserdata(L, 1);
1464     const int id = http_header_hkey_get(k, (uint32_t)klen);
1465     magnet_push_buffer(L, http_header_response_get(r, id, k, klen));
1466     return 1;
1467 }
1468 
1469 static int magnet_resphdr_set_kv(lua_State *L, request_st * const r) {
1470     const const_buffer k = magnet_checkconstbuffer(L, -2);
1471     const const_buffer v = magnet_checkconstbuffer(L, -1);
1472     const enum http_header_e id = http_header_hkey_get(k.ptr, (uint32_t)k.len);
1473 
1474     switch (id) {
1475       /*case HTTP_HEADER_OTHER:*/
1476       default:
1477         break;
1478 
1479       case HTTP_HEADER_CONTENT_LENGTH:
1480         /* lighttpd handles Content-Length or Transfer-Encoding for response */
1481         return 0; /* silently ignore; do not allow modification */
1482 
1483       /* do not permit modification of hop-by-hop (connection) headers */
1484 
1485       case HTTP_HEADER_CONNECTION:
1486         /* do not permit modification of Connection, incl add/remove tokens */
1487         /* future: might provide a different interface to set r->keep_alive = 0,
1488          *         and also handle in context if HTTP/2 */
1489       case HTTP_HEADER_TRANSFER_ENCODING:
1490         return 0; /* silently ignore; do not allow modification */
1491     }
1492 
1493     if (0 == v.len) {
1494         http_header_response_unset(r, id, k.ptr, k.len);
1495         return 0;
1496     }
1497 
1498     buffer * const vb = http_header_response_set_ptr(r, id, k.ptr, k.len);
1499     buffer_copy_string_len(vb, v.ptr, v.len);
1500 
1501     if (r->http_version >= HTTP_VERSION_2) {
1502         /* handle multi-line response headers with HTTP/2
1503          * (lowercase header name and mark r->resp_header_repeated)
1504          * (similar to http_header.c:http_header_response_insert_addtl()) */
1505         for (char *n = vb->ptr; (n = strchr(n, '\n')); ) {
1506             r->resp_header_repeated = 1;
1507             do {
1508                 ++n;
1509                 if (light_isupper(*n)) *n |= 0x20;
1510             } while (*n != ':' && *n != '\n' && *n != '\0');
1511         }
1512     }
1513 
1514     return 0;
1515 }
1516 
1517 static int magnet_resphdr_set(lua_State *L) {
1518     /*const_buffer k = magnet_checkconstbuffer(L, 2);*/
1519     /*const_buffer v = magnet_checkconstbuffer(L, 3);*/
1520     request_st * const r = **(request_st ***)lua_touserdata(L, 1);
1521     return magnet_resphdr_set_kv(L, r);
1522 }
1523 
1524 static int magnet_resphdr_pairs(lua_State *L) {
1525     request_st * const r = **(request_st ***)lua_touserdata(L, 1);
1526     return magnet_array_pairs(L, &r->resp_headers);
1527 }
1528 
1529 static int magnet_status_get(lua_State *L) {
1530 	/* __index: param 1 is the (empty) table the value was not found in */
1531 	const_buffer key = magnet_checkconstbuffer(L, 2);
1532 	int *i = status_counter_get_counter(key.ptr, key.len);
1533 	lua_pushinteger(L, (lua_Integer)*i);
1534 
1535 	return 1;
1536 }
1537 
1538 static int magnet_status_set(lua_State *L) {
1539 	/* __newindex: param 1 is the (empty) table the value is supposed to be set in */
1540 	const_buffer key = magnet_checkconstbuffer(L, 2);
1541 	int counter = (int) luaL_checkinteger(L, 3);
1542 
1543 	status_counter_set(key.ptr, key.len, counter);
1544 
1545 	return 0;
1546 }
1547 
1548 static int magnet_status_pairs(lua_State *L) {
1549 	return magnet_array_pairs(L, &plugin_stats);
1550 }
1551 
1552 
1553 static int
1554 magnet_req_item_get (lua_State *L)
1555 {
1556     size_t klen;
1557     const char * const k = luaL_checklstring(L, 2, &klen);
1558     request_st * const r = **(request_st ***)lua_touserdata(L, 1);
1559     switch (klen) {
1560       case 8:
1561         if (0 == memcmp(k, "bytes_in", 8)) {
1562             off_t bytes = r->http_version <= HTTP_VERSION_1_1
1563               ? r->con->bytes_read - r->bytes_read_ckpt
1564               : r->read_queue.bytes_in;
1565             lua_pushinteger(L, (lua_Integer)bytes);
1566             return 1;
1567         }
1568         break;
1569       case 9:
1570         if (0 == memcmp(k, "bytes_out", 9)) {
1571             off_t bytes = r->http_version <= HTTP_VERSION_1_1
1572               ? r->con->bytes_written - r->bytes_written_ckpt
1573               : r->write_queue.bytes_out;
1574             lua_pushinteger(L, (lua_Integer)bytes);
1575             return 1;
1576         }
1577         if (0 == memcmp(k, "stream_id", 9)) {
1578             lua_pushinteger(L, (lua_Integer)r->h2id);
1579             return 1;
1580         }
1581         if (0 == memcmp(k, "req_count", 9)) {
1582             lua_pushinteger(L, (lua_Integer)r->con->request_count);
1583             return 1;
1584         }
1585         break;
1586       case 10:
1587         if (0 == memcmp(k, "start_time", 10)) {
1588             lua_pushinteger(L, (lua_Integer)r->start_hp.tv_sec);
1589             lua_pushinteger(L, (lua_Integer)r->start_hp.tv_nsec);
1590             lua_pushcclosure(L, magnet_return_upvalue2, 2);
1591             return 1;
1592         }
1593         if (0 == memcmp(k, "keep_alive", 10)) {
1594             lua_pushinteger(L, (lua_Integer)r->keep_alive);
1595             return 1;
1596         }
1597         break;
1598       case 11:
1599         if (0 == memcmp(k, "http_status", 11)) {
1600             lua_pushinteger(L, (lua_Integer)r->http_status);
1601             return 1;
1602         }
1603         break;
1604       case 14:
1605         if (0 == memcmp(k, "req_header_len", 14)) {
1606             lua_pushinteger(L, (lua_Integer)r->rqst_header_len);
1607             return 1;
1608         }
1609         break;
1610       case 15:
1611         if (0 == memcmp(k, "resp_header_len", 15)) {
1612             lua_pushinteger(L, (lua_Integer)r->resp_header_len);
1613             return 1;
1614         }
1615         break;
1616       default:
1617         break;
1618     }
1619     return luaL_error(L, "r.req_item['%s'] invalid", k);
1620 }
1621 
1622 static int
1623 magnet_req_item_set (lua_State *L)
1624 {
1625     size_t klen;
1626     const char * const k = luaL_checklstring(L, 2, &klen);
1627     int v = (int)luaL_checkinteger(L, 3);
1628 
1629     request_st * const r = **(request_st ***)lua_touserdata(L, 1);
1630     switch (klen) {
1631       case 10:
1632         if (0 == memcmp(k, "keep_alive", 10)) {
1633             if (v == 0 || v == -1) r->keep_alive = v;
1634             return 0;
1635         }
1636         break;
1637       default:
1638         break;
1639     }
1640     return luaL_error(L, "r.req_item['%s'] invalid or read-only", k);
1641 }
1642 
1643 
1644 typedef struct {
1645 	const char *name;
1646 	uint32_t nlen;
1647 	enum {
1648 		MAGNET_ENV_UNSET,
1649 
1650 		MAGNET_ENV_PHYSICAL_PATH,
1651 		MAGNET_ENV_PHYSICAL_REL_PATH,
1652 		MAGNET_ENV_PHYSICAL_DOC_ROOT,
1653 		MAGNET_ENV_PHYSICAL_BASEDIR,
1654 
1655 		MAGNET_ENV_URI_PATH,
1656 		MAGNET_ENV_URI_PATH_RAW,
1657 		MAGNET_ENV_URI_SCHEME,
1658 		MAGNET_ENV_URI_AUTHORITY,
1659 		MAGNET_ENV_URI_QUERY,
1660 
1661 		MAGNET_ENV_REQUEST_METHOD,
1662 		MAGNET_ENV_REQUEST_URI,
1663 		MAGNET_ENV_REQUEST_ORIG_URI,
1664 		MAGNET_ENV_REQUEST_PATH_INFO,
1665 		MAGNET_ENV_REQUEST_REMOTE_ADDR,
1666 		MAGNET_ENV_REQUEST_REMOTE_PORT,
1667 		MAGNET_ENV_REQUEST_SERVER_ADDR,
1668 		MAGNET_ENV_REQUEST_SERVER_PORT,
1669 		MAGNET_ENV_REQUEST_PROTOCOL,
1670 		MAGNET_ENV_REQUEST_STAGE,
1671 
1672 		/* remove after lighttpd 1.4.65 */
1673 		MAGNET_ENV_RESPONSE_HTTP_STATUS,
1674 		MAGNET_ENV_RESPONSE_BODY_LENGTH,
1675 		MAGNET_ENV_RESPONSE_BODY
1676 	} type;
1677 } magnet_env_t;
1678 
1679 /*(NB: coordinate any changes with scan offsets in magnet_env_get_id())*/
1680 static const magnet_env_t magnet_env[] = {
1681     { CONST_STR_LEN("physical.path"),        MAGNET_ENV_PHYSICAL_PATH },
1682     { CONST_STR_LEN("physical.rel-path"),    MAGNET_ENV_PHYSICAL_REL_PATH },
1683     { CONST_STR_LEN("physical.doc-root"),    MAGNET_ENV_PHYSICAL_DOC_ROOT },
1684     { CONST_STR_LEN("physical.basedir"),     MAGNET_ENV_PHYSICAL_BASEDIR },
1685 
1686     { CONST_STR_LEN("uri.path"),             MAGNET_ENV_URI_PATH },
1687     { CONST_STR_LEN("uri.path-raw"),         MAGNET_ENV_URI_PATH_RAW },
1688     { CONST_STR_LEN("uri.scheme"),           MAGNET_ENV_URI_SCHEME },
1689     { CONST_STR_LEN("uri.authority"),        MAGNET_ENV_URI_AUTHORITY },
1690     { CONST_STR_LEN("uri.query"),            MAGNET_ENV_URI_QUERY },
1691 
1692     { CONST_STR_LEN("request.method"),       MAGNET_ENV_REQUEST_METHOD },
1693     { CONST_STR_LEN("request.uri"),          MAGNET_ENV_REQUEST_URI },
1694     { CONST_STR_LEN("request.orig-uri"),     MAGNET_ENV_REQUEST_ORIG_URI },
1695     { CONST_STR_LEN("request.path-info"),    MAGNET_ENV_REQUEST_PATH_INFO },
1696     { CONST_STR_LEN("request.remote-ip"),    MAGNET_ENV_REQUEST_REMOTE_ADDR },
1697     { CONST_STR_LEN("request.remote-addr"),  MAGNET_ENV_REQUEST_REMOTE_ADDR },
1698     { CONST_STR_LEN("request.remote-port"),  MAGNET_ENV_REQUEST_REMOTE_PORT },
1699     { CONST_STR_LEN("request.server-addr"),  MAGNET_ENV_REQUEST_SERVER_ADDR },
1700     { CONST_STR_LEN("request.server-port"),  MAGNET_ENV_REQUEST_SERVER_PORT },
1701     { CONST_STR_LEN("request.protocol"),     MAGNET_ENV_REQUEST_PROTOCOL },
1702     { CONST_STR_LEN("request.stage"),        MAGNET_ENV_REQUEST_STAGE },
1703 
1704     { CONST_STR_LEN("response.http-status"), MAGNET_ENV_RESPONSE_HTTP_STATUS },
1705     { CONST_STR_LEN("response.body-length"), MAGNET_ENV_RESPONSE_BODY_LENGTH },
1706     { CONST_STR_LEN("response.body"),        MAGNET_ENV_RESPONSE_BODY },
1707 
1708     { NULL, 0, MAGNET_ENV_UNSET }
1709 };
1710 
1711 __attribute_cold__
1712 __attribute_noinline__
1713 static buffer *
1714 magnet_env_get_laddr_by_id (request_st * const r, const int id)
1715 {
1716     buffer * const dest = r->tmp_buf;
1717     const server_socket * const srv_socket = r->con->srv_socket;
1718     switch (id) {
1719       case MAGNET_ENV_REQUEST_SERVER_ADDR: /* local IP without port */
1720         if (sock_addr_is_addr_wildcard(&srv_socket->addr)) {
1721             sock_addr addrbuf;
1722             socklen_t addrlen = sizeof(addrbuf);
1723             const int fd = r->con->fd;
1724             if (0 == getsockname(fd,(struct sockaddr *)&addrbuf,&addrlen)) {
1725                 char buf[INET6_ADDRSTRLEN + 1];
1726                 const char *s = sock_addr_inet_ntop(&addrbuf, buf, sizeof(buf));
1727                 if (NULL != s) {
1728                     buffer_copy_string_len(dest, s, strlen(s));
1729                     break;
1730                 }
1731             }
1732         }
1733         buffer_copy_string_len(dest, srv_socket->srv_token->ptr,
1734                                srv_socket->srv_token_colon);
1735         break;
1736       case MAGNET_ENV_REQUEST_SERVER_PORT:
1737       {
1738         const buffer * const srv_token = srv_socket->srv_token;
1739         const uint32_t tlen = buffer_clen(srv_token);
1740         uint32_t portoffset = srv_socket->srv_token_colon;
1741         portoffset = portoffset < tlen ? portoffset+1 : tlen;
1742         buffer_copy_string_len(dest, srv_token->ptr+portoffset,
1743                                tlen-portoffset);
1744         break;
1745       }
1746       default:
1747         break;
1748     }
1749     return dest;
1750 }
1751 
1752 static buffer *
1753 magnet_env_get_buffer_by_id (request_st * const r, const int id)
1754 {
1755 	buffer *dest = r->tmp_buf;
1756 	buffer_clear(dest);
1757 
1758 	switch (id) {
1759 	case MAGNET_ENV_PHYSICAL_PATH: dest = &r->physical.path; break;
1760 	case MAGNET_ENV_PHYSICAL_REL_PATH: dest = &r->physical.rel_path; break;
1761 	case MAGNET_ENV_PHYSICAL_DOC_ROOT: dest = &r->physical.doc_root; break;
1762 	case MAGNET_ENV_PHYSICAL_BASEDIR: dest = &r->physical.basedir; break;
1763 
1764 	case MAGNET_ENV_URI_PATH: dest = &r->uri.path; break;
1765 	case MAGNET_ENV_URI_PATH_RAW:
1766 	    {
1767 		uint32_t len = buffer_clen(&r->target);
1768 		char *qmark = memchr(r->target.ptr, '?', len);
1769 		buffer_copy_string_len(dest, r->target.ptr, qmark ? (uint32_t)(qmark - r->target.ptr) : len);
1770 		break;
1771 	    }
1772 	case MAGNET_ENV_URI_SCHEME: dest = &r->uri.scheme; break;
1773 	case MAGNET_ENV_URI_AUTHORITY: dest = &r->uri.authority; break;
1774 	case MAGNET_ENV_URI_QUERY: dest = &r->uri.query; break;
1775 
1776 	case MAGNET_ENV_REQUEST_METHOD:
1777 		http_method_append(dest, r->http_method);
1778 		break;
1779 	case MAGNET_ENV_REQUEST_URI:      dest = &r->target; break;
1780 	case MAGNET_ENV_REQUEST_ORIG_URI: dest = &r->target_orig; break;
1781 	case MAGNET_ENV_REQUEST_PATH_INFO: dest = &r->pathinfo; break;
1782 	case MAGNET_ENV_REQUEST_REMOTE_ADDR: dest = &r->con->dst_addr_buf; break;
1783 	case MAGNET_ENV_REQUEST_REMOTE_PORT:
1784 		buffer_append_int(dest, sock_addr_get_port(&r->con->dst_addr));
1785 		break;
1786 	case MAGNET_ENV_REQUEST_SERVER_ADDR: /* local IP without port */
1787 	case MAGNET_ENV_REQUEST_SERVER_PORT:
1788 		return magnet_env_get_laddr_by_id(r, id);
1789 	case MAGNET_ENV_REQUEST_PROTOCOL:
1790 		http_version_append(dest, r->http_version);
1791 		break;
1792 	case MAGNET_ENV_REQUEST_STAGE:
1793 		if (http_request_state_is_keep_alive(r))
1794 			buffer_append_string_len(dest, CONST_STR_LEN("keep-alive"));
1795 		else
1796 			http_request_state_append(dest, r->state);
1797 		break;
1798 
1799 	/* remove after lighttpd 1.4.65 */
1800 	case MAGNET_ENV_RESPONSE_HTTP_STATUS:
1801 		buffer_append_int(dest, r->http_status);
1802 		break;
1803 	case MAGNET_ENV_RESPONSE_BODY_LENGTH:
1804 		if (!r->resp_body_finished)
1805 			return NULL;
1806 		log_error(r->conf.errh, __FILE__, __LINE__,
1807 		          "lighty.r.req_attr['response.body-length'] is deprecated "
1808 		          "and will be removed. Use lighty.r.resp_body.len instead.");
1809 		buffer_append_int(dest, chunkqueue_length(&r->write_queue));
1810 		break;
1811 	case MAGNET_ENV_RESPONSE_BODY:
1812 		if (!r->resp_body_finished)
1813 			return NULL;
1814 		log_error(r->conf.errh, __FILE__, __LINE__,
1815 		          "lighty.r.req_attr['response.body'] is deprecated "
1816 		          "and will be removed. Use lighty.r.resp_body.get instead.");
1817 		if (0 == chunkqueue_length(&r->write_queue)
1818 		    || !(dest = chunkqueue_read_squash(&r->write_queue,r->conf.errh)))
1819 			buffer_copy_string_len((dest = r->tmp_buf), CONST_STR_LEN(""));
1820 		break;
1821 
1822 	case MAGNET_ENV_UNSET:
1823 		return NULL;
1824 	}
1825 
1826 	return dest;
1827 }
1828 
1829 __attribute_pure__
1830 static int magnet_env_get_id(const char * const key, const size_t klen) {
1831     /*(NB: ensure offsets match position in magnet_env[])*/
1832     int i; /* magnet_env[] scan offset */
1833     switch (*key) {
1834       case 'r': /* request.* or response.* */
1835         i = klen > 7 && key[7] == '.' ? 9 : 20;
1836         break;
1837       case 'u': /* uri.* */
1838       default:
1839         i = 4;
1840         break;
1841       case 'p': /* physical.* */
1842         i = 0;
1843         break;
1844     }
1845     for (; i < (int)(sizeof(magnet_env)/sizeof(*magnet_env)); ++i) {
1846         if (klen == magnet_env[i].nlen
1847             && 0 == memcmp(key, magnet_env[i].name, klen))
1848             return magnet_env[i].type;
1849     }
1850     return MAGNET_ENV_UNSET;
1851 }
1852 
1853 static int magnet_env_get(lua_State *L) {
1854     size_t klen;
1855     const char * const k = luaL_checklstring(L, 2, &klen);
1856     const int env_id = magnet_env_get_id(k, klen);
1857     request_st * const r = **(request_st ***)lua_touserdata(L, 1);
1858     magnet_push_buffer(L, magnet_env_get_buffer_by_id(r, env_id));
1859     return 1;
1860 }
1861 
1862 __attribute_cold__
1863 static int
1864 magnet_env_set_raddr_by_id (lua_State *L, request_st * const r, const int id,
1865                             const const_buffer * const val)
1866 {
1867     connection * const con = r->con;
1868     switch (id) {
1869       case MAGNET_ENV_REQUEST_REMOTE_ADDR:
1870        #ifdef HAVE_SYS_UN_H
1871         if (val->len && *val->ptr == '/'
1872             && 0 == sock_addr_assign(&con->dst_addr, AF_UNIX, 0, val->ptr)) {
1873         }
1874         else
1875        #endif
1876         {
1877             sock_addr saddr;
1878             saddr.plain.sa_family = AF_UNSPEC;
1879             if (1 == sock_addr_from_str_numeric(&saddr, val->ptr, r->conf.errh)
1880                 && saddr.plain.sa_family != AF_UNSPEC) {
1881                 sock_addr_set_port(&saddr, 0);
1882                 memcpy(&con->dst_addr, &saddr, sizeof(sock_addr));
1883             }
1884             else {
1885                 return luaL_error(L,
1886                                   "r.req_attr['remote-addr'] invalid addr: %s",
1887                                   val->ptr);
1888             }
1889         }
1890         buffer_copy_string_len(&con->dst_addr_buf, val->ptr, val->len);
1891         config_cond_cache_reset_item(r, COMP_HTTP_REMOTE_IP);
1892         break;
1893       case MAGNET_ENV_REQUEST_REMOTE_PORT:
1894         sock_addr_set_port(&con->dst_addr, (unsigned short)atoi(val->ptr));
1895         break;
1896       default:
1897         break;
1898     }
1899     return 0;
1900 }
1901 
1902 static int magnet_env_set(lua_State *L) {
1903     size_t klen;
1904     const char * const key = luaL_checklstring(L, 2, &klen);
1905     const_buffer val = magnet_checkconstbuffer(L, 3);
1906 
1907     const int env_id = magnet_env_get_id(key, klen);
1908     request_st * const r = **(request_st ***)lua_touserdata(L, 1);
1909 
1910     switch (env_id) {
1911       default:
1912         break;
1913       case MAGNET_ENV_URI_PATH_RAW:
1914       {
1915         /* modify uri-path of r->target; preserve query-part, if present */
1916         /* XXX: should we require that resulting path begin with '/' or %2F ? */
1917         const uint32_t len = buffer_clen(&r->target);
1918         const char * const qmark = memchr(r->target.ptr, '?', len);
1919         if (NULL != qmark)
1920             buffer_copy_string_len(r->tmp_buf, qmark,
1921                                    len - (uint32_t)(qmark - r->target.ptr));
1922         buffer_copy_string_len(&r->target, val.ptr, val.len);
1923         if (NULL != qmark)
1924             buffer_append_string_buffer(&r->target, r->tmp_buf);
1925         return 0;
1926       }
1927       case MAGNET_ENV_REQUEST_REMOTE_ADDR:
1928       case MAGNET_ENV_REQUEST_REMOTE_PORT:
1929         return magnet_env_set_raddr_by_id(L, r, env_id, &val);
1930       /*case MAGNET_ENV_REQUEST_STAGE:*//*(change attempts silently ignored)*/
1931       /* remove after lighttpd 1.4.65 */
1932       /*case MAGNET_ENV_RESPONSE_HTTP_STATUS:*/
1933       /*case MAGNET_ENV_RESPONSE_BODY_LENGTH:*/
1934       case MAGNET_ENV_RESPONSE_BODY:
1935         return luaL_error(L, "r.req_attr['%s'] is read-only", key);
1936     }
1937 
1938     buffer * const dest = magnet_env_get_buffer_by_id(r, env_id);
1939     if (NULL == dest)
1940         return luaL_error(L, "couldn't store '%s' in r.req_attr[]", key);
1941 
1942     if (lua_isnoneornil(L, 3)) {
1943         if (env_id==MAGNET_ENV_URI_QUERY || env_id==MAGNET_ENV_PHYSICAL_PATH)
1944             buffer_clear(dest);
1945         else
1946             buffer_blank(dest);
1947     }
1948     else {
1949         buffer_copy_string_len(dest, val.ptr, val.len);
1950         /* NB: setting r->uri.query does not modify query-part in r->target */
1951     }
1952 
1953     switch (env_id) {
1954       case MAGNET_ENV_URI_SCHEME:
1955         buffer_to_lower(dest);
1956         config_cond_cache_reset_item(r, COMP_HTTP_SCHEME);
1957         break;
1958       case MAGNET_ENV_URI_AUTHORITY:
1959         r->server_name = dest;
1960         buffer_to_lower(dest);
1961         config_cond_cache_reset_item(r, COMP_HTTP_HOST);
1962         break;
1963       case MAGNET_ENV_URI_PATH:
1964         config_cond_cache_reset_item(r, COMP_HTTP_URL);
1965         break;
1966       case MAGNET_ENV_URI_QUERY:
1967         config_cond_cache_reset_item(r, COMP_HTTP_QUERY_STRING);
1968         break;
1969       default:
1970         break;
1971     }
1972 
1973     return 0;
1974 }
1975 
1976 static int magnet_env_next(lua_State *L) {
1977 	/* ignore previous key: use upvalue for current pos */
1978 	lua_settop(L, 0);
1979 	const int pos = lua_tointeger(L, lua_upvalueindex(1));
1980 
1981 	if (NULL == magnet_env[pos].name) return 0; /* end of list */
1982 	/* Update our positional upval to reflect our new current position */
1983 	lua_pushinteger(L, pos + 1);
1984 	lua_replace(L, lua_upvalueindex(1));
1985 
1986 	/* key to return */
1987 	lua_pushlstring(L, magnet_env[pos].name, magnet_env[pos].nlen);
1988 
1989 	/* get value */
1990 	request_st * const r = lua_touserdata(L, lua_upvalueindex(2));
1991 	magnet_push_buffer(L, magnet_env_get_buffer_by_id(r, magnet_env[pos].type));
1992 
1993 	/* return 2 items on the stack (key, value) */
1994 	return 2;
1995 }
1996 
1997 static int magnet_env_pairs(lua_State *L) {
1998     lua_pushinteger(L, 0); /* Push our current pos (the start) into upval 1 */
1999     request_st * const r = **(request_st ***)lua_touserdata(L, 1);
2000     lua_pushlightuserdata(L, r); /* Push request_st *r into upval 2 */
2001     lua_pushcclosure(L, magnet_env_next, 2); /* Push new closure with 2 upvals*/
2002     return 1;
2003 }
2004 
2005 static int magnet_envvar_get(lua_State *L) {
2006     size_t klen;
2007     const char * const k = luaL_checklstring(L, 2, &klen);
2008     const request_st * const r = **(request_st ***)lua_touserdata(L, 1);
2009     magnet_push_buffer(L, http_header_env_get(r, k, klen));
2010     return 1;
2011 }
2012 
2013 static int magnet_envvar_set(lua_State *L) {
2014     request_st * const r = **(request_st ***)lua_touserdata(L, 1);
2015     const_buffer key = magnet_checkconstbuffer(L, 2);
2016     if (__builtin_expect( (lua_isnil(L, 3)), 0)) {
2017         buffer * const v = http_header_env_get(r, key.ptr, key.len);
2018         if (v) buffer_clear(v); /*(unset)*/
2019         return 0;
2020     }
2021     const_buffer val = magnet_checkconstbuffer(L, 3);
2022     http_header_env_set(r, key.ptr, key.len, val.ptr, val.len);
2023     return 0;
2024 }
2025 
2026 static int magnet_envvar_pairs(lua_State *L) {
2027     request_st * const r = **(request_st ***)lua_touserdata(L, 1);
2028     return magnet_array_pairs(L, &r->env);
2029 }
2030 
2031 
2032 static int magnet_respbody_add(lua_State *L) {
2033     request_st * const r = lua_touserdata(L, lua_upvalueindex(1));
2034     if (lua_isstring(L, -1)) {
2035         const_buffer data = magnet_checkconstbuffer(L, -1);
2036         http_chunk_append_mem(r, data.ptr, data.len);
2037         return 1; /* boolean true */
2038     }
2039     else if (!lua_istable(L, -1))
2040         return 0; /* boolean false */
2041 
2042     /* note: differs from magnet_attach_content();
2043      * magnet_attach_content() has misnamed 'length' param which
2044      * is treated as 0-offset pos one after end of range to send.
2045      * Here, 'length' means 'length', as one would expect */
2046     for (int i=1, end=0, n=(int)lua_rawlen(L,-1); !end && i <= n; ++i) {
2047         lua_rawgeti(L, -1, i);
2048 
2049         if (lua_isstring(L, -1)) {
2050             const_buffer data = magnet_checkconstbuffer(L, -1);
2051             http_chunk_append_mem(r, data.ptr, data.len);
2052         }
2053         else if (lua_istable(L, -1)) {
2054             lua_getfield(L, -1, "filename");
2055             lua_getfield(L, -2, "length");
2056             lua_getfield(L, -3, "offset");
2057 
2058             if (lua_isstring(L, -3)) { /* filename has to be a string */
2059                 off_t off = (off_t) luaL_optinteger(L, -1, 0);
2060                 off_t len = (off_t) luaL_optinteger(L, -2, -1);
2061                 /*(-1 len as flag to use file size minus offset (below))*/
2062                 buffer stor; /*(note: do not free magnet_checkbuffer() result)*/
2063                 const buffer * const fn = magnet_checkbuffer(L, -3, &stor);
2064                 stat_cache_entry * const sce = (!buffer_is_blank(fn))
2065                   ? stat_cache_get_entry_open(fn, r->conf.follow_symlink)
2066                   : NULL;
2067                 if (sce && (sce->fd >= 0 || sce->st.st_size == 0)) {
2068                     /* treat negative offset as bytes from end of file */
2069                     /* treat negative len as bytes from offset to end of file */
2070                     if (off > sce->st.st_size)
2071                         off = sce->st.st_size;
2072                     else if (off < 0) {
2073                         off = sce->st.st_size - off;
2074                         if (off < 0) off = 0;
2075                     }
2076                     if (len < 0 || sce->st.st_size - off < len)
2077                         len = sce->st.st_size - off;
2078                     if (len)
2079                         http_chunk_append_file_ref_range(r, sce, off, len);
2080                 }
2081                 else {
2082                     log_error(r->conf.errh, __FILE__, __LINE__,
2083                       "error opening file '%s'", fn->ptr);
2084                     end = 1;
2085                 }
2086             }
2087             else {
2088                 log_error(r->conf.errh, __FILE__, __LINE__,
2089                   "body[%d] table field \"filename\" must be a string", i);
2090                 end = 1;
2091             }
2092 
2093             lua_pop(L, 3);
2094         }
2095         else if (lua_isnil(L, -1)) { /* end of list */
2096             end = 1;
2097         }
2098         else {
2099             log_error(r->conf.errh, __FILE__, __LINE__,
2100               "body[%d] is neither a string nor a table", i);
2101             end = 1;
2102         }
2103 
2104         lua_pop(L, 1); /* pop the content[...] entry value */
2105     }
2106 
2107     return 1; /* boolean true */
2108 }
2109 
2110 
2111 static int magnet_respbody(lua_State *L) {
2112     request_st * const r = **(request_st ***)lua_touserdata(L, 1);
2113     size_t klen;
2114     const char * const k = luaL_checklstring(L, 2, &klen);
2115     switch (k[0]) {
2116       case 'a': /* add; r.resp_body.add */
2117         if (k[1] == 'd' && k[2] == 'd' && k[3] == '\0') {
2118             lua_pushlightuserdata(L, r);
2119             lua_pushcclosure(L, magnet_respbody_add, 1);
2120             return 1;
2121         }
2122         break;
2123       case 'b':
2124         if (klen == 8 && 0 == memcmp(k, "bytes_in", 8)) {
2125             lua_pushinteger(L, r->write_queue.bytes_in);
2126             return 1;
2127         }
2128         if (klen == 9 && 0 == memcmp(k, "bytes_out", 9)) {
2129             lua_pushinteger(L, r->write_queue.bytes_out);
2130             return 1;
2131         }
2132         break;
2133      #if 0 /*(future: provide pairs() interface to iterate over chunkqueue)*/
2134            /*(might convert chunks into table of strings, {filename="..."})*/
2135            /*(what about c->offset into chunk?)*/
2136      #endif
2137       case 'g': /* get; r.resp_body.get */
2138         if (k[1] == 'e' && k[2] == 't' && k[3] == '\0') {
2139             if (r->resp_body_finished) {
2140                 chunkqueue * const cq = &r->write_queue;
2141                 chunkqueue_length(cq)
2142                   ? magnet_push_buffer(L,
2143                                        chunkqueue_read_squash(cq,r->conf.errh))
2144                   : (void)lua_pushlstring(L, "", 0);
2145             }
2146             else
2147                 lua_pushnil(L); /*(?maybe return -1 instead if len unknown?)*/
2148             return 1;
2149         }
2150         break;
2151       case 'l': /* len; r.resp_body.len */
2152         if (k[1] == 'e' && k[2] == 'n' && k[3] == '\0') {
2153             if (r->resp_body_finished)
2154                 lua_pushinteger(L, chunkqueue_length(&r->write_queue));
2155             else
2156                 lua_pushnil(L); /*(?maybe return -1 instead if len unknown?)*/
2157             return 1;
2158         }
2159         break;
2160       case 's': /* set; r.resp_body.set */
2161         if (k[1] == 'e' && k[2] == 't' && k[3] == '\0') {
2162             http_response_body_clear(r, 0); /* clear respbody, then add */
2163             lua_pushlightuserdata(L, r);
2164             lua_pushcclosure(L, magnet_respbody_add, 1);
2165             return 1;
2166         }
2167         break;
2168       default:
2169         break;
2170     }
2171     lua_pushliteral(L, "r.resp_body invalid method or param");
2172     lua_error(L);
2173     return 0;
2174 }
2175 
2176 static int magnet_reqbody(lua_State *L) {
2177     const request_st * const r = **(request_st ***)lua_touserdata(L, 1);
2178     size_t klen;
2179     const char * const k = luaL_checklstring(L, 2, &klen);
2180     switch (k[0]) {
2181       case 'b':
2182         if (klen == 8 && 0 == memcmp(k, "bytes_in", 8)) {
2183             lua_pushinteger(L, r->reqbody_queue.bytes_in);
2184             return 1;
2185         }
2186         if (klen == 9 && 0 == memcmp(k, "bytes_out", 9)) {
2187             lua_pushinteger(L, r->reqbody_queue.bytes_out);
2188             return 1;
2189         }
2190         break;
2191       case 'l': /* len */
2192         if (k[1] == 'e' && k[2] == 'n' && k[3] == '\0') {
2193             lua_pushinteger(L, r->reqbody_length);
2194             return 1;
2195         }
2196         break;
2197       default:
2198         break;
2199     }
2200     lua_pushliteral(L, "r.req_body invalid method or param");
2201     lua_error(L);
2202     return 0;
2203 }
2204 
2205 
2206 __attribute_cold__
2207 static int magnet_lighty_result_get(lua_State *L) {
2208     /* __index: param 1 is the lighty table the value was not found in */
2209     lua_getfield(L, 1, "result"); /* lighty.result */
2210     lua_pushvalue(L, 2);
2211     lua_rawget(L, -2);
2212     if (lua_isnil(L, -1)) {
2213         const_buffer k = magnet_checkconstbuffer(L, 2);
2214         if (k.len == 7 && 0 == memcmp(k.ptr, "content", 7)) {
2215             lua_createtable(L, 0, 0); /* create "content" table on demand */
2216             lua_pushvalue(L, 2);      /* k: "content" */
2217             lua_pushvalue(L, -2);     /* v: table */
2218             lua_rawset(L, 3); /* set in "lighty.result" */
2219         }
2220     }
2221     lua_replace(L, 3);
2222     return 1;
2223 }
2224 
2225 __attribute_cold__
2226 static int magnet_lighty_result_set(lua_State *L) {
2227     /* __newindex: param 1 is lighty table the value is supposed to be set in */
2228     /* assign value to table, replacing existing value, if any
2229      * (expecting "content" here, but compatible with prior misuse potential)
2230      * (special-case "header" back into lighty.header) */
2231     const_buffer k = magnet_checkconstbuffer(L, 2);
2232     if (k.len != 6 || 0 != memcmp(k.ptr, "header", 6)) {
2233         lua_getfield(L, 1, "result"); /* lighty.result */
2234         lua_replace(L, 1); /* replace param 1, original target table */
2235     }
2236     lua_rawset(L, -3);
2237     return 0;
2238 }
2239 
2240 
2241 static void magnet_copy_response_header(lua_State * const L, request_st * const r, const int lighty_table_ndx) {
2242     if (lua_getfield_and_type(L, lighty_table_ndx, "header") == LUA_TTABLE) {
2243         /* walk lighty.header */
2244         for (lua_pushnil(L); lua_next(L, -2); ) {
2245             if (lua_isstring(L, -1) && lua_isstring(L, -2))
2246                 magnet_resphdr_set_kv(L, r);
2247             /* unset value after use while walking table entries */
2248             lua_pop(L, 1);
2249             lua_pushvalue(L, -1);
2250             lua_pushnil(L);
2251             lua_rawset(L, -4);
2252         }
2253     }
2254     /*lua_pop(L, 1);*/ /* pop lighty.header */ /* defer to later */
2255 }
2256 
2257 /**
2258  * walk through the content array set by lua script, e.g.
2259  *   lighy.header["Content-Type"] = "text/html"
2260  *   lighty.content =
2261  *     { "<html><body><pre>", { file = "/content" } , "</pre></body></html>" }
2262  *   return 200
2263  */
2264 __attribute_cold__
2265 __attribute_noinline__
2266 static void magnet_attach_content_table(lua_State * const L, request_st * const r) {
2267 		for (int i=1, end=0, n=(int)lua_rawlen(L,-1); !end && i <= n; ++i) {
2268 			lua_rawgeti(L, -1, i);
2269 
2270 			/* -1 is the value and should be the value ... aka a table */
2271 			if (lua_isstring(L, -1)) {
2272 				const_buffer data = magnet_checkconstbuffer(L, -1);
2273 				http_chunk_append_mem(r, data.ptr, data.len);
2274 			} else if (lua_istable(L, -1)) {
2275 				lua_getfield(L, -1, "filename");
2276 				lua_getfield(L, -2, "length"); /* (0-based) end of range (not actually "length") */
2277 				lua_getfield(L, -3, "offset"); /* (0-based) start of range */
2278 
2279 				if (lua_isstring(L, -3)) { /* filename has to be a string */
2280 					/*(luaL_optinteger might raise error, which we want to avoid)*/
2281 					/*off_t off = (off_t) luaL_optinteger(L, -1, 0);*/
2282 					/*off_t len = (off_t) luaL_optinteger(L, -2, -1);*/ /*(-1 as flag to use file size minus offset (below))*/
2283 					int isnum = 1;
2284 					off_t off = lua_isnil(L, -1) ? 0 : (off_t) lua_tointegerx(L, -1, &isnum);
2285 					if (!isnum) {
2286 						off = 0;
2287 						log_error(r->conf.errh, __FILE__, __LINE__,
2288 						  "content[%d] is a table and field \"offset\" must be an integer", i);
2289 					}
2290 					isnum = 1;
2291 					off_t len = lua_isnil(L, -2) ? -1 : (off_t) lua_tointegerx(L, -2, &isnum);
2292 					/*(-1 len as flag to use file size minus offset (below))*/
2293 					if (!isnum) {
2294 						len = -1;
2295 						log_error(r->conf.errh, __FILE__, __LINE__,
2296 						  "content[%d] is a table and field \"length\" must be an integer", i);
2297 					}
2298 					if (off < 0) {
2299 						log_error(r->conf.errh, __FILE__, __LINE__,
2300 						  "offset for '%s' is negative", lua_tostring(L, -3));
2301 						end = 1;
2302 					} else if (len >= off) {
2303 						len -= off;
2304 					} else if (-1 != len) {
2305 						log_error(r->conf.errh, __FILE__, __LINE__,
2306 						  "offset > length for '%s'", lua_tostring(L, -3));
2307 						end = 1;
2308 					}
2309 
2310 					if (!end && 0 != len) {
2311 						buffer stor; /*(note: do not free magnet_checkbuffer() result)*/
2312 						const buffer * const fn = magnet_checkbuffer(L, -3, &stor);
2313 						stat_cache_entry * const sce = (!buffer_is_blank(fn))
2314 						  ? stat_cache_get_entry_open(fn, r->conf.follow_symlink)
2315 						  : NULL;
2316 						if (sce && (sce->fd >= 0 || sce->st.st_size == 0)) {
2317 							if (len == -1 || sce->st.st_size - off < len)
2318 								len = sce->st.st_size - off;
2319 							if (len > 0)
2320 								http_chunk_append_file_ref_range(r, sce, off, len);
2321 						} else {
2322 							log_error(r->conf.errh, __FILE__, __LINE__,
2323 							  "error opening file content '%s' at offset %lld",
2324 							          lua_tostring(L, -3), (long long)off);
2325 							end = 1;
2326 						}
2327 					}
2328 				} else {
2329 					log_error(r->conf.errh, __FILE__, __LINE__,
2330 					  "content[%d] is a table and field \"filename\" must be a string", i);
2331 					end = 1;
2332 				}
2333 
2334 				lua_pop(L, 3);
2335 			} else if (lua_isnil(L, -1)) {
2336 				/* end of list */
2337 				end = 1;
2338 			} else {
2339 				log_error(r->conf.errh, __FILE__, __LINE__,
2340 				  "content[%d] is neither a string nor a table", i);
2341 				end = 1;
2342 			}
2343 
2344 			lua_pop(L, 1); /* pop the content[...] entry value */
2345 		}
2346 }
2347 
2348 static void magnet_attach_content(lua_State * const L, request_st * const r, const int lighty_table_ndx) {
2349     if (lua_getfield_and_type(L, lighty_table_ndx, "result") != LUA_TTABLE) {
2350         /*lua_pop(L, 1);*/ /* pop nil lighty.result */ /* defer to later */
2351         return;
2352     }
2353     switch (lua_getfield_and_type(L, -1, "content")) {/*lighty.result.content*/
2354       case LUA_TNIL:
2355         break;
2356       case LUA_TTABLE:
2357         /* content found and is a table */
2358         http_response_body_clear(r, 0);
2359         magnet_attach_content_table(L, r);
2360         /* assign nil to content to remove from "result" table */
2361         lua_pushnil(L);
2362         lua_setfield(L, -3, "content");
2363         break;
2364       default:
2365         log_error(r->conf.errh, __FILE__, __LINE__,
2366           "lighty.content has to be a table");
2367         break;
2368     }
2369     /* defer lua_pop() to later */
2370     /*lua_pop(L, 2);*/ /* pop lighty.result.content and lighty.result */
2371 }
2372 
2373 __attribute_cold__
2374 static void magnet_mainenv_metatable(lua_State * const L) {
2375     if (luaL_newmetatable(L, "li.mainenv")) {                 /* (sp += 1) */
2376         lua_pushglobaltable(L);                               /* (sp += 1) */
2377         lua_setfield(L, -2, "__index"); /* { __index = _G }      (sp -= 1) */
2378         lua_pushboolean(L, 0);                                /* (sp += 1) */
2379         lua_setfield(L, -2, "__metatable"); /* protect metatable (sp -= 1) */
2380     }
2381 }
2382 
2383 static void
2384 magnet_request_userdata_method (lua_State * const L, request_st ** const rr, const char *meta)
2385 {
2386     /*(meta is name of cached metatable; meta must start w/ "li." prefix)*/
2387     *(request_st ***)lua_newuserdata0(L, sizeof(request_st **)) = rr;
2388     luaL_newmetatable(L, meta); /*(should not fail; init'd in script setup)*/
2389     lua_setmetatable(L, -2);
2390     lua_setfield(L, -2, meta+3); /*(meta+3 to skip over "li." prefix)*/
2391 }
2392 
2393 static void
2394 magnet_request_table (lua_State * const L, request_st ** const rr)
2395 {
2396     /* r table
2397      *
2398      * r.req_header[]         HTTP request headers
2399      * r.req_attr[]           HTTP request attributes / components (strings)
2400      * r.req_item[]           HTTP request items (struct members, statistics)
2401      * r.req_env[]            HTTP request environment variables
2402      * r.req_body.*           HTTP request body accessors
2403      * r.req_body.bytes_in    HTTP request body chunkqueue bytes_in
2404      * r.req_body.bytes_out   HTTP request body chunkqueue bytes_out
2405      * r.resp_header[]        HTTP response headers
2406      * r.resp_body.*          HTTP response body accessors
2407      * r.resp_body.len        HTTP response body length
2408      * r.resp_body.add()      HTTP response body add (string or table)
2409      * r.resp_body.set()      HTTP response body set (string or table)
2410      * r.resp_body.bytes_in   HTTP response body chunkqueue bytes_in
2411      * r.resp_body.bytes_out  HTTP response body chunkqueue bytes_out
2412      */
2413     lua_createtable(L, 0, 7);                                 /* (sp += 1) */
2414 
2415     /* userdata methods share ptr-ptr to external object userdata rr
2416      * (similar functionality to that provided w/ luaL_setfuncs() in lua 5.2+)*/
2417     magnet_request_userdata_method(L, rr, "li.req_header"); /* req_header */
2418     magnet_request_userdata_method(L, rr, "li.req_attr");   /* req_attr */
2419     magnet_request_userdata_method(L, rr, "li.req_item");   /* req_item */
2420     magnet_request_userdata_method(L, rr, "li.req_env");    /* req_env */
2421     magnet_request_userdata_method(L, rr, "li.resp_header");/* resp_header */
2422     magnet_request_userdata_method(L, rr, "li.resp_body");  /* resp_body */
2423     magnet_request_userdata_method(L, rr, "li.req_body");   /* req_body */
2424 
2425     lua_createtable(L, 0, 2); /* metatable for r table           (sp += 1) */
2426     lua_pushcfunction(L, magnet_newindex_readonly);           /* (sp += 1) */
2427     lua_setfield(L, -2, "__newindex");                        /* (sp -= 1) */
2428     lua_pushboolean(L, 0);                                    /* (sp += 1) */
2429     lua_setfield(L, -2, "__metatable"); /* protect metatable     (sp -= 1) */
2430     lua_setmetatable(L, -2); /* tie the metatable to r           (sp -= 1) */
2431 }
2432 
2433 static int
2434 magnet_request_iter (lua_State *L)
2435 {
2436     /* upvalue 1: (connection *) in linked list
2437      * upvalue 2: index into h2con->r[]
2438      * upvalue 3: request userdata
2439      * upvalue 4: request table (references r in userdata) */
2440     connection *con = lua_touserdata(L, lua_upvalueindex(1));
2441 
2442     /* skip over HTTP/2 connections with no active requests */
2443     while (con && con->h2 && 0 == con->h2->rused)
2444         con = con->next;
2445     if (NULL == con)
2446         return 0;
2447 
2448     /* set (request_st *)r */
2449     int32_t i = -1;
2450     if (con->h2) {
2451         /* get index into h2con->r[] */
2452         i = lua_tointeger(L, lua_upvalueindex(2));
2453         /* set (request_st *)r in userdata */
2454         if (-1 == i)
2455             *(request_st **)lua_touserdata(L,lua_upvalueindex(3))=&con->request;
2456         else
2457             *(request_st **)lua_touserdata(L,lua_upvalueindex(3))=con->h2->r[i];
2458         /* step to next index into h2con->r[] */
2459         if ((uint32_t)++i == con->h2->rused)
2460             i = -1;
2461         lua_pushinteger(L, i);
2462         lua_replace(L, lua_upvalueindex(2));
2463     }
2464     else {
2465         /* set (request_st *) in userdata */
2466         *(request_st **)lua_touserdata(L, lua_upvalueindex(3)) = &con->request;
2467     }
2468 
2469     if (-1 == i) {
2470         /* step to next connection */
2471         con = con->next;
2472         lua_pushlightuserdata(L, con);
2473         lua_replace(L, lua_upvalueindex(1));
2474     }
2475 
2476     /* return request object (which references (request_st *)r in userdata) */
2477     lua_pushvalue(L, lua_upvalueindex(4));
2478     return 1;
2479 }
2480 
2481 static int
2482 magnet_irequests (lua_State *L)
2483 {
2484     /* NB: iterator request object *is invalid* outside of iteration
2485      * For efficiency, r is stored in userdata as upvalue to iteration
2486      * and is invalid (and may be cleaned up) outside of iterator loop.
2487      * A C pointer into userdata is stored in iterator request object methods.
2488      * The iterator request object is *reused* for each iteration loop and the
2489      * upvalue to the userdata is changed each iteration to point to next r.
2490      * The iterator request object *must not* be saved for use outside
2491      * the iteration loop.  Extract data that must be saved and store data
2492      * in a persistent object if data is to be used outside iterator loop.
2493      * (Were it desirable to produce a persistent request object for use outside
2494      *  the iteration loop, a future enhancement would be to add a method such
2495      *  as lighty.server.irequests_clone(r) which creates a new request object
2496      *  pointing into a new userdata, and saving that new userdata in the new
2497      *  request object table as '_r_userdata')
2498      * NB: iterator request objects should generally be treated read-only.
2499      * Modifications may in some cases be unsafe and cause lighttpd to crash. */
2500     request_st *r = magnet_get_request(L);
2501     lua_pushlightuserdata(L, r->con->srv->conns);
2502     lua_pushinteger(L, -1);
2503     request_st ** const r_userdata =
2504       (request_st **)lua_newuserdata0(L, sizeof(request_st *));
2505     magnet_request_table(L, r_userdata);
2506     lua_pushcclosure(L, magnet_request_iter, 4);
2507     return 1;
2508 }
2509 
2510 static int
2511 magnet_server_stats_get (lua_State *L)
2512 {
2513     size_t klen;
2514     const char * const k = luaL_checklstring(L, 2, &klen);
2515     const request_st * const r = magnet_get_request(L);
2516     const server * const srv = r->con->srv;
2517     switch (klen) {
2518       case 6:
2519         if (0 == memcmp(k, "uptime", 6)) {
2520             lua_pushinteger(L, (lua_Integer)(log_epoch_secs - srv->startup_ts));
2521             return 1;
2522         }
2523         break;
2524       case 7:
2525         if (0 == memcmp(k, "version", 7)) {
2526             lua_pushlstring(L, BUF_PTR_LEN(srv->default_server_tag));
2527             return 1;
2528         }
2529         break;
2530       case 12:
2531         /*(could calculate from irequests: ++count on remote-addr/port change)*/
2532         if (0 == memcmp(k, "clients_open", 12)) {
2533             lua_pushinteger(L, (lua_Integer)
2534                             (srv->srvconf.max_conns - srv->lim_conns));
2535             return 1;
2536         }
2537         break;
2538       default:
2539         break;
2540     }
2541     return luaL_error(L, "server.stats['%s'] invalid", k);
2542 }
2543 
2544 
2545 __attribute_cold__
2546 static void
2547 magnet_req_header_metatable (lua_State * const L)
2548 {
2549     if (luaL_newmetatable(L, "li.req_header") == 0)           /* (sp += 1) */
2550         return;
2551 
2552     lua_pushcfunction(L, magnet_reqhdr_get);                  /* (sp += 1) */
2553     lua_setfield(L, -2, "__index");                           /* (sp -= 1) */
2554     lua_pushcfunction(L, magnet_reqhdr_set);                  /* (sp += 1) */
2555     lua_setfield(L, -2, "__newindex");                        /* (sp -= 1) */
2556     lua_pushcfunction(L, magnet_reqhdr_pairs);                /* (sp += 1) */
2557     lua_setfield(L, -2, "__pairs");                           /* (sp -= 1) */
2558     lua_pushboolean(L, 0);                                    /* (sp += 1) */
2559     lua_setfield(L, -2, "__metatable"); /* protect metatable     (sp -= 1) */
2560 }
2561 
2562 __attribute_cold__
2563 static void
2564 magnet_req_attr_metatable (lua_State * const L)
2565 {
2566     if (luaL_newmetatable(L, "li.req_attr") == 0)             /* (sp += 1) */
2567         return;
2568 
2569     lua_pushcfunction(L, magnet_env_get);                     /* (sp += 1) */
2570     lua_setfield(L, -2, "__index");                           /* (sp -= 1) */
2571     lua_pushcfunction(L, magnet_env_set);                     /* (sp += 1) */
2572     lua_setfield(L, -2, "__newindex");                        /* (sp -= 1) */
2573     lua_pushcfunction(L, magnet_env_pairs);                   /* (sp += 1) */
2574     lua_setfield(L, -2, "__pairs");                           /* (sp -= 1) */
2575     lua_pushboolean(L, 0);                                    /* (sp += 1) */
2576     lua_setfield(L, -2, "__metatable"); /* protect metatable     (sp -= 1) */
2577 }
2578 
2579 __attribute_cold__
2580 static void
2581 magnet_req_item_metatable (lua_State * const L)
2582 {
2583     if (luaL_newmetatable(L, "li.req_item") == 0)             /* (sp += 1) */
2584         return;
2585 
2586     lua_pushcfunction(L, magnet_req_item_get);                /* (sp += 1) */
2587     lua_setfield(L, -2, "__index");                           /* (sp -= 1) */
2588     lua_pushcfunction(L, magnet_req_item_set);                /* (sp += 1) */
2589     lua_setfield(L, -2, "__newindex");                        /* (sp -= 1) */
2590     lua_pushboolean(L, 0);                                    /* (sp += 1) */
2591     lua_setfield(L, -2, "__metatable"); /* protect metatable     (sp -= 1) */
2592 }
2593 
2594 __attribute_cold__
2595 static void
2596 magnet_req_env_metatable (lua_State * const L)
2597 {
2598     if (luaL_newmetatable(L, "li.req_env") == 0)              /* (sp += 1) */
2599         return;
2600 
2601     lua_pushcfunction(L, magnet_envvar_get);                  /* (sp += 1) */
2602     lua_setfield(L, -2, "__index");                           /* (sp -= 1) */
2603     lua_pushcfunction(L, magnet_envvar_set);                  /* (sp += 1) */
2604     lua_setfield(L, -2, "__newindex");                        /* (sp -= 1) */
2605     lua_pushcfunction(L, magnet_envvar_pairs);                /* (sp += 1) */
2606     lua_setfield(L, -2, "__pairs");                           /* (sp -= 1) */
2607     lua_pushboolean(L, 0);                                    /* (sp += 1) */
2608     lua_setfield(L, -2, "__metatable"); /* protect metatable     (sp -= 1) */
2609 }
2610 
2611 __attribute_cold__
2612 static void
2613 magnet_resp_header_metatable (lua_State * const L)
2614 {
2615     if (luaL_newmetatable(L, "li.resp_header") == 0)          /* (sp += 1) */
2616         return;
2617 
2618     lua_pushcfunction(L, magnet_resphdr_get);                 /* (sp += 1) */
2619     lua_setfield(L, -2, "__index");                           /* (sp -= 1) */
2620     lua_pushcfunction(L, magnet_resphdr_set);                 /* (sp += 1) */
2621     lua_setfield(L, -2, "__newindex");                        /* (sp -= 1) */
2622     lua_pushcfunction(L, magnet_resphdr_pairs);               /* (sp += 1) */
2623     lua_setfield(L, -2, "__pairs");                           /* (sp -= 1) */
2624     lua_pushboolean(L, 0);                                    /* (sp += 1) */
2625     lua_setfield(L, -2, "__metatable"); /* protect metatable     (sp -= 1) */
2626 }
2627 
2628 __attribute_cold__
2629 static void
2630 magnet_resp_body_metatable (lua_State * const L)
2631 {
2632     if (luaL_newmetatable(L, "li.resp_body") == 0)            /* (sp += 1) */
2633         return;
2634 
2635     lua_pushcfunction(L, magnet_respbody);                    /* (sp += 1) */
2636     lua_setfield(L, -2, "__index");                           /* (sp -= 1) */
2637     lua_pushcfunction(L, magnet_newindex_readonly);           /* (sp += 1) */
2638     lua_setfield(L, -2, "__newindex");                        /* (sp -= 1) */
2639     lua_pushboolean(L, 0);                                    /* (sp += 1) */
2640     lua_setfield(L, -2, "__metatable"); /* protect metatable     (sp -= 1) */
2641 }
2642 
2643 __attribute_cold__
2644 static void
2645 magnet_req_body_metatable (lua_State * const L)
2646 {
2647     if (luaL_newmetatable(L, "li.req_body") == 0)             /* (sp += 1) */
2648         return;
2649 
2650     lua_pushcfunction(L, magnet_reqbody);                     /* (sp += 1) */
2651     lua_setfield(L, -2, "__index");                           /* (sp -= 1) */
2652     lua_pushcfunction(L, magnet_newindex_readonly);           /* (sp += 1) */
2653     lua_setfield(L, -2, "__newindex");                        /* (sp -= 1) */
2654     lua_pushboolean(L, 0);                                    /* (sp += 1) */
2655     lua_setfield(L, -2, "__metatable"); /* protect metatable     (sp -= 1) */
2656 }
2657 
2658 __attribute_cold__
2659 static int magnet_atpanic(lua_State *L) {
2660 	request_st * const r = magnet_get_request(L);
2661 	log_error(r->conf.errh, __FILE__, __LINE__, "(lua-atpanic) %s",
2662 	          lua_isstring(L, 1) ? lua_tostring(L, 1) : "");
2663 	/*longjmp(exceptionjmp, 1);*//*(must be init with setjmp() elsewhere)*/
2664 	return 0;
2665 }
2666 
2667 __attribute_cold__
2668 static int magnet_print(lua_State *L) {
2669 	const_buffer cb = magnet_checkconstbuffer(L, 1);
2670 	request_st * const r = magnet_get_request(L);
2671 	log_error(r->conf.errh, __FILE__, __LINE__, "(lua-print) %s", cb.ptr);
2672 	return 0;
2673 }
2674 
2675 __attribute_cold__
2676 static void
2677 magnet_plugin_stats_table (lua_State * const L)
2678 {
2679     lua_createtable(L, 0, 0); /* {}                              (sp += 1) */
2680     lua_createtable(L, 0, 4); /* metatable for plugin_stats      (sp += 1) */
2681     lua_pushcfunction(L, magnet_status_get);                  /* (sp += 1) */
2682     lua_setfield(L, -2, "__index");                           /* (sp -= 1) */
2683     lua_pushcfunction(L, magnet_status_set);                  /* (sp += 1) */
2684     lua_setfield(L, -2, "__newindex");                        /* (sp -= 1) */
2685     lua_pushcfunction(L, magnet_status_pairs);                /* (sp += 1) */
2686     lua_setfield(L, -2, "__pairs");                           /* (sp -= 1) */
2687     lua_pushboolean(L, 0);                                    /* (sp += 1) */
2688     lua_setfield(L, -2, "__metatable"); /* protect metatable     (sp -= 1) */
2689     lua_setmetatable(L, -2);                                  /* (sp -= 1) */
2690 }
2691 
2692 __attribute_cold__
2693 static void
2694 magnet_server_stats_table (lua_State * const L)
2695 {
2696     lua_createtable(L, 0, 0); /* {}                              (sp += 1) */
2697     lua_createtable(L, 0, 3); /* metatable for stats             (sp += 1) */
2698     lua_pushcfunction(L, magnet_server_stats_get);            /* (sp += 1) */
2699     lua_setfield(L, -2, "__index");                           /* (sp -= 1) */
2700     lua_pushcfunction(L, magnet_newindex_readonly);           /* (sp += 1) */
2701     lua_setfield(L, -2, "__newindex");                        /* (sp -= 1) */
2702     lua_pushboolean(L, 0);                                    /* (sp += 1) */
2703     lua_setfield(L, -2, "__metatable"); /* protect metatable     (sp -= 1) */
2704     lua_setmetatable(L, -2);                                  /* (sp -= 1) */
2705 }
2706 
2707 __attribute_cold__
2708 static void
2709 magnet_server_table (lua_State * const L)
2710 {
2711     lua_createtable(L, 0, 3); /* {}                              (sp += 1) */
2712     lua_pushcfunction(L, magnet_irequests);                   /* (sp += 1) */
2713     lua_setfield(L, -2, "irequests"); /* iterate over requests   (sp -= 1) */
2714     magnet_plugin_stats_table(L);                             /* (sp += 1) */
2715     lua_setfield(L, -2, "plugin_stats");                      /* (sp -= 1) */
2716     magnet_server_stats_table(L);                             /* (sp += 1) */
2717     lua_setfield(L, -2, "stats");                             /* (sp -= 1) */
2718     lua_createtable(L, 0, 2); /* metatable for server table      (sp += 1) */
2719     lua_pushcfunction(L, magnet_newindex_readonly);           /* (sp += 1) */
2720     lua_setfield(L, -2, "__newindex");                        /* (sp -= 1) */
2721     lua_pushboolean(L, 0);                                    /* (sp += 1) */
2722     lua_setfield(L, -2, "__metatable"); /* protect metatable     (sp -= 1) */
2723     lua_setmetatable(L, -2); /* tie the metatable to server      (sp -= 1) */
2724 }
2725 
2726 __attribute_cold__
2727 static void
2728 magnet_script_setup_global_state (lua_State * const L)
2729 {
2730     lua_atpanic(L, magnet_atpanic);
2731 
2732     lua_pushglobaltable(L);                                   /* (sp += 1) */
2733     /* override default print() function */
2734     lua_pushcfunction(L, magnet_print);                       /* (sp += 1) */
2735     lua_setfield(L, -2, "print");                             /* (sp -= 1) */
2736   #if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 502
2737     /* override default pairs() function to our __pairs capable version */
2738     lua_getglobal(L, "pairs"); /* push original pairs()          (sp += 1) */
2739     lua_pushcclosure(L, magnet_pairs, 1);            /* (sp -= 1; sp += 1) */
2740     lua_setfield(L, -2, "pairs");                             /* (sp -= 1) */
2741   #endif
2742     lua_pop(L, 1); /* pop global table */                     /* (sp -= 1) */
2743 
2744     magnet_req_header_metatable(L);    /* init for mem locality  (sp += 1) */
2745     magnet_req_attr_metatable(L);      /* init for mem locality  (sp += 1) */
2746     magnet_req_item_metatable(L);      /* init for mem locality  (sp += 1) */
2747     magnet_req_env_metatable(L);       /* init for mem locality  (sp += 1) */
2748     magnet_resp_header_metatable(L);   /* init for mem locality  (sp += 1) */
2749     magnet_resp_body_metatable(L);     /* init for mem locality  (sp += 1) */
2750     magnet_req_body_metatable(L);      /* init for mem locality  (sp += 1) */
2751     magnet_stat_metatable(L);    /* init table for mem locality  (sp += 1) */
2752     magnet_readdir_metatable(L); /* init table for mem locality  (sp += 1) */
2753     lua_pop(L, 9);               /* pop init'd metatables        (sp -= 9) */
2754 }
2755 
2756 __attribute_cold__
2757 static void
2758 magnet_init_lighty_table (lua_State * const L, request_st **rr)
2759 {
2760     /* lighty table
2761      *
2762      * lighty.r.*                HTTP request object methods
2763      * lighty.c.*                lighttpd C methods callable from lua
2764      * lighty.server.*           lighttpd server object methods
2765      *
2766      * (older interface)
2767      *
2768      * lighty.request[]      HTTP request headers
2769      * lighty.req_env[]      environment variables
2770      * lighty.env[]          lighttpd request metadata,
2771      *                       various url components,
2772      *                       physical file paths;
2773      *                       might contain nil values
2774      *
2775      * lighty.header[]       (script) HTTP response headers
2776      * lighty.content[]      (script) HTTP response body (table of string/file)
2777      *
2778      * lighty.status[]       lighttpd status counters
2779      */
2780 
2781     /*(adjust the preallocation if more entries are added)*/
2782     lua_createtable(L, 0, 9); /* lighty.* (returned on stack)    (sp += 1) */
2783 
2784     magnet_request_table(L, rr); /* lighty.r                     (sp += 1) */
2785     lua_setfield(L, -2, "r"); /* lighty.r = {}                   (sp -= 1) */
2786 
2787     magnet_server_table(L); /* lighty.server                     (sp += 1) */
2788     lua_setfield(L, -2, "server"); /* server = {}                (sp -= 1) */
2789 
2790     /* compatibility with previous mod_magnet interfaces in top of lighty.* */
2791     lua_getfield(L, -1, "r");                                 /* (sp += 1) */
2792     /* alias lighty.request -> lighty.r.req_header */
2793     lua_getfield(L, -1, "req_header");                        /* (sp += 1) */
2794     lua_setfield(L, -3, "request"); /* request = {}              (sp -= 1) */
2795     /* alias lighty.env     -> lighty.r.req_attr */
2796     lua_getfield(L, -1, "req_attr");                          /* (sp += 1) */
2797     lua_setfield(L, -3, "env"); /* env = {}                      (sp -= 1) */
2798     /* alias lighty.req_env -> lighty.r.req_env */
2799     lua_getfield(L, -1, "req_env");                           /* (sp += 1) */
2800     lua_setfield(L, -3, "req_env"); /* req_env = {}              (sp -= 1) */
2801     lua_pop(L, 1);                                            /* (sp -= 1) */
2802 
2803     /* alias lighty.server.stats -> lighty.status */
2804     lua_getfield(L, -1, "server");                            /* (sp += 1) */
2805     lua_getfield(L, -1, "plugin_stats");                      /* (sp += 1) */
2806     lua_setfield(L, -3, "status"); /* status = {}                (sp -= 1) */
2807     lua_pop(L, 1);                                            /* (sp -= 1) */
2808 
2809     lua_pushinteger(L, MAGNET_RESTART_REQUEST);
2810     lua_setfield(L, -2, "RESTART_REQUEST");
2811 
2812     /* alias lighty.c.stat -> lighty.stat */
2813     lua_pushcfunction(L, magnet_stat);                        /* (sp += 1) */
2814     lua_setfield(L, -2, "stat"); /* -1 is the env we want to set (sp -= 1) */
2815 
2816     /* add empty 'header' and 'result' tables; ('content' is under 'result') */
2817     /* (prefer newer lighty.r.resp_header(), lighty.r.resp_body() interfaces) */
2818     lua_createtable(L, 0, 8); /* {}                              (sp += 1) */
2819     lua_setfield(L, -2, "header"); /* header = {}                (sp -= 1) */
2820 
2821     lua_createtable(L, 0, 1); /* {}                              (sp += 1) */
2822     lua_setfield(L, -2, "result"); /* result = {}                (sp -= 1) */
2823 
2824     static const luaL_Reg cmethods[] = {
2825       { "stat",             magnet_stat }
2826      ,{ "time",             magnet_time }
2827      ,{ "hrtime",           magnet_hrtime }
2828      ,{ "rand",             magnet_rand }
2829      ,{ "md",               magnet_md_once   } /* message digest */
2830      ,{ "hmac",             magnet_hmac_once } /* HMAC */
2831      ,{ "digest_eq",        magnet_digest_eq } /* timing-safe eq fixed len */
2832      ,{ "secret_eq",        magnet_secret_eq } /* timing-safe eq variable len */
2833      ,{ "b64urldec",        magnet_b64urldec } /* validate and decode base64url */
2834      ,{ "b64urlenc",        magnet_b64urlenc } /* base64url encode, no padding */
2835      ,{ "b64dec",           magnet_b64stddec } /* validate and decode base64 */
2836      ,{ "b64enc",           magnet_b64stdenc } /* base64 encode, no padding */
2837      ,{ "hexdec",           magnet_hexdec } /* validate and decode hex str */
2838      ,{ "hexenc",           magnet_hexenc } /* uc; lc w/ lua s = s:lower() */
2839      ,{ "xmlenc",           magnet_xmlenc } /* xml-encode/html-encode: <>&'\" */
2840      ,{ "urldec",           magnet_urldec } /* url-decode (path) */
2841      ,{ "urlenc",           magnet_urlenc } /* url-encode (path) */
2842      ,{ "urldec_query",     magnet_urldec_query } /* url-decode query-string */
2843      ,{ "urlenc_query",     magnet_urlenc_query } /* url-encode query-string */
2844      ,{ "urlenc_normalize", magnet_urlenc_normalize }/* url-enc normalization */
2845      ,{ "fspath_simplify",  magnet_fspath_simplify } /* simplify fspath */
2846      ,{ "cookie_tokens",    magnet_cookie_tokens } /* parse cookie tokens */
2847      ,{ "header_tokens",    magnet_header_tokens } /* parse header tokens seq */
2848      ,{ "readdir",          magnet_readdir } /* dir walk */
2849      ,{ "quoteddec",        magnet_quoteddec } /* quoted-string decode */
2850      ,{ "quotedenc",        magnet_quotedenc } /* quoted-string encode */
2851      ,{ NULL, NULL }
2852     };
2853 
2854     lua_createtable(L, 0, sizeof(cmethods)/sizeof(luaL_Reg)-1);/*(sp += 1) */
2855     luaL_setfuncs(L, cmethods, 0);
2856     lua_createtable(L, 0, 2); /* metatable for c table           (sp += 1) */
2857     lua_pushcfunction(L, magnet_newindex_readonly);           /* (sp += 1) */
2858     lua_setfield(L, -2, "__newindex");                        /* (sp -= 1) */
2859     lua_pushboolean(L, 0);                                    /* (sp += 1) */
2860     lua_setfield(L, -2, "__metatable"); /* protect metatable     (sp -= 1) */
2861     lua_setmetatable(L, -2); /* tie the metatable to c           (sp -= 1) */
2862     lua_setfield(L, -2, "c"); /* c = {}                          (sp -= 1) */
2863 
2864     lua_createtable(L, 0, 3); /* metatable for lighty table      (sp += 1) */
2865     lua_pushcfunction(L, magnet_lighty_result_get);           /* (sp += 1) */
2866     lua_setfield(L, -2, "__index");                           /* (sp -= 1) */
2867     lua_pushcfunction(L, magnet_lighty_result_set);           /* (sp += 1) */
2868     lua_setfield(L, -2, "__newindex");                        /* (sp -= 1) */
2869     lua_pushboolean(L, 0);                                    /* (sp += 1) */
2870     lua_setfield(L, -2, "__metatable"); /* protect metatable     (sp -= 1) */
2871     lua_setmetatable(L, -2); /* tie the metatable to lighty      (sp -= 1) */
2872 
2873     /* lighty table (returned on stack) */
2874 }
2875 
2876 static void magnet_clear_table(lua_State * const L, int ndx) {
2877     /*(avoid lua_absindex() func call since expecting empty tables for legacy
2878      * interfaces to lighty.header and lighty.content, though not script-env)*/
2879     /*ndx = lua_absindex(ndx);*//*(lua 5.2+)*/
2880     if (ndx < 0) --ndx;
2881     for (lua_pushnil(L); lua_next(L, ndx); ) {
2882         lua_pop(L, 1);
2883         lua_pushvalue(L, -1);
2884         lua_pushnil(L);
2885         lua_rawset(L, ndx < 0 ? ndx - 2 : ndx);
2886     }
2887 }
2888 
2889 static void magnet_reset_lighty_table(lua_State * const L, const int lighty_table_ndx) {
2890     /* clear response tables (release mem if reusing lighty table) */
2891     if (lua_getfield_and_type(L, lighty_table_ndx, "result") == LUA_TTABLE)
2892         magnet_clear_table(L, -1); /*lighty.result*/
2893     else {
2894         lua_createtable(L, 0, 1);
2895         lua_setfield(L, lighty_table_ndx, "result");
2896     }
2897 
2898     if (lua_getfield_and_type(L, lighty_table_ndx, "header") == LUA_TTABLE)
2899         magnet_clear_table(L, -1); /*lighty.header*/
2900     else {
2901         lua_createtable(L, 0, 0);
2902         lua_setfield(L, lighty_table_ndx, "header");
2903     }
2904 
2905     /* pop two tables (or nils) added by two lua_getfield_and_type() calls */
2906     /*lua_pop(L, 2);*/ /* defer to later */
2907 }
2908 
2909 __attribute_cold__
2910 static int magnet_traceback(lua_State *L) {
2911 	if (!lua_isstring(L, 1))  /* 'message' not a string? */
2912 		return 1;  /* keep it intact */
2913 	if (lua_getglobal_and_type(L, "debug") != LUA_TTABLE) {
2914 		lua_pop(L, 1);
2915 		return 1;
2916 	}
2917 	if (lua_getfield_and_type(L, -1, "traceback") != LUA_TFUNCTION) {
2918 		lua_pop(L, 2);
2919 		return 1;
2920 	}
2921 	lua_pushvalue(L, 1);  /* pass error message */
2922 	lua_pushinteger(L, 2);  /* skip this function and traceback */
2923 	lua_call(L, 2, 1);  /* call debug.traceback */
2924 	return 1;
2925 }
2926 
2927 __attribute_cold__
2928 __attribute_noinline__
2929 static int
2930 magnet_script_setup (request_st * const r, plugin_data * const p, script * const sc)
2931 {
2932 	lua_State * const L = sc->L;
2933 	const int func_ndx = 1;
2934 	if (lua_isfunction(L, func_ndx)) {
2935 		/* initial setup for global lua_State */
2936 		magnet_script_setup_global_state(L);
2937 		/*force_assert(lua_gettop(L) == 1);*/ /* errfunc_ndx = 2 */
2938 		lua_pushcfunction(L, magnet_traceback);/*errfunc*//* (sp += 1) */
2939 		/* create empty table for script environment (reused)
2940 		 *   setmetatable({}, {__index = _G})
2941 		 *     if a function symbol is not defined in our env,
2942 		 *     __index will lookup in the global env. */
2943 		lua_createtable(L, 0, 1); /* env_ndx = 3 */       /* (sp += 1) */
2944 		magnet_mainenv_metatable(L);                      /* (sp += 1) */
2945 		lua_setmetatable(L, -2);                          /* (sp -= 1) */
2946 		/* set script env in first upvalue (_ENV upvalue) for func */
2947 		lua_pushvalue(L, -1);                             /* (sp += 1) */
2948 		magnet_setfenv_mainfn(L, func_ndx);               /* (sp -= 1) */
2949 		/* shared userdata (ud_ndx = 4) */
2950 		request_st ** const r_userdata =                  /* (sp += 1) */
2951 		  (request_st **)lua_newuserdata0(L, sizeof(request_st *));
2952 		/* insert lighty table (lighty_table_ndx = 5) */
2953 		magnet_init_lighty_table(L, r_userdata); /* lighty.* (sp += 1) */
2954 		return 1;
2955 	}
2956 	else {
2957 		if (lua_isstring(L, func_ndx))
2958 			log_error(r->conf.errh, __FILE__, __LINE__,
2959 			  "loading script %s failed: %s", sc->name.ptr,
2960 			  lua_tostring(L, func_ndx));
2961 		else /*(lua_gettop(L) == 0)*/
2962 			log_perror(r->conf.errh, __FILE__, __LINE__,
2963 			  "loading script %s failed", sc->name.ptr);
2964 		lua_settop(L, 0);
2965 
2966 		if (p->conf.stage != -1) { /* skip for response-start */
2967 			r->http_status = 500;
2968 			r->handler_module = NULL;
2969 		}
2970 
2971 		return 0;
2972 	}
2973 }
2974 
2975 static handler_t
2976 magnet_attract (request_st * const r, plugin_data * const p, script * const sc)
2977 {
2978 	lua_State * const L = sc->L;
2979 	const int func_ndx = 1;
2980 	const int errfunc_ndx = 2;
2981 	const int env_ndx = 3;
2982 	const int ud_ndx = 4;
2983 	const int lighty_table_ndx = 5;
2984 
2985 	if (__builtin_expect( (lua_gettop(L) != lighty_table_ndx), 0)) {
2986 		if (!magnet_script_setup(r, p, sc))
2987 			return HANDLER_FINISHED;
2988 	}
2989 
2990 	/* set r in global state for L for out-of-band access to r
2991 	 * (r-conf.errh and others) */
2992         magnet_set_request(L, r);
2993 	/* set r in userdata shared by lighty.r object methods */
2994 	*(request_st **)lua_touserdata(L, ud_ndx) = r;
2995 
2996 	/* add lighty table to script-env
2997 	 * script-env is cleared at the end of each script run */
2998 	lua_pushvalue(L, lighty_table_ndx);                       /* (sp += 1) */
2999 	lua_setfield(L, env_ndx, "lighty"); /* lighty.*              (sp -= 1) */
3000 
3001 	/* push script func; pcall will consume the func value */
3002 	lua_pushvalue(L, func_ndx);                               /* (sp += 1) */
3003 	int ret = lua_pcall(L, 0, 1, errfunc_ndx);       /* (sp -= 1; sp += 1) */
3004 
3005 	handler_t result = HANDLER_GO_ON;
3006 	if (0 != ret) {
3007 			log_error(r->conf.errh, __FILE__, __LINE__,
3008 			  "lua_pcall(): %s", lua_tostring(L, -1));
3009 			/*lua_pop(L, 1);*/ /* pop error msg */ /* defer to later */
3010 			/* only func,errfunc,env,ud,lighty table should remain on stack */
3011 			/*(lua_pop() deferred, so lighty_table_ndx+1)*/
3012 			/*force_assert(lua_gettop(L) == lighty_table_ndx);*/
3013 
3014 			if (p->conf.stage != -1) { /* skip for response-start */
3015 				r->http_status = 500;
3016 				r->handler_module = NULL;
3017 			}
3018 
3019 			result = HANDLER_FINISHED;
3020 	}
3021 	else {
3022 		/* should have func,errfunc,env,ud,lighty table, return value on stack*/
3023 		/*force_assert(lua_gettop(L) == lighty_table_ndx+1);*/
3024 
3025 		/*(luaL_optinteger might raise error, which we want to avoid)*/
3026 		/*lua_return_value = (int) luaL_optinteger(L, -1, -1);*/
3027 		int isnum = 1;
3028 		int lua_return_value = lua_isnil(L, -1)
3029 		  ? 0
3030 		  : (int) lua_tointegerx(L, -1, &isnum);
3031 		if (!isnum) {
3032 			lua_return_value = -1;
3033 			log_error(r->conf.errh, __FILE__, __LINE__,
3034 			  "lua_pcall(): unexpected non-integer return type: %s",
3035 			  luaL_typename(L, -1));
3036 		}
3037 		/*lua_pop(L, 1);*/ /* pop return value */ /* defer to later */
3038 		/*force_assert(lua_istable(sc->L, -1));*/
3039 
3040 		magnet_copy_response_header(L, r, lighty_table_ndx);
3041 
3042 		if (lua_return_value >= 200) {
3043 			r->http_status = lua_return_value;
3044 			r->resp_body_finished = 1;
3045 			/*(note: body may already have been set via lighty.r.resp_body.*)*/
3046 			magnet_attach_content(L, r, lighty_table_ndx);
3047 			if (!chunkqueue_is_empty(&r->write_queue)) {
3048 				r->handler_module = p->self;
3049 			}
3050 			result = HANDLER_FINISHED;
3051 		} else if (lua_return_value >= 100 && p->conf.stage != -1) {
3052 			/*(skip for response-start; send response as-is w/ added headers)*/
3053 			/*(custom lua code should not return 101 Switching Protocols)*/
3054 			r->http_status = lua_return_value;
3055 			result = http_response_send_1xx(r)
3056 			  ? HANDLER_GO_ON
3057 			  : HANDLER_ERROR;
3058 		} else if (MAGNET_RESTART_REQUEST == lua_return_value) {
3059 			/*(could detect restart loops in same way as is done in mod_rewrite,
3060 			 * but using r->env means that we do not need to reset plugin state
3061 			 * at end of every request, as is done in mod_rewrite.  mod_rewrite
3062 			 * always restarts the request processing (if request is rewritten),
3063 			 * whereas mod_magnet can be used in many other ways)*/
3064 			buffer *vb =
3065 			  http_header_env_get(r, CONST_STR_LEN("_L_MAGNET_RESTART"));
3066 			if (NULL == vb) {
3067 				vb =
3068 				  http_header_env_set_ptr(r,CONST_STR_LEN("_L_MAGNET_RESTART"));
3069 				buffer_append_string_len(vb, "0", 1);
3070 			}
3071 			result = HANDLER_COMEBACK;
3072 			if (++*vb->ptr-'0' >= 10) {
3073 				log_error(r->conf.errh, __FILE__, __LINE__,
3074 				  "too many request restarts (infinite loop?) for %s",
3075 				  sc->name.ptr);
3076 				result = HANDLER_ERROR;
3077 			}
3078 		}
3079 
3080 	}
3081 	magnet_clear_table(L, env_ndx);
3082 	magnet_reset_lighty_table(L, lighty_table_ndx);
3083 	/* reset stack to have only func, errfunc, env, ud, lighty table */
3084 	lua_settop(L, lighty_table_ndx); /*(handle deferred lua_pop()s)*/
3085 	return result;
3086 }
3087 
3088 static handler_t magnet_attract_array(request_st * const r, plugin_data * const p, int stage) {
3089 	mod_magnet_patch_config(r, p);
3090 	p->conf.stage = stage;
3091 
3092 	script * const *scripts;
3093 	switch (stage) {
3094 	  case  1: scripts = p->conf.url_raw; break;
3095 	  case  0: scripts = p->conf.physical_path; break;
3096 	  case -1: scripts = p->conf.response_start; break;
3097 	  default: scripts = NULL; break;
3098 	}
3099 	if (NULL == scripts) return HANDLER_GO_ON; /* no scripts set */
3100 
3101 	/*(always check at least mtime and size to trigger script reload)*/
3102 	const int etag_flags = r->conf.etag_flags | ETAG_USE_MTIME | ETAG_USE_SIZE;
3103 	int req_env_inited = 0;
3104 
3105 	/* execute scripts sequentially while HANDLER_GO_ON */
3106 	handler_t rc = HANDLER_GO_ON;
3107 	do {
3108 		script_cache_check_script(*scripts, etag_flags);
3109 		if ((*scripts)->req_env_init && !req_env_inited) {
3110 			/*(request env init is deferred until needed)*/
3111 			req_env_inited = 1;
3112 			r->con->srv->request_env(r);
3113 		}
3114 		rc = magnet_attract(r, p, *scripts);
3115 	} while (rc == HANDLER_GO_ON && *++scripts);
3116 
3117 	if (r->error_handler_saved_status) {
3118 		/* retrieve (possibly modified) REDIRECT_STATUS and store as number */
3119 		int x;
3120 		const buffer * const vb = http_header_env_get(r, CONST_STR_LEN("REDIRECT_STATUS"));
3121 		if (vb && (x = http_header_str_to_code(vb->ptr)) != -1)
3122 			r->error_handler_saved_status =
3123 			  r->error_handler_saved_status > 0 ? (int)x : -(int)x;
3124 	}
3125 
3126 	return rc;
3127 }
3128 
3129 URIHANDLER_FUNC(mod_magnet_uri_handler) {
3130 	return magnet_attract_array(r, p_d, 1);
3131 }
3132 
3133 URIHANDLER_FUNC(mod_magnet_physical) {
3134 	return magnet_attract_array(r, p_d, 0);
3135 }
3136 
3137 URIHANDLER_FUNC(mod_magnet_response_start) {
3138 	return magnet_attract_array(r, p_d, -1);
3139 }
3140 
3141 
3142 int mod_magnet_plugin_init(plugin *p);
3143 int mod_magnet_plugin_init(plugin *p) {
3144 	p->version     = LIGHTTPD_VERSION_ID;
3145 	p->name        = "magnet";
3146 
3147 	p->init        = mod_magnet_init;
3148 	p->handle_uri_clean  = mod_magnet_uri_handler;
3149 	p->handle_physical   = mod_magnet_physical;
3150 	p->handle_response_start = mod_magnet_response_start;
3151 	p->set_defaults  = mod_magnet_set_defaults;
3152 	p->cleanup     = mod_magnet_free;
3153 
3154 	return 0;
3155 }
3156