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