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