xref: /lighttpd1.4/src/mod_magnet.c (revision 9ac5da27)
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                 if (__builtin_expect( (s[1] != '0'), 0)
1100                     || __builtin_expect( (s[2] != '0'), 0)) {
1101                     unsigned char hhi = hex2int(((unsigned char *)s)[1]);
1102                     unsigned char hlo = hex2int(((unsigned char *)s)[2]);
1103                     if (0xFF == hhi || 0xFF == hlo)
1104                         break;
1105                     *d++ = (hhi << 4) | hlo;
1106                 }
1107                 c = (hi << 4) | lo;
1108                 s += 4;
1109             }
1110             break;
1111           case '0': case '1': case '2': case '3':
1112             if (s+3 <= end
1113                 /*&& ((unsigned char *)s)[0] - '0' < 4*//* 0-3 */
1114                 && ((unsigned char *)s)[1] - '0' < 8    /* 0-7 */
1115                 && ((unsigned char *)s)[2] - '0' < 8) { /* 0-7 */
1116                 c = ((s[0]-'0') << 6) | ((s[1]-'0') << 3) | (s[2]-'0');
1117                 s += 2;
1118             }
1119             else if (*s == '0')
1120                 c = '\0'; /*(special-case "\\0" not part of octal "\\ooo")*/
1121             break;
1122         }
1123         *d++ = c;
1124     }
1125     buffer_truncate(b, d - b->ptr);
1126 }
1127 
1128 static int magnet_bsdec(lua_State *L) {
1129     if (lua_isnoneornil(L, -1)) {
1130         lua_pushlstring(L, "", 0);
1131         return 1;
1132     }
1133     const_buffer s = magnet_checkconstbuffer(L, -1);
1134     if (0 == s.len) {
1135         lua_pushvalue(L, -1);
1136         return 1;
1137     }
1138     const char *ptr = s.ptr;
1139     size_t len = s.len;
1140     if (ptr[0] == '"' && ptr[len-1] == '"') {
1141         /*(ignore double-quotes ('"') surrounding string for convenience)*/
1142         ++ptr;
1143         len -= 2;
1144     }
1145     buffer * const b = magnet_tmpbuf_acquire(L);
1146     magnet_buffer_append_bsdec(b, ptr, len);
1147     lua_pushlstring(L, BUF_PTR_LEN(b));
1148     magnet_tmpbuf_release(b);
1149     return 1;
1150 }
1151 
1152 static int magnet_bsenc(lua_State *L, const buffer_bs_escape_t esc) {
1153     if (lua_isnoneornil(L, -1)) {
1154         lua_pushlstring(L, "", 0);
1155         return 1;
1156     }
1157     const_buffer s = magnet_checkconstbuffer(L, -1);
1158     if (0 == s.len) {
1159         lua_pushvalue(L, -1);
1160         return 1;
1161     }
1162     buffer * const b = magnet_tmpbuf_acquire(L);
1163     buffer_append_bs_escaped(b, s.ptr, s.len, esc);
1164     lua_pushlstring(L, BUF_PTR_LEN(b));
1165     magnet_tmpbuf_release(b);
1166     return 1;
1167 }
1168 
1169 static int magnet_bsenc_default(lua_State *L) {
1170     return magnet_bsenc(L, BS_ESCAPE_DEFAULT);
1171 }
1172 
1173 static int magnet_bsenc_json(lua_State *L) {
1174     return magnet_bsenc(L, BS_ESCAPE_JSON);
1175 }
1176 
1177 static int magnet_xmlenc(lua_State *L) {
1178     if (lua_isnoneornil(L, -1)) {
1179         lua_pushlstring(L, "", 0);
1180         return 1;
1181     }
1182     const_buffer s = magnet_checkconstbuffer(L, -1);
1183     if (0 == s.len) {
1184         lua_pushvalue(L, -1);
1185         return 1;
1186     }
1187     buffer * const b = magnet_tmpbuf_acquire(L);
1188   #if 1
1189     buffer_append_string_encoded(b, s.ptr, s.len, ENCODING_MINIMAL_XML);
1190   #else
1191     const char *e;
1192     size_t i, n, elen;
1193     for (i = 0, n = 0; i < s.len; ++i) {
1194         switch (s.ptr[i]) {
1195           default: continue;
1196           case '<':  e = "&lt;";   elen = sizeof("&lt;")-1;   break;
1197           case '>':  e = "&gt;";   elen = sizeof("&gt;")-1;   break;
1198           case '&':  e = "&amp;";  elen = sizeof("&amp;")-1;  break;
1199           case '\'': e = "&apos;"; elen = sizeof("&apos;")-1; break;
1200           case '"':  e = "&quot;"; elen = sizeof("&quot;")-1; break;
1201           /*(XXX: would be good idea to add CTRLs, DEL, '`' */
1202         }
1203         buffer_append_str2(b, s.ptr+n, i-n, e, elen);
1204         n = i+1;
1205     }
1206     if (i-n)
1207         buffer_append_string_len(b, s.ptr+n, i-n);
1208   #endif
1209     lua_pushlstring(L, BUF_PTR_LEN(b));
1210     magnet_tmpbuf_release(b);
1211     return 1;
1212 }
1213 
1214 static int magnet_urldec(lua_State *L) {
1215     /* url-decode and replace non-printable chars with '_'
1216      * This function should not be used on query-string unless it is used on
1217      * portions of query-string after splitting on '&', replacing '+' w/ ' ' */
1218     if (lua_isnoneornil(L, -1)) {
1219         lua_pushlstring(L, "", 0);
1220         return 1;
1221     }
1222     const_buffer s = magnet_checkconstbuffer(L, -1);
1223     if (0 == s.len) {
1224         lua_pushvalue(L, -1);
1225         return 1;
1226     }
1227     buffer * const b = magnet_tmpbuf_acquire(L);
1228     buffer_copy_string_len(b, s.ptr, s.len);
1229     buffer_urldecode_path(b);
1230     lua_pushlstring(L, BUF_PTR_LEN(b));
1231     magnet_tmpbuf_release(b);
1232     return 1;
1233 }
1234 
1235 static int magnet_urlenc(lua_State *L) {
1236     /* url-encode path
1237      * ('?' is encoded, if present)
1238      *  caller must split string if '?' is part of query-string)
1239      * ('/' is not encoded; caller must encode if not path separator) */
1240     if (lua_isnoneornil(L, -1)) {
1241         lua_pushlstring(L, "", 0);
1242         return 1;
1243     }
1244     const_buffer s = magnet_checkconstbuffer(L, -1);
1245     if (0 == s.len) {
1246         lua_pushvalue(L, -1);
1247         return 1;
1248     }
1249     buffer * const b = magnet_tmpbuf_acquire(L);
1250     buffer_append_string_encoded(b, s.ptr, s.len, ENCODING_REL_URI);
1251     lua_pushlstring(L, BUF_PTR_LEN(b));
1252     magnet_tmpbuf_release(b);
1253     return 1;
1254 }
1255 
1256 static void magnet_urldec_query_part(buffer * const b, const char *s, const size_t slen) {
1257     buffer_clear(b);
1258     char *p = buffer_extend(b, slen);
1259     for (size_t i = 0; i < slen; ++i)
1260         p[i] = (s[i] != '+') ? s[i] : ' ';
1261     buffer_urldecode_path(b);
1262 }
1263 
1264 static int magnet_urldec_query(lua_State *L) {
1265     /* split on '&' and '=', url-decode and replace non-printable chars w/ '_',
1266      * and store components in table
1267      * (string input should be query-string without leading '?')
1268      * (note: duplicated keys replace earlier values, but this interface returns
1269      *  a table useful for lookups, so this limitation is often acceptable) */
1270     lua_createtable(L, 0, 0);
1271     if (lua_isnoneornil(L, 1)) {
1272         return 1;
1273     }
1274     const_buffer s = magnet_checkconstbuffer(L, 1);
1275     if (0 == s.len) {
1276         return 1;
1277     }
1278     buffer * const b = magnet_tmpbuf_acquire(L);
1279     for (const char *qs = s.ptr, *eq, *amp; *qs; qs = amp+1) {
1280         for (amp = qs, eq = NULL; *amp && *amp != '&'; ++amp) {
1281             if (*amp == '=' && !eq) eq = amp;
1282         }
1283         if (amp != qs) {
1284             if (eq) {
1285                 magnet_urldec_query_part(b, qs, (size_t)(eq - qs));
1286                 lua_pushlstring(L, BUF_PTR_LEN(b));
1287                 magnet_urldec_query_part(b, eq+1, (size_t)(amp - (eq+1)));
1288                 lua_pushlstring(L, BUF_PTR_LEN(b));
1289             }
1290             else {
1291                 magnet_urldec_query_part(b, qs, (size_t)(amp - qs));
1292                 lua_pushlstring(L, BUF_PTR_LEN(b));
1293                 lua_pushlstring(L, "", 0); /*(lua_pushnil() would delete key)*/
1294             }
1295             lua_rawset(L, -3);
1296         }
1297         if (*amp == '\0') break;
1298     }
1299     magnet_tmpbuf_release(b);
1300     return 1;
1301 }
1302 
1303 static void magnet_urlenc_query_part(buffer * const b, const char * const s, const size_t slen, const int iskey) {
1304     /* encode query part (each part is typically much smaller than chunk buffer)
1305      * all required chars plus '&' ';' '+' '\'' (and encode '=' if part of key)
1306      * (burl_append(b,str,len,BURL_ENCODE_ALL) works, but over-encodes) */
1307   #if 0
1308     /* alternative: (over-encodes some, but less than burl_append()) */
1309     UNUSED(iskey);
1310     buffer_append_string_encoded(b, s, slen, ENCODING_REL_URI);
1311   #else
1312     static const char hex_chars_uc[] = "0123456789ABCDEF";
1313     char * const p = buffer_string_prepare_append(b, slen*3);
1314     int j = 0;
1315     for (size_t i = 0; i < slen; ++i, ++j) {
1316         int c = s[i];
1317         if (!light_isalnum(c)) switch (c) {
1318           case ' ':
1319             c = '+';
1320             break;
1321           /*case '\'':*//*(ok in url query-part, but might be misused in HTML)*/
1322           case '!': case '$': case '(': case ')': case '*': case ',': case '-':
1323           case '.': case '/': case ':': case '?': case '@': case '_': case '~':
1324             break;
1325           case '=':
1326             if (!iskey) break;
1327             __attribute_fallthrough__
1328           default:
1329             p[j]   = '%';
1330             p[++j] = hex_chars_uc[(s[i] >> 4) & 0xF];
1331             p[++j] = hex_chars_uc[s[i] & 0xF];
1332             continue;
1333         }
1334         p[j] = c;
1335     }
1336     buffer_commit(b, j);
1337   #endif
1338 }
1339 
1340 static int magnet_urlenc_query(lua_State *L) {
1341     /* encode pairs in lua table into query string
1342      * (caller should add leading '?' or '&' when appending to full URL)
1343      * (caller should skip empty table if appending to existing query-string) */
1344     if (!lua_istable(L, 1)) {
1345         lua_pushlstring(L, "", 0);
1346         return 1;
1347     }
1348     buffer * const b = magnet_tmpbuf_acquire(L);
1349     const_buffer s;
1350     for (lua_pushnil(L); lua_next(L, -2); lua_pop(L, 1)) {
1351         if (lua_isstring(L, -2)) {
1352             if (!buffer_is_blank(b))
1353                 buffer_append_char(b, '&');
1354             s = magnet_checkconstbuffer(L, -2);
1355             magnet_urlenc_query_part(b, s.ptr, s.len, 1);
1356             if (!lua_isnil(L, -1)) {
1357                 s = magnet_checkconstbuffer(L, -1);
1358                 buffer_append_char(b, '=');
1359                 magnet_urlenc_query_part(b, s.ptr, s.len, 0);
1360             }
1361         }
1362     }
1363     lua_pushlstring(L, BUF_PTR_LEN(b));
1364     magnet_tmpbuf_release(b);
1365     return 1;
1366 }
1367 
1368 static int magnet_urlenc_normalize(lua_State *L) {
1369     /* normalize url-encoding
1370      * url-encode (and url-decode safe chars) to normalize url-path
1371      * ('?' is treated as start of query-string and is not encoded;
1372      *  caller must encode '?' if intended to be part of url-path)
1373      * ('/' is not encoded; caller must encode if not path separator)
1374      * (burl_append() is not exposed here; caller might want to build
1375      *  url with lighty.c.urlenc() and lighty.c.urlenc_query(),
1376      *  then call lighty.c.urlenc_normalize()) */
1377     if (lua_isnoneornil(L, -1)) {
1378         lua_pushlstring(L, "", 0);
1379         return 1;
1380     }
1381     const_buffer s = magnet_checkconstbuffer(L, -1);
1382     if (0 == s.len) {
1383         lua_pushvalue(L, -1);
1384         return 1;
1385     }
1386     buffer * const b = magnet_tmpbuf_acquire(L);
1387     buffer * const t = chunk_buffer_acquire();
1388   #if 0 /*(?maybe have different interface to use config policy?)*/
1389     request_st * const r = magnet_get_request(L);
1390     const int flags = r->conf.http_parseopts;
1391   #else
1392     const int flags = HTTP_PARSEOPT_URL_NORMALIZE
1393                     | HTTP_PARSEOPT_URL_NORMALIZE_UNRESERVED
1394                     | HTTP_PARSEOPT_URL_NORMALIZE_REQUIRED
1395                     | HTTP_PARSEOPT_URL_NORMALIZE_PATH_2F_DECODE
1396                     | HTTP_PARSEOPT_URL_NORMALIZE_PATH_DOTSEG_REMOVE
1397                     | HTTP_PARSEOPT_URL_NORMALIZE_QUERY_20_PLUS;
1398   #endif
1399     buffer_copy_string_len(b, s.ptr, s.len);
1400     burl_normalize(b, t, flags);
1401     lua_pushlstring(L, BUF_PTR_LEN(b));
1402     chunk_buffer_release(t);
1403     magnet_tmpbuf_release(b);
1404     return 1;
1405 }
1406 
1407 static int magnet_fspath_simplify(lua_State *L) {
1408     /* simplify filesystem path */
1409     if (lua_isnoneornil(L, -1)) {
1410         lua_pushlstring(L, "", 0);
1411         return 1;
1412     }
1413     const_buffer s = magnet_checkconstbuffer(L, -1);
1414     if (0 == s.len) {
1415         lua_pushvalue(L, -1);
1416         return 1;
1417     }
1418     buffer * const b = magnet_tmpbuf_acquire(L);
1419     buffer_copy_string_len(b, s.ptr, s.len);
1420     buffer_path_simplify(b);
1421     lua_pushlstring(L, BUF_PTR_LEN(b));
1422     magnet_tmpbuf_release(b);
1423     return 1;
1424 }
1425 
1426 __attribute_pure__
1427 static const char * magnet_scan_quoted_string (const char *s) {
1428     /* scan to end of of quoted-string (with s starting at '"')
1429      * loose parse; non-validating
1430      * - permit missing '"' at end of string (caller should check)
1431      * - stop at stray '\\' at end of string missing closing '"'
1432      * - not rejecting non-WS CTL chars
1433      */
1434     /*force_assert(*s == '"');*/
1435     do { ++s; } while (*s && *s != '"' && (*s != '\\' || (s[1] ? ++s : 0)));
1436     /*do { ++s; } while (*s && *s != '"' && (*s != '\\' || (*++s || (--s, 0))));*/
1437     return s;
1438 }
1439 
1440 static const char * magnet_push_quoted_string_range (lua_State *L, const char *b, const char *s) {
1441     /* quoted-string is unmodified (except for quoted-string end consistency)
1442      * including surrounding double-quotes and with quoted-pair unmodified */
1443     if (__builtin_expect( (*s == '"'), 1))
1444         lua_pushlstring(L, b, (size_t)(++s-b));
1445     else { /*(else invalid quoted-string, but handle anyway)*/
1446         /* append closing '"' for consistency */
1447         lua_pushlstring(L, b, (size_t)(s-b));
1448         if (*s != '\\')
1449             lua_pushlstring(L, "\"", 1);
1450         else { /* unescaped backslash at end of string; escape and close '"' */
1451             lua_pushlstring(L, "\\\\\"", 3);
1452             ++s; /*(now *s == '\0')*/
1453         }
1454         lua_concat(L, 2);
1455     }
1456     return s;
1457 }
1458 
1459 static const char * magnet_push_quoted_string(lua_State *L, const char *s) {
1460     return magnet_push_quoted_string_range(L, s, magnet_scan_quoted_string(s));
1461 }
1462 
1463 static const char * magnet_cookie_param_push_token(lua_State *L, const char *s) {
1464     const char *b = s;
1465     while (*s!='=' /*(note: not strictly rejecting all 'separators')*/
1466             && *s!=';' && *s!=' ' && *s!='\t' && *s!='\r' && *s!='\n' && *s)
1467         ++s;
1468     lua_pushlstring(L, b, (size_t)(s-b));
1469     return s;
1470 }
1471 
1472 static int magnet_cookie_tokens(lua_State *L) {
1473     /*(special-case cookies (';' separator); dup cookie-names overwritten)*/
1474     lua_createtable(L, 0, 0);
1475     if (lua_isnoneornil(L, 1))
1476         return 1;
1477     const char *s = luaL_checkstring(L, 1);
1478     do {
1479         while (*s==';' || *s==' ' || *s=='\t' || *s=='\r' || *s=='\n')
1480             ++s;
1481         if (*s == '\0') break;
1482         s = magnet_cookie_param_push_token(L, s);
1483         while (           *s==' ' || *s=='\t' || *s=='\r' || *s=='\n')
1484             ++s;
1485         if (*s == '=') {
1486             do {
1487                 ++s;
1488             } while (     *s==' ' || *s=='\t' || *s=='\r' || *s=='\n');
1489             if (*s==';' || *s=='\0')
1490                 lua_pushlstring(L, "", 0); /*(lua_pushnil() would delete key)*/
1491             else if (*s != '"')
1492                 s = magnet_cookie_param_push_token(L, s);
1493             else
1494                 s = magnet_push_quoted_string(L, s);
1495         }
1496         else {
1497             lua_pushlstring(L, "", 0); /*(lua_pushnil() would delete key)*/
1498         }
1499         lua_settable(L, -3);
1500         while (*s!=';' && *s!='\0') ++s; /* ignore/skip stray tokens */
1501     } while (*s++);
1502     return 1;
1503 }
1504 
1505 static const char * magnet_push_token(lua_State *L, const char *s) {
1506     const char *b = s;
1507     while (               *s!=' ' && *s!='\t' && *s!='\r' && *s!='\n'
1508            && *s!=',' && *s!=';' && *s!='=' && *s)
1509         ++s;
1510     lua_pushlstring(L, b, (size_t)(s-b));
1511     return s;
1512 }
1513 
1514 static int magnet_header_tokens(lua_State *L) {
1515     /* split into sequence of tokens/words
1516      *   Intermediate table is then more convenient to walk once quoted-string
1517      *   parsed into table entries since quoted-string may contain separators.
1518      *   Each token can be passed to lighty.c.quoteddec()
1519      *     (lighty.c.quoteddec() returns string as-is if not quoted-string)
1520      * (note: non-validating;
1521      *  e.g. existence of '=' token does not mean that next token is value,
1522      *       and '=' in value which is not part of quoted-string will be
1523      *       treated as separate token)
1524      * (note: case is preserved; non-quoted-string tokens are not lower-cased)
1525      * (words separated by whitespace are separate tokens unless quoted-string)
1526      *   (if that format not permitted in a specific header, caller must detect)
1527      * (optional whitespace (OWS) and bad whitespace (BWS) are removed)
1528      * (caller can create lookup table from sequence table, as appropriate) */
1529     lua_createtable(L, 0, 0);
1530     if (lua_isnoneornil(L, 1))
1531         return 1;
1532     const char *s = luaL_checkstring(L, 1);
1533     int i = 0;
1534     do {
1535         while (           *s==' ' || *s=='\t' || *s=='\r' || *s=='\n')
1536             ++s;
1537         if (*s=='\0') break;
1538         if (*s==',' || *s==';' || *s=='=')
1539             lua_pushlstring(L, s++, 1);
1540         else if (*s != '"')
1541             s = magnet_push_token(L, s);
1542         else
1543             s = magnet_push_quoted_string(L, s);
1544         lua_rawseti(L, -2, ++i);
1545     } while (*s);
1546     return 1;
1547 }
1548 
1549 static int magnet_reqhdr_get(lua_State *L) {
1550     size_t klen;
1551     const char * const k = luaL_checklstring(L, 2, &klen);
1552     const request_st * const r = **(request_st ***)lua_touserdata(L, 1);
1553     const int id = http_header_hkey_get(k, (uint32_t)klen);
1554     magnet_push_buffer(L, http_header_request_get(r, id, k, klen));
1555     return 1;
1556 }
1557 
1558 static int magnet_reqhdr_set(lua_State *L) {
1559     const_buffer k = magnet_checkconstbuffer(L, 2);
1560     const_buffer v = magnet_checkconstbuffer(L, 3);
1561 
1562     request_st * const r = **(request_st ***)lua_touserdata(L, 1);
1563     enum http_header_e id = http_header_hkey_get(k.ptr, (uint32_t)k.len);
1564 
1565     switch (id) {
1566       /*case HTTP_HEADER_OTHER:*/
1567       default:
1568         break;
1569 
1570       case HTTP_HEADER_HOST:
1571         /* do not allow Host to be unset, even if HTTP/1.0
1572          * (change Host to something else, if you must */
1573         if (0 == v.len) return 0;
1574 
1575         /*(must set r->http_host if r->http_host was not previously set)*/
1576         /* copied from request.c:http_request_header_set_Host() */
1577         r->http_host = http_header_request_set_ptr(r, HTTP_HEADER_HOST,
1578                                                    CONST_STR_LEN("Host"));
1579         buffer_copy_string_len_lc(r->http_host, v.ptr, v.len);
1580         return 0;
1581 
1582       case HTTP_HEADER_CONTENT_LENGTH:
1583         /* not attempting to handle Content-Length modification; may revisit */
1584         /* future: might permit setting to 0 to force discard of request body
1585          * but would have to check if request body present, and if
1586          * Content-Length was set, or if Transfer-Encoding: chunked,
1587          * and handle resetting internal chunked encoding state,
1588          * as well as making sure that this is handled properly for HTTP/2 */
1589         return 0; /* silently ignore; do not allow modification */
1590 
1591       /* do not permit modification of hop-by-hop (connection) headers */
1592 
1593       case HTTP_HEADER_CONNECTION:
1594         /* do not permit modification of Connection, incl add/remove tokens */
1595         /* future: might provide a different interface to set r->keep_alive = 0,
1596          *         and also handle in context if HTTP/2 */
1597       case HTTP_HEADER_TRANSFER_ENCODING:
1598       case HTTP_HEADER_SET_COOKIE:/*(response hdr;avoid accidental reflection)*/
1599         return 0; /* silently ignore; do not allow modification */
1600      #if 0 /*(eh, if script sets Upgrade, script probably intends this action)*/
1601       case HTTP_HEADER_UPGRADE:
1602         /* note: modifications here do not modify Connection header
1603          *       to add or remove "upgrade" token */
1604         /* future: might allow removal of existing tokens, but not addition */
1605         if (0 != v.len) return 0; /* do not allow Upgrade other than to unset */
1606         break;
1607      #endif
1608      #if 0 /*(eh, if script sets TE, script probably intends this action)*/
1609       case HTTP_HEADER_TE:
1610         if (0 != v.len) return 0; /* do not allow TE other than to unset */
1611         break;
1612      #endif
1613     }
1614 
1615     v.len
1616       ? http_header_request_set(r, id, k.ptr, k.len, v.ptr, v.len)
1617       : http_header_request_unset(r, id, k.ptr, k.len);
1618     return 0;
1619 }
1620 
1621 static int magnet_reqhdr_pairs(lua_State *L) {
1622     request_st * const r = **(request_st ***)lua_touserdata(L, 1);
1623     return magnet_array_pairs(L, &r->rqst_headers);
1624 }
1625 
1626 static int magnet_resphdr_get(lua_State *L) {
1627     /* Note: access to lighttpd r->resp_headers here is *independent* from
1628      * the (pending) changes in the (deprecated) lua lighty.header[] table */
1629     size_t klen;
1630     const char * const k = luaL_checklstring(L, 2, &klen);
1631     const request_st * const r = **(request_st ***)lua_touserdata(L, 1);
1632     const int id = http_header_hkey_get(k, (uint32_t)klen);
1633     magnet_push_buffer(L, http_header_response_get(r, id, k, klen));
1634     return 1;
1635 }
1636 
1637 static int magnet_resphdr_set_kv(lua_State *L, request_st * const r) {
1638     const const_buffer k = magnet_checkconstbuffer(L, -2);
1639     const const_buffer v = magnet_checkconstbuffer(L, -1);
1640     const enum http_header_e id = http_header_hkey_get(k.ptr, (uint32_t)k.len);
1641 
1642     switch (id) {
1643       /*case HTTP_HEADER_OTHER:*/
1644       default:
1645         break;
1646 
1647       case HTTP_HEADER_CONTENT_LENGTH:
1648         /* lighttpd handles Content-Length or Transfer-Encoding for response */
1649         return 0; /* silently ignore; do not allow modification */
1650 
1651       /* do not permit modification of hop-by-hop (connection) headers */
1652 
1653       case HTTP_HEADER_CONNECTION:
1654         /* do not permit modification of Connection, incl add/remove tokens */
1655         /* future: might provide a different interface to set r->keep_alive = 0,
1656          *         and also handle in context if HTTP/2 */
1657       case HTTP_HEADER_TRANSFER_ENCODING:
1658         return 0; /* silently ignore; do not allow modification */
1659     }
1660 
1661     if (0 == v.len) {
1662         http_header_response_unset(r, id, k.ptr, k.len);
1663         return 0;
1664     }
1665 
1666     buffer * const vb = http_header_response_set_ptr(r, id, k.ptr, k.len);
1667     buffer_copy_string_len(vb, v.ptr, v.len);
1668 
1669     if (r->http_version >= HTTP_VERSION_2) {
1670         /* handle multi-line response headers with HTTP/2
1671          * (lowercase header name and mark r->resp_header_repeated)
1672          * (similar to http_header.c:http_header_response_insert_addtl()) */
1673         for (char *n = vb->ptr; (n = strchr(n, '\n')); ) {
1674             r->resp_header_repeated = 1;
1675             do {
1676                 ++n;
1677                 if (light_isupper(*n)) *n |= 0x20;
1678             } while (*n != ':' && *n != '\n' && *n != '\0');
1679         }
1680     }
1681 
1682     return 0;
1683 }
1684 
1685 static int magnet_resphdr_set(lua_State *L) {
1686     /*const_buffer k = magnet_checkconstbuffer(L, 2);*/
1687     /*const_buffer v = magnet_checkconstbuffer(L, 3);*/
1688     request_st * const r = **(request_st ***)lua_touserdata(L, 1);
1689     return magnet_resphdr_set_kv(L, r);
1690 }
1691 
1692 static int magnet_resphdr_pairs(lua_State *L) {
1693     request_st * const r = **(request_st ***)lua_touserdata(L, 1);
1694     return magnet_array_pairs(L, &r->resp_headers);
1695 }
1696 
1697 static int magnet_plugin_stats_get(lua_State *L) {
1698     const_buffer k = magnet_checkconstbuffer(L, 2);
1699     lua_pushinteger(L, (lua_Integer)*plugin_stats_get_ptr(k.ptr, k.len));
1700     return 1;
1701 }
1702 
1703 static int magnet_plugin_stats_set(lua_State *L) {
1704     const_buffer k = magnet_checkconstbuffer(L, 2);
1705     plugin_stats_set(k.ptr, k.len, luaL_checkinteger(L, 3));
1706     return 0;
1707 }
1708 
1709 static int magnet_plugin_stats_pairs(lua_State *L) {
1710     return magnet_array_pairs(L, &plugin_stats);
1711 }
1712 
1713 
1714 static int
1715 magnet_req_item_get (lua_State *L)
1716 {
1717     size_t klen;
1718     const char * const k = luaL_checklstring(L, 2, &klen);
1719     request_st * const r = **(request_st ***)lua_touserdata(L, 1);
1720     switch (klen) {
1721       case 8:
1722         if (0 == memcmp(k, "bytes_in", 8)) {
1723             lua_pushinteger(L, (lua_Integer)http_request_stats_bytes_in(r));
1724             return 1;
1725         }
1726         break;
1727       case 9:
1728         if (0 == memcmp(k, "bytes_out", 9)) {
1729             lua_pushinteger(L, (lua_Integer)http_request_stats_bytes_out(r));
1730             return 1;
1731         }
1732         if (0 == memcmp(k, "stream_id", 9)) {
1733             lua_pushinteger(L, (lua_Integer)r->h2id);
1734             return 1;
1735         }
1736         if (0 == memcmp(k, "req_count", 9)) {
1737             lua_pushinteger(L, (lua_Integer)r->con->request_count);
1738             return 1;
1739         }
1740         break;
1741       case 10:
1742         if (0 == memcmp(k, "start_time", 10)) {
1743             lua_pushinteger(L, (lua_Integer)r->start_hp.tv_sec);
1744             lua_pushinteger(L, (lua_Integer)r->start_hp.tv_nsec);
1745             lua_pushcclosure(L, magnet_return_upvalue2, 2);
1746             return 1;
1747         }
1748         if (0 == memcmp(k, "keep_alive", 10)) {
1749             lua_pushinteger(L, (lua_Integer)r->keep_alive);
1750             return 1;
1751         }
1752         break;
1753       case 11:
1754         if (0 == memcmp(k, "http_status", 11)) {
1755             lua_pushinteger(L, (lua_Integer)r->http_status);
1756             return 1;
1757         }
1758         break;
1759       case 14:
1760         if (0 == memcmp(k, "req_header_len", 14)) {
1761             lua_pushinteger(L, (lua_Integer)r->rqst_header_len);
1762             return 1;
1763         }
1764         break;
1765       case 15:
1766         if (0 == memcmp(k, "resp_header_len", 15)) {
1767             lua_pushinteger(L, (lua_Integer)r->resp_header_len);
1768             return 1;
1769         }
1770         break;
1771       default:
1772         break;
1773     }
1774     return luaL_error(L, "r.req_item['%s'] invalid", k);
1775 }
1776 
1777 static int
1778 magnet_req_item_set (lua_State *L)
1779 {
1780     size_t klen;
1781     const char * const k = luaL_checklstring(L, 2, &klen);
1782     int v = (int)luaL_checkinteger(L, 3);
1783 
1784     request_st * const r = **(request_st ***)lua_touserdata(L, 1);
1785     switch (klen) {
1786       case 10:
1787         if (0 == memcmp(k, "keep_alive", 10)) {
1788             if (v == 0 || v == -1) r->keep_alive = v;
1789             return 0;
1790         }
1791         break;
1792       default:
1793         break;
1794     }
1795     return luaL_error(L, "r.req_item['%s'] invalid or read-only", k);
1796 }
1797 
1798 
1799 typedef struct {
1800 	const char *name;
1801 	uint32_t nlen;
1802 	enum {
1803 		MAGNET_ENV_UNSET,
1804 
1805 		MAGNET_ENV_PHYSICAL_PATH,
1806 		MAGNET_ENV_PHYSICAL_REL_PATH,
1807 		MAGNET_ENV_PHYSICAL_DOC_ROOT,
1808 		MAGNET_ENV_PHYSICAL_BASEDIR,
1809 
1810 		MAGNET_ENV_URI_PATH,
1811 		MAGNET_ENV_URI_PATH_RAW,
1812 		MAGNET_ENV_URI_SCHEME,
1813 		MAGNET_ENV_URI_AUTHORITY,
1814 		MAGNET_ENV_URI_QUERY,
1815 
1816 		MAGNET_ENV_REQUEST_METHOD,
1817 		MAGNET_ENV_REQUEST_URI,
1818 		MAGNET_ENV_REQUEST_ORIG_URI,
1819 		MAGNET_ENV_REQUEST_PATH_INFO,
1820 		MAGNET_ENV_REQUEST_REMOTE_ADDR,
1821 		MAGNET_ENV_REQUEST_REMOTE_PORT,
1822 		MAGNET_ENV_REQUEST_SERVER_ADDR,
1823 		MAGNET_ENV_REQUEST_SERVER_PORT,
1824 		MAGNET_ENV_REQUEST_PROTOCOL,
1825 		MAGNET_ENV_REQUEST_SERVER_NAME,
1826 		MAGNET_ENV_REQUEST_STAGE,
1827 
1828 		/* remove after lighttpd 1.4.65 */
1829 		MAGNET_ENV_RESPONSE_HTTP_STATUS,
1830 		MAGNET_ENV_RESPONSE_BODY_LENGTH,
1831 		MAGNET_ENV_RESPONSE_BODY
1832 	} type;
1833 } magnet_env_t;
1834 
1835 /*(NB: coordinate any changes with scan offsets in magnet_env_get_id())*/
1836 static const magnet_env_t magnet_env[] = {
1837     { CONST_STR_LEN("physical.path"),        MAGNET_ENV_PHYSICAL_PATH },
1838     { CONST_STR_LEN("physical.rel-path"),    MAGNET_ENV_PHYSICAL_REL_PATH },
1839     { CONST_STR_LEN("physical.doc-root"),    MAGNET_ENV_PHYSICAL_DOC_ROOT },
1840     { CONST_STR_LEN("physical.basedir"),     MAGNET_ENV_PHYSICAL_BASEDIR },
1841 
1842     { CONST_STR_LEN("uri.path"),             MAGNET_ENV_URI_PATH },
1843     { CONST_STR_LEN("uri.path-raw"),         MAGNET_ENV_URI_PATH_RAW },
1844     { CONST_STR_LEN("uri.scheme"),           MAGNET_ENV_URI_SCHEME },
1845     { CONST_STR_LEN("uri.authority"),        MAGNET_ENV_URI_AUTHORITY },
1846     { CONST_STR_LEN("uri.query"),            MAGNET_ENV_URI_QUERY },
1847 
1848     { CONST_STR_LEN("request.method"),       MAGNET_ENV_REQUEST_METHOD },
1849     { CONST_STR_LEN("request.uri"),          MAGNET_ENV_REQUEST_URI },
1850     { CONST_STR_LEN("request.orig-uri"),     MAGNET_ENV_REQUEST_ORIG_URI },
1851     { CONST_STR_LEN("request.path-info"),    MAGNET_ENV_REQUEST_PATH_INFO },
1852     { CONST_STR_LEN("request.remote-ip"),    MAGNET_ENV_REQUEST_REMOTE_ADDR },
1853     { CONST_STR_LEN("request.remote-addr"),  MAGNET_ENV_REQUEST_REMOTE_ADDR },
1854     { CONST_STR_LEN("request.remote-port"),  MAGNET_ENV_REQUEST_REMOTE_PORT },
1855     { CONST_STR_LEN("request.server-addr"),  MAGNET_ENV_REQUEST_SERVER_ADDR },
1856     { CONST_STR_LEN("request.server-port"),  MAGNET_ENV_REQUEST_SERVER_PORT },
1857     { CONST_STR_LEN("request.protocol"),     MAGNET_ENV_REQUEST_PROTOCOL },
1858     { CONST_STR_LEN("request.server-name"),  MAGNET_ENV_REQUEST_SERVER_NAME },
1859     { CONST_STR_LEN("request.stage"),        MAGNET_ENV_REQUEST_STAGE },
1860 
1861     { CONST_STR_LEN("response.http-status"), MAGNET_ENV_RESPONSE_HTTP_STATUS },
1862     { CONST_STR_LEN("response.body-length"), MAGNET_ENV_RESPONSE_BODY_LENGTH },
1863     { CONST_STR_LEN("response.body"),        MAGNET_ENV_RESPONSE_BODY },
1864 
1865     { NULL, 0, MAGNET_ENV_UNSET }
1866 };
1867 
1868 __attribute_cold__
1869 static void
1870 magnet_env_get_uri_path_raw (buffer * const dest, const buffer * const target)
1871 {
1872     const uint32_t len = buffer_clen(target);
1873     const char * const qmark = memchr(target->ptr, '?', len);
1874     buffer_copy_string_len(dest, target->ptr,
1875                            qmark ? (uint32_t)(qmark - target->ptr) : len);
1876 }
1877 
1878 __attribute_cold__
1879 static int
1880 magnet_env_set_uri_path_raw (request_st * const r,
1881                              const const_buffer * const val)
1882 {
1883     /* modify uri-path of r->target; preserve query-part, if present */
1884     /* XXX: should we require that resulting path begin with '/' or %2F ? */
1885     const uint32_t len = buffer_clen(&r->target);
1886     const char * const qmark = memchr(r->target.ptr, '?', len);
1887     if (NULL != qmark)
1888         buffer_copy_string_len(r->tmp_buf, qmark,
1889                                len - (uint32_t)(qmark - r->target.ptr));
1890     buffer_copy_string_len(&r->target, val->ptr, val->len);
1891     if (NULL != qmark)
1892         buffer_append_string_buffer(&r->target, r->tmp_buf);
1893     return 0;
1894 }
1895 
1896 __attribute_cold__
1897 __attribute_noinline__
1898 static buffer *
1899 magnet_env_get_laddr_by_id (request_st * const r, const int id)
1900 {
1901     buffer * const dest = r->tmp_buf;
1902     const server_socket * const srv_socket = r->con->srv_socket;
1903     switch (id) {
1904       case MAGNET_ENV_REQUEST_SERVER_ADDR: /* local IP without port */
1905         if (sock_addr_is_addr_wildcard(&srv_socket->addr)) {
1906             sock_addr addrbuf;
1907             socklen_t addrlen = sizeof(addrbuf);
1908             const int fd = r->con->fd;
1909             if (0 == getsockname(fd,(struct sockaddr *)&addrbuf,&addrlen)) {
1910                 char buf[INET6_ADDRSTRLEN + 1];
1911                 const char *s = sock_addr_inet_ntop(&addrbuf, buf, sizeof(buf));
1912                 if (NULL != s) {
1913                     buffer_copy_string_len(dest, s, strlen(s));
1914                     break;
1915                 }
1916             }
1917         }
1918         buffer_copy_string_len(dest, srv_socket->srv_token->ptr,
1919                                srv_socket->srv_token_colon);
1920         break;
1921       case MAGNET_ENV_REQUEST_SERVER_PORT:
1922       {
1923         const buffer * const srv_token = srv_socket->srv_token;
1924         const uint32_t tlen = buffer_clen(srv_token);
1925         uint32_t portoffset = srv_socket->srv_token_colon;
1926         portoffset = portoffset < tlen ? portoffset+1 : tlen;
1927         buffer_copy_string_len(dest, srv_token->ptr+portoffset,
1928                                tlen-portoffset);
1929         break;
1930       }
1931       default:
1932         break;
1933     }
1934     return dest;
1935 }
1936 
1937 static buffer *
1938 magnet_env_get_buffer_by_id (request_st * const r, const int id)
1939 {
1940 	buffer *dest = r->tmp_buf;
1941 	buffer_clear(dest);
1942 
1943 	switch (id) {
1944 	case MAGNET_ENV_PHYSICAL_PATH: dest = &r->physical.path; break;
1945 	case MAGNET_ENV_PHYSICAL_REL_PATH: dest = &r->physical.rel_path; break;
1946 	case MAGNET_ENV_PHYSICAL_DOC_ROOT: dest = &r->physical.doc_root; break;
1947 	case MAGNET_ENV_PHYSICAL_BASEDIR: dest = &r->physical.basedir; break;
1948 
1949 	case MAGNET_ENV_URI_PATH: dest = &r->uri.path; break;
1950 	case MAGNET_ENV_URI_PATH_RAW:
1951 		magnet_env_get_uri_path_raw(dest, &r->target);
1952 		break;
1953 	case MAGNET_ENV_URI_SCHEME: dest = &r->uri.scheme; break;
1954 	case MAGNET_ENV_URI_AUTHORITY: dest = &r->uri.authority; break;
1955 	case MAGNET_ENV_URI_QUERY: dest = &r->uri.query; break;
1956 
1957 	case MAGNET_ENV_REQUEST_METHOD:
1958 		http_method_append(dest, r->http_method);
1959 		break;
1960 	case MAGNET_ENV_REQUEST_URI:      dest = &r->target; break;
1961 	case MAGNET_ENV_REQUEST_ORIG_URI: dest = &r->target_orig; break;
1962 	case MAGNET_ENV_REQUEST_PATH_INFO: dest = &r->pathinfo; break;
1963 	case MAGNET_ENV_REQUEST_REMOTE_ADDR: dest = &r->con->dst_addr_buf; break;
1964 	case MAGNET_ENV_REQUEST_REMOTE_PORT:
1965 		buffer_append_int(dest, sock_addr_get_port(&r->con->dst_addr));
1966 		break;
1967 	case MAGNET_ENV_REQUEST_SERVER_ADDR: /* local IP without port */
1968 	case MAGNET_ENV_REQUEST_SERVER_PORT:
1969 		return magnet_env_get_laddr_by_id(r, id);
1970 	case MAGNET_ENV_REQUEST_PROTOCOL:
1971 		http_version_append(dest, r->http_version);
1972 		break;
1973 	case MAGNET_ENV_REQUEST_SERVER_NAME:
1974 		buffer_copy_buffer(dest, r->server_name);
1975 		break;
1976 	case MAGNET_ENV_REQUEST_STAGE:
1977 		if (http_request_state_is_keep_alive(r))
1978 			buffer_append_string_len(dest, CONST_STR_LEN("keep-alive"));
1979 		else
1980 			http_request_state_append(dest, r->state);
1981 		break;
1982 
1983 	/* remove after lighttpd 1.4.65 */
1984 	case MAGNET_ENV_RESPONSE_HTTP_STATUS:
1985 		buffer_append_int(dest, r->http_status);
1986 		break;
1987 	case MAGNET_ENV_RESPONSE_BODY_LENGTH:
1988 		if (!r->resp_body_finished)
1989 			return NULL;
1990 		log_error(r->conf.errh, __FILE__, __LINE__,
1991 		          "lighty.r.req_attr['response.body-length'] is deprecated "
1992 		          "and will be removed. Use lighty.r.resp_body.len instead.");
1993 		buffer_append_int(dest, chunkqueue_length(&r->write_queue));
1994 		break;
1995 	case MAGNET_ENV_RESPONSE_BODY:
1996 		if (!r->resp_body_finished)
1997 			return NULL;
1998 		log_error(r->conf.errh, __FILE__, __LINE__,
1999 		          "lighty.r.req_attr['response.body'] is deprecated "
2000 		          "and will be removed. Use lighty.r.resp_body.get instead.");
2001 		if (0 == chunkqueue_length(&r->write_queue)
2002 		    || !(dest = chunkqueue_read_squash(&r->write_queue,r->conf.errh)))
2003 			buffer_copy_string_len((dest = r->tmp_buf), CONST_STR_LEN(""));
2004 		break;
2005 
2006 	case MAGNET_ENV_UNSET:
2007 		return NULL;
2008 	}
2009 
2010 	return dest;
2011 }
2012 
2013 __attribute_pure__
2014 static int magnet_env_get_id(const char * const key, const size_t klen) {
2015     /*(NB: ensure offsets match position in magnet_env[])*/
2016     int i; /* magnet_env[] scan offset */
2017     switch (*key) {
2018       case 'r': /* request.* or response.* */
2019         i = klen > 7 && key[7] == '.' ? 9 : 21;
2020         break;
2021       case 'u': /* uri.* */
2022       default:
2023         i = 4;
2024         break;
2025       case 'p': /* physical.* */
2026         i = 0;
2027         break;
2028     }
2029     for (; i < (int)(sizeof(magnet_env)/sizeof(*magnet_env)); ++i) {
2030         if (klen == magnet_env[i].nlen
2031             && 0 == memcmp(key, magnet_env[i].name, klen))
2032             return magnet_env[i].type;
2033     }
2034     return MAGNET_ENV_UNSET;
2035 }
2036 
2037 static int magnet_env_get(lua_State *L) {
2038     size_t klen;
2039     const char * const k = luaL_checklstring(L, 2, &klen);
2040     const int env_id = magnet_env_get_id(k, klen);
2041     request_st * const r = **(request_st ***)lua_touserdata(L, 1);
2042     magnet_push_buffer(L, magnet_env_get_buffer_by_id(r, env_id));
2043     return 1;
2044 }
2045 
2046 __attribute_cold__
2047 static int
2048 magnet_env_set_raddr_by_id (lua_State *L, request_st * const r, const int id,
2049                             const const_buffer * const val)
2050 {
2051     connection * const con = r->con;
2052     switch (id) {
2053       case MAGNET_ENV_REQUEST_REMOTE_ADDR:
2054        #ifdef HAVE_SYS_UN_H
2055         if (val->len && *val->ptr == '/'
2056             && 0 == sock_addr_assign(&con->dst_addr, AF_UNIX, 0, val->ptr)) {
2057         }
2058         else
2059        #endif
2060         {
2061             sock_addr saddr;
2062             saddr.plain.sa_family = AF_UNSPEC;
2063             if (1 == sock_addr_from_str_numeric(&saddr, val->ptr, r->conf.errh)
2064                 && saddr.plain.sa_family != AF_UNSPEC) {
2065                 sock_addr_set_port(&saddr, 0);
2066                 memcpy(&con->dst_addr, &saddr, sizeof(sock_addr));
2067             }
2068             else {
2069                 return luaL_error(L,
2070                                   "r.req_attr['remote-addr'] invalid addr: %s",
2071                                   val->ptr);
2072             }
2073         }
2074         buffer_copy_string_len(&con->dst_addr_buf, val->ptr, val->len);
2075         config_cond_cache_reset_item(r, COMP_HTTP_REMOTE_IP);
2076         break;
2077       case MAGNET_ENV_REQUEST_REMOTE_PORT:
2078         sock_addr_set_port(&con->dst_addr, (unsigned short)atoi(val->ptr));
2079         break;
2080       default:
2081         break;
2082     }
2083     return 0;
2084 }
2085 
2086 #if 0
2087 __attribute_cold__
2088 static int
2089 magnet_env_set_server_name (request_st * const r,
2090                             const const_buffer * const val)
2091 {
2092     r->server_name = &r->server_name_buf;
2093     buffer_copy_string_len(&r->server_name_buf, val->ptr, val->len);
2094     return 0;
2095 }
2096 #endif
2097 
2098 static int magnet_env_set(lua_State *L) {
2099     size_t klen;
2100     const char * const key = luaL_checklstring(L, 2, &klen);
2101     const_buffer val = magnet_checkconstbuffer(L, 3);
2102 
2103     const int env_id = magnet_env_get_id(key, klen);
2104     request_st * const r = **(request_st ***)lua_touserdata(L, 1);
2105 
2106     switch (env_id) {
2107       default:
2108         break;
2109       case MAGNET_ENV_URI_PATH_RAW:
2110         return magnet_env_set_uri_path_raw(r, &val);
2111       case MAGNET_ENV_REQUEST_REMOTE_ADDR:
2112       case MAGNET_ENV_REQUEST_REMOTE_PORT:
2113         return magnet_env_set_raddr_by_id(L, r, env_id, &val);
2114      #if 0 /*(leave read-only for now; change attempts silently ignored)*/
2115       case MAGNET_ENV_REQUEST_SERVER_NAME:
2116         return magnet_env_set_server_name(r, &val);
2117      #endif
2118       /*case MAGNET_ENV_REQUEST_STAGE:*//*(change attempts silently ignored)*/
2119       /* remove after lighttpd 1.4.65 */
2120       /*case MAGNET_ENV_RESPONSE_HTTP_STATUS:*/
2121       /*case MAGNET_ENV_RESPONSE_BODY_LENGTH:*/
2122       case MAGNET_ENV_RESPONSE_BODY:
2123         return luaL_error(L, "r.req_attr['%s'] is read-only", key);
2124     }
2125 
2126     buffer * const dest = magnet_env_get_buffer_by_id(r, env_id);
2127     if (NULL == dest)
2128         return luaL_error(L, "couldn't store '%s' in r.req_attr[]", key);
2129 
2130     if (lua_isnoneornil(L, 3)) {
2131         if (env_id==MAGNET_ENV_URI_QUERY || env_id==MAGNET_ENV_PHYSICAL_PATH)
2132             buffer_clear(dest);
2133         else
2134             buffer_blank(dest);
2135     }
2136     else {
2137         buffer_copy_string_len(dest, val.ptr, val.len);
2138         /* NB: setting r->uri.query does not modify query-part in r->target */
2139     }
2140 
2141     switch (env_id) {
2142       case MAGNET_ENV_URI_SCHEME:
2143         buffer_to_lower(dest);
2144         config_cond_cache_reset_item(r, COMP_HTTP_SCHEME);
2145         break;
2146       case MAGNET_ENV_URI_AUTHORITY:
2147         r->server_name = dest;
2148         buffer_to_lower(dest);
2149         config_cond_cache_reset_item(r, COMP_HTTP_HOST);
2150         break;
2151       case MAGNET_ENV_URI_PATH:
2152         config_cond_cache_reset_item(r, COMP_HTTP_URL);
2153         break;
2154       case MAGNET_ENV_URI_QUERY:
2155         config_cond_cache_reset_item(r, COMP_HTTP_QUERY_STRING);
2156         break;
2157       default:
2158         break;
2159     }
2160 
2161     return 0;
2162 }
2163 
2164 static int magnet_env_next(lua_State *L) {
2165 	/* ignore previous key: use upvalue for current pos */
2166 	lua_settop(L, 0);
2167 	const int pos = lua_tointeger(L, lua_upvalueindex(1));
2168 
2169 	if (NULL == magnet_env[pos].name) return 0; /* end of list */
2170 	/* Update our positional upval to reflect our new current position */
2171 	lua_pushinteger(L, pos + 1);
2172 	lua_replace(L, lua_upvalueindex(1));
2173 
2174 	/* key to return */
2175 	lua_pushlstring(L, magnet_env[pos].name, magnet_env[pos].nlen);
2176 
2177 	/* get value */
2178 	request_st * const r = lua_touserdata(L, lua_upvalueindex(2));
2179 	magnet_push_buffer(L, magnet_env_get_buffer_by_id(r, magnet_env[pos].type));
2180 
2181 	/* return 2 items on the stack (key, value) */
2182 	return 2;
2183 }
2184 
2185 static int magnet_env_pairs(lua_State *L) {
2186     lua_pushinteger(L, 0); /* Push our current pos (the start) into upval 1 */
2187     request_st * const r = **(request_st ***)lua_touserdata(L, 1);
2188     lua_pushlightuserdata(L, r); /* Push request_st *r into upval 2 */
2189     lua_pushcclosure(L, magnet_env_next, 2); /* Push new closure with 2 upvals*/
2190     return 1;
2191 }
2192 
2193 static int magnet_envvar_get(lua_State *L) {
2194     size_t klen;
2195     const char * const k = luaL_checklstring(L, 2, &klen);
2196     const request_st * const r = **(request_st ***)lua_touserdata(L, 1);
2197     magnet_push_buffer(L, http_header_env_get(r, k, klen));
2198     return 1;
2199 }
2200 
2201 static int magnet_envvar_set(lua_State *L) {
2202     request_st * const r = **(request_st ***)lua_touserdata(L, 1);
2203     const_buffer key = magnet_checkconstbuffer(L, 2);
2204     if (__builtin_expect( (lua_isnil(L, 3)), 0)) {
2205         buffer * const v = http_header_env_get(r, key.ptr, key.len);
2206         if (v) buffer_clear(v); /*(unset)*/
2207         return 0;
2208     }
2209     const_buffer val = magnet_checkconstbuffer(L, 3);
2210     http_header_env_set(r, key.ptr, key.len, val.ptr, val.len);
2211     return 0;
2212 }
2213 
2214 static int magnet_envvar_pairs(lua_State *L) {
2215     request_st * const r = **(request_st ***)lua_touserdata(L, 1);
2216     return magnet_array_pairs(L, &r->env);
2217 }
2218 
2219 
2220 static int magnet_respbody_add(lua_State *L) {
2221     request_st * const r = lua_touserdata(L, lua_upvalueindex(1));
2222     if (lua_isstring(L, -1)) {
2223         const_buffer data = magnet_checkconstbuffer(L, -1);
2224         http_chunk_append_mem(r, data.ptr, data.len);
2225         return 1; /* boolean true */
2226     }
2227     else if (!lua_istable(L, -1))
2228         return 0; /* boolean false */
2229 
2230     /* note: differs from magnet_attach_content();
2231      * magnet_attach_content() has misnamed 'length' param which
2232      * is treated as 0-offset pos one after end of range to send.
2233      * Here, 'length' means 'length', as one would expect */
2234     for (int i=1, end=0, n=(int)lua_rawlen(L,-1); !end && i <= n; ++i) {
2235         lua_rawgeti(L, -1, i);
2236 
2237         if (lua_isstring(L, -1)) {
2238             const_buffer data = magnet_checkconstbuffer(L, -1);
2239             http_chunk_append_mem(r, data.ptr, data.len);
2240         }
2241         else if (lua_istable(L, -1)) {
2242             lua_getfield(L, -1, "filename");
2243             lua_getfield(L, -2, "length");
2244             lua_getfield(L, -3, "offset");
2245 
2246             if (lua_isstring(L, -3)) { /* filename has to be a string */
2247                 off_t off = (off_t) luaL_optinteger(L, -1, 0);
2248                 off_t len = (off_t) luaL_optinteger(L, -2, -1);
2249                 /*(-1 len as flag to use file size minus offset (below))*/
2250                 buffer stor; /*(note: do not free magnet_checkbuffer() result)*/
2251                 const buffer * const fn = magnet_checkbuffer(L, -3, &stor);
2252                 stat_cache_entry * const sce = (!buffer_is_blank(fn))
2253                   ? stat_cache_get_entry_open(fn, r->conf.follow_symlink)
2254                   : NULL;
2255                 if (sce && (sce->fd >= 0 || sce->st.st_size == 0)) {
2256                     /* treat negative offset as bytes from end of file */
2257                     /* treat negative len as bytes from offset to end of file */
2258                     if (off > sce->st.st_size)
2259                         off = sce->st.st_size;
2260                     else if (off < 0) {
2261                         off = sce->st.st_size - off;
2262                         if (off < 0) off = 0;
2263                     }
2264                     if (len < 0 || sce->st.st_size - off < len)
2265                         len = sce->st.st_size - off;
2266                     if (len)
2267                         http_chunk_append_file_ref_range(r, sce, off, len);
2268                 }
2269                 else {
2270                     log_error(r->conf.errh, __FILE__, __LINE__,
2271                       "error opening file '%s'", fn->ptr);
2272                     end = 1;
2273                 }
2274             }
2275             else {
2276                 log_error(r->conf.errh, __FILE__, __LINE__,
2277                   "body[%d] table field \"filename\" must be a string", i);
2278                 end = 1;
2279             }
2280 
2281             lua_pop(L, 3);
2282         }
2283         else if (lua_isnil(L, -1)) { /* end of list */
2284             end = 1;
2285         }
2286         else {
2287             log_error(r->conf.errh, __FILE__, __LINE__,
2288               "body[%d] is neither a string nor a table", i);
2289             end = 1;
2290         }
2291 
2292         lua_pop(L, 1); /* pop the content[...] entry value */
2293     }
2294 
2295     return 1; /* boolean true */
2296 }
2297 
2298 
2299 static int magnet_respbody(lua_State *L) {
2300     request_st * const r = **(request_st ***)lua_touserdata(L, 1);
2301     size_t klen;
2302     const char * const k = luaL_checklstring(L, 2, &klen);
2303     switch (k[0]) {
2304       case 'a': /* add; r.resp_body.add */
2305         if (k[1] == 'd' && k[2] == 'd' && k[3] == '\0') {
2306             lua_pushlightuserdata(L, r);
2307             lua_pushcclosure(L, magnet_respbody_add, 1);
2308             return 1;
2309         }
2310         break;
2311       case 'b':
2312         if (klen == 8 && 0 == memcmp(k, "bytes_in", 8)) {
2313             lua_pushinteger(L, r->write_queue.bytes_in);
2314             return 1;
2315         }
2316         if (klen == 9 && 0 == memcmp(k, "bytes_out", 9)) {
2317             lua_pushinteger(L, r->write_queue.bytes_out);
2318             return 1;
2319         }
2320         break;
2321      #if 0 /*(future: provide pairs() interface to iterate over chunkqueue)*/
2322            /*(might convert chunks into table of strings, {filename="..."})*/
2323            /*(what about c->offset into chunk?)*/
2324      #endif
2325       case 'g': /* get; r.resp_body.get */
2326         if (k[1] == 'e' && k[2] == 't' && k[3] == '\0') {
2327             if (r->resp_body_finished) {
2328                 chunkqueue * const cq = &r->write_queue;
2329                 chunkqueue_length(cq)
2330                   ? magnet_push_buffer(L,
2331                                        chunkqueue_read_squash(cq,r->conf.errh))
2332                   : (void)lua_pushlstring(L, "", 0);
2333             }
2334             else
2335                 lua_pushnil(L); /*(?maybe return -1 instead if len unknown?)*/
2336             return 1;
2337         }
2338         break;
2339       case 'l': /* len; r.resp_body.len */
2340         if (k[1] == 'e' && k[2] == 'n' && k[3] == '\0') {
2341             if (r->resp_body_finished)
2342                 lua_pushinteger(L, chunkqueue_length(&r->write_queue));
2343             else
2344                 lua_pushnil(L); /*(?maybe return -1 instead if len unknown?)*/
2345             return 1;
2346         }
2347         break;
2348       case 's': /* set; r.resp_body.set */
2349         if (k[1] == 'e' && k[2] == 't' && k[3] == '\0') {
2350             http_response_body_clear(r, 0); /* clear respbody, then add */
2351             lua_pushlightuserdata(L, r);
2352             lua_pushcclosure(L, magnet_respbody_add, 1);
2353             return 1;
2354         }
2355         break;
2356       default:
2357         break;
2358     }
2359     lua_pushliteral(L, "r.resp_body invalid method or param");
2360     lua_error(L);
2361     return 0;
2362 }
2363 
2364 
2365 static int magnet_reqbody_add(lua_State *L) {
2366     request_st * const r = lua_touserdata(L, lua_upvalueindex(1));
2367     chunkqueue * const cq = &r->reqbody_queue;
2368     const int tempfile = (cq->last && cq->last->file.is_temp);
2369     if (lua_isstring(L, -1)) {
2370         const_buffer data = magnet_checkconstbuffer(L, -1);
2371         r->reqbody_length += data.len;
2372         if (r->reqbody_length <= 65536 && !tempfile)
2373             chunkqueue_append_mem(cq, data.ptr, data.len);
2374         else if (chunkqueue_append_mem_to_tempfile(cq, data.ptr, data.len,
2375                                                    r->conf.errh))
2376             return 0; /* boolean false */
2377         return 1; /* boolean true */
2378     }
2379     else if (!lua_istable(L, -1))
2380         return 0; /* boolean false */
2381 
2382     for (int i=1, end=0, n=(int)lua_rawlen(L,-1); !end && i <= n; ++i) {
2383         lua_rawgeti(L, -1, i);
2384 
2385         if (lua_isstring(L, -1)) {
2386             const_buffer data = magnet_checkconstbuffer(L, -1);
2387             r->reqbody_length += data.len;
2388             if (r->reqbody_length <= 65536 && !tempfile)
2389                 chunkqueue_append_mem(cq, data.ptr, data.len);
2390             else if (chunkqueue_append_mem_to_tempfile(cq, data.ptr, data.len,
2391                                                        r->conf.errh))
2392                 return 0; /* boolean false */
2393         }
2394         else if (lua_isnil(L, -1)) { /* end of list */
2395             end = 1;
2396         }
2397         else {
2398             log_error(r->conf.errh, __FILE__, __LINE__,
2399               "body[%d] table must contain strings", i);
2400             end = 1;
2401         }
2402 
2403         lua_pop(L, 1); /* pop the content[...] entry value */
2404     }
2405 
2406     return 1; /* boolean true */
2407 }
2408 
2409 
2410 static int magnet_reqbody(lua_State *L) {
2411     request_st * const r = **(request_st ***)lua_touserdata(L, 1);
2412     size_t klen;
2413     const char * const k = luaL_checklstring(L, 2, &klen);
2414     switch (k[0]) {
2415       case 'a': /* add; r.req_body.add */
2416         if (k[1] == 'd' && k[2] == 'd' && k[3] == '\0') {
2417             chunkqueue * const cq = &r->reqbody_queue;
2418             if (cq->bytes_in == (off_t)r->reqbody_length) {
2419                 lua_pushlightuserdata(L, r);
2420                 lua_pushcclosure(L, magnet_reqbody_add, 1);
2421             }
2422             else /* reqbody not yet collected */
2423                 lua_pushnil(L);
2424             return 1;
2425         }
2426         break;
2427       case 'b':
2428         if (klen == 8 && 0 == memcmp(k, "bytes_in", 8)) {
2429             lua_pushinteger(L, r->reqbody_queue.bytes_in);
2430             return 1;
2431         }
2432         if (klen == 9 && 0 == memcmp(k, "bytes_out", 9)) {
2433             lua_pushinteger(L, r->reqbody_queue.bytes_out);
2434             return 1;
2435         }
2436         break;
2437       case 'c': /* collect; r.req_body.collect */
2438         if (klen == 7 && 0 == memcmp(k, "collect", 7)) {
2439             chunkqueue * const cq = &r->reqbody_queue;
2440             if (cq->bytes_in == (off_t)r->reqbody_length)
2441                 lua_pushboolean(L, 1);
2442             else if (NULL == r->handler_module) {
2443                 r->conf.stream_request_body &=
2444                   ~(FDEVENT_STREAM_REQUEST|FDEVENT_STREAM_REQUEST_BUFMIN);
2445                 r->handler_module = plugin_data_singleton->self;
2446                 lua_pushboolean(L, 0);
2447             }
2448             else if (0 == strcmp(r->handler_module->name, "security3")) {
2449                 /*(mod_security3 uses similar technique to collect req body)*/
2450                 lua_pushboolean(L, 0);
2451             }
2452             else {
2453                 log_error(r->conf.errh, __FILE__, __LINE__,
2454                   "unable to collect request body (handler already set); "
2455                   "(perhaps load mod_magnet earlier in server.modules, "
2456                   "before mod_%s; or require r.req_env['REMOTE_USER'] before "
2457                   "attempting r.req_body.collect?)", r->handler_module->name);
2458                 lua_pushnil(L);
2459             }
2460             return 1;
2461         }
2462         break;
2463       case 'g': /* get; r.req_body.get */
2464         if (k[1] == 'e' && k[2] == 't' && k[3] == '\0') {
2465             chunkqueue * const cq = &r->reqbody_queue;
2466             if (cq->bytes_in == (off_t)r->reqbody_length)
2467                 chunkqueue_length(cq)
2468                   ? magnet_push_buffer(L,
2469                                        chunkqueue_read_squash(cq, r->conf.errh))
2470                   : (void)lua_pushlstring(L, "", 0);
2471             else
2472                 lua_pushnil(L); /*(?maybe return -1 instead if len unknown?)*/
2473             return 1;
2474         }
2475         break;
2476       case 'l': /* len */
2477         if (k[1] == 'e' && k[2] == 'n' && k[3] == '\0') {
2478             lua_pushinteger(L, r->reqbody_length);
2479             return 1;
2480         }
2481         break;
2482       case 's': /* set; r.req_body.set */
2483         if (k[1] == 'e' && k[2] == 't' && k[3] == '\0') {
2484             chunkqueue * const cq = &r->reqbody_queue;
2485             if (cq->bytes_in == (off_t)r->reqbody_length) {
2486                 r->reqbody_length = 0;
2487                 chunkqueue_reset(&r->reqbody_queue);
2488                 lua_pushlightuserdata(L, r);
2489                 lua_pushcclosure(L, magnet_reqbody_add, 1);
2490             }
2491             else /* reqbody not yet collected */
2492                 lua_pushnil(L);
2493             return 1;
2494         }
2495         break;
2496       default:
2497         break;
2498     }
2499     lua_pushliteral(L, "r.req_body invalid method or param");
2500     lua_error(L);
2501     return 0;
2502 }
2503 
2504 
2505 __attribute_cold__
2506 static int magnet_lighty_result_get(lua_State *L) {
2507     /* __index: param 1 is the lighty table the value was not found in */
2508     lua_pushvalue(L, 2);
2509     lua_rawget(L, lua_upvalueindex(1));
2510     if (lua_isnil(L, -1)) {
2511         const_buffer k = magnet_checkconstbuffer(L, 2);
2512         if (   (k.len == 6 && 0 == memcmp(k.ptr, "header", 6))
2513             || (k.len == 7 && 0 == memcmp(k.ptr, "content", 7))) {
2514             lua_pop(L, 1);            /* pop nil */
2515             lua_createtable(L, 0, 0); /* create "header","content" on demand */
2516             lua_pushvalue(L, 2);      /* k: "header" or "content" */
2517             lua_pushvalue(L, -2);     /* v: table */
2518             lua_rawset(L, lua_upvalueindex(1)); /* set in result table */
2519         }
2520     }
2521     return 1;
2522 }
2523 
2524 __attribute_cold__
2525 static int magnet_lighty_result_set(lua_State *L) {
2526     /* __newindex: param 1 is lighty table the value is supposed to be set in */
2527     /* assign value to alternate table; replacing existing value, if any */
2528     lua_rawset(L, lua_upvalueindex(1)); /* set in result table */
2529     return 0;
2530 }
2531 
2532 
2533 __attribute_cold__
2534 __attribute_noinline__
2535 static void magnet_copy_response_header(lua_State * const L, request_st * const r) {
2536     for (lua_pushnil(L); lua_next(L, -2); lua_pop(L, 1)) {
2537         if (lua_isstring(L, -1) && lua_isstring(L, -2))
2538             magnet_resphdr_set_kv(L, r);
2539     }
2540 }
2541 
2542 /**
2543  * (deprecated API)
2544  * walk through the content array set by lua script, e.g.
2545  *   lighty.header["Content-Type"] = "text/html"
2546  *   lighty.content =
2547  *     { "<html><body><pre>", { file = "/content" } , "</pre></body></html>" }
2548  *   return 200
2549  */
2550 __attribute_cold__
2551 __attribute_noinline__
2552 static void magnet_attach_content(lua_State * const L, request_st * const r) {
2553 		http_response_body_clear(r, 0);
2554 		for (int i=1, end=0, n=(int)lua_rawlen(L,-1); !end && i <= n; ++i) {
2555 			lua_rawgeti(L, -1, i);
2556 
2557 			/* -1 is the value and should be the value ... aka a table */
2558 			if (lua_isstring(L, -1)) {
2559 				const_buffer data = magnet_checkconstbuffer(L, -1);
2560 				http_chunk_append_mem(r, data.ptr, data.len);
2561 			} else if (lua_istable(L, -1)) {
2562 				lua_getfield(L, -1, "filename");
2563 				lua_getfield(L, -2, "length"); /* (0-based) end of range (not actually "length") */
2564 				lua_getfield(L, -3, "offset"); /* (0-based) start of range */
2565 
2566 				if (lua_isstring(L, -3)) { /* filename has to be a string */
2567 					/*(luaL_optinteger might raise error, which we want to avoid)*/
2568 					/*off_t off = (off_t) luaL_optinteger(L, -1, 0);*/
2569 					/*off_t len = (off_t) luaL_optinteger(L, -2, -1);*/ /*(-1 as flag to use file size minus offset (below))*/
2570 					int isnum = 1;
2571 					off_t off = lua_isnil(L, -1) ? 0 : (off_t) lua_tointegerx(L, -1, &isnum);
2572 					if (!isnum) {
2573 						off = 0;
2574 						log_error(r->conf.errh, __FILE__, __LINE__,
2575 						  "content[%d] is a table and field \"offset\" must be an integer", i);
2576 					}
2577 					isnum = 1;
2578 					off_t len = lua_isnil(L, -2) ? -1 : (off_t) lua_tointegerx(L, -2, &isnum);
2579 					/*(-1 len as flag to use file size minus offset (below))*/
2580 					if (!isnum) {
2581 						len = -1;
2582 						log_error(r->conf.errh, __FILE__, __LINE__,
2583 						  "content[%d] is a table and field \"length\" must be an integer", i);
2584 					}
2585 					if (off < 0) {
2586 						log_error(r->conf.errh, __FILE__, __LINE__,
2587 						  "offset for '%s' is negative", lua_tostring(L, -3));
2588 						end = 1;
2589 					} else if (len >= off) {
2590 						len -= off;
2591 					} else if (-1 != len) {
2592 						log_error(r->conf.errh, __FILE__, __LINE__,
2593 						  "offset > length for '%s'", lua_tostring(L, -3));
2594 						end = 1;
2595 					}
2596 
2597 					if (!end && 0 != len) {
2598 						buffer stor; /*(note: do not free magnet_checkbuffer() result)*/
2599 						const buffer * const fn = magnet_checkbuffer(L, -3, &stor);
2600 						stat_cache_entry * const sce = (!buffer_is_blank(fn))
2601 						  ? stat_cache_get_entry_open(fn, r->conf.follow_symlink)
2602 						  : NULL;
2603 						if (sce && (sce->fd >= 0 || sce->st.st_size == 0)) {
2604 							if (len == -1 || sce->st.st_size - off < len)
2605 								len = sce->st.st_size - off;
2606 							if (len > 0)
2607 								http_chunk_append_file_ref_range(r, sce, off, len);
2608 						} else {
2609 							log_error(r->conf.errh, __FILE__, __LINE__,
2610 							  "error opening file content '%s' at offset %lld",
2611 							          lua_tostring(L, -3), (long long)off);
2612 							end = 1;
2613 						}
2614 					}
2615 				} else {
2616 					log_error(r->conf.errh, __FILE__, __LINE__,
2617 					  "content[%d] is a table and field \"filename\" must be a string", i);
2618 					end = 1;
2619 				}
2620 
2621 				lua_pop(L, 3);
2622 			} else if (lua_isnil(L, -1)) {
2623 				/* end of list */
2624 				end = 1;
2625 			} else {
2626 				log_error(r->conf.errh, __FILE__, __LINE__,
2627 				  "content[%d] is neither a string nor a table", i);
2628 				end = 1;
2629 			}
2630 
2631 			lua_pop(L, 1); /* pop the content[...] entry value */
2632 		}
2633 }
2634 
2635 __attribute_cold__
2636 static void magnet_mainenv_metatable(lua_State * const L) {
2637     if (luaL_newmetatable(L, "li.mainenv")) {                 /* (sp += 1) */
2638         lua_pushglobaltable(L);                               /* (sp += 1) */
2639         lua_setfield(L, -2, "__index"); /* { __index = _G }      (sp -= 1) */
2640         lua_pushboolean(L, 0);                                /* (sp += 1) */
2641         lua_setfield(L, -2, "__metatable"); /* protect metatable (sp -= 1) */
2642     }
2643 }
2644 
2645 static void
2646 magnet_request_userdata_method (lua_State * const L, request_st ** const rr, const char *meta)
2647 {
2648     /*(meta is name of cached metatable; meta must start w/ "li." prefix)*/
2649     *(request_st ***)lua_newuserdata0(L, sizeof(request_st **)) = rr;
2650   #ifdef __COVERITY__ /* shut up coverity; read the comment below */
2651     if (luaL_newmetatable(L, meta)) { }
2652   #else
2653     luaL_newmetatable(L, meta); /*(should not fail; init'd in script setup)*/
2654   #endif
2655     lua_setmetatable(L, -2);
2656     lua_setfield(L, -2, meta+3); /*(meta+3 to skip over "li." prefix)*/
2657 }
2658 
2659 static void
2660 magnet_request_table (lua_State * const L, request_st ** const rr)
2661 {
2662     /* r table
2663      *
2664      * r.req_header[]         HTTP request headers
2665      * r.req_attr[]           HTTP request attributes / components (strings)
2666      * r.req_item[]           HTTP request items (struct members, statistics)
2667      * r.req_env[]            HTTP request environment variables
2668      * r.req_body.*           HTTP request body accessors
2669      * r.req_body.bytes_in    HTTP request body chunkqueue bytes_in
2670      * r.req_body.bytes_out   HTTP request body chunkqueue bytes_out
2671      * r.resp_header[]        HTTP response headers
2672      * r.resp_body.*          HTTP response body accessors
2673      * r.resp_body.len        HTTP response body length
2674      * r.resp_body.add()      HTTP response body add (string or table)
2675      * r.resp_body.set()      HTTP response body set (string or table)
2676      * r.resp_body.bytes_in   HTTP response body chunkqueue bytes_in
2677      * r.resp_body.bytes_out  HTTP response body chunkqueue bytes_out
2678      */
2679     lua_createtable(L, 0, 7);                                 /* (sp += 1) */
2680 
2681     /* userdata methods share ptr-ptr to external object userdata rr
2682      * (similar functionality to that provided w/ luaL_setfuncs() in lua 5.2+)*/
2683     magnet_request_userdata_method(L, rr, "li.req_header"); /* req_header */
2684     magnet_request_userdata_method(L, rr, "li.req_attr");   /* req_attr */
2685     magnet_request_userdata_method(L, rr, "li.req_item");   /* req_item */
2686     magnet_request_userdata_method(L, rr, "li.req_env");    /* req_env */
2687     magnet_request_userdata_method(L, rr, "li.resp_header");/* resp_header */
2688     magnet_request_userdata_method(L, rr, "li.resp_body");  /* resp_body */
2689     magnet_request_userdata_method(L, rr, "li.req_body");   /* req_body */
2690 
2691     lua_createtable(L, 0, 2); /* metatable for r table           (sp += 1) */
2692     lua_pushcfunction(L, magnet_newindex_readonly);           /* (sp += 1) */
2693     lua_setfield(L, -2, "__newindex");                        /* (sp -= 1) */
2694     lua_pushboolean(L, 0);                                    /* (sp += 1) */
2695     lua_setfield(L, -2, "__metatable"); /* protect metatable     (sp -= 1) */
2696     lua_setmetatable(L, -2); /* tie the metatable to r           (sp -= 1) */
2697 }
2698 
2699 static int
2700 magnet_request_iter (lua_State *L)
2701 {
2702     /* upvalue 1: (connection *) in linked list
2703      * upvalue 2: index into h2con->r[]
2704      * upvalue 3: request userdata
2705      * upvalue 4: request table (references r in userdata) */
2706     connection *con = lua_touserdata(L, lua_upvalueindex(1));
2707 
2708     /* skip over HTTP/2 connections with no active requests */
2709     while (con && con->h2 && 0 == con->h2->rused)
2710         con = con->next;
2711     if (NULL == con)
2712         return 0;
2713 
2714     /* set (request_st *)r */
2715     int32_t i = -1;
2716     if (con->h2) {
2717         /* get index into h2con->r[] */
2718         i = lua_tointeger(L, lua_upvalueindex(2));
2719         /* set (request_st *)r in userdata */
2720         if (-1 == i)
2721             *(request_st **)lua_touserdata(L,lua_upvalueindex(3))=&con->request;
2722         else
2723             *(request_st **)lua_touserdata(L,lua_upvalueindex(3))=con->h2->r[i];
2724         /* step to next index into h2con->r[] */
2725         if ((uint32_t)++i == con->h2->rused)
2726             i = -1;
2727         lua_pushinteger(L, i);
2728         lua_replace(L, lua_upvalueindex(2));
2729     }
2730     else {
2731         /* set (request_st *) in userdata */
2732         *(request_st **)lua_touserdata(L, lua_upvalueindex(3)) = &con->request;
2733     }
2734 
2735     if (-1 == i) {
2736         /* step to next connection */
2737         con = con->next;
2738         lua_pushlightuserdata(L, con);
2739         lua_replace(L, lua_upvalueindex(1));
2740     }
2741 
2742     /* return request object (which references (request_st *)r in userdata) */
2743     lua_pushvalue(L, lua_upvalueindex(4));
2744     return 1;
2745 }
2746 
2747 static int
2748 magnet_irequests (lua_State *L)
2749 {
2750     /* NB: iterator request object *is invalid* outside of iteration
2751      * For efficiency, r is stored in userdata as upvalue to iteration
2752      * and is invalid (and may be cleaned up) outside of iterator loop.
2753      * A C pointer into userdata is stored in iterator request object methods.
2754      * The iterator request object is *reused* for each iteration loop and the
2755      * upvalue to the userdata is changed each iteration to point to next r.
2756      * The iterator request object *must not* be saved for use outside
2757      * the iteration loop.  Extract data that must be saved and store data
2758      * in a persistent object if data is to be used outside iterator loop.
2759      * (Were it desirable to produce a persistent request object for use outside
2760      *  the iteration loop, a future enhancement would be to add a method such
2761      *  as lighty.server.irequests_clone(r) which creates a new request object
2762      *  pointing into a new userdata, and saving that new userdata in the new
2763      *  request object table as '_r_userdata')
2764      * NB: iterator request objects should generally be treated read-only.
2765      * Modifications may in some cases be unsafe and cause lighttpd to crash. */
2766     request_st *r = magnet_get_request(L);
2767     lua_pushlightuserdata(L, r->con->srv->conns);
2768     lua_pushinteger(L, -1);
2769     request_st ** const r_userdata =
2770       (request_st **)lua_newuserdata0(L, sizeof(request_st *));
2771     magnet_request_table(L, r_userdata);
2772     lua_pushcclosure(L, magnet_request_iter, 4);
2773     return 1;
2774 }
2775 
2776 static int
2777 magnet_server_stats_get (lua_State *L)
2778 {
2779     size_t klen;
2780     const char * const k = luaL_checklstring(L, 2, &klen);
2781     const request_st * const r = magnet_get_request(L);
2782     const server * const srv = r->con->srv;
2783     switch (klen) {
2784       case 6:
2785         if (0 == memcmp(k, "uptime", 6)) {
2786             lua_pushinteger(L, (lua_Integer)(log_epoch_secs - srv->startup_ts));
2787             return 1;
2788         }
2789         break;
2790       case 7:
2791         if (0 == memcmp(k, "version", 7)) {
2792             lua_pushlstring(L, BUF_PTR_LEN(srv->default_server_tag));
2793             return 1;
2794         }
2795         break;
2796       case 12:
2797         /*(could calculate from irequests: ++count on remote-addr/port change)*/
2798         if (0 == memcmp(k, "clients_open", 12)) {
2799             lua_pushinteger(L, (lua_Integer)
2800                             (srv->srvconf.max_conns - srv->lim_conns));
2801             return 1;
2802         }
2803         break;
2804       default:
2805         break;
2806     }
2807     return luaL_error(L, "server.stats['%s'] invalid", k);
2808 }
2809 
2810 
2811 __attribute_cold__
2812 static void
2813 magnet_req_header_metatable (lua_State * const L)
2814 {
2815     if (luaL_newmetatable(L, "li.req_header") == 0)           /* (sp += 1) */
2816         return;
2817 
2818     lua_pushcfunction(L, magnet_reqhdr_get);                  /* (sp += 1) */
2819     lua_setfield(L, -2, "__index");                           /* (sp -= 1) */
2820     lua_pushcfunction(L, magnet_reqhdr_set);                  /* (sp += 1) */
2821     lua_setfield(L, -2, "__newindex");                        /* (sp -= 1) */
2822     lua_pushcfunction(L, magnet_reqhdr_pairs);                /* (sp += 1) */
2823     lua_setfield(L, -2, "__pairs");                           /* (sp -= 1) */
2824     lua_pushboolean(L, 0);                                    /* (sp += 1) */
2825     lua_setfield(L, -2, "__metatable"); /* protect metatable     (sp -= 1) */
2826 }
2827 
2828 __attribute_cold__
2829 static void
2830 magnet_req_attr_metatable (lua_State * const L)
2831 {
2832     if (luaL_newmetatable(L, "li.req_attr") == 0)             /* (sp += 1) */
2833         return;
2834 
2835     lua_pushcfunction(L, magnet_env_get);                     /* (sp += 1) */
2836     lua_setfield(L, -2, "__index");                           /* (sp -= 1) */
2837     lua_pushcfunction(L, magnet_env_set);                     /* (sp += 1) */
2838     lua_setfield(L, -2, "__newindex");                        /* (sp -= 1) */
2839     lua_pushcfunction(L, magnet_env_pairs);                   /* (sp += 1) */
2840     lua_setfield(L, -2, "__pairs");                           /* (sp -= 1) */
2841     lua_pushboolean(L, 0);                                    /* (sp += 1) */
2842     lua_setfield(L, -2, "__metatable"); /* protect metatable     (sp -= 1) */
2843 }
2844 
2845 __attribute_cold__
2846 static void
2847 magnet_req_item_metatable (lua_State * const L)
2848 {
2849     if (luaL_newmetatable(L, "li.req_item") == 0)             /* (sp += 1) */
2850         return;
2851 
2852     lua_pushcfunction(L, magnet_req_item_get);                /* (sp += 1) */
2853     lua_setfield(L, -2, "__index");                           /* (sp -= 1) */
2854     lua_pushcfunction(L, magnet_req_item_set);                /* (sp += 1) */
2855     lua_setfield(L, -2, "__newindex");                        /* (sp -= 1) */
2856     lua_pushboolean(L, 0);                                    /* (sp += 1) */
2857     lua_setfield(L, -2, "__metatable"); /* protect metatable     (sp -= 1) */
2858 }
2859 
2860 __attribute_cold__
2861 static void
2862 magnet_req_env_metatable (lua_State * const L)
2863 {
2864     if (luaL_newmetatable(L, "li.req_env") == 0)              /* (sp += 1) */
2865         return;
2866 
2867     lua_pushcfunction(L, magnet_envvar_get);                  /* (sp += 1) */
2868     lua_setfield(L, -2, "__index");                           /* (sp -= 1) */
2869     lua_pushcfunction(L, magnet_envvar_set);                  /* (sp += 1) */
2870     lua_setfield(L, -2, "__newindex");                        /* (sp -= 1) */
2871     lua_pushcfunction(L, magnet_envvar_pairs);                /* (sp += 1) */
2872     lua_setfield(L, -2, "__pairs");                           /* (sp -= 1) */
2873     lua_pushboolean(L, 0);                                    /* (sp += 1) */
2874     lua_setfield(L, -2, "__metatable"); /* protect metatable     (sp -= 1) */
2875 }
2876 
2877 __attribute_cold__
2878 static void
2879 magnet_resp_header_metatable (lua_State * const L)
2880 {
2881     if (luaL_newmetatable(L, "li.resp_header") == 0)          /* (sp += 1) */
2882         return;
2883 
2884     lua_pushcfunction(L, magnet_resphdr_get);                 /* (sp += 1) */
2885     lua_setfield(L, -2, "__index");                           /* (sp -= 1) */
2886     lua_pushcfunction(L, magnet_resphdr_set);                 /* (sp += 1) */
2887     lua_setfield(L, -2, "__newindex");                        /* (sp -= 1) */
2888     lua_pushcfunction(L, magnet_resphdr_pairs);               /* (sp += 1) */
2889     lua_setfield(L, -2, "__pairs");                           /* (sp -= 1) */
2890     lua_pushboolean(L, 0);                                    /* (sp += 1) */
2891     lua_setfield(L, -2, "__metatable"); /* protect metatable     (sp -= 1) */
2892 }
2893 
2894 __attribute_cold__
2895 static void
2896 magnet_resp_body_metatable (lua_State * const L)
2897 {
2898     if (luaL_newmetatable(L, "li.resp_body") == 0)            /* (sp += 1) */
2899         return;
2900 
2901     lua_pushcfunction(L, magnet_respbody);                    /* (sp += 1) */
2902     lua_setfield(L, -2, "__index");                           /* (sp -= 1) */
2903     lua_pushcfunction(L, magnet_newindex_readonly);           /* (sp += 1) */
2904     lua_setfield(L, -2, "__newindex");                        /* (sp -= 1) */
2905     lua_pushboolean(L, 0);                                    /* (sp += 1) */
2906     lua_setfield(L, -2, "__metatable"); /* protect metatable     (sp -= 1) */
2907 }
2908 
2909 __attribute_cold__
2910 static void
2911 magnet_req_body_metatable (lua_State * const L)
2912 {
2913     if (luaL_newmetatable(L, "li.req_body") == 0)             /* (sp += 1) */
2914         return;
2915 
2916     lua_pushcfunction(L, magnet_reqbody);                     /* (sp += 1) */
2917     lua_setfield(L, -2, "__index");                           /* (sp -= 1) */
2918     lua_pushcfunction(L, magnet_newindex_readonly);           /* (sp += 1) */
2919     lua_setfield(L, -2, "__newindex");                        /* (sp -= 1) */
2920     lua_pushboolean(L, 0);                                    /* (sp += 1) */
2921     lua_setfield(L, -2, "__metatable"); /* protect metatable     (sp -= 1) */
2922 }
2923 
2924 __attribute_cold__
2925 static int magnet_atpanic(lua_State *L) {
2926 	request_st * const r = magnet_get_request(L);
2927 	log_error(r->conf.errh, __FILE__, __LINE__, "(lua-atpanic) %s",
2928 	          lua_isstring(L, 1) ? lua_tostring(L, 1) : "");
2929 	/*longjmp(exceptionjmp, 1);*//*(must be init with setjmp() elsewhere)*/
2930 	return 0;
2931 }
2932 
2933 __attribute_cold__
2934 static int magnet_print(lua_State *L) {
2935 	const_buffer cb = magnet_checkconstbuffer(L, 1);
2936 	request_st * const r = magnet_get_request(L);
2937 	log_error(r->conf.errh, __FILE__, __LINE__, "(lua-print) %s", cb.ptr);
2938 	return 0;
2939 }
2940 
2941 __attribute_cold__
2942 static void
2943 magnet_plugin_stats_table (lua_State * const L)
2944 {
2945     lua_createtable(L, 0, 0); /* {}                              (sp += 1) */
2946     lua_createtable(L, 0, 4); /* metatable for plugin_stats      (sp += 1) */
2947     lua_pushcfunction(L, magnet_plugin_stats_get);            /* (sp += 1) */
2948     lua_setfield(L, -2, "__index");                           /* (sp -= 1) */
2949     lua_pushcfunction(L, magnet_plugin_stats_set);            /* (sp += 1) */
2950     lua_setfield(L, -2, "__newindex");                        /* (sp -= 1) */
2951     lua_pushcfunction(L, magnet_plugin_stats_pairs);          /* (sp += 1) */
2952     lua_setfield(L, -2, "__pairs");                           /* (sp -= 1) */
2953     lua_pushboolean(L, 0);                                    /* (sp += 1) */
2954     lua_setfield(L, -2, "__metatable"); /* protect metatable     (sp -= 1) */
2955     lua_setmetatable(L, -2);                                  /* (sp -= 1) */
2956 }
2957 
2958 __attribute_cold__
2959 static void
2960 magnet_server_stats_table (lua_State * const L)
2961 {
2962     lua_createtable(L, 0, 0); /* {}                              (sp += 1) */
2963     lua_createtable(L, 0, 3); /* metatable for stats             (sp += 1) */
2964     lua_pushcfunction(L, magnet_server_stats_get);            /* (sp += 1) */
2965     lua_setfield(L, -2, "__index");                           /* (sp -= 1) */
2966     lua_pushcfunction(L, magnet_newindex_readonly);           /* (sp += 1) */
2967     lua_setfield(L, -2, "__newindex");                        /* (sp -= 1) */
2968     lua_pushboolean(L, 0);                                    /* (sp += 1) */
2969     lua_setfield(L, -2, "__metatable"); /* protect metatable     (sp -= 1) */
2970     lua_setmetatable(L, -2);                                  /* (sp -= 1) */
2971 }
2972 
2973 __attribute_cold__
2974 static void
2975 magnet_server_table (lua_State * const L)
2976 {
2977     lua_createtable(L, 0, 3); /* {}                              (sp += 1) */
2978     lua_pushcfunction(L, magnet_irequests);                   /* (sp += 1) */
2979     lua_setfield(L, -2, "irequests"); /* iterate over requests   (sp -= 1) */
2980     magnet_plugin_stats_table(L);                             /* (sp += 1) */
2981     lua_setfield(L, -2, "plugin_stats");                      /* (sp -= 1) */
2982     magnet_server_stats_table(L);                             /* (sp += 1) */
2983     lua_setfield(L, -2, "stats");                             /* (sp -= 1) */
2984     lua_createtable(L, 0, 2); /* metatable for server table      (sp += 1) */
2985     lua_pushcfunction(L, magnet_newindex_readonly);           /* (sp += 1) */
2986     lua_setfield(L, -2, "__newindex");                        /* (sp -= 1) */
2987     lua_pushboolean(L, 0);                                    /* (sp += 1) */
2988     lua_setfield(L, -2, "__metatable"); /* protect metatable     (sp -= 1) */
2989     lua_setmetatable(L, -2); /* tie the metatable to server      (sp -= 1) */
2990 }
2991 
2992 __attribute_cold__
2993 static void
2994 magnet_script_setup_global_state (lua_State * const L)
2995 {
2996     lua_atpanic(L, magnet_atpanic);
2997 
2998     lua_pushglobaltable(L);                                   /* (sp += 1) */
2999     /* override default print() function */
3000     lua_pushcfunction(L, magnet_print);                       /* (sp += 1) */
3001     lua_setfield(L, -2, "print");                             /* (sp -= 1) */
3002   #if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 502
3003     /* override default pairs() function to our __pairs capable version */
3004     lua_getglobal(L, "pairs"); /* push original pairs()          (sp += 1) */
3005     lua_pushcclosure(L, magnet_pairs, 1);            /* (sp -= 1; sp += 1) */
3006     lua_setfield(L, -2, "pairs");                             /* (sp -= 1) */
3007   #endif
3008     lua_pop(L, 1); /* pop global table */                     /* (sp -= 1) */
3009 
3010     magnet_req_header_metatable(L);    /* init for mem locality  (sp += 1) */
3011     magnet_req_attr_metatable(L);      /* init for mem locality  (sp += 1) */
3012     magnet_req_item_metatable(L);      /* init for mem locality  (sp += 1) */
3013     magnet_req_env_metatable(L);       /* init for mem locality  (sp += 1) */
3014     magnet_resp_header_metatable(L);   /* init for mem locality  (sp += 1) */
3015     magnet_resp_body_metatable(L);     /* init for mem locality  (sp += 1) */
3016     magnet_req_body_metatable(L);      /* init for mem locality  (sp += 1) */
3017     magnet_stat_metatable(L);    /* init table for mem locality  (sp += 1) */
3018     magnet_readdir_metatable(L); /* init table for mem locality  (sp += 1) */
3019     lua_pop(L, 9);               /* pop init'd metatables        (sp -= 9) */
3020 }
3021 
3022 __attribute_cold__
3023 static void
3024 magnet_init_lighty_table (lua_State * const L, request_st **rr,
3025                           const int result_ndx)
3026 {
3027     /* lighty table
3028      *
3029      * lighty.r.*                HTTP request object methods
3030      * lighty.c.*                lighttpd C methods callable from lua
3031      * lighty.server.*           lighttpd server object methods
3032      *
3033      * (older interface)
3034      *
3035      * lighty.request[]      HTTP request headers
3036      * lighty.req_env[]      environment variables
3037      * lighty.env[]          lighttpd request metadata,
3038      *                       various url components,
3039      *                       physical file paths;
3040      *                       might contain nil values
3041      *
3042      * lighty.header[]       (script) HTTP response headers
3043      * lighty.content[]      (script) HTTP response body (table of string/file)
3044      *
3045      * lighty.status[]       lighttpd status counters
3046      */
3047 
3048     /*(adjust the preallocation if more entries are added)*/
3049     lua_createtable(L, 0, 9); /* lighty.* (returned on stack)    (sp += 1) */
3050 
3051     magnet_request_table(L, rr); /* lighty.r                     (sp += 1) */
3052     lua_setfield(L, -2, "r"); /* lighty.r = {}                   (sp -= 1) */
3053 
3054     magnet_server_table(L); /* lighty.server                     (sp += 1) */
3055     lua_setfield(L, -2, "server"); /* server = {}                (sp -= 1) */
3056 
3057     /* compatibility with previous mod_magnet interfaces in top of lighty.* */
3058     lua_getfield(L, -1, "r");                                 /* (sp += 1) */
3059     /* alias lighty.request -> lighty.r.req_header */
3060     lua_getfield(L, -1, "req_header");                        /* (sp += 1) */
3061     lua_setfield(L, -3, "request"); /* request = {}              (sp -= 1) */
3062     /* alias lighty.env     -> lighty.r.req_attr */
3063     lua_getfield(L, -1, "req_attr");                          /* (sp += 1) */
3064     lua_setfield(L, -3, "env"); /* env = {}                      (sp -= 1) */
3065     /* alias lighty.req_env -> lighty.r.req_env */
3066     lua_getfield(L, -1, "req_env");                           /* (sp += 1) */
3067     lua_setfield(L, -3, "req_env"); /* req_env = {}              (sp -= 1) */
3068     lua_pop(L, 1);                                            /* (sp -= 1) */
3069 
3070     /* alias lighty.server.stats -> lighty.status */
3071     lua_getfield(L, -1, "server");                            /* (sp += 1) */
3072     lua_getfield(L, -1, "plugin_stats");                      /* (sp += 1) */
3073     lua_setfield(L, -3, "status"); /* status = {}                (sp -= 1) */
3074     lua_pop(L, 1);                                            /* (sp -= 1) */
3075 
3076     lua_pushinteger(L, MAGNET_RESTART_REQUEST);
3077     lua_setfield(L, -2, "RESTART_REQUEST");
3078 
3079     /* alias lighty.c.stat -> lighty.stat */
3080     lua_pushcfunction(L, magnet_stat);                        /* (sp += 1) */
3081     lua_setfield(L, -2, "stat"); /* -1 is the env we want to set (sp -= 1) */
3082 
3083     static const luaL_Reg cmethods[] = {
3084       { "stat",             magnet_stat }
3085      ,{ "time",             magnet_time }
3086      ,{ "hrtime",           magnet_hrtime }
3087      ,{ "rand",             magnet_rand }
3088      ,{ "md",               magnet_md_once   } /* message digest */
3089      ,{ "hmac",             magnet_hmac_once } /* HMAC */
3090      ,{ "digest_eq",        magnet_digest_eq } /* timing-safe eq fixed len */
3091      ,{ "secret_eq",        magnet_secret_eq } /* timing-safe eq variable len */
3092      ,{ "b64urldec",        magnet_b64urldec } /* validate and decode base64url */
3093      ,{ "b64urlenc",        magnet_b64urlenc } /* base64url encode, no padding */
3094      ,{ "b64dec",           magnet_b64stddec } /* validate and decode base64 */
3095      ,{ "b64enc",           magnet_b64stdenc } /* base64 encode, no padding */
3096      ,{ "hexdec",           magnet_hexdec } /* validate and decode hex str */
3097      ,{ "hexenc",           magnet_hexenc } /* uc; lc w/ lua s = s:lower() */
3098      ,{ "xmlenc",           magnet_xmlenc } /* xml-encode/html-encode: <>&'\" */
3099      ,{ "urldec",           magnet_urldec } /* url-decode (path) */
3100      ,{ "urlenc",           magnet_urlenc } /* url-encode (path) */
3101      ,{ "urldec_query",     magnet_urldec_query } /* url-decode query-string */
3102      ,{ "urlenc_query",     magnet_urlenc_query } /* url-encode query-string */
3103      ,{ "urlenc_normalize", magnet_urlenc_normalize }/* url-enc normalization */
3104      ,{ "fspath_simplify",  magnet_fspath_simplify } /* simplify fspath */
3105      ,{ "cookie_tokens",    magnet_cookie_tokens } /* parse cookie tokens */
3106      ,{ "header_tokens",    magnet_header_tokens } /* parse header tokens seq */
3107      ,{ "readdir",          magnet_readdir } /* dir walk */
3108      ,{ "quoteddec",        magnet_quoteddec } /* quoted-string decode */
3109      ,{ "quotedenc",        magnet_quotedenc } /* quoted-string encode */
3110      ,{ "bsdec",            magnet_bsdec } /* backspace-escape decode */
3111      ,{ "bsenc",            magnet_bsenc_default } /* backspace-escape encode */
3112      ,{ "bsenc_json",       magnet_bsenc_json } /* backspace-escape encode json */
3113      ,{ NULL, NULL }
3114     };
3115 
3116     lua_createtable(L, 0, sizeof(cmethods)/sizeof(luaL_Reg)-1);/*(sp += 1) */
3117     luaL_setfuncs(L, cmethods, 0);
3118     lua_createtable(L, 0, 2); /* metatable for c table           (sp += 1) */
3119     lua_pushcfunction(L, magnet_newindex_readonly);           /* (sp += 1) */
3120     lua_setfield(L, -2, "__newindex");                        /* (sp -= 1) */
3121     lua_pushboolean(L, 0);                                    /* (sp += 1) */
3122     lua_setfield(L, -2, "__metatable"); /* protect metatable     (sp -= 1) */
3123     lua_setmetatable(L, -2); /* tie the metatable to c           (sp -= 1) */
3124     lua_setfield(L, -2, "c"); /* c = {}                          (sp -= 1) */
3125 
3126     /* lighty.* table is read-only;
3127      * provide alternative scratch table for legacy API, historical (mis)use */
3128     lua_createtable(L, 0, 3); /* metatable for lighty table      (sp += 1) */
3129     lua_pushvalue(L, result_ndx);                             /* (sp += 1) */
3130     lua_pushcclosure(L, magnet_lighty_result_get, 1);/* (sp -= 1; sp += 1) */
3131     lua_setfield(L, -2, "__index");                           /* (sp -= 1) */
3132     lua_pushvalue(L, result_ndx);                             /* (sp += 1) */
3133     lua_pushcclosure(L, magnet_lighty_result_set, 1);/* (sp -= 1; sp += 1) */
3134     lua_setfield(L, -2, "__newindex");                        /* (sp -= 1) */
3135     lua_pushboolean(L, 0);                                    /* (sp += 1) */
3136     lua_setfield(L, -2, "__metatable"); /* protect metatable     (sp -= 1) */
3137     lua_setmetatable(L, -2); /* tie the metatable to lighty      (sp -= 1) */
3138 
3139     /* lighty table (returned on stack) */
3140 }
3141 
3142 static void magnet_clear_table(lua_State * const L, int ndx) {
3143     /*(avoid lua_absindex() func call since expecting empty result tables for
3144      * legacy interfaces to lighty.header and .content, though not script-env)*/
3145     /*ndx = lua_absindex(ndx);*//*(lua 5.2+)*/
3146     if (ndx < 0) --ndx;
3147     for (lua_pushnil(L); lua_next(L, ndx); ) {
3148         lua_pop(L, 1);
3149         lua_pushvalue(L, -1);
3150         lua_pushnil(L);
3151         lua_rawset(L, ndx < 0 ? ndx - 2 : ndx);
3152     }
3153 }
3154 
3155 __attribute_cold__
3156 static int magnet_traceback(lua_State *L) {
3157 	if (!lua_isstring(L, 1))  /* 'message' not a string? */
3158 		return 1;  /* keep it intact */
3159 	if (lua_getglobal_and_type(L, "debug") != LUA_TTABLE) {
3160 		lua_pop(L, 1);
3161 		return 1;
3162 	}
3163 	if (lua_getfield_and_type(L, -1, "traceback") != LUA_TFUNCTION) {
3164 		lua_pop(L, 2);
3165 		return 1;
3166 	}
3167 	lua_pushvalue(L, 1);  /* pass error message */
3168 	lua_pushinteger(L, 2);  /* skip this function and traceback */
3169 	lua_call(L, 2, 1);  /* call debug.traceback */
3170 	return 1;
3171 }
3172 
3173 __attribute_cold__
3174 __attribute_noinline__
3175 static int
3176 magnet_script_setup (request_st * const r, plugin_data * const p, script * const sc)
3177 {
3178 	lua_State * const L = sc->L;
3179 	const int func_ndx = 1;
3180 	if (lua_isfunction(L, func_ndx)) {
3181 		/* initial setup for global lua_State */
3182 		magnet_script_setup_global_state(L);
3183 		/*force_assert(lua_gettop(L) == 1);*/ /* errfunc_ndx = 2 */
3184 		lua_pushcfunction(L, magnet_traceback);/*errfunc*//* (sp += 1) */
3185 		/* create empty table for script environment (reused)
3186 		 *   setmetatable({}, {__index = _G})
3187 		 *     if a function symbol is not defined in our env,
3188 		 *     __index will lookup in the global env. */
3189 		lua_createtable(L, 0, 1); /* env_ndx = 3 */       /* (sp += 1) */
3190 		magnet_mainenv_metatable(L);                      /* (sp += 1) */
3191 		lua_setmetatable(L, -2);                          /* (sp -= 1) */
3192 		/* set script env in first upvalue (_ENV upvalue) for func */
3193 		lua_pushvalue(L, -1);                             /* (sp += 1) */
3194 		magnet_setfenv_mainfn(L, func_ndx);               /* (sp -= 1) */
3195 		/* result table (modifiable) (for mod_magnet legacy API) */
3196 		/* (prefer lighty.r.resp_header(), lighty.r.resp_body()) */
3197 		lua_createtable(L, 0, 2); /* (result_ndx = 4) */  /* (sp += 1) */
3198 		const int result_ndx = 4;
3199 		/* shared userdata (ud_ndx = 5) */
3200 		request_st ** const r_userdata =                  /* (sp += 1) */
3201 		  (request_st **)lua_newuserdata0(L, sizeof(request_st *));
3202 		/* insert lighty table (lighty_table_ndx = 6) */
3203 		magnet_init_lighty_table(L,r_userdata,result_ndx);/* (sp += 1) */
3204 		return 1;
3205 	}
3206 	else {
3207 		if (lua_isstring(L, func_ndx))
3208 			log_error(r->conf.errh, __FILE__, __LINE__,
3209 			  "loading script %s failed: %s", sc->name.ptr,
3210 			  lua_tostring(L, func_ndx));
3211 		else /*(lua_gettop(L) == 0)*/
3212 			log_perror(r->conf.errh, __FILE__, __LINE__,
3213 			  "loading script %s failed", sc->name.ptr);
3214 		lua_settop(L, 0);
3215 
3216 		if (p->conf.stage >= 0) { /*(before response_start)*/
3217 			r->http_status = 500;
3218 			r->handler_module = NULL;
3219 		}
3220 
3221 		return 0;
3222 	}
3223 }
3224 
3225 static handler_t
3226 magnet_attract (request_st * const r, plugin_data * const p, script * const sc)
3227 {
3228 	lua_State * const L = sc->L;
3229 	const int func_ndx = 1;
3230 	const int errfunc_ndx = 2;
3231 	const int env_ndx = 3;
3232 	const int result_ndx = 4;
3233 	const int ud_ndx = 5;
3234 	const int lighty_table_ndx = 6;
3235 
3236 	if (__builtin_expect( (lua_gettop(L) != lighty_table_ndx), 0)) {
3237 		if (!magnet_script_setup(r, p, sc))
3238 			return HANDLER_FINISHED;
3239 	}
3240 
3241 	/* set r in global state for L for out-of-band access to r
3242 	 * (r-conf.errh and others) */
3243         magnet_set_request(L, r);
3244 	/* set r in userdata shared by lighty.r object methods */
3245 	*(request_st **)lua_touserdata(L, ud_ndx) = r;
3246 
3247 	/* add lighty table to script-env
3248 	 * script-env is cleared at the end of each script run */
3249 	lua_pushvalue(L, lighty_table_ndx);                       /* (sp += 1) */
3250 	lua_setfield(L, env_ndx, "lighty"); /* lighty.*              (sp -= 1) */
3251 
3252 	/* push script func; pcall will consume the func value */
3253 	lua_pushvalue(L, func_ndx);                               /* (sp += 1) */
3254 	int ret = lua_pcall(L, 0, 1, errfunc_ndx);       /* (sp -= 1; sp += 1) */
3255 
3256 	handler_t result = HANDLER_GO_ON;
3257 	if (0 != ret) {
3258 			size_t errlen;
3259 			const char * const err = lua_tolstring(L, -1, &errlen);
3260 			log_error_multiline(r->conf.errh, __FILE__, __LINE__,
3261 			                    err, errlen, "lua: ");
3262 			/*lua_pop(L, 1);*/ /* pop error msg */ /* defer to later */
3263 			if (p->conf.stage >= 0) { /*(before response_start)*/
3264 				r->http_status = 500;
3265 				r->handler_module = NULL;
3266 				result = HANDLER_FINISHED;
3267 			}
3268 	}
3269 	else do {
3270 		/*(luaL_optinteger might raise error, which we want to avoid)*/
3271 		/*lua_return_value = (int) luaL_optinteger(L, -1, -1);*/
3272 		int isnum = 1;
3273 		int lua_return_value = lua_isnil(L, -1)
3274 		  ? 0
3275 		  : (int) lua_tointegerx(L, -1, &isnum);
3276 		if (!isnum) {
3277 			log_error(r->conf.errh, __FILE__, __LINE__,
3278 			  "lua_pcall(): unexpected non-integer return type: %s",
3279 			  luaL_typename(L, -1));
3280 			break;
3281 		}
3282 		/*lua_pop(L, 1);*/ /* pop return value */ /* defer to later */
3283 		/*force_assert(lua_istable(sc->L, -1));*/
3284 
3285 		if (lua_getfield_and_type(L, result_ndx, "header") == LUA_TTABLE) {
3286 			magnet_copy_response_header(L, r); /* deprecated legacy API */
3287 		}
3288 		/*lua_pop(L, 1);*//* defer to later */
3289 
3290 		if (lua_return_value >= 200) {
3291 			r->http_status = lua_return_value;
3292 			r->resp_body_finished = 1;
3293 			/*(note: body may already have been set via lighty.r.resp_body.*)*/
3294 			if (lua_getfield_and_type(L, result_ndx, "content") == LUA_TTABLE) {
3295 				magnet_attach_content(L, r); /* deprecated legacy API */
3296 			}
3297 			/*lua_pop(L, 1);*//* defer to later */
3298 			if (!chunkqueue_is_empty(&r->write_queue)) {
3299 				r->handler_module = p->self;
3300 			}
3301 			result = HANDLER_FINISHED;
3302 		} else if (lua_return_value >= 100) {
3303 			/*(skip for response-start; send response as-is w/ added headers)*/
3304 			if (p->conf.stage < 0) break;
3305 			/*(custom lua code should not return 101 Switching Protocols)*/
3306 			r->http_status = lua_return_value;
3307 			result = http_response_send_1xx(r)
3308 			  ? HANDLER_GO_ON
3309 			  : HANDLER_ERROR;
3310 		} else if (MAGNET_RESTART_REQUEST == lua_return_value) {
3311 			/*(could detect restart loops in same way as is done in mod_rewrite,
3312 			 * but using r->env means that we do not need to reset plugin state
3313 			 * at end of every request, as is done in mod_rewrite.  mod_rewrite
3314 			 * always restarts the request processing (if request is rewritten),
3315 			 * whereas mod_magnet can be used in many other ways)*/
3316 			buffer *vb =
3317 			  http_header_env_get(r, CONST_STR_LEN("_L_MAGNET_RESTART"));
3318 			if (NULL == vb) {
3319 				vb =
3320 				  http_header_env_set_ptr(r,CONST_STR_LEN("_L_MAGNET_RESTART"));
3321 				buffer_append_char(vb, '0');
3322 			}
3323 			result = HANDLER_COMEBACK;
3324 			if (++*vb->ptr-'0' >= 10) {
3325 				log_error(r->conf.errh, __FILE__, __LINE__,
3326 				  "too many request restarts (infinite loop?) for %s",
3327 				  sc->name.ptr);
3328 				result = HANDLER_ERROR;
3329 			}
3330 		}
3331 	} while (0);
3332 	magnet_clear_table(L, env_ndx);
3333 	magnet_clear_table(L, result_ndx);
3334 	/* reset stack to reuse stack up to lighty table; pop the excess */
3335 	lua_settop(L, lighty_table_ndx); /*(handle deferred lua_pop()s)*/
3336 	return result;
3337 }
3338 
3339 static handler_t magnet_attract_array(request_st * const r, plugin_data * const p, int stage) {
3340 	mod_magnet_patch_config(r, p);
3341 	p->conf.stage = stage;
3342 
3343 	script * const *scripts;
3344 	switch (stage) {
3345 	  case  1: scripts = p->conf.url_raw; break;
3346 	  case  0: scripts = p->conf.physical_path; break;
3347 	  case -1: scripts = p->conf.response_start; break;
3348 	  default: scripts = NULL; break;
3349 	}
3350 	if (NULL == scripts) return HANDLER_GO_ON; /* no scripts set */
3351 
3352 	/*(always check at least mtime and size to trigger script reload)*/
3353 	const int etag_flags = r->conf.etag_flags | ETAG_USE_MTIME | ETAG_USE_SIZE;
3354 	int req_env_inited = 0;
3355 
3356 	/* execute scripts sequentially while HANDLER_GO_ON */
3357 	handler_t rc = HANDLER_GO_ON;
3358 	do {
3359 		script_cache_check_script(*scripts, etag_flags);
3360 		if ((*scripts)->req_env_init && !req_env_inited) {
3361 			/*(request env init is deferred until needed)*/
3362 			req_env_inited = 1;
3363 			r->con->srv->request_env(r);
3364 		}
3365 		rc = magnet_attract(r, p, *scripts);
3366 	} while (rc == HANDLER_GO_ON && *++scripts);
3367 
3368 	if (r->error_handler_saved_status) {
3369 		/* retrieve (possibly modified) REDIRECT_STATUS and store as number */
3370 		int x;
3371 		const buffer * const vb = http_header_env_get(r, CONST_STR_LEN("REDIRECT_STATUS"));
3372 		if (vb && (x = http_header_str_to_code(vb->ptr)) != -1)
3373 			r->error_handler_saved_status =
3374 			  r->error_handler_saved_status > 0 ? (int)x : -(int)x;
3375 	}
3376 
3377 	return rc;
3378 }
3379 
3380 URIHANDLER_FUNC(mod_magnet_uri_handler) {
3381 	return magnet_attract_array(r, p_d, 1);
3382 }
3383 
3384 URIHANDLER_FUNC(mod_magnet_physical) {
3385 	return magnet_attract_array(r, p_d, 0);
3386 }
3387 
3388 URIHANDLER_FUNC(mod_magnet_response_start) {
3389 	return magnet_attract_array(r, p_d, -1);
3390 }
3391 
3392 SUBREQUEST_FUNC(mod_magnet_handle_subrequest) {
3393     /* read entire request body from network and then restart request */
3394     UNUSED(p_d);
3395 
3396     if (r->state == CON_STATE_READ_POST) {
3397         /*(streaming flags were removed when magnet installed this handler)*/
3398         handler_t rc = r->con->reqbody_read(r);
3399         if (rc != HANDLER_GO_ON) return rc;
3400         if (r->state == CON_STATE_READ_POST)
3401             return HANDLER_WAIT_FOR_EVENT;
3402     }
3403 
3404     buffer_clear(&r->physical.path);
3405     r->handler_module = NULL;
3406     return HANDLER_COMEBACK;
3407 }
3408 
3409 
3410 int mod_magnet_plugin_init(plugin *p);
3411 int mod_magnet_plugin_init(plugin *p) {
3412 	p->version     = LIGHTTPD_VERSION_ID;
3413 	p->name        = "magnet";
3414 
3415 	p->init        = mod_magnet_init;
3416 	p->handle_uri_clean  = mod_magnet_uri_handler;
3417 	p->handle_physical   = mod_magnet_physical;
3418 	p->handle_response_start = mod_magnet_response_start;
3419 	p->handle_subrequest = mod_magnet_handle_subrequest;
3420 	p->set_defaults  = mod_magnet_set_defaults;
3421 	p->cleanup     = mod_magnet_free;
3422 
3423 	return 0;
3424 }
3425