]> granicus.if.org Git - apache/blob - modules/lua/mod_lua.c
apply patch from zhiguo zhao <zhaozg@gmail.com> to significantly improve server scope...
[apache] / modules / lua / mod_lua.c
1 /**
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements.  See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License.  You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18 #include "mod_lua.h"
19 #include <string.h>
20 #include <stdlib.h>
21 #include <ctype.h>
22
23 #include "lua_apr.h"
24 #include "lua_config.h"
25
26 APR_IMPLEMENT_OPTIONAL_HOOK_RUN_ALL(ap_lua, AP_LUA, int, lua_open,
27                                     (lua_State *L, apr_pool_t *p),
28                                     (L, p), OK, DECLINED)
29
30 APR_IMPLEMENT_OPTIONAL_HOOK_RUN_ALL(ap_lua, AP_LUA, int, lua_request,
31                                     (lua_State *L, request_rec *r),
32                                     (L, r), OK, DECLINED)
33
34      module AP_MODULE_DECLARE_DATA lua_module;
35
36 /**
37  * error reporting if lua has an error. 
38  * Extracts the error from lua stack and prints
39  */
40 static void report_lua_error(lua_State *L, request_rec *r)
41 {
42     const char *lua_response;
43     r->status = HTTP_INTERNAL_SERVER_ERROR;
44     r->content_type = "text/html";
45
46     ap_rputs("<b>Error!</b>\n", r);
47     ap_rputs("<p>", r);
48     lua_response = lua_tostring(L, -1);
49     ap_rputs(lua_response, r);
50     ap_rputs("</p>\n", r);
51
52     ap_log_perror(APLOG_MARK, APLOG_WARNING, 0, r->pool, "Lua error: %s",
53                   lua_response);
54 }
55
56 static void lua_open_callback(lua_State *L, apr_pool_t *p, void *ctx)
57 {
58     ap_lua_init(L, p);
59     ap_lua_load_apache2_lmodule(L);
60     ap_lua_load_request_lmodule(L, p);
61     ap_lua_load_config_lmodule(L);
62 }
63
64 static int lua_open_hook(lua_State *L, apr_pool_t *p)
65 {
66     lua_open_callback(L, p, NULL);
67     return OK;
68 }
69
70 /*
71 static apr_status_t luahood(ap_filter_t *f, apr_bucket_brigade *bb) {
72     apr_bucket* b;
73     apr_status_t rs;
74     for ( b = APR_BRIGADE_FIRST(bb);
75           b != APR_BRIGADE_SENTINEL(bb);
76           b = APR_BUCKET_NEXT(b)) 
77     {
78         if (APR_BUCKET_IS_EOS(b)) {kl
79             break;
80         }
81         const char *buffer;
82         size_t bytes;
83         if (( rs = apr_bucket_read(b, &buffer, &bytes, APR_BLOCK_READ))) {
84             ap_log_rerror(APLOG_MARK, APLOG_WARNING, rs, f->r, "read failure in luahood");
85             return rs;
86         }
87         char *mine = apr_pstrmemdup(f->r->pool, buffer, bytes);
88         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, f->r, "sending '%s'", mine);
89     }
90     
91     ap_pass_brigade(f->next, bb);
92     
93     return OK;
94 }
95 */
96
97 /**
98  * "main"
99  */
100 static int lua_handler(request_rec *r)
101 {
102     ap_lua_dir_cfg *dcfg;
103     if (strcmp(r->handler, "lua-script")) {
104         return DECLINED;
105     }
106
107     ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "handling [%s] in mod_lua",
108                   r->filename);
109     dcfg = ap_get_module_config(r->per_dir_config, &lua_module);
110
111     if (!r->header_only) {
112         lua_State *L;
113         const ap_lua_dir_cfg *cfg = ap_get_module_config(r->per_dir_config,
114                                                       &lua_module);
115         ap_lua_request_cfg *rcfg =
116             ap_get_module_config(r->request_config, &lua_module);
117         mapped_request_details *d = rcfg->mapped_request_details;
118         ap_lua_vm_spec *spec = NULL;
119
120         if (!d) {
121             d = apr_palloc(r->pool, sizeof(mapped_request_details));
122             spec = apr_pcalloc(r->pool, sizeof(ap_lua_vm_spec));
123             spec->scope = dcfg->vm_scope;
124                         spec->pool = spec->scope==APL_SCOPE_SERVER ? cfg->pool : r->pool;
125             spec->file = r->filename;
126             spec->code_cache_style = dcfg->code_cache_style;
127                         spec->package_paths = cfg->package_paths;
128                         spec->package_cpaths = cfg->package_cpaths;
129                         spec->vm_server_pool_min = cfg->vm_server_pool_min;
130                         spec->vm_server_pool_max = cfg->vm_server_pool_max;
131                         spec->cb = &lua_open_callback;
132                         spec->cb_arg = NULL;
133             d->spec = spec;
134             d->function_name = "handle";
135         }
136
137         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
138                       "request details scope:%u, cache:%u, filename:%s, function:%s",
139                       d->spec->scope,
140                       d->spec->code_cache_style,
141                       d->spec->file,
142                       d->function_name);
143         L = ap_lua_get_lua_state(r->pool,
144                               d->spec);
145
146         if (!L) {
147             /* TODO annotate spec with failure reason */
148             r->status = HTTP_INTERNAL_SERVER_ERROR;
149             ap_rputs("Unable to compile VM, see logs", r);
150             return HTTP_INTERNAL_SERVER_ERROR;
151         }
152         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "got a vm!");
153         lua_getglobal(L, d->function_name);
154         if (!lua_isfunction(L, -1)) {
155             ap_log_rerror(APLOG_MARK, APLOG_CRIT, 0, r,
156                           "lua: Unable to find function %s in %s",
157                           d->function_name,
158                           d->spec->file);
159             return HTTP_INTERNAL_SERVER_ERROR;
160         }
161         ap_lua_run_lua_request(L, r);
162         if (lua_pcall(L, 1, 0, 0)) {
163             report_lua_error(L, r);
164         }
165     }
166     return OK;
167 }
168
169
170
171 /**
172  * Like mod_alias except for lua handler fun :-) 
173  */
174 static int lua_alias_munger(request_rec *r)
175 {
176     ap_lua_vm_spec *spec;
177     ap_lua_request_cfg *rcfg = ap_get_module_config(r->request_config,
178                                                  &lua_module);
179     const ap_lua_dir_cfg *cfg =
180         ap_get_module_config(r->per_dir_config, &lua_module);
181     int i;
182     ap_regmatch_t matches[AP_MAX_REG_MATCH];
183
184     for (i = 0; i < cfg->mapped_handlers->nelts; i++) {
185         const ap_lua_mapped_handler_spec *cnd =
186             ((const ap_lua_mapped_handler_spec **) cfg->mapped_handlers->elts)[i];
187
188         if (OK ==
189             ap_regexec(cnd->uri_pattern, r->uri, AP_MAX_REG_MATCH, matches,
190                        0)) {
191             mapped_request_details *d;
192             r->handler = "lua-script";
193
194             spec = apr_pcalloc(r->pool, sizeof(ap_lua_vm_spec));
195             spec->file =
196                 ap_pregsub(r->pool, cnd->file_name, r->uri, AP_MAX_REG_MATCH,
197                            matches);
198             spec->scope = cnd->scope;
199             spec->code_cache_style = cnd->code_cache_style;
200             spec->bytecode = cnd->bytecode;
201             spec->bytecode_len = cnd->bytecode_len;
202             if (spec->scope == APL_SCOPE_ONCE) {
203                 spec->pool = r->pool;
204             }
205
206             d = apr_palloc(r->pool, sizeof(mapped_request_details));
207
208             d->function_name =
209                 ap_pregsub(r->pool, cnd->function_name, r->uri,
210                            AP_MAX_REG_MATCH, matches);
211             d->spec = spec;
212
213             /* now do replacement on method name where? */
214             r->filename = apr_pstrdup(r->pool, spec->file);
215             rcfg->mapped_request_details = d;
216             return OK;
217         }
218     }
219     return DECLINED;
220 }
221
222 /* ---------------- Configury stuff --------------- */
223
224 /** harnesses for magic hooks **/
225
226 static int lua_request_rec_hook_harness(request_rec *r, const char *name)
227 {
228     int rc;
229     lua_State *L;
230     ap_lua_vm_spec *spec;
231     ap_lua_server_cfg *server_cfg = ap_get_module_config(r->server->module_config,
232                                                       &lua_module);
233     const ap_lua_dir_cfg *cfg =
234         (ap_lua_dir_cfg *) ap_get_module_config(r->per_dir_config,
235                                              &lua_module);
236     apr_array_header_t *hook_specs =
237         apr_hash_get(cfg->hooks, name, APR_HASH_KEY_STRING);
238     if (hook_specs) {
239         int i;
240         for (i = 0; i < hook_specs->nelts; i++) {
241             ap_lua_mapped_handler_spec *hook_spec =
242                 ((ap_lua_mapped_handler_spec **) hook_specs->elts)[i];
243
244             if (hook_spec == NULL) {
245                 continue;
246             }
247             spec = apr_pcalloc(r->pool, sizeof(ap_lua_vm_spec));
248
249             spec->file = hook_spec->file_name;
250             spec->code_cache_style = hook_spec->code_cache_style;
251             spec->scope = hook_spec->scope;
252                         spec->vm_server_pool_min = cfg->vm_server_pool_min;
253                         spec->vm_server_pool_max = cfg->vm_server_pool_max;
254             spec->bytecode = hook_spec->bytecode;
255             spec->bytecode_len = hook_spec->bytecode_len;
256             spec->pool = spec->scope==APL_SCOPE_SERVER ? cfg->pool : r->pool;
257                         spec->package_paths = cfg->package_paths;
258                         spec->package_cpaths = cfg->package_cpaths;
259                         spec->cb = &lua_open_callback;
260                         spec->cb_arg = NULL;
261
262             apr_filepath_merge(&spec->file, server_cfg->root_path,
263                                spec->file, APR_FILEPATH_NOTRELATIVE, r->pool);
264             L = ap_lua_get_lua_state(r->pool,
265                                   spec);
266
267
268
269             if (!L) {
270                 ap_log_rerror(APLOG_MARK, APLOG_CRIT, 0, r,
271                               "lua: Failed to obtain lua interpreter for %s %s",
272                               hook_spec->function_name, hook_spec->file_name);
273                 return HTTP_INTERNAL_SERVER_ERROR;
274             }
275
276             if (hook_spec->function_name != NULL) {
277                 lua_getglobal(L, hook_spec->function_name);
278                 if (!lua_isfunction(L, -1)) {
279                     ap_log_rerror(APLOG_MARK, APLOG_CRIT, 0, r,
280                                   "lua: Unable to find function %s in %s",
281                                   hook_spec->function_name,
282                                   hook_spec->file_name);
283                     return HTTP_INTERNAL_SERVER_ERROR;
284                 }
285
286                 ap_lua_run_lua_request(L, r);
287             }
288             else {
289                 int t;
290                 ap_lua_run_lua_request(L, r);
291
292                 t = lua_gettop(L);
293                 lua_setglobal(L, "r");
294                 lua_settop(L, t);
295             }
296
297             if (lua_pcall(L, 1, 1, 0)) {
298                 report_lua_error(L, r);
299                 return HTTP_INTERNAL_SERVER_ERROR;
300             }
301             rc = DECLINED;
302             if (lua_isnumber(L, -1)) {
303                 rc = lua_tointeger(L, -1);
304             }
305             if (rc != DECLINED) {
306                 return rc;
307             }
308         }
309     }
310     return DECLINED;
311 }
312
313
314 static apr_size_t config_getstr(ap_configfile_t *cfg, char *buf,
315                                 size_t bufsiz)
316 {
317     apr_size_t i = 0;
318
319     if (cfg->getstr) {
320         const char *res = (cfg->getstr) (buf, bufsiz, cfg->param);
321         if (res) {
322             i = strlen(buf);
323             if (i && buf[i - 1] == '\n')
324                 ++cfg->line_number;
325         }
326         else {
327             buf[0] = '\0';
328             i = 0;
329         }
330     }
331     else {
332         while (i < bufsiz) {
333             int ch = (cfg->getch) (cfg->param);
334             if (ch == EOF)
335                 break;
336             buf[i++] = ch;
337             if (ch == '\n') {
338                 ++cfg->line_number;
339                 break;
340             }
341         }
342     }
343     return i;
344 }
345
346 typedef struct cr_ctx
347 {
348     cmd_parms *cmd;
349     ap_configfile_t *cfp;
350     size_t startline;
351     const char *endstr;
352     char buf[HUGE_STRING_LEN];
353 } cr_ctx;
354
355
356 /* Okay, this deserves a little explaination -- in order for the errors that lua
357  * generates to be 'accuarate', including line numbers, we basically inject
358  * N line number new lines into the 'top' of the chunk reader..... 
359  *
360  * be happy. this is cool.
361  *
362  */
363 static const char *lf =
364     "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
365 #define N_LF 32
366
367 static const char *direct_chunkreader(lua_State *lvm, void *udata,
368                                       size_t *plen)
369 {
370     const char *p;
371     struct cr_ctx *ctx = udata;
372
373     if (ctx->startline) {
374         *plen = ctx->startline > N_LF ? N_LF : ctx->startline;
375         ctx->startline -= *plen;
376         return lf;
377     }
378     *plen = config_getstr(ctx->cfp, ctx->buf, HUGE_STRING_LEN);
379
380     for (p = ctx->buf; isspace(*p); ++p);
381     if (p[0] == '<' && p[1] == '/') {
382         apr_size_t i = 0;
383         while (i < strlen(ctx->endstr)) {
384             if (tolower(p[i + 2]) != ctx->endstr[i])
385                 return ctx->buf;
386             ++i;
387         }
388         *plen = 0;
389         return NULL;
390     }
391     /*fprintf(stderr, "buf read: %s\n", ctx->buf); */
392     return ctx->buf;
393 }
394
395 static int ldump_writer(lua_State *L, const void *b, size_t size, void *B)
396 {
397     (void) L;
398     luaL_addlstring((luaL_Buffer *) B, (const char *) b, size);
399     return 0;
400 }
401
402 typedef struct hack_section_baton
403 {
404     const char *name;
405     ap_lua_mapped_handler_spec *spec;
406 } hack_section_baton;
407
408 /* You can be unhappy now.
409  *
410  * This is uncool.
411  *
412  * When you create a <Section handler in httpd, the only 'easy' way to create
413  * a directory context is to parse the section, and convert it into a 'normal'
414  * Configureation option, and then collapse the entire section, in memory,
415  * back into the parent section -- from which you can then get the new directive
416  * invoked.... anyways. evil. Rici taught me how to do this hack :-)
417  */
418 static const char *hack_section_handler(cmd_parms *cmd, void *_cfg,
419                                         const char *arg)
420 {
421     ap_lua_dir_cfg *cfg = (ap_lua_dir_cfg *) _cfg;
422     ap_directive_t *directive = cmd->directive;
423     hack_section_baton *baton = directive->data;
424
425     apr_array_header_t *hook_specs =
426         apr_hash_get(cfg->hooks, baton->name, APR_HASH_KEY_STRING);
427     if (!hook_specs) {
428         hook_specs =
429             apr_array_make(cmd->pool, 2, sizeof(ap_lua_mapped_handler_spec *));
430         apr_hash_set(cfg->hooks, apr_pstrdup(cmd->pool, baton->name),
431                      APR_HASH_KEY_STRING, hook_specs);
432     }
433
434     baton->spec->scope = cfg->vm_scope;
435
436     *(ap_lua_mapped_handler_spec **) apr_array_push(hook_specs) = baton->spec;
437
438     return NULL;
439 }
440
441 static const char *register_named_block_function_hook(const char *name,
442                                                       cmd_parms *cmd,
443                                                       void *mconfig,
444                                                       const char *line)
445 {
446     const char *function;
447     ap_lua_mapped_handler_spec *spec;
448
449     if (line && line[0] == '>') {
450         function = NULL;
451     }
452     else {
453         const char *word;
454         apr_size_t wordlen;
455         word = ap_getword_conf(cmd->temp_pool, &line);
456         wordlen = strlen(word);
457         if (wordlen == 0 || word[wordlen - 1] != '>') {
458             return apr_pstrcat(cmd->pool, cmd->directive->directive,
459                                "> takes exactly one argument", NULL);
460         }
461         else {
462             function = apr_pstrndup(cmd->pool, word, wordlen - 1);
463         }
464     }
465
466     spec = apr_pcalloc(cmd->pool, sizeof(ap_lua_mapped_handler_spec));
467
468     {
469         cr_ctx ctx;
470         char buf[32];
471         lua_State *lvm;
472         char *tmp;
473         int rv;
474         ap_directive_t **current;
475         hack_section_baton *baton;
476
477         apr_snprintf(buf, sizeof(buf), "%u", cmd->config_file->line_number);
478         spec->file_name =
479             apr_pstrcat(cmd->pool, cmd->config_file->name, ":", buf, NULL);
480         if (function) {
481             spec->function_name = (char *) function;
482         }
483         else {
484             function = NULL;
485         }
486         spec->code_cache_style = APL_CODE_CACHE_FOREVER;
487
488         ctx.cmd = cmd;
489         tmp = apr_pstrdup(cmd->pool, cmd->err_directive->directive + 1);
490         ap_str_tolower(tmp);
491         ctx.endstr = tmp;
492         ctx.cfp = cmd->config_file;
493         ctx.startline = cmd->config_file->line_number;
494
495         /* This lua State is used only to compile the input strings -> bytecode, so we don't need anything extra. */
496         lvm = luaL_newstate();
497
498         lua_settop(lvm, 0);
499
500         rv = lua_load(lvm, direct_chunkreader, &ctx, spec->file_name);
501
502         if (rv != 0) {
503             const char *errstr =
504                 apr_pstrcat(cmd->pool, "Lua Error:", lua_tostring(lvm, -1),
505                             NULL);
506             lua_close(lvm);
507             return errstr;
508         }
509         else {
510             luaL_Buffer b;
511             luaL_buffinit(lvm, &b);
512             lua_dump(lvm, ldump_writer, &b);
513             luaL_pushresult(&b);
514             spec->bytecode_len = lua_strlen(lvm, -1);
515             spec->bytecode =
516                 apr_pstrmemdup(cmd->pool, lua_tostring(lvm, -1),
517                                spec->bytecode_len);
518             lua_close(lvm);
519         }
520
521         current = mconfig;
522
523         /* Here, we have to replace our current config node for the next pass */
524         if (!*current) {
525             *current = apr_pcalloc(cmd->pool, sizeof(**current));
526         }
527
528         baton = apr_pcalloc(cmd->pool, sizeof(hack_section_baton));
529         baton->name = name;
530         baton->spec = spec;
531
532         (*current)->filename = cmd->config_file->name;
533         (*current)->line_num = cmd->config_file->line_number;
534         (*current)->directive =
535             apr_pstrdup(cmd->pool, "Lua_____ByteCodeHack");
536         (*current)->args = NULL;
537         (*current)->data = baton;
538     }
539
540     return NULL;
541 }
542
543 static const char *register_named_file_function_hook(const char *name,
544                                                      cmd_parms *cmd,
545                                                      void *_cfg,
546                                                      const char *file,
547                                                      const char *function)
548 {
549     ap_lua_mapped_handler_spec *spec;
550     ap_lua_dir_cfg *cfg = (ap_lua_dir_cfg *) _cfg;
551
552     apr_array_header_t *hook_specs =
553         apr_hash_get(cfg->hooks, name, APR_HASH_KEY_STRING);
554     if (!hook_specs) {
555         hook_specs =
556             apr_array_make(cmd->pool, 2, sizeof(ap_lua_mapped_handler_spec *));
557         apr_hash_set(cfg->hooks, apr_pstrdup(cmd->pool, name),
558                      APR_HASH_KEY_STRING, hook_specs);
559     }
560
561     spec = apr_pcalloc(cmd->pool, sizeof(ap_lua_mapped_handler_spec));
562     spec->file_name = apr_pstrdup(cmd->pool, file);
563     spec->function_name = apr_pstrdup(cmd->pool, function);
564     spec->scope = cfg->vm_scope;
565     spec->code_cache_style = APL_CODE_CACHE_STAT;
566     /*
567        int code_cache_style;
568        char *function_name;
569        char *file_name;
570        int scope;
571      */
572     *(ap_lua_mapped_handler_spec **) apr_array_push(hook_specs) = spec;
573     return NULL;
574 }
575
576 static int lua_check_user_id_harness(request_rec *r)
577 {
578     return lua_request_rec_hook_harness(r, "check_user_id");
579 }
580
581 static int lua_translate_name_harness(request_rec *r)
582 {
583     return lua_request_rec_hook_harness(r, "translate_name");
584 }
585
586 static int lua_fixup_harness(request_rec *r)
587 {
588     return lua_request_rec_hook_harness(r, "fixups");
589 }
590
591 static int lua_map_to_storage_harness(request_rec *r)
592 {
593     return lua_request_rec_hook_harness(r, "map_to_storage");
594 }
595
596 static int lua_type_checker_harness(request_rec *r)
597 {
598     return lua_request_rec_hook_harness(r, "type_checker");
599 }
600
601 static int lua_access_checker_harness(request_rec *r)
602 {
603     return lua_request_rec_hook_harness(r, "access_checker");
604 }
605
606 static int lua_auth_checker_harness(request_rec *r)
607 {
608     return lua_request_rec_hook_harness(r, "auth_checker");
609 }
610
611 static void lua_insert_filter_harness(request_rec *r)
612 {
613     /* ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, "LuaHookInsertFilter not yet implemented"); */
614 }
615
616 static int lua_quick_harness(request_rec *r, int lookup)
617 {
618     if (lookup) {
619         return DECLINED;
620     }
621     return lua_request_rec_hook_harness(r, "quick");
622 }
623
624 static const char *register_translate_name_hook(cmd_parms *cmd, void *_cfg,
625                                                 const char *file,
626                                                 const char *function)
627 {
628     return register_named_file_function_hook("translate_name", cmd, _cfg,
629                                              file, function);
630 }
631
632 static const char *register_translate_name_block(cmd_parms *cmd, void *_cfg,
633                                                  const char *line)
634 {
635     return register_named_block_function_hook("translate_name", cmd, _cfg,
636                                               line);
637 }
638
639
640 static const char *register_fixups_hook(cmd_parms *cmd, void *_cfg,
641                                         const char *file,
642                                         const char *function)
643 {
644     return register_named_file_function_hook("fixups", cmd, _cfg, file,
645                                              function);
646 }
647 static const char *register_fixups_block(cmd_parms *cmd, void *_cfg,
648                                          const char *line)
649 {
650     return register_named_block_function_hook("fixups", cmd, _cfg, line);
651 }
652
653 static const char *register_map_to_storage_hook(cmd_parms *cmd, void *_cfg,
654                                                 const char *file,
655                                                 const char *function)
656 {
657     return register_named_file_function_hook("map_to_storage", cmd, _cfg,
658                                              file, function);
659 }
660 static const char *register_map_to_storage_block(cmd_parms *cmd, void *_cfg,
661                                                  const char *line)
662 {
663     return register_named_block_function_hook("map_to_storage", cmd, _cfg,
664                                               line);
665 }
666
667 static const char *register_check_user_id_hook(cmd_parms *cmd, void *_cfg,
668                                                const char *file,
669                                                const char *function)
670 {
671     return register_named_file_function_hook("check_user_id", cmd, _cfg, file,
672                                              function);
673 }
674 static const char *register_check_user_id_block(cmd_parms *cmd, void *_cfg,
675                                                 const char *line)
676 {
677     return register_named_block_function_hook("check_user_id", cmd, _cfg,
678                                               line);
679 }
680
681 static const char *register_type_checker_hook(cmd_parms *cmd, void *_cfg,
682                                               const char *file,
683                                               const char *function)
684 {
685     return register_named_file_function_hook("type_checker", cmd, _cfg, file,
686                                              function);
687 }
688 static const char *register_type_checker_block(cmd_parms *cmd, void *_cfg,
689                                                const char *line)
690 {
691     return register_named_block_function_hook("type_checker", cmd, _cfg,
692                                               line);
693 }
694
695 static const char *register_access_checker_hook(cmd_parms *cmd, void *_cfg,
696                                                 const char *file,
697                                                 const char *function)
698 {
699     return register_named_file_function_hook("access_checker", cmd, _cfg,
700                                              file, function);
701 }
702 static const char *register_access_checker_block(cmd_parms *cmd, void *_cfg,
703                                                  const char *line)
704 {
705     return register_named_block_function_hook("access_checker", cmd, _cfg,
706                                               line);
707 }
708
709 static const char *register_auth_checker_hook(cmd_parms *cmd, void *_cfg,
710                                               const char *file,
711                                               const char *function)
712 {
713     return register_named_file_function_hook("auth_checker", cmd, _cfg, file,
714                                              function);
715 }
716 static const char *register_auth_checker_block(cmd_parms *cmd, void *_cfg,
717                                                const char *line)
718 {
719     return register_named_block_function_hook("auth_checker", cmd, _cfg,
720                                               line);
721 }
722
723 static const char *register_insert_filter_hook(cmd_parms *cmd, void *_cfg,
724                                                const char *file,
725                                                const char *function)
726 {
727     return "LuaHookInsertFilter not yet implemented";
728 }
729
730 static const char *register_quick_hook(cmd_parms *cmd, void *_cfg,
731                                        const char *file, const char *function)
732 {
733     return register_named_file_function_hook("quick", cmd, _cfg, file,
734                                              function);
735 }
736 static const char *register_quick_block(cmd_parms *cmd, void *_cfg,
737                                         const char *line)
738 {
739     return "LuaQuickHook in an inline block not yet implemented";
740 }
741
742
743
744 static const char *register_package_helper(cmd_parms *cmd, const char *arg,
745                                            apr_array_header_t *dir_array)
746 {
747     apr_status_t rv;
748
749     ap_lua_server_cfg *server_cfg =
750         ap_get_module_config(cmd->server->module_config, &lua_module);
751     char *fixed_filename;
752     rv = apr_filepath_merge(&fixed_filename, server_cfg->root_path, arg,
753                             APR_FILEPATH_NOTRELATIVE, cmd->pool);
754     if (rv != APR_SUCCESS) {
755         return apr_psprintf(cmd->pool,
756                             "Unable to build full path to file, %s", arg);
757     }
758
759     *(const char **) apr_array_push(dir_array) = fixed_filename;
760     return NULL;
761 }
762
763
764 /**
765  * Called for config directive which looks like
766  * LuaPackagePath /lua/package/path/mapped/thing/like/this/?.lua
767  */
768 static const char *register_package_dir(cmd_parms *cmd, void *_cfg,
769                                         const char *arg)
770 {
771     ap_lua_dir_cfg *cfg = (ap_lua_dir_cfg *) _cfg;
772
773     return register_package_helper(cmd, arg, cfg->package_paths);
774 }
775
776 /**
777  * Called for config directive which looks like
778  * LuaPackageCPath /lua/package/path/mapped/thing/like/this/?.so
779  */
780 static const char *register_package_cdir(cmd_parms *cmd, void *_cfg,
781                                          const char *arg)
782 {
783     ap_lua_dir_cfg *cfg = (ap_lua_dir_cfg *) _cfg;
784
785     return register_package_helper(cmd, arg, cfg->package_cpaths);
786 }
787
788 /**
789  * Called for config directive which looks like
790  * LuaCodeCache 
791  */
792 static const char *register_code_cache(cmd_parms *cmd, void *_cfg,
793                                        const char *arg)
794 {
795     ap_lua_dir_cfg *cfg = (ap_lua_dir_cfg *) _cfg;
796     if (strcmp("stat", arg) == 0) {
797         cfg->code_cache_style = APL_CODE_CACHE_STAT;
798     }
799     else if (strcmp("forever", arg) == 0) {
800         cfg->code_cache_style = APL_CODE_CACHE_FOREVER;
801     }
802     else if (strcmp("never", arg) == 0) {
803         cfg->code_cache_style = APL_CODE_CACHE_NEVER;
804     }
805     else {
806         return apr_psprintf(cmd->pool,
807                             "Invalid value for LuaCodeCache, '%s', acceptable values are %s",
808                             arg, "'stat', 'forever', and 'never'");
809     }
810     return NULL;
811 }
812
813 static const char *register_lua_scope(cmd_parms *cmd, void *_cfg,
814                                       const char *scope, const char *min,
815                                       const char *max)
816 {
817     ap_lua_dir_cfg *cfg = (ap_lua_dir_cfg *) _cfg;
818     if (strcmp("once", scope) == 0) {
819         cfg->vm_scope = APL_SCOPE_ONCE;
820     }
821     else if (strcmp("request", scope) == 0) {
822         cfg->vm_scope = APL_SCOPE_REQUEST;
823     }
824     else if (strcmp("conn", scope) == 0) {
825         cfg->vm_scope = APL_SCOPE_CONN;
826     }
827     else if (strcmp("server", scope) == 0) {
828         cfg->vm_scope = APL_SCOPE_SERVER;
829         if (min)
830             cfg->vm_server_pool_min = atoi(min);
831         if (max)
832             cfg->vm_server_pool_max = atoi(max);
833     }
834     else {
835         return apr_psprintf(cmd->pool,
836                             "Invalid value for LuaScope, '%s', acceptable values are %s",
837                             scope, "'once', 'request', 'conn', and 'server'");
838     }
839     return NULL;
840 }
841
842
843 /**
844  * Called for config directive which looks like
845  * AddLuaHandler /alias /path/to/lua/file.lua [handler_function_name]
846  */
847 static const char *lua_map_handler(cmd_parms *cmd, void *_cfg,
848                                    const char *path, const char *file,
849                                    const char *function)
850 {
851     ap_lua_dir_cfg *cfg = (ap_lua_dir_cfg *) _cfg;
852     apr_status_t rv;
853     const char *function_name;
854     function_name = function ? function : "handle";
855     rv = ap_lua_map_handler(cfg, file, function_name, path, "once");
856     if (rv != APR_SUCCESS) {
857         return apr_psprintf(cmd->pool,
858                             "Unable to configure a lua handler for path '%s', handler %s#%s",
859                             path, file, function_name);
860     }
861     return NULL;
862 }
863
864 static const char *register_lua_root(cmd_parms *cmd, void *_cfg,
865                                      const char *root)
866 {
867     /* ap_lua_dir_cfg* cfg = (ap_lua_dir_cfg*)_cfg; */
868     ap_lua_server_cfg *cfg =
869         ap_get_module_config(cmd->server->module_config, &lua_module);
870
871     cfg->root_path = root;
872     return NULL;
873 }
874
875 /*******************************/
876
877 command_rec lua_commands[] = {
878
879     AP_INIT_TAKE1("LuaRoot", register_lua_root, NULL, OR_ALL,
880                   "Specify the base path for resolving relative paths for mod_lua directives"),
881
882
883     AP_INIT_TAKE1("LuaPackagePath", register_package_dir, NULL, OR_ALL,
884                   "Add a directory to lua's package.path"),
885
886     AP_INIT_TAKE1("LuaPackageCPath", register_package_cdir, NULL, OR_ALL,
887                   "Add a directory to lua's package.cpath"),
888
889     AP_INIT_TAKE23("LuaMapHandler", lua_map_handler, NULL, OR_ALL,
890                    "Map a path to a lua handler"),
891
892     AP_INIT_TAKE2("LuaHookTranslateName", register_translate_name_hook, NULL,
893                   OR_ALL,
894                   "Provide a hook for the translate name phase of request processing"),
895     AP_INIT_RAW_ARGS("<LuaHookTranslateName", register_translate_name_block,
896                      NULL,
897                      EXEC_ON_READ | OR_ALL,
898                      "Provide a hook for the translate name phase of request processing"),
899
900     AP_INIT_TAKE2("LuaHookFixups", register_fixups_hook, NULL, OR_ALL,
901                   "Provide a hook for the fixups phase of request processing"),
902     AP_INIT_RAW_ARGS("<LuaHookFixups", register_fixups_block, NULL,
903                      EXEC_ON_READ | OR_ALL,
904                      "Provide a inline hook for the fixups phase of request processing"),
905
906 /* todo: test */
907     AP_INIT_TAKE2("LuaHookMapToStorage", register_map_to_storage_hook, NULL,
908                   OR_ALL,
909                   "Provide a hook for the map_to_storage phase of request processing"),
910     AP_INIT_RAW_ARGS("<LuaHookMapToStorage", register_map_to_storage_block,
911                      NULL,
912                      EXEC_ON_READ | OR_ALL,
913                      "Provide a hook for the map_to_storage phase of request processing"),
914
915     /* todo: test */
916     AP_INIT_TAKE2("LuaHookCheckUserID", register_check_user_id_hook, NULL,
917                   OR_ALL,
918                   "Provide a hook for the check_user_id phase of request processing"),
919     AP_INIT_RAW_ARGS("<LuaHookCheckUserID", register_check_user_id_block,
920                      NULL,
921                      EXEC_ON_READ | OR_ALL,
922                      "Provide a hook for the check_user_id phase of request processing"),
923
924     /* todo: test */
925     AP_INIT_TAKE2("LuaHookTypeChecker", register_type_checker_hook, NULL,
926                   OR_ALL,
927                   "Provide a hook for the type_checker phase of request processing"),
928     AP_INIT_RAW_ARGS("<LuaHookTypeChecker", register_type_checker_block, NULL,
929                      EXEC_ON_READ | OR_ALL,
930                      "Provide a hook for the type_checker phase of request processing"),
931
932     /* todo: test */
933     AP_INIT_TAKE2("LuaHookAccessChecker", register_access_checker_hook, NULL,
934                   OR_ALL,
935                   "Provide a hook for the access_checker phase of request processing"),
936     AP_INIT_RAW_ARGS("<LuaHookAccessChecker", register_access_checker_block,
937                      NULL,
938                      EXEC_ON_READ | OR_ALL,
939                      "Provide a hook for the access_checker phase of request processing"),
940
941     /* todo: test */
942     AP_INIT_TAKE2("LuaHookAuthChecker", register_auth_checker_hook, NULL,
943                   OR_ALL,
944                   "Provide a hook for the auth_checker phase of request processing"),
945     AP_INIT_RAW_ARGS("<LuaHookAuthChecker", register_auth_checker_block, NULL,
946                      EXEC_ON_READ | OR_ALL,
947                      "Provide a hook for the auth_checker phase of request processing"),
948
949     /* todo: test */
950     AP_INIT_TAKE2("LuaHookInsertFilter", register_insert_filter_hook, NULL,
951                   OR_ALL,
952                   "Provide a hook for the insert_filter phase of request processing"),
953
954     AP_INIT_TAKE1("LuaCodeCache", register_code_cache, NULL, OR_ALL,
955                   "Configure the compiled code cache. \
956                    Default is to stat the file each time, options are stat|forever|never"),
957
958     AP_INIT_TAKE123("LuaScope", register_lua_scope, NULL, OR_ALL,
959                     "One of once, request, conn, server -- default is once"),
960
961     AP_INIT_TAKE2("LuaQuickHandler", register_quick_hook, NULL, OR_ALL,
962                   "Provide a hook for the quick handler of request processing"),
963     AP_INIT_RAW_ARGS("<LuaQuickHandler", register_quick_block, NULL,
964                      EXEC_ON_READ | OR_ALL,
965                      "Provide a hook for the quick handler of request processing"),
966
967     AP_INIT_RAW_ARGS("Lua_____ByteCodeHack", hack_section_handler, NULL,
968                      OR_ALL,
969                      "(internal) Byte code handler"),
970     {NULL}
971 };
972
973
974 static void *create_dir_config(apr_pool_t *p, char *dir)
975 {
976     ap_lua_dir_cfg *cfg = apr_pcalloc(p, sizeof(ap_lua_dir_cfg));
977     cfg->package_paths = apr_array_make(p, 2, sizeof(char *));
978     cfg->package_cpaths = apr_array_make(p, 2, sizeof(char *));
979     cfg->mapped_handlers =
980         apr_array_make(p, 1, sizeof(ap_lua_mapped_handler_spec *));
981     cfg->code_cache_style = APL_CODE_CACHE_STAT;
982     cfg->pool = p;
983     cfg->hooks = apr_hash_make(p);
984     cfg->dir = apr_pstrdup(p, dir);
985     cfg->vm_scope = APL_SCOPE_ONCE;
986     return cfg;
987 }
988
989 static int create_request_config(request_rec *r)
990 {
991     ap_lua_request_cfg *cfg = apr_palloc(r->pool, sizeof(ap_lua_request_cfg));
992     cfg->mapped_request_details = NULL;
993     cfg->request_scoped_vms = apr_hash_make(r->pool);
994     ap_set_module_config(r->request_config, &lua_module, cfg);
995     return OK;
996 }
997
998 static void *create_server_config(apr_pool_t *p, server_rec *s)
999 {
1000
1001     ap_lua_server_cfg *cfg = apr_pcalloc(p, sizeof(ap_lua_server_cfg));
1002     cfg->code_cache = apr_pcalloc(p, sizeof(ap_lua_code_cache));
1003     apr_thread_rwlock_create(&cfg->code_cache->compiled_files_lock, p);
1004     cfg->code_cache->compiled_files = apr_hash_make(p);
1005     cfg->vm_reslists = apr_hash_make(p);
1006     apr_thread_rwlock_create(&cfg->vm_reslists_lock, p);
1007     cfg->code_cache->pool = p;
1008     cfg->root_path = NULL;
1009
1010     return cfg;
1011 }
1012
1013 static int lua_request_hook(lua_State *L, request_rec *r)
1014 {
1015     ap_lua_push_request(L, r);
1016     return OK;
1017 }
1018
1019 static void lua_register_hooks(apr_pool_t *p)
1020 {
1021     /* ap_register_output_filter("luahood", luahood, NULL, AP_FTYPE_RESOURCE); */
1022     ap_hook_handler(lua_handler, NULL, NULL, APR_HOOK_MIDDLE);
1023     ap_hook_create_request(create_request_config, NULL, NULL,
1024                            APR_HOOK_MIDDLE);
1025
1026     /* http_request.h hooks */
1027     ap_hook_translate_name(lua_translate_name_harness, NULL, NULL,
1028                            APR_HOOK_MIDDLE);
1029     ap_hook_fixups(lua_fixup_harness, NULL, NULL, APR_HOOK_MIDDLE);
1030     ap_hook_map_to_storage(lua_map_to_storage_harness, NULL, NULL,
1031                            APR_HOOK_MIDDLE);
1032     ap_hook_check_user_id(lua_check_user_id_harness, NULL, NULL,
1033                           APR_HOOK_MIDDLE);
1034     ap_hook_type_checker(lua_type_checker_harness, NULL, NULL,
1035                          APR_HOOK_MIDDLE);
1036     ap_hook_access_checker(lua_access_checker_harness, NULL, NULL,
1037                            APR_HOOK_MIDDLE);
1038     ap_hook_auth_checker(lua_auth_checker_harness, NULL, NULL,
1039                          APR_HOOK_MIDDLE);
1040     ap_hook_insert_filter(lua_insert_filter_harness, NULL, NULL,
1041                           APR_HOOK_MIDDLE);
1042     ap_hook_quick_handler(lua_quick_harness, NULL, NULL, APR_HOOK_FIRST);
1043
1044     /* ap_hook_translate_name(lua_alias_munger, NULL, NULL, APR_HOOK_MIDDLE); */
1045     ap_hook_translate_name(lua_alias_munger, NULL, NULL, APR_HOOK_MIDDLE);
1046
1047     APR_OPTIONAL_HOOK(ap_lua, lua_open, lua_open_hook, NULL, NULL,
1048                       APR_HOOK_REALLY_FIRST);
1049
1050     APR_OPTIONAL_HOOK(ap_lua, lua_request, lua_request_hook, NULL, NULL,
1051                       APR_HOOK_REALLY_FIRST);
1052 }
1053
1054 AP_DECLARE_MODULE(lua) = {
1055     STANDARD20_MODULE_STUFF,
1056     create_dir_config,          /* create per-dir    config structures */
1057     NULL,                       /* merge  per-dir    config structures */
1058     create_server_config,       /* create per-server config structures */
1059     NULL,                       /* merge  per-server config structures */
1060     lua_commands,               /* table of config file commands       */
1061     lua_register_hooks          /* register hooks                      */
1062 };