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