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