xref: /lighttpd1.4/src/mod_magnet.c (revision b5490082)
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_string_len(b, CONST_STR_LEN("&"));
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_string_len(b, CONST_STR_LEN("="));
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.headers[] 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             off_t bytes = r->http_version <= HTTP_VERSION_1_1
1605               ? r->con->bytes_read - r->bytes_read_ckpt
1606               : r->read_queue.bytes_in;
1607             lua_pushinteger(L, (lua_Integer)bytes);
1608             return 1;
1609         }
1610         break;
1611       case 9:
1612         if (0 == memcmp(k, "bytes_out", 9)) {
1613             off_t bytes = r->http_version <= HTTP_VERSION_1_1
1614               ? r->con->bytes_written - r->bytes_written_ckpt
1615               : r->write_queue.bytes_out;
1616             lua_pushinteger(L, (lua_Integer)bytes);
1617             return 1;
1618         }
1619         if (0 == memcmp(k, "stream_id", 9)) {
1620             lua_pushinteger(L, (lua_Integer)r->h2id);
1621             return 1;
1622         }
1623         if (0 == memcmp(k, "req_count", 9)) {
1624             lua_pushinteger(L, (lua_Integer)r->con->request_count);
1625             return 1;
1626         }
1627         break;
1628       case 10:
1629         if (0 == memcmp(k, "start_time", 10)) {
1630             lua_pushinteger(L, (lua_Integer)r->start_hp.tv_sec);
1631             lua_pushinteger(L, (lua_Integer)r->start_hp.tv_nsec);
1632             lua_pushcclosure(L, magnet_return_upvalue2, 2);
1633             return 1;
1634         }
1635         if (0 == memcmp(k, "keep_alive", 10)) {
1636             lua_pushinteger(L, (lua_Integer)r->keep_alive);
1637             return 1;
1638         }
1639         break;
1640       case 11:
1641         if (0 == memcmp(k, "http_status", 11)) {
1642             lua_pushinteger(L, (lua_Integer)r->http_status);
1643             return 1;
1644         }
1645         break;
1646       case 14:
1647         if (0 == memcmp(k, "req_header_len", 14)) {
1648             lua_pushinteger(L, (lua_Integer)r->rqst_header_len);
1649             return 1;
1650         }
1651         break;
1652       case 15:
1653         if (0 == memcmp(k, "resp_header_len", 15)) {
1654             lua_pushinteger(L, (lua_Integer)r->resp_header_len);
1655             return 1;
1656         }
1657         break;
1658       default:
1659         break;
1660     }
1661     return luaL_error(L, "r.req_item['%s'] invalid", k);
1662 }
1663 
1664 static int
1665 magnet_req_item_set (lua_State *L)
1666 {
1667     size_t klen;
1668     const char * const k = luaL_checklstring(L, 2, &klen);
1669     int v = (int)luaL_checkinteger(L, 3);
1670 
1671     request_st * const r = **(request_st ***)lua_touserdata(L, 1);
1672     switch (klen) {
1673       case 10:
1674         if (0 == memcmp(k, "keep_alive", 10)) {
1675             if (v == 0 || v == -1) r->keep_alive = v;
1676             return 0;
1677         }
1678         break;
1679       default:
1680         break;
1681     }
1682     return luaL_error(L, "r.req_item['%s'] invalid or read-only", k);
1683 }
1684 
1685 
1686 typedef struct {
1687 	const char *name;
1688 	uint32_t nlen;
1689 	enum {
1690 		MAGNET_ENV_UNSET,
1691 
1692 		MAGNET_ENV_PHYSICAL_PATH,
1693 		MAGNET_ENV_PHYSICAL_REL_PATH,
1694 		MAGNET_ENV_PHYSICAL_DOC_ROOT,
1695 		MAGNET_ENV_PHYSICAL_BASEDIR,
1696 
1697 		MAGNET_ENV_URI_PATH,
1698 		MAGNET_ENV_URI_PATH_RAW,
1699 		MAGNET_ENV_URI_SCHEME,
1700 		MAGNET_ENV_URI_AUTHORITY,
1701 		MAGNET_ENV_URI_QUERY,
1702 
1703 		MAGNET_ENV_REQUEST_METHOD,
1704 		MAGNET_ENV_REQUEST_URI,
1705 		MAGNET_ENV_REQUEST_ORIG_URI,
1706 		MAGNET_ENV_REQUEST_PATH_INFO,
1707 		MAGNET_ENV_REQUEST_REMOTE_ADDR,
1708 		MAGNET_ENV_REQUEST_REMOTE_PORT,
1709 		MAGNET_ENV_REQUEST_SERVER_ADDR,
1710 		MAGNET_ENV_REQUEST_SERVER_PORT,
1711 		MAGNET_ENV_REQUEST_PROTOCOL,
1712 		MAGNET_ENV_REQUEST_STAGE,
1713 
1714 		/* remove after lighttpd 1.4.65 */
1715 		MAGNET_ENV_RESPONSE_HTTP_STATUS,
1716 		MAGNET_ENV_RESPONSE_BODY_LENGTH,
1717 		MAGNET_ENV_RESPONSE_BODY
1718 	} type;
1719 } magnet_env_t;
1720 
1721 /*(NB: coordinate any changes with scan offsets in magnet_env_get_id())*/
1722 static const magnet_env_t magnet_env[] = {
1723     { CONST_STR_LEN("physical.path"),        MAGNET_ENV_PHYSICAL_PATH },
1724     { CONST_STR_LEN("physical.rel-path"),    MAGNET_ENV_PHYSICAL_REL_PATH },
1725     { CONST_STR_LEN("physical.doc-root"),    MAGNET_ENV_PHYSICAL_DOC_ROOT },
1726     { CONST_STR_LEN("physical.basedir"),     MAGNET_ENV_PHYSICAL_BASEDIR },
1727 
1728     { CONST_STR_LEN("uri.path"),             MAGNET_ENV_URI_PATH },
1729     { CONST_STR_LEN("uri.path-raw"),         MAGNET_ENV_URI_PATH_RAW },
1730     { CONST_STR_LEN("uri.scheme"),           MAGNET_ENV_URI_SCHEME },
1731     { CONST_STR_LEN("uri.authority"),        MAGNET_ENV_URI_AUTHORITY },
1732     { CONST_STR_LEN("uri.query"),            MAGNET_ENV_URI_QUERY },
1733 
1734     { CONST_STR_LEN("request.method"),       MAGNET_ENV_REQUEST_METHOD },
1735     { CONST_STR_LEN("request.uri"),          MAGNET_ENV_REQUEST_URI },
1736     { CONST_STR_LEN("request.orig-uri"),     MAGNET_ENV_REQUEST_ORIG_URI },
1737     { CONST_STR_LEN("request.path-info"),    MAGNET_ENV_REQUEST_PATH_INFO },
1738     { CONST_STR_LEN("request.remote-ip"),    MAGNET_ENV_REQUEST_REMOTE_ADDR },
1739     { CONST_STR_LEN("request.remote-addr"),  MAGNET_ENV_REQUEST_REMOTE_ADDR },
1740     { CONST_STR_LEN("request.remote-port"),  MAGNET_ENV_REQUEST_REMOTE_PORT },
1741     { CONST_STR_LEN("request.server-addr"),  MAGNET_ENV_REQUEST_SERVER_ADDR },
1742     { CONST_STR_LEN("request.server-port"),  MAGNET_ENV_REQUEST_SERVER_PORT },
1743     { CONST_STR_LEN("request.protocol"),     MAGNET_ENV_REQUEST_PROTOCOL },
1744     { CONST_STR_LEN("request.stage"),        MAGNET_ENV_REQUEST_STAGE },
1745 
1746     { CONST_STR_LEN("response.http-status"), MAGNET_ENV_RESPONSE_HTTP_STATUS },
1747     { CONST_STR_LEN("response.body-length"), MAGNET_ENV_RESPONSE_BODY_LENGTH },
1748     { CONST_STR_LEN("response.body"),        MAGNET_ENV_RESPONSE_BODY },
1749 
1750     { NULL, 0, MAGNET_ENV_UNSET }
1751 };
1752 
1753 __attribute_cold__
1754 static void
1755 magnet_env_get_uri_path_raw (buffer * const dest, const buffer * const target)
1756 {
1757     const uint32_t len = buffer_clen(target);
1758     const char * const qmark = memchr(target->ptr, '?', len);
1759     buffer_copy_string_len(dest, target->ptr,
1760                            qmark ? (uint32_t)(qmark - target->ptr) : len);
1761 }
1762 
1763 __attribute_cold__
1764 static int
1765 magnet_env_set_uri_path_raw (request_st * const r,
1766                              const const_buffer * const val)
1767 {
1768     /* modify uri-path of r->target; preserve query-part, if present */
1769     /* XXX: should we require that resulting path begin with '/' or %2F ? */
1770     const uint32_t len = buffer_clen(&r->target);
1771     const char * const qmark = memchr(r->target.ptr, '?', len);
1772     if (NULL != qmark)
1773         buffer_copy_string_len(r->tmp_buf, qmark,
1774                                len - (uint32_t)(qmark - r->target.ptr));
1775     buffer_copy_string_len(&r->target, val->ptr, val->len);
1776     if (NULL != qmark)
1777         buffer_append_string_buffer(&r->target, r->tmp_buf);
1778     return 0;
1779 }
1780 
1781 __attribute_cold__
1782 __attribute_noinline__
1783 static buffer *
1784 magnet_env_get_laddr_by_id (request_st * const r, const int id)
1785 {
1786     buffer * const dest = r->tmp_buf;
1787     const server_socket * const srv_socket = r->con->srv_socket;
1788     switch (id) {
1789       case MAGNET_ENV_REQUEST_SERVER_ADDR: /* local IP without port */
1790         if (sock_addr_is_addr_wildcard(&srv_socket->addr)) {
1791             sock_addr addrbuf;
1792             socklen_t addrlen = sizeof(addrbuf);
1793             const int fd = r->con->fd;
1794             if (0 == getsockname(fd,(struct sockaddr *)&addrbuf,&addrlen)) {
1795                 char buf[INET6_ADDRSTRLEN + 1];
1796                 const char *s = sock_addr_inet_ntop(&addrbuf, buf, sizeof(buf));
1797                 if (NULL != s) {
1798                     buffer_copy_string_len(dest, s, strlen(s));
1799                     break;
1800                 }
1801             }
1802         }
1803         buffer_copy_string_len(dest, srv_socket->srv_token->ptr,
1804                                srv_socket->srv_token_colon);
1805         break;
1806       case MAGNET_ENV_REQUEST_SERVER_PORT:
1807       {
1808         const buffer * const srv_token = srv_socket->srv_token;
1809         const uint32_t tlen = buffer_clen(srv_token);
1810         uint32_t portoffset = srv_socket->srv_token_colon;
1811         portoffset = portoffset < tlen ? portoffset+1 : tlen;
1812         buffer_copy_string_len(dest, srv_token->ptr+portoffset,
1813                                tlen-portoffset);
1814         break;
1815       }
1816       default:
1817         break;
1818     }
1819     return dest;
1820 }
1821 
1822 static buffer *
1823 magnet_env_get_buffer_by_id (request_st * const r, const int id)
1824 {
1825 	buffer *dest = r->tmp_buf;
1826 	buffer_clear(dest);
1827 
1828 	switch (id) {
1829 	case MAGNET_ENV_PHYSICAL_PATH: dest = &r->physical.path; break;
1830 	case MAGNET_ENV_PHYSICAL_REL_PATH: dest = &r->physical.rel_path; break;
1831 	case MAGNET_ENV_PHYSICAL_DOC_ROOT: dest = &r->physical.doc_root; break;
1832 	case MAGNET_ENV_PHYSICAL_BASEDIR: dest = &r->physical.basedir; break;
1833 
1834 	case MAGNET_ENV_URI_PATH: dest = &r->uri.path; break;
1835 	case MAGNET_ENV_URI_PATH_RAW:
1836 		magnet_env_get_uri_path_raw(dest, &r->target);
1837 		break;
1838 	case MAGNET_ENV_URI_SCHEME: dest = &r->uri.scheme; break;
1839 	case MAGNET_ENV_URI_AUTHORITY: dest = &r->uri.authority; break;
1840 	case MAGNET_ENV_URI_QUERY: dest = &r->uri.query; break;
1841 
1842 	case MAGNET_ENV_REQUEST_METHOD:
1843 		http_method_append(dest, r->http_method);
1844 		break;
1845 	case MAGNET_ENV_REQUEST_URI:      dest = &r->target; break;
1846 	case MAGNET_ENV_REQUEST_ORIG_URI: dest = &r->target_orig; break;
1847 	case MAGNET_ENV_REQUEST_PATH_INFO: dest = &r->pathinfo; break;
1848 	case MAGNET_ENV_REQUEST_REMOTE_ADDR: dest = &r->con->dst_addr_buf; break;
1849 	case MAGNET_ENV_REQUEST_REMOTE_PORT:
1850 		buffer_append_int(dest, sock_addr_get_port(&r->con->dst_addr));
1851 		break;
1852 	case MAGNET_ENV_REQUEST_SERVER_ADDR: /* local IP without port */
1853 	case MAGNET_ENV_REQUEST_SERVER_PORT:
1854 		return magnet_env_get_laddr_by_id(r, id);
1855 	case MAGNET_ENV_REQUEST_PROTOCOL:
1856 		http_version_append(dest, r->http_version);
1857 		break;
1858 	case MAGNET_ENV_REQUEST_STAGE:
1859 		if (http_request_state_is_keep_alive(r))
1860 			buffer_append_string_len(dest, CONST_STR_LEN("keep-alive"));
1861 		else
1862 			http_request_state_append(dest, r->state);
1863 		break;
1864 
1865 	/* remove after lighttpd 1.4.65 */
1866 	case MAGNET_ENV_RESPONSE_HTTP_STATUS:
1867 		buffer_append_int(dest, r->http_status);
1868 		break;
1869 	case MAGNET_ENV_RESPONSE_BODY_LENGTH:
1870 		if (!r->resp_body_finished)
1871 			return NULL;
1872 		log_error(r->conf.errh, __FILE__, __LINE__,
1873 		          "lighty.r.req_attr['response.body-length'] is deprecated "
1874 		          "and will be removed. Use lighty.r.resp_body.len instead.");
1875 		buffer_append_int(dest, chunkqueue_length(&r->write_queue));
1876 		break;
1877 	case MAGNET_ENV_RESPONSE_BODY:
1878 		if (!r->resp_body_finished)
1879 			return NULL;
1880 		log_error(r->conf.errh, __FILE__, __LINE__,
1881 		          "lighty.r.req_attr['response.body'] is deprecated "
1882 		          "and will be removed. Use lighty.r.resp_body.get instead.");
1883 		if (0 == chunkqueue_length(&r->write_queue)
1884 		    || !(dest = chunkqueue_read_squash(&r->write_queue,r->conf.errh)))
1885 			buffer_copy_string_len((dest = r->tmp_buf), CONST_STR_LEN(""));
1886 		break;
1887 
1888 	case MAGNET_ENV_UNSET:
1889 		return NULL;
1890 	}
1891 
1892 	return dest;
1893 }
1894 
1895 __attribute_pure__
1896 static int magnet_env_get_id(const char * const key, const size_t klen) {
1897     /*(NB: ensure offsets match position in magnet_env[])*/
1898     int i; /* magnet_env[] scan offset */
1899     switch (*key) {
1900       case 'r': /* request.* or response.* */
1901         i = klen > 7 && key[7] == '.' ? 9 : 20;
1902         break;
1903       case 'u': /* uri.* */
1904       default:
1905         i = 4;
1906         break;
1907       case 'p': /* physical.* */
1908         i = 0;
1909         break;
1910     }
1911     for (; i < (int)(sizeof(magnet_env)/sizeof(*magnet_env)); ++i) {
1912         if (klen == magnet_env[i].nlen
1913             && 0 == memcmp(key, magnet_env[i].name, klen))
1914             return magnet_env[i].type;
1915     }
1916     return MAGNET_ENV_UNSET;
1917 }
1918 
1919 static int magnet_env_get(lua_State *L) {
1920     size_t klen;
1921     const char * const k = luaL_checklstring(L, 2, &klen);
1922     const int env_id = magnet_env_get_id(k, klen);
1923     request_st * const r = **(request_st ***)lua_touserdata(L, 1);
1924     magnet_push_buffer(L, magnet_env_get_buffer_by_id(r, env_id));
1925     return 1;
1926 }
1927 
1928 __attribute_cold__
1929 static int
1930 magnet_env_set_raddr_by_id (lua_State *L, request_st * const r, const int id,
1931                             const const_buffer * const val)
1932 {
1933     connection * const con = r->con;
1934     switch (id) {
1935       case MAGNET_ENV_REQUEST_REMOTE_ADDR:
1936        #ifdef HAVE_SYS_UN_H
1937         if (val->len && *val->ptr == '/'
1938             && 0 == sock_addr_assign(&con->dst_addr, AF_UNIX, 0, val->ptr)) {
1939         }
1940         else
1941        #endif
1942         {
1943             sock_addr saddr;
1944             saddr.plain.sa_family = AF_UNSPEC;
1945             if (1 == sock_addr_from_str_numeric(&saddr, val->ptr, r->conf.errh)
1946                 && saddr.plain.sa_family != AF_UNSPEC) {
1947                 sock_addr_set_port(&saddr, 0);
1948                 memcpy(&con->dst_addr, &saddr, sizeof(sock_addr));
1949             }
1950             else {
1951                 return luaL_error(L,
1952                                   "r.req_attr['remote-addr'] invalid addr: %s",
1953                                   val->ptr);
1954             }
1955         }
1956         buffer_copy_string_len(&con->dst_addr_buf, val->ptr, val->len);
1957         config_cond_cache_reset_item(r, COMP_HTTP_REMOTE_IP);
1958         break;
1959       case MAGNET_ENV_REQUEST_REMOTE_PORT:
1960         sock_addr_set_port(&con->dst_addr, (unsigned short)atoi(val->ptr));
1961         break;
1962       default:
1963         break;
1964     }
1965     return 0;
1966 }
1967 
1968 static int magnet_env_set(lua_State *L) {
1969     size_t klen;
1970     const char * const key = luaL_checklstring(L, 2, &klen);
1971     const_buffer val = magnet_checkconstbuffer(L, 3);
1972 
1973     const int env_id = magnet_env_get_id(key, klen);
1974     request_st * const r = **(request_st ***)lua_touserdata(L, 1);
1975 
1976     switch (env_id) {
1977       default:
1978         break;
1979       case MAGNET_ENV_URI_PATH_RAW:
1980         return magnet_env_set_uri_path_raw(r, &val);
1981       case MAGNET_ENV_REQUEST_REMOTE_ADDR:
1982       case MAGNET_ENV_REQUEST_REMOTE_PORT:
1983         return magnet_env_set_raddr_by_id(L, r, env_id, &val);
1984       /*case MAGNET_ENV_REQUEST_STAGE:*//*(change attempts silently ignored)*/
1985       /* remove after lighttpd 1.4.65 */
1986       /*case MAGNET_ENV_RESPONSE_HTTP_STATUS:*/
1987       /*case MAGNET_ENV_RESPONSE_BODY_LENGTH:*/
1988       case MAGNET_ENV_RESPONSE_BODY:
1989         return luaL_error(L, "r.req_attr['%s'] is read-only", key);
1990     }
1991 
1992     buffer * const dest = magnet_env_get_buffer_by_id(r, env_id);
1993     if (NULL == dest)
1994         return luaL_error(L, "couldn't store '%s' in r.req_attr[]", key);
1995 
1996     if (lua_isnoneornil(L, 3)) {
1997         if (env_id==MAGNET_ENV_URI_QUERY || env_id==MAGNET_ENV_PHYSICAL_PATH)
1998             buffer_clear(dest);
1999         else
2000             buffer_blank(dest);
2001     }
2002     else {
2003         buffer_copy_string_len(dest, val.ptr, val.len);
2004         /* NB: setting r->uri.query does not modify query-part in r->target */
2005     }
2006 
2007     switch (env_id) {
2008       case MAGNET_ENV_URI_SCHEME:
2009         buffer_to_lower(dest);
2010         config_cond_cache_reset_item(r, COMP_HTTP_SCHEME);
2011         break;
2012       case MAGNET_ENV_URI_AUTHORITY:
2013         r->server_name = dest;
2014         buffer_to_lower(dest);
2015         config_cond_cache_reset_item(r, COMP_HTTP_HOST);
2016         break;
2017       case MAGNET_ENV_URI_PATH:
2018         config_cond_cache_reset_item(r, COMP_HTTP_URL);
2019         break;
2020       case MAGNET_ENV_URI_QUERY:
2021         config_cond_cache_reset_item(r, COMP_HTTP_QUERY_STRING);
2022         break;
2023       default:
2024         break;
2025     }
2026 
2027     return 0;
2028 }
2029 
2030 static int magnet_env_next(lua_State *L) {
2031 	/* ignore previous key: use upvalue for current pos */
2032 	lua_settop(L, 0);
2033 	const int pos = lua_tointeger(L, lua_upvalueindex(1));
2034 
2035 	if (NULL == magnet_env[pos].name) return 0; /* end of list */
2036 	/* Update our positional upval to reflect our new current position */
2037 	lua_pushinteger(L, pos + 1);
2038 	lua_replace(L, lua_upvalueindex(1));
2039 
2040 	/* key to return */
2041 	lua_pushlstring(L, magnet_env[pos].name, magnet_env[pos].nlen);
2042 
2043 	/* get value */
2044 	request_st * const r = lua_touserdata(L, lua_upvalueindex(2));
2045 	magnet_push_buffer(L, magnet_env_get_buffer_by_id(r, magnet_env[pos].type));
2046 
2047 	/* return 2 items on the stack (key, value) */
2048 	return 2;
2049 }
2050 
2051 static int magnet_env_pairs(lua_State *L) {
2052     lua_pushinteger(L, 0); /* Push our current pos (the start) into upval 1 */
2053     request_st * const r = **(request_st ***)lua_touserdata(L, 1);
2054     lua_pushlightuserdata(L, r); /* Push request_st *r into upval 2 */
2055     lua_pushcclosure(L, magnet_env_next, 2); /* Push new closure with 2 upvals*/
2056     return 1;
2057 }
2058 
2059 static int magnet_envvar_get(lua_State *L) {
2060     size_t klen;
2061     const char * const k = luaL_checklstring(L, 2, &klen);
2062     const request_st * const r = **(request_st ***)lua_touserdata(L, 1);
2063     magnet_push_buffer(L, http_header_env_get(r, k, klen));
2064     return 1;
2065 }
2066 
2067 static int magnet_envvar_set(lua_State *L) {
2068     request_st * const r = **(request_st ***)lua_touserdata(L, 1);
2069     const_buffer key = magnet_checkconstbuffer(L, 2);
2070     if (__builtin_expect( (lua_isnil(L, 3)), 0)) {
2071         buffer * const v = http_header_env_get(r, key.ptr, key.len);
2072         if (v) buffer_clear(v); /*(unset)*/
2073         return 0;
2074     }
2075     const_buffer val = magnet_checkconstbuffer(L, 3);
2076     http_header_env_set(r, key.ptr, key.len, val.ptr, val.len);
2077     return 0;
2078 }
2079 
2080 static int magnet_envvar_pairs(lua_State *L) {
2081     request_st * const r = **(request_st ***)lua_touserdata(L, 1);
2082     return magnet_array_pairs(L, &r->env);
2083 }
2084 
2085 
2086 static int magnet_respbody_add(lua_State *L) {
2087     request_st * const r = lua_touserdata(L, lua_upvalueindex(1));
2088     if (lua_isstring(L, -1)) {
2089         const_buffer data = magnet_checkconstbuffer(L, -1);
2090         http_chunk_append_mem(r, data.ptr, data.len);
2091         return 1; /* boolean true */
2092     }
2093     else if (!lua_istable(L, -1))
2094         return 0; /* boolean false */
2095 
2096     /* note: differs from magnet_attach_content();
2097      * magnet_attach_content() has misnamed 'length' param which
2098      * is treated as 0-offset pos one after end of range to send.
2099      * Here, 'length' means 'length', as one would expect */
2100     for (int i=1, end=0, n=(int)lua_rawlen(L,-1); !end && i <= n; ++i) {
2101         lua_rawgeti(L, -1, i);
2102 
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         }
2107         else if (lua_istable(L, -1)) {
2108             lua_getfield(L, -1, "filename");
2109             lua_getfield(L, -2, "length");
2110             lua_getfield(L, -3, "offset");
2111 
2112             if (lua_isstring(L, -3)) { /* filename has to be a string */
2113                 off_t off = (off_t) luaL_optinteger(L, -1, 0);
2114                 off_t len = (off_t) luaL_optinteger(L, -2, -1);
2115                 /*(-1 len as flag to use file size minus offset (below))*/
2116                 buffer stor; /*(note: do not free magnet_checkbuffer() result)*/
2117                 const buffer * const fn = magnet_checkbuffer(L, -3, &stor);
2118                 stat_cache_entry * const sce = (!buffer_is_blank(fn))
2119                   ? stat_cache_get_entry_open(fn, r->conf.follow_symlink)
2120                   : NULL;
2121                 if (sce && (sce->fd >= 0 || sce->st.st_size == 0)) {
2122                     /* treat negative offset as bytes from end of file */
2123                     /* treat negative len as bytes from offset to end of file */
2124                     if (off > sce->st.st_size)
2125                         off = sce->st.st_size;
2126                     else if (off < 0) {
2127                         off = sce->st.st_size - off;
2128                         if (off < 0) off = 0;
2129                     }
2130                     if (len < 0 || sce->st.st_size - off < len)
2131                         len = sce->st.st_size - off;
2132                     if (len)
2133                         http_chunk_append_file_ref_range(r, sce, off, len);
2134                 }
2135                 else {
2136                     log_error(r->conf.errh, __FILE__, __LINE__,
2137                       "error opening file '%s'", fn->ptr);
2138                     end = 1;
2139                 }
2140             }
2141             else {
2142                 log_error(r->conf.errh, __FILE__, __LINE__,
2143                   "body[%d] table field \"filename\" must be a string", i);
2144                 end = 1;
2145             }
2146 
2147             lua_pop(L, 3);
2148         }
2149         else if (lua_isnil(L, -1)) { /* end of list */
2150             end = 1;
2151         }
2152         else {
2153             log_error(r->conf.errh, __FILE__, __LINE__,
2154               "body[%d] is neither a string nor a table", i);
2155             end = 1;
2156         }
2157 
2158         lua_pop(L, 1); /* pop the content[...] entry value */
2159     }
2160 
2161     return 1; /* boolean true */
2162 }
2163 
2164 
2165 static int magnet_respbody(lua_State *L) {
2166     request_st * const r = **(request_st ***)lua_touserdata(L, 1);
2167     size_t klen;
2168     const char * const k = luaL_checklstring(L, 2, &klen);
2169     switch (k[0]) {
2170       case 'a': /* add; r.resp_body.add */
2171         if (k[1] == 'd' && k[2] == 'd' && k[3] == '\0') {
2172             lua_pushlightuserdata(L, r);
2173             lua_pushcclosure(L, magnet_respbody_add, 1);
2174             return 1;
2175         }
2176         break;
2177       case 'b':
2178         if (klen == 8 && 0 == memcmp(k, "bytes_in", 8)) {
2179             lua_pushinteger(L, r->write_queue.bytes_in);
2180             return 1;
2181         }
2182         if (klen == 9 && 0 == memcmp(k, "bytes_out", 9)) {
2183             lua_pushinteger(L, r->write_queue.bytes_out);
2184             return 1;
2185         }
2186         break;
2187      #if 0 /*(future: provide pairs() interface to iterate over chunkqueue)*/
2188            /*(might convert chunks into table of strings, {filename="..."})*/
2189            /*(what about c->offset into chunk?)*/
2190      #endif
2191       case 'g': /* get; r.resp_body.get */
2192         if (k[1] == 'e' && k[2] == 't' && k[3] == '\0') {
2193             if (r->resp_body_finished) {
2194                 chunkqueue * const cq = &r->write_queue;
2195                 chunkqueue_length(cq)
2196                   ? magnet_push_buffer(L,
2197                                        chunkqueue_read_squash(cq,r->conf.errh))
2198                   : (void)lua_pushlstring(L, "", 0);
2199             }
2200             else
2201                 lua_pushnil(L); /*(?maybe return -1 instead if len unknown?)*/
2202             return 1;
2203         }
2204         break;
2205       case 'l': /* len; r.resp_body.len */
2206         if (k[1] == 'e' && k[2] == 'n' && k[3] == '\0') {
2207             if (r->resp_body_finished)
2208                 lua_pushinteger(L, chunkqueue_length(&r->write_queue));
2209             else
2210                 lua_pushnil(L); /*(?maybe return -1 instead if len unknown?)*/
2211             return 1;
2212         }
2213         break;
2214       case 's': /* set; r.resp_body.set */
2215         if (k[1] == 'e' && k[2] == 't' && k[3] == '\0') {
2216             http_response_body_clear(r, 0); /* clear respbody, then add */
2217             lua_pushlightuserdata(L, r);
2218             lua_pushcclosure(L, magnet_respbody_add, 1);
2219             return 1;
2220         }
2221         break;
2222       default:
2223         break;
2224     }
2225     lua_pushliteral(L, "r.resp_body invalid method or param");
2226     lua_error(L);
2227     return 0;
2228 }
2229 
2230 static int magnet_reqbody(lua_State *L) {
2231     const request_st * const r = **(request_st ***)lua_touserdata(L, 1);
2232     size_t klen;
2233     const char * const k = luaL_checklstring(L, 2, &klen);
2234     switch (k[0]) {
2235       case 'b':
2236         if (klen == 8 && 0 == memcmp(k, "bytes_in", 8)) {
2237             lua_pushinteger(L, r->reqbody_queue.bytes_in);
2238             return 1;
2239         }
2240         if (klen == 9 && 0 == memcmp(k, "bytes_out", 9)) {
2241             lua_pushinteger(L, r->reqbody_queue.bytes_out);
2242             return 1;
2243         }
2244         break;
2245       case 'l': /* len */
2246         if (k[1] == 'e' && k[2] == 'n' && k[3] == '\0') {
2247             lua_pushinteger(L, r->reqbody_length);
2248             return 1;
2249         }
2250         break;
2251       default:
2252         break;
2253     }
2254     lua_pushliteral(L, "r.req_body invalid method or param");
2255     lua_error(L);
2256     return 0;
2257 }
2258 
2259 
2260 __attribute_cold__
2261 static int magnet_lighty_result_get(lua_State *L) {
2262     /* __index: param 1 is the lighty table the value was not found in */
2263     lua_getfield(L, 1, "result"); /* lighty.result */
2264     lua_pushvalue(L, 2);
2265     lua_rawget(L, -2);
2266     if (lua_isnil(L, -1)) {
2267         const_buffer k = magnet_checkconstbuffer(L, 2);
2268         if (k.len == 7 && 0 == memcmp(k.ptr, "content", 7)) {
2269             lua_createtable(L, 0, 0); /* create "content" table on demand */
2270             lua_pushvalue(L, 2);      /* k: "content" */
2271             lua_pushvalue(L, -2);     /* v: table */
2272             lua_rawset(L, 3); /* set in "lighty.result" */
2273         }
2274     }
2275     lua_replace(L, 3);
2276     return 1;
2277 }
2278 
2279 __attribute_cold__
2280 static int magnet_lighty_result_set(lua_State *L) {
2281     /* __newindex: param 1 is lighty table the value is supposed to be set in */
2282     /* assign value to table, replacing existing value, if any
2283      * (expecting "content" here, but compatible with prior misuse potential)
2284      * (special-case "header" back into lighty.header) */
2285     const_buffer k = magnet_checkconstbuffer(L, 2);
2286     if (k.len != 6 || 0 != memcmp(k.ptr, "header", 6)) {
2287         lua_getfield(L, 1, "result"); /* lighty.result */
2288         lua_replace(L, 1); /* replace param 1, original target table */
2289     }
2290     lua_rawset(L, -3);
2291     return 0;
2292 }
2293 
2294 
2295 static void magnet_copy_response_header(lua_State * const L, request_st * const r, const int lighty_table_ndx) {
2296     if (lua_getfield_and_type(L, lighty_table_ndx, "header") == LUA_TTABLE) {
2297         /* walk lighty.header */
2298         for (lua_pushnil(L); lua_next(L, -2); ) {
2299             if (lua_isstring(L, -1) && lua_isstring(L, -2))
2300                 magnet_resphdr_set_kv(L, r);
2301             /* unset value after use while walking table entries */
2302             lua_pop(L, 1);
2303             lua_pushvalue(L, -1);
2304             lua_pushnil(L);
2305             lua_rawset(L, -4);
2306         }
2307     }
2308     /*lua_pop(L, 1);*/ /* pop lighty.header */ /* defer to later */
2309 }
2310 
2311 /**
2312  * walk through the content array set by lua script, e.g.
2313  *   lighy.header["Content-Type"] = "text/html"
2314  *   lighty.content =
2315  *     { "<html><body><pre>", { file = "/content" } , "</pre></body></html>" }
2316  *   return 200
2317  */
2318 __attribute_cold__
2319 __attribute_noinline__
2320 static void magnet_attach_content_table(lua_State * const L, request_st * const r) {
2321 		for (int i=1, end=0, n=(int)lua_rawlen(L,-1); !end && i <= n; ++i) {
2322 			lua_rawgeti(L, -1, i);
2323 
2324 			/* -1 is the value and should be the value ... aka a table */
2325 			if (lua_isstring(L, -1)) {
2326 				const_buffer data = magnet_checkconstbuffer(L, -1);
2327 				http_chunk_append_mem(r, data.ptr, data.len);
2328 			} else if (lua_istable(L, -1)) {
2329 				lua_getfield(L, -1, "filename");
2330 				lua_getfield(L, -2, "length"); /* (0-based) end of range (not actually "length") */
2331 				lua_getfield(L, -3, "offset"); /* (0-based) start of range */
2332 
2333 				if (lua_isstring(L, -3)) { /* filename has to be a string */
2334 					/*(luaL_optinteger might raise error, which we want to avoid)*/
2335 					/*off_t off = (off_t) luaL_optinteger(L, -1, 0);*/
2336 					/*off_t len = (off_t) luaL_optinteger(L, -2, -1);*/ /*(-1 as flag to use file size minus offset (below))*/
2337 					int isnum = 1;
2338 					off_t off = lua_isnil(L, -1) ? 0 : (off_t) lua_tointegerx(L, -1, &isnum);
2339 					if (!isnum) {
2340 						off = 0;
2341 						log_error(r->conf.errh, __FILE__, __LINE__,
2342 						  "content[%d] is a table and field \"offset\" must be an integer", i);
2343 					}
2344 					isnum = 1;
2345 					off_t len = lua_isnil(L, -2) ? -1 : (off_t) lua_tointegerx(L, -2, &isnum);
2346 					/*(-1 len as flag to use file size minus offset (below))*/
2347 					if (!isnum) {
2348 						len = -1;
2349 						log_error(r->conf.errh, __FILE__, __LINE__,
2350 						  "content[%d] is a table and field \"length\" must be an integer", i);
2351 					}
2352 					if (off < 0) {
2353 						log_error(r->conf.errh, __FILE__, __LINE__,
2354 						  "offset for '%s' is negative", lua_tostring(L, -3));
2355 						end = 1;
2356 					} else if (len >= off) {
2357 						len -= off;
2358 					} else if (-1 != len) {
2359 						log_error(r->conf.errh, __FILE__, __LINE__,
2360 						  "offset > length for '%s'", lua_tostring(L, -3));
2361 						end = 1;
2362 					}
2363 
2364 					if (!end && 0 != len) {
2365 						buffer stor; /*(note: do not free magnet_checkbuffer() result)*/
2366 						const buffer * const fn = magnet_checkbuffer(L, -3, &stor);
2367 						stat_cache_entry * const sce = (!buffer_is_blank(fn))
2368 						  ? stat_cache_get_entry_open(fn, r->conf.follow_symlink)
2369 						  : NULL;
2370 						if (sce && (sce->fd >= 0 || sce->st.st_size == 0)) {
2371 							if (len == -1 || sce->st.st_size - off < len)
2372 								len = sce->st.st_size - off;
2373 							if (len > 0)
2374 								http_chunk_append_file_ref_range(r, sce, off, len);
2375 						} else {
2376 							log_error(r->conf.errh, __FILE__, __LINE__,
2377 							  "error opening file content '%s' at offset %lld",
2378 							          lua_tostring(L, -3), (long long)off);
2379 							end = 1;
2380 						}
2381 					}
2382 				} else {
2383 					log_error(r->conf.errh, __FILE__, __LINE__,
2384 					  "content[%d] is a table and field \"filename\" must be a string", i);
2385 					end = 1;
2386 				}
2387 
2388 				lua_pop(L, 3);
2389 			} else if (lua_isnil(L, -1)) {
2390 				/* end of list */
2391 				end = 1;
2392 			} else {
2393 				log_error(r->conf.errh, __FILE__, __LINE__,
2394 				  "content[%d] is neither a string nor a table", i);
2395 				end = 1;
2396 			}
2397 
2398 			lua_pop(L, 1); /* pop the content[...] entry value */
2399 		}
2400 }
2401 
2402 static void magnet_attach_content(lua_State * const L, request_st * const r, const int lighty_table_ndx) {
2403     if (lua_getfield_and_type(L, lighty_table_ndx, "result") != LUA_TTABLE) {
2404         /*lua_pop(L, 1);*/ /* pop nil lighty.result */ /* defer to later */
2405         return;
2406     }
2407     switch (lua_getfield_and_type(L, -1, "content")) {/*lighty.result.content*/
2408       case LUA_TNIL:
2409         break;
2410       case LUA_TTABLE:
2411         /* content found and is a table */
2412         http_response_body_clear(r, 0);
2413         magnet_attach_content_table(L, r);
2414         /* assign nil to content to remove from "result" table */
2415         lua_pushnil(L);
2416         lua_setfield(L, -3, "content");
2417         break;
2418       default:
2419         log_error(r->conf.errh, __FILE__, __LINE__,
2420           "lighty.content has to be a table");
2421         break;
2422     }
2423     /* defer lua_pop() to later */
2424     /*lua_pop(L, 2);*/ /* pop lighty.result.content and lighty.result */
2425 }
2426 
2427 __attribute_cold__
2428 static void magnet_mainenv_metatable(lua_State * const L) {
2429     if (luaL_newmetatable(L, "li.mainenv")) {                 /* (sp += 1) */
2430         lua_pushglobaltable(L);                               /* (sp += 1) */
2431         lua_setfield(L, -2, "__index"); /* { __index = _G }      (sp -= 1) */
2432         lua_pushboolean(L, 0);                                /* (sp += 1) */
2433         lua_setfield(L, -2, "__metatable"); /* protect metatable (sp -= 1) */
2434     }
2435 }
2436 
2437 static void
2438 magnet_request_userdata_method (lua_State * const L, request_st ** const rr, const char *meta)
2439 {
2440     /*(meta is name of cached metatable; meta must start w/ "li." prefix)*/
2441     *(request_st ***)lua_newuserdata0(L, sizeof(request_st **)) = rr;
2442     luaL_newmetatable(L, meta); /*(should not fail; init'd in script setup)*/
2443     lua_setmetatable(L, -2);
2444     lua_setfield(L, -2, meta+3); /*(meta+3 to skip over "li." prefix)*/
2445 }
2446 
2447 static void
2448 magnet_request_table (lua_State * const L, request_st ** const rr)
2449 {
2450     /* r table
2451      *
2452      * r.req_header[]         HTTP request headers
2453      * r.req_attr[]           HTTP request attributes / components (strings)
2454      * r.req_item[]           HTTP request items (struct members, statistics)
2455      * r.req_env[]            HTTP request environment variables
2456      * r.req_body.*           HTTP request body accessors
2457      * r.req_body.bytes_in    HTTP request body chunkqueue bytes_in
2458      * r.req_body.bytes_out   HTTP request body chunkqueue bytes_out
2459      * r.resp_header[]        HTTP response headers
2460      * r.resp_body.*          HTTP response body accessors
2461      * r.resp_body.len        HTTP response body length
2462      * r.resp_body.add()      HTTP response body add (string or table)
2463      * r.resp_body.set()      HTTP response body set (string or table)
2464      * r.resp_body.bytes_in   HTTP response body chunkqueue bytes_in
2465      * r.resp_body.bytes_out  HTTP response body chunkqueue bytes_out
2466      */
2467     lua_createtable(L, 0, 7);                                 /* (sp += 1) */
2468 
2469     /* userdata methods share ptr-ptr to external object userdata rr
2470      * (similar functionality to that provided w/ luaL_setfuncs() in lua 5.2+)*/
2471     magnet_request_userdata_method(L, rr, "li.req_header"); /* req_header */
2472     magnet_request_userdata_method(L, rr, "li.req_attr");   /* req_attr */
2473     magnet_request_userdata_method(L, rr, "li.req_item");   /* req_item */
2474     magnet_request_userdata_method(L, rr, "li.req_env");    /* req_env */
2475     magnet_request_userdata_method(L, rr, "li.resp_header");/* resp_header */
2476     magnet_request_userdata_method(L, rr, "li.resp_body");  /* resp_body */
2477     magnet_request_userdata_method(L, rr, "li.req_body");   /* req_body */
2478 
2479     lua_createtable(L, 0, 2); /* metatable for r table           (sp += 1) */
2480     lua_pushcfunction(L, magnet_newindex_readonly);           /* (sp += 1) */
2481     lua_setfield(L, -2, "__newindex");                        /* (sp -= 1) */
2482     lua_pushboolean(L, 0);                                    /* (sp += 1) */
2483     lua_setfield(L, -2, "__metatable"); /* protect metatable     (sp -= 1) */
2484     lua_setmetatable(L, -2); /* tie the metatable to r           (sp -= 1) */
2485 }
2486 
2487 static int
2488 magnet_request_iter (lua_State *L)
2489 {
2490     /* upvalue 1: (connection *) in linked list
2491      * upvalue 2: index into h2con->r[]
2492      * upvalue 3: request userdata
2493      * upvalue 4: request table (references r in userdata) */
2494     connection *con = lua_touserdata(L, lua_upvalueindex(1));
2495 
2496     /* skip over HTTP/2 connections with no active requests */
2497     while (con && con->h2 && 0 == con->h2->rused)
2498         con = con->next;
2499     if (NULL == con)
2500         return 0;
2501 
2502     /* set (request_st *)r */
2503     int32_t i = -1;
2504     if (con->h2) {
2505         /* get index into h2con->r[] */
2506         i = lua_tointeger(L, lua_upvalueindex(2));
2507         /* set (request_st *)r in userdata */
2508         if (-1 == i)
2509             *(request_st **)lua_touserdata(L,lua_upvalueindex(3))=&con->request;
2510         else
2511             *(request_st **)lua_touserdata(L,lua_upvalueindex(3))=con->h2->r[i];
2512         /* step to next index into h2con->r[] */
2513         if ((uint32_t)++i == con->h2->rused)
2514             i = -1;
2515         lua_pushinteger(L, i);
2516         lua_replace(L, lua_upvalueindex(2));
2517     }
2518     else {
2519         /* set (request_st *) in userdata */
2520         *(request_st **)lua_touserdata(L, lua_upvalueindex(3)) = &con->request;
2521     }
2522 
2523     if (-1 == i) {
2524         /* step to next connection */
2525         con = con->next;
2526         lua_pushlightuserdata(L, con);
2527         lua_replace(L, lua_upvalueindex(1));
2528     }
2529 
2530     /* return request object (which references (request_st *)r in userdata) */
2531     lua_pushvalue(L, lua_upvalueindex(4));
2532     return 1;
2533 }
2534 
2535 static int
2536 magnet_irequests (lua_State *L)
2537 {
2538     /* NB: iterator request object *is invalid* outside of iteration
2539      * For efficiency, r is stored in userdata as upvalue to iteration
2540      * and is invalid (and may be cleaned up) outside of iterator loop.
2541      * A C pointer into userdata is stored in iterator request object methods.
2542      * The iterator request object is *reused* for each iteration loop and the
2543      * upvalue to the userdata is changed each iteration to point to next r.
2544      * The iterator request object *must not* be saved for use outside
2545      * the iteration loop.  Extract data that must be saved and store data
2546      * in a persistent object if data is to be used outside iterator loop.
2547      * (Were it desirable to produce a persistent request object for use outside
2548      *  the iteration loop, a future enhancement would be to add a method such
2549      *  as lighty.server.irequests_clone(r) which creates a new request object
2550      *  pointing into a new userdata, and saving that new userdata in the new
2551      *  request object table as '_r_userdata')
2552      * NB: iterator request objects should generally be treated read-only.
2553      * Modifications may in some cases be unsafe and cause lighttpd to crash. */
2554     request_st *r = magnet_get_request(L);
2555     lua_pushlightuserdata(L, r->con->srv->conns);
2556     lua_pushinteger(L, -1);
2557     request_st ** const r_userdata =
2558       (request_st **)lua_newuserdata0(L, sizeof(request_st *));
2559     magnet_request_table(L, r_userdata);
2560     lua_pushcclosure(L, magnet_request_iter, 4);
2561     return 1;
2562 }
2563 
2564 static int
2565 magnet_server_stats_get (lua_State *L)
2566 {
2567     size_t klen;
2568     const char * const k = luaL_checklstring(L, 2, &klen);
2569     const request_st * const r = magnet_get_request(L);
2570     const server * const srv = r->con->srv;
2571     switch (klen) {
2572       case 6:
2573         if (0 == memcmp(k, "uptime", 6)) {
2574             lua_pushinteger(L, (lua_Integer)(log_epoch_secs - srv->startup_ts));
2575             return 1;
2576         }
2577         break;
2578       case 7:
2579         if (0 == memcmp(k, "version", 7)) {
2580             lua_pushlstring(L, BUF_PTR_LEN(srv->default_server_tag));
2581             return 1;
2582         }
2583         break;
2584       case 12:
2585         /*(could calculate from irequests: ++count on remote-addr/port change)*/
2586         if (0 == memcmp(k, "clients_open", 12)) {
2587             lua_pushinteger(L, (lua_Integer)
2588                             (srv->srvconf.max_conns - srv->lim_conns));
2589             return 1;
2590         }
2591         break;
2592       default:
2593         break;
2594     }
2595     return luaL_error(L, "server.stats['%s'] invalid", k);
2596 }
2597 
2598 
2599 __attribute_cold__
2600 static void
2601 magnet_req_header_metatable (lua_State * const L)
2602 {
2603     if (luaL_newmetatable(L, "li.req_header") == 0)           /* (sp += 1) */
2604         return;
2605 
2606     lua_pushcfunction(L, magnet_reqhdr_get);                  /* (sp += 1) */
2607     lua_setfield(L, -2, "__index");                           /* (sp -= 1) */
2608     lua_pushcfunction(L, magnet_reqhdr_set);                  /* (sp += 1) */
2609     lua_setfield(L, -2, "__newindex");                        /* (sp -= 1) */
2610     lua_pushcfunction(L, magnet_reqhdr_pairs);                /* (sp += 1) */
2611     lua_setfield(L, -2, "__pairs");                           /* (sp -= 1) */
2612     lua_pushboolean(L, 0);                                    /* (sp += 1) */
2613     lua_setfield(L, -2, "__metatable"); /* protect metatable     (sp -= 1) */
2614 }
2615 
2616 __attribute_cold__
2617 static void
2618 magnet_req_attr_metatable (lua_State * const L)
2619 {
2620     if (luaL_newmetatable(L, "li.req_attr") == 0)             /* (sp += 1) */
2621         return;
2622 
2623     lua_pushcfunction(L, magnet_env_get);                     /* (sp += 1) */
2624     lua_setfield(L, -2, "__index");                           /* (sp -= 1) */
2625     lua_pushcfunction(L, magnet_env_set);                     /* (sp += 1) */
2626     lua_setfield(L, -2, "__newindex");                        /* (sp -= 1) */
2627     lua_pushcfunction(L, magnet_env_pairs);                   /* (sp += 1) */
2628     lua_setfield(L, -2, "__pairs");                           /* (sp -= 1) */
2629     lua_pushboolean(L, 0);                                    /* (sp += 1) */
2630     lua_setfield(L, -2, "__metatable"); /* protect metatable     (sp -= 1) */
2631 }
2632 
2633 __attribute_cold__
2634 static void
2635 magnet_req_item_metatable (lua_State * const L)
2636 {
2637     if (luaL_newmetatable(L, "li.req_item") == 0)             /* (sp += 1) */
2638         return;
2639 
2640     lua_pushcfunction(L, magnet_req_item_get);                /* (sp += 1) */
2641     lua_setfield(L, -2, "__index");                           /* (sp -= 1) */
2642     lua_pushcfunction(L, magnet_req_item_set);                /* (sp += 1) */
2643     lua_setfield(L, -2, "__newindex");                        /* (sp -= 1) */
2644     lua_pushboolean(L, 0);                                    /* (sp += 1) */
2645     lua_setfield(L, -2, "__metatable"); /* protect metatable     (sp -= 1) */
2646 }
2647 
2648 __attribute_cold__
2649 static void
2650 magnet_req_env_metatable (lua_State * const L)
2651 {
2652     if (luaL_newmetatable(L, "li.req_env") == 0)              /* (sp += 1) */
2653         return;
2654 
2655     lua_pushcfunction(L, magnet_envvar_get);                  /* (sp += 1) */
2656     lua_setfield(L, -2, "__index");                           /* (sp -= 1) */
2657     lua_pushcfunction(L, magnet_envvar_set);                  /* (sp += 1) */
2658     lua_setfield(L, -2, "__newindex");                        /* (sp -= 1) */
2659     lua_pushcfunction(L, magnet_envvar_pairs);                /* (sp += 1) */
2660     lua_setfield(L, -2, "__pairs");                           /* (sp -= 1) */
2661     lua_pushboolean(L, 0);                                    /* (sp += 1) */
2662     lua_setfield(L, -2, "__metatable"); /* protect metatable     (sp -= 1) */
2663 }
2664 
2665 __attribute_cold__
2666 static void
2667 magnet_resp_header_metatable (lua_State * const L)
2668 {
2669     if (luaL_newmetatable(L, "li.resp_header") == 0)          /* (sp += 1) */
2670         return;
2671 
2672     lua_pushcfunction(L, magnet_resphdr_get);                 /* (sp += 1) */
2673     lua_setfield(L, -2, "__index");                           /* (sp -= 1) */
2674     lua_pushcfunction(L, magnet_resphdr_set);                 /* (sp += 1) */
2675     lua_setfield(L, -2, "__newindex");                        /* (sp -= 1) */
2676     lua_pushcfunction(L, magnet_resphdr_pairs);               /* (sp += 1) */
2677     lua_setfield(L, -2, "__pairs");                           /* (sp -= 1) */
2678     lua_pushboolean(L, 0);                                    /* (sp += 1) */
2679     lua_setfield(L, -2, "__metatable"); /* protect metatable     (sp -= 1) */
2680 }
2681 
2682 __attribute_cold__
2683 static void
2684 magnet_resp_body_metatable (lua_State * const L)
2685 {
2686     if (luaL_newmetatable(L, "li.resp_body") == 0)            /* (sp += 1) */
2687         return;
2688 
2689     lua_pushcfunction(L, magnet_respbody);                    /* (sp += 1) */
2690     lua_setfield(L, -2, "__index");                           /* (sp -= 1) */
2691     lua_pushcfunction(L, magnet_newindex_readonly);           /* (sp += 1) */
2692     lua_setfield(L, -2, "__newindex");                        /* (sp -= 1) */
2693     lua_pushboolean(L, 0);                                    /* (sp += 1) */
2694     lua_setfield(L, -2, "__metatable"); /* protect metatable     (sp -= 1) */
2695 }
2696 
2697 __attribute_cold__
2698 static void
2699 magnet_req_body_metatable (lua_State * const L)
2700 {
2701     if (luaL_newmetatable(L, "li.req_body") == 0)             /* (sp += 1) */
2702         return;
2703 
2704     lua_pushcfunction(L, magnet_reqbody);                     /* (sp += 1) */
2705     lua_setfield(L, -2, "__index");                           /* (sp -= 1) */
2706     lua_pushcfunction(L, magnet_newindex_readonly);           /* (sp += 1) */
2707     lua_setfield(L, -2, "__newindex");                        /* (sp -= 1) */
2708     lua_pushboolean(L, 0);                                    /* (sp += 1) */
2709     lua_setfield(L, -2, "__metatable"); /* protect metatable     (sp -= 1) */
2710 }
2711 
2712 __attribute_cold__
2713 static int magnet_atpanic(lua_State *L) {
2714 	request_st * const r = magnet_get_request(L);
2715 	log_error(r->conf.errh, __FILE__, __LINE__, "(lua-atpanic) %s",
2716 	          lua_isstring(L, 1) ? lua_tostring(L, 1) : "");
2717 	/*longjmp(exceptionjmp, 1);*//*(must be init with setjmp() elsewhere)*/
2718 	return 0;
2719 }
2720 
2721 __attribute_cold__
2722 static int magnet_print(lua_State *L) {
2723 	const_buffer cb = magnet_checkconstbuffer(L, 1);
2724 	request_st * const r = magnet_get_request(L);
2725 	log_error(r->conf.errh, __FILE__, __LINE__, "(lua-print) %s", cb.ptr);
2726 	return 0;
2727 }
2728 
2729 __attribute_cold__
2730 static void
2731 magnet_plugin_stats_table (lua_State * const L)
2732 {
2733     lua_createtable(L, 0, 0); /* {}                              (sp += 1) */
2734     lua_createtable(L, 0, 4); /* metatable for plugin_stats      (sp += 1) */
2735     lua_pushcfunction(L, magnet_status_get);                  /* (sp += 1) */
2736     lua_setfield(L, -2, "__index");                           /* (sp -= 1) */
2737     lua_pushcfunction(L, magnet_status_set);                  /* (sp += 1) */
2738     lua_setfield(L, -2, "__newindex");                        /* (sp -= 1) */
2739     lua_pushcfunction(L, magnet_status_pairs);                /* (sp += 1) */
2740     lua_setfield(L, -2, "__pairs");                           /* (sp -= 1) */
2741     lua_pushboolean(L, 0);                                    /* (sp += 1) */
2742     lua_setfield(L, -2, "__metatable"); /* protect metatable     (sp -= 1) */
2743     lua_setmetatable(L, -2);                                  /* (sp -= 1) */
2744 }
2745 
2746 __attribute_cold__
2747 static void
2748 magnet_server_stats_table (lua_State * const L)
2749 {
2750     lua_createtable(L, 0, 0); /* {}                              (sp += 1) */
2751     lua_createtable(L, 0, 3); /* metatable for stats             (sp += 1) */
2752     lua_pushcfunction(L, magnet_server_stats_get);            /* (sp += 1) */
2753     lua_setfield(L, -2, "__index");                           /* (sp -= 1) */
2754     lua_pushcfunction(L, magnet_newindex_readonly);           /* (sp += 1) */
2755     lua_setfield(L, -2, "__newindex");                        /* (sp -= 1) */
2756     lua_pushboolean(L, 0);                                    /* (sp += 1) */
2757     lua_setfield(L, -2, "__metatable"); /* protect metatable     (sp -= 1) */
2758     lua_setmetatable(L, -2);                                  /* (sp -= 1) */
2759 }
2760 
2761 __attribute_cold__
2762 static void
2763 magnet_server_table (lua_State * const L)
2764 {
2765     lua_createtable(L, 0, 3); /* {}                              (sp += 1) */
2766     lua_pushcfunction(L, magnet_irequests);                   /* (sp += 1) */
2767     lua_setfield(L, -2, "irequests"); /* iterate over requests   (sp -= 1) */
2768     magnet_plugin_stats_table(L);                             /* (sp += 1) */
2769     lua_setfield(L, -2, "plugin_stats");                      /* (sp -= 1) */
2770     magnet_server_stats_table(L);                             /* (sp += 1) */
2771     lua_setfield(L, -2, "stats");                             /* (sp -= 1) */
2772     lua_createtable(L, 0, 2); /* metatable for server table      (sp += 1) */
2773     lua_pushcfunction(L, magnet_newindex_readonly);           /* (sp += 1) */
2774     lua_setfield(L, -2, "__newindex");                        /* (sp -= 1) */
2775     lua_pushboolean(L, 0);                                    /* (sp += 1) */
2776     lua_setfield(L, -2, "__metatable"); /* protect metatable     (sp -= 1) */
2777     lua_setmetatable(L, -2); /* tie the metatable to server      (sp -= 1) */
2778 }
2779 
2780 __attribute_cold__
2781 static void
2782 magnet_script_setup_global_state (lua_State * const L)
2783 {
2784     lua_atpanic(L, magnet_atpanic);
2785 
2786     lua_pushglobaltable(L);                                   /* (sp += 1) */
2787     /* override default print() function */
2788     lua_pushcfunction(L, magnet_print);                       /* (sp += 1) */
2789     lua_setfield(L, -2, "print");                             /* (sp -= 1) */
2790   #if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 502
2791     /* override default pairs() function to our __pairs capable version */
2792     lua_getglobal(L, "pairs"); /* push original pairs()          (sp += 1) */
2793     lua_pushcclosure(L, magnet_pairs, 1);            /* (sp -= 1; sp += 1) */
2794     lua_setfield(L, -2, "pairs");                             /* (sp -= 1) */
2795   #endif
2796     lua_pop(L, 1); /* pop global table */                     /* (sp -= 1) */
2797 
2798     magnet_req_header_metatable(L);    /* init for mem locality  (sp += 1) */
2799     magnet_req_attr_metatable(L);      /* init for mem locality  (sp += 1) */
2800     magnet_req_item_metatable(L);      /* init for mem locality  (sp += 1) */
2801     magnet_req_env_metatable(L);       /* init for mem locality  (sp += 1) */
2802     magnet_resp_header_metatable(L);   /* init for mem locality  (sp += 1) */
2803     magnet_resp_body_metatable(L);     /* init for mem locality  (sp += 1) */
2804     magnet_req_body_metatable(L);      /* init for mem locality  (sp += 1) */
2805     magnet_stat_metatable(L);    /* init table for mem locality  (sp += 1) */
2806     magnet_readdir_metatable(L); /* init table for mem locality  (sp += 1) */
2807     lua_pop(L, 9);               /* pop init'd metatables        (sp -= 9) */
2808 }
2809 
2810 __attribute_cold__
2811 static void
2812 magnet_init_lighty_table (lua_State * const L, request_st **rr)
2813 {
2814     /* lighty table
2815      *
2816      * lighty.r.*                HTTP request object methods
2817      * lighty.c.*                lighttpd C methods callable from lua
2818      * lighty.server.*           lighttpd server object methods
2819      *
2820      * (older interface)
2821      *
2822      * lighty.request[]      HTTP request headers
2823      * lighty.req_env[]      environment variables
2824      * lighty.env[]          lighttpd request metadata,
2825      *                       various url components,
2826      *                       physical file paths;
2827      *                       might contain nil values
2828      *
2829      * lighty.header[]       (script) HTTP response headers
2830      * lighty.content[]      (script) HTTP response body (table of string/file)
2831      *
2832      * lighty.status[]       lighttpd status counters
2833      */
2834 
2835     /*(adjust the preallocation if more entries are added)*/
2836     lua_createtable(L, 0, 9); /* lighty.* (returned on stack)    (sp += 1) */
2837 
2838     magnet_request_table(L, rr); /* lighty.r                     (sp += 1) */
2839     lua_setfield(L, -2, "r"); /* lighty.r = {}                   (sp -= 1) */
2840 
2841     magnet_server_table(L); /* lighty.server                     (sp += 1) */
2842     lua_setfield(L, -2, "server"); /* server = {}                (sp -= 1) */
2843 
2844     /* compatibility with previous mod_magnet interfaces in top of lighty.* */
2845     lua_getfield(L, -1, "r");                                 /* (sp += 1) */
2846     /* alias lighty.request -> lighty.r.req_header */
2847     lua_getfield(L, -1, "req_header");                        /* (sp += 1) */
2848     lua_setfield(L, -3, "request"); /* request = {}              (sp -= 1) */
2849     /* alias lighty.env     -> lighty.r.req_attr */
2850     lua_getfield(L, -1, "req_attr");                          /* (sp += 1) */
2851     lua_setfield(L, -3, "env"); /* env = {}                      (sp -= 1) */
2852     /* alias lighty.req_env -> lighty.r.req_env */
2853     lua_getfield(L, -1, "req_env");                           /* (sp += 1) */
2854     lua_setfield(L, -3, "req_env"); /* req_env = {}              (sp -= 1) */
2855     lua_pop(L, 1);                                            /* (sp -= 1) */
2856 
2857     /* alias lighty.server.stats -> lighty.status */
2858     lua_getfield(L, -1, "server");                            /* (sp += 1) */
2859     lua_getfield(L, -1, "plugin_stats");                      /* (sp += 1) */
2860     lua_setfield(L, -3, "status"); /* status = {}                (sp -= 1) */
2861     lua_pop(L, 1);                                            /* (sp -= 1) */
2862 
2863     lua_pushinteger(L, MAGNET_RESTART_REQUEST);
2864     lua_setfield(L, -2, "RESTART_REQUEST");
2865 
2866     /* alias lighty.c.stat -> lighty.stat */
2867     lua_pushcfunction(L, magnet_stat);                        /* (sp += 1) */
2868     lua_setfield(L, -2, "stat"); /* -1 is the env we want to set (sp -= 1) */
2869 
2870     /* add empty 'header' and 'result' tables; ('content' is under 'result') */
2871     /* (prefer newer lighty.r.resp_header(), lighty.r.resp_body() interfaces) */
2872     lua_createtable(L, 0, 8); /* {}                              (sp += 1) */
2873     lua_setfield(L, -2, "header"); /* header = {}                (sp -= 1) */
2874 
2875     lua_createtable(L, 0, 1); /* {}                              (sp += 1) */
2876     lua_setfield(L, -2, "result"); /* result = {}                (sp -= 1) */
2877 
2878     static const luaL_Reg cmethods[] = {
2879       { "stat",             magnet_stat }
2880      ,{ "time",             magnet_time }
2881      ,{ "hrtime",           magnet_hrtime }
2882      ,{ "rand",             magnet_rand }
2883      ,{ "md",               magnet_md_once   } /* message digest */
2884      ,{ "hmac",             magnet_hmac_once } /* HMAC */
2885      ,{ "digest_eq",        magnet_digest_eq } /* timing-safe eq fixed len */
2886      ,{ "secret_eq",        magnet_secret_eq } /* timing-safe eq variable len */
2887      ,{ "b64urldec",        magnet_b64urldec } /* validate and decode base64url */
2888      ,{ "b64urlenc",        magnet_b64urlenc } /* base64url encode, no padding */
2889      ,{ "b64dec",           magnet_b64stddec } /* validate and decode base64 */
2890      ,{ "b64enc",           magnet_b64stdenc } /* base64 encode, no padding */
2891      ,{ "hexdec",           magnet_hexdec } /* validate and decode hex str */
2892      ,{ "hexenc",           magnet_hexenc } /* uc; lc w/ lua s = s:lower() */
2893      ,{ "xmlenc",           magnet_xmlenc } /* xml-encode/html-encode: <>&'\" */
2894      ,{ "urldec",           magnet_urldec } /* url-decode (path) */
2895      ,{ "urlenc",           magnet_urlenc } /* url-encode (path) */
2896      ,{ "urldec_query",     magnet_urldec_query } /* url-decode query-string */
2897      ,{ "urlenc_query",     magnet_urlenc_query } /* url-encode query-string */
2898      ,{ "urlenc_normalize", magnet_urlenc_normalize }/* url-enc normalization */
2899      ,{ "fspath_simplify",  magnet_fspath_simplify } /* simplify fspath */
2900      ,{ "cookie_tokens",    magnet_cookie_tokens } /* parse cookie tokens */
2901      ,{ "header_tokens",    magnet_header_tokens } /* parse header tokens seq */
2902      ,{ "readdir",          magnet_readdir } /* dir walk */
2903      ,{ "quoteddec",        magnet_quoteddec } /* quoted-string decode */
2904      ,{ "quotedenc",        magnet_quotedenc } /* quoted-string encode */
2905      ,{ NULL, NULL }
2906     };
2907 
2908     lua_createtable(L, 0, sizeof(cmethods)/sizeof(luaL_Reg)-1);/*(sp += 1) */
2909     luaL_setfuncs(L, cmethods, 0);
2910     lua_createtable(L, 0, 2); /* metatable for c table           (sp += 1) */
2911     lua_pushcfunction(L, magnet_newindex_readonly);           /* (sp += 1) */
2912     lua_setfield(L, -2, "__newindex");                        /* (sp -= 1) */
2913     lua_pushboolean(L, 0);                                    /* (sp += 1) */
2914     lua_setfield(L, -2, "__metatable"); /* protect metatable     (sp -= 1) */
2915     lua_setmetatable(L, -2); /* tie the metatable to c           (sp -= 1) */
2916     lua_setfield(L, -2, "c"); /* c = {}                          (sp -= 1) */
2917 
2918     lua_createtable(L, 0, 3); /* metatable for lighty table      (sp += 1) */
2919     lua_pushcfunction(L, magnet_lighty_result_get);           /* (sp += 1) */
2920     lua_setfield(L, -2, "__index");                           /* (sp -= 1) */
2921     lua_pushcfunction(L, magnet_lighty_result_set);           /* (sp += 1) */
2922     lua_setfield(L, -2, "__newindex");                        /* (sp -= 1) */
2923     lua_pushboolean(L, 0);                                    /* (sp += 1) */
2924     lua_setfield(L, -2, "__metatable"); /* protect metatable     (sp -= 1) */
2925     lua_setmetatable(L, -2); /* tie the metatable to lighty      (sp -= 1) */
2926 
2927     /* lighty table (returned on stack) */
2928 }
2929 
2930 static void magnet_clear_table(lua_State * const L, int ndx) {
2931     /*(avoid lua_absindex() func call since expecting empty tables for legacy
2932      * interfaces to lighty.header and lighty.content, though not script-env)*/
2933     /*ndx = lua_absindex(ndx);*//*(lua 5.2+)*/
2934     if (ndx < 0) --ndx;
2935     for (lua_pushnil(L); lua_next(L, ndx); ) {
2936         lua_pop(L, 1);
2937         lua_pushvalue(L, -1);
2938         lua_pushnil(L);
2939         lua_rawset(L, ndx < 0 ? ndx - 2 : ndx);
2940     }
2941 }
2942 
2943 static void magnet_reset_lighty_table(lua_State * const L, const int lighty_table_ndx) {
2944     /* clear response tables (release mem if reusing lighty table) */
2945     if (lua_getfield_and_type(L, lighty_table_ndx, "result") == LUA_TTABLE)
2946         magnet_clear_table(L, -1); /*lighty.result*/
2947     else {
2948         lua_createtable(L, 0, 1);
2949         lua_setfield(L, lighty_table_ndx, "result");
2950     }
2951 
2952     if (lua_getfield_and_type(L, lighty_table_ndx, "header") == LUA_TTABLE)
2953         magnet_clear_table(L, -1); /*lighty.header*/
2954     else {
2955         lua_createtable(L, 0, 0);
2956         lua_setfield(L, lighty_table_ndx, "header");
2957     }
2958 
2959     /* pop two tables (or nils) added by two lua_getfield_and_type() calls */
2960     /*lua_pop(L, 2);*/ /* defer to later */
2961 }
2962 
2963 __attribute_cold__
2964 static int magnet_traceback(lua_State *L) {
2965 	if (!lua_isstring(L, 1))  /* 'message' not a string? */
2966 		return 1;  /* keep it intact */
2967 	if (lua_getglobal_and_type(L, "debug") != LUA_TTABLE) {
2968 		lua_pop(L, 1);
2969 		return 1;
2970 	}
2971 	if (lua_getfield_and_type(L, -1, "traceback") != LUA_TFUNCTION) {
2972 		lua_pop(L, 2);
2973 		return 1;
2974 	}
2975 	lua_pushvalue(L, 1);  /* pass error message */
2976 	lua_pushinteger(L, 2);  /* skip this function and traceback */
2977 	lua_call(L, 2, 1);  /* call debug.traceback */
2978 	return 1;
2979 }
2980 
2981 __attribute_cold__
2982 __attribute_noinline__
2983 static int
2984 magnet_script_setup (request_st * const r, plugin_data * const p, script * const sc)
2985 {
2986 	lua_State * const L = sc->L;
2987 	const int func_ndx = 1;
2988 	if (lua_isfunction(L, func_ndx)) {
2989 		/* initial setup for global lua_State */
2990 		magnet_script_setup_global_state(L);
2991 		/*force_assert(lua_gettop(L) == 1);*/ /* errfunc_ndx = 2 */
2992 		lua_pushcfunction(L, magnet_traceback);/*errfunc*//* (sp += 1) */
2993 		/* create empty table for script environment (reused)
2994 		 *   setmetatable({}, {__index = _G})
2995 		 *     if a function symbol is not defined in our env,
2996 		 *     __index will lookup in the global env. */
2997 		lua_createtable(L, 0, 1); /* env_ndx = 3 */       /* (sp += 1) */
2998 		magnet_mainenv_metatable(L);                      /* (sp += 1) */
2999 		lua_setmetatable(L, -2);                          /* (sp -= 1) */
3000 		/* set script env in first upvalue (_ENV upvalue) for func */
3001 		lua_pushvalue(L, -1);                             /* (sp += 1) */
3002 		magnet_setfenv_mainfn(L, func_ndx);               /* (sp -= 1) */
3003 		/* shared userdata (ud_ndx = 4) */
3004 		request_st ** const r_userdata =                  /* (sp += 1) */
3005 		  (request_st **)lua_newuserdata0(L, sizeof(request_st *));
3006 		/* insert lighty table (lighty_table_ndx = 5) */
3007 		magnet_init_lighty_table(L, r_userdata); /* lighty.* (sp += 1) */
3008 		return 1;
3009 	}
3010 	else {
3011 		if (lua_isstring(L, func_ndx))
3012 			log_error(r->conf.errh, __FILE__, __LINE__,
3013 			  "loading script %s failed: %s", sc->name.ptr,
3014 			  lua_tostring(L, func_ndx));
3015 		else /*(lua_gettop(L) == 0)*/
3016 			log_perror(r->conf.errh, __FILE__, __LINE__,
3017 			  "loading script %s failed", sc->name.ptr);
3018 		lua_settop(L, 0);
3019 
3020 		if (p->conf.stage != -1) { /* skip for response-start */
3021 			r->http_status = 500;
3022 			r->handler_module = NULL;
3023 		}
3024 
3025 		return 0;
3026 	}
3027 }
3028 
3029 static handler_t
3030 magnet_attract (request_st * const r, plugin_data * const p, script * const sc)
3031 {
3032 	lua_State * const L = sc->L;
3033 	const int func_ndx = 1;
3034 	const int errfunc_ndx = 2;
3035 	const int env_ndx = 3;
3036 	const int ud_ndx = 4;
3037 	const int lighty_table_ndx = 5;
3038 
3039 	if (__builtin_expect( (lua_gettop(L) != lighty_table_ndx), 0)) {
3040 		if (!magnet_script_setup(r, p, sc))
3041 			return HANDLER_FINISHED;
3042 	}
3043 
3044 	/* set r in global state for L for out-of-band access to r
3045 	 * (r-conf.errh and others) */
3046         magnet_set_request(L, r);
3047 	/* set r in userdata shared by lighty.r object methods */
3048 	*(request_st **)lua_touserdata(L, ud_ndx) = r;
3049 
3050 	/* add lighty table to script-env
3051 	 * script-env is cleared at the end of each script run */
3052 	lua_pushvalue(L, lighty_table_ndx);                       /* (sp += 1) */
3053 	lua_setfield(L, env_ndx, "lighty"); /* lighty.*              (sp -= 1) */
3054 
3055 	/* push script func; pcall will consume the func value */
3056 	lua_pushvalue(L, func_ndx);                               /* (sp += 1) */
3057 	int ret = lua_pcall(L, 0, 1, errfunc_ndx);       /* (sp -= 1; sp += 1) */
3058 
3059 	handler_t result = HANDLER_GO_ON;
3060 	if (0 != ret) {
3061 			log_error(r->conf.errh, __FILE__, __LINE__,
3062 			  "lua_pcall(): %s", lua_tostring(L, -1));
3063 			/*lua_pop(L, 1);*/ /* pop error msg */ /* defer to later */
3064 			/* only func,errfunc,env,ud,lighty table should remain on stack */
3065 			/*(lua_pop() deferred, so lighty_table_ndx+1)*/
3066 			/*force_assert(lua_gettop(L) == lighty_table_ndx);*/
3067 
3068 			if (p->conf.stage != -1) { /* skip for response-start */
3069 				r->http_status = 500;
3070 				r->handler_module = NULL;
3071 			}
3072 
3073 			result = HANDLER_FINISHED;
3074 	}
3075 	else {
3076 		/* should have func,errfunc,env,ud,lighty table, return value on stack*/
3077 		/*force_assert(lua_gettop(L) == lighty_table_ndx+1);*/
3078 
3079 		/*(luaL_optinteger might raise error, which we want to avoid)*/
3080 		/*lua_return_value = (int) luaL_optinteger(L, -1, -1);*/
3081 		int isnum = 1;
3082 		int lua_return_value = lua_isnil(L, -1)
3083 		  ? 0
3084 		  : (int) lua_tointegerx(L, -1, &isnum);
3085 		if (!isnum) {
3086 			lua_return_value = -1;
3087 			log_error(r->conf.errh, __FILE__, __LINE__,
3088 			  "lua_pcall(): unexpected non-integer return type: %s",
3089 			  luaL_typename(L, -1));
3090 		}
3091 		/*lua_pop(L, 1);*/ /* pop return value */ /* defer to later */
3092 		/*force_assert(lua_istable(sc->L, -1));*/
3093 
3094 		magnet_copy_response_header(L, r, lighty_table_ndx);
3095 
3096 		if (lua_return_value >= 200) {
3097 			r->http_status = lua_return_value;
3098 			r->resp_body_finished = 1;
3099 			/*(note: body may already have been set via lighty.r.resp_body.*)*/
3100 			magnet_attach_content(L, r, lighty_table_ndx);
3101 			if (!chunkqueue_is_empty(&r->write_queue)) {
3102 				r->handler_module = p->self;
3103 			}
3104 			result = HANDLER_FINISHED;
3105 		} else if (lua_return_value >= 100 && p->conf.stage != -1) {
3106 			/*(skip for response-start; send response as-is w/ added headers)*/
3107 			/*(custom lua code should not return 101 Switching Protocols)*/
3108 			r->http_status = lua_return_value;
3109 			result = http_response_send_1xx(r)
3110 			  ? HANDLER_GO_ON
3111 			  : HANDLER_ERROR;
3112 		} else if (MAGNET_RESTART_REQUEST == lua_return_value) {
3113 			/*(could detect restart loops in same way as is done in mod_rewrite,
3114 			 * but using r->env means that we do not need to reset plugin state
3115 			 * at end of every request, as is done in mod_rewrite.  mod_rewrite
3116 			 * always restarts the request processing (if request is rewritten),
3117 			 * whereas mod_magnet can be used in many other ways)*/
3118 			buffer *vb =
3119 			  http_header_env_get(r, CONST_STR_LEN("_L_MAGNET_RESTART"));
3120 			if (NULL == vb) {
3121 				vb =
3122 				  http_header_env_set_ptr(r,CONST_STR_LEN("_L_MAGNET_RESTART"));
3123 				buffer_append_string_len(vb, "0", 1);
3124 			}
3125 			result = HANDLER_COMEBACK;
3126 			if (++*vb->ptr-'0' >= 10) {
3127 				log_error(r->conf.errh, __FILE__, __LINE__,
3128 				  "too many request restarts (infinite loop?) for %s",
3129 				  sc->name.ptr);
3130 				result = HANDLER_ERROR;
3131 			}
3132 		}
3133 
3134 	}
3135 	magnet_clear_table(L, env_ndx);
3136 	magnet_reset_lighty_table(L, lighty_table_ndx);
3137 	/* reset stack to have only func, errfunc, env, ud, lighty table */
3138 	lua_settop(L, lighty_table_ndx); /*(handle deferred lua_pop()s)*/
3139 	return result;
3140 }
3141 
3142 static handler_t magnet_attract_array(request_st * const r, plugin_data * const p, int stage) {
3143 	mod_magnet_patch_config(r, p);
3144 	p->conf.stage = stage;
3145 
3146 	script * const *scripts;
3147 	switch (stage) {
3148 	  case  1: scripts = p->conf.url_raw; break;
3149 	  case  0: scripts = p->conf.physical_path; break;
3150 	  case -1: scripts = p->conf.response_start; break;
3151 	  default: scripts = NULL; break;
3152 	}
3153 	if (NULL == scripts) return HANDLER_GO_ON; /* no scripts set */
3154 
3155 	/*(always check at least mtime and size to trigger script reload)*/
3156 	const int etag_flags = r->conf.etag_flags | ETAG_USE_MTIME | ETAG_USE_SIZE;
3157 	int req_env_inited = 0;
3158 
3159 	/* execute scripts sequentially while HANDLER_GO_ON */
3160 	handler_t rc = HANDLER_GO_ON;
3161 	do {
3162 		script_cache_check_script(*scripts, etag_flags);
3163 		if ((*scripts)->req_env_init && !req_env_inited) {
3164 			/*(request env init is deferred until needed)*/
3165 			req_env_inited = 1;
3166 			r->con->srv->request_env(r);
3167 		}
3168 		rc = magnet_attract(r, p, *scripts);
3169 	} while (rc == HANDLER_GO_ON && *++scripts);
3170 
3171 	if (r->error_handler_saved_status) {
3172 		/* retrieve (possibly modified) REDIRECT_STATUS and store as number */
3173 		int x;
3174 		const buffer * const vb = http_header_env_get(r, CONST_STR_LEN("REDIRECT_STATUS"));
3175 		if (vb && (x = http_header_str_to_code(vb->ptr)) != -1)
3176 			r->error_handler_saved_status =
3177 			  r->error_handler_saved_status > 0 ? (int)x : -(int)x;
3178 	}
3179 
3180 	return rc;
3181 }
3182 
3183 URIHANDLER_FUNC(mod_magnet_uri_handler) {
3184 	return magnet_attract_array(r, p_d, 1);
3185 }
3186 
3187 URIHANDLER_FUNC(mod_magnet_physical) {
3188 	return magnet_attract_array(r, p_d, 0);
3189 }
3190 
3191 URIHANDLER_FUNC(mod_magnet_response_start) {
3192 	return magnet_attract_array(r, p_d, -1);
3193 }
3194 
3195 
3196 int mod_magnet_plugin_init(plugin *p);
3197 int mod_magnet_plugin_init(plugin *p) {
3198 	p->version     = LIGHTTPD_VERSION_ID;
3199 	p->name        = "magnet";
3200 
3201 	p->init        = mod_magnet_init;
3202 	p->handle_uri_clean  = mod_magnet_uri_handler;
3203 	p->handle_physical   = mod_magnet_physical;
3204 	p->handle_response_start = mod_magnet_response_start;
3205 	p->set_defaults  = mod_magnet_set_defaults;
3206 	p->cleanup     = mod_magnet_free;
3207 
3208 	return 0;
3209 }
3210