OSDN Git Service

HmlSubPath.
[hmh/apache_module.git] / mod_hml.c
1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2  * contributor license agreements.  See the NOTICE file distributed with
3  * this work for additional information regarding copyright ownership.
4  * The ASF licenses this file to You under the Apache License, Version 2.0
5  * (the "License"); you may not use this file except in compliance with
6  * the License.  You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include "apr.h"
18 #include "apr_strings.h"
19 #include "apr_thread_proc.h"    /* for RLIMIT stuff */
20 #include "apr_optional.h"
21 #include "apr_buckets.h"
22 #include "apr_lib.h"
23 #include "apr_poll.h"
24
25 #define APR_WANT_STRFUNC
26 #define APR_WANT_MEMFUNC
27 #include "apr_want.h"
28
29 #define CORE_PRIVATE
30
31 #include "util_filter.h"
32 #include "ap_config.h"
33 #include "httpd.h"
34 #include "http_config.h"
35 #include "http_request.h"
36 #include "http_core.h"
37 #include "http_protocol.h"
38 #include "http_main.h"
39 #include "http_log.h"
40 #include "util_script.h"
41 #include "ap_mpm.h"
42 #include "mod_core.h"
43 //#include "mod_hml.h"
44
45 module AP_MODULE_DECLARE_DATA hml_module;
46
47 //static APR_OPTIONAL_FN_TYPE(ap_register_include_handler) *cgi_pfn_reg_with_ssi;
48 //static APR_OPTIONAL_FN_TYPE(ap_ssi_get_tag_and_value) *cgi_pfn_gtv;
49 //static APR_OPTIONAL_FN_TYPE(ap_ssi_parse_string) *cgi_pfn_ps;
50 //static APR_OPTIONAL_FN_TYPE(ap_hml_build_command) *hml_build_command;
51
52 /* Read and discard the data in the brigade produced by a CGI script */
53 static void discard_script_output(apr_bucket_brigade *bb);
54
55 /* KLUDGE --- for back-combatibility, we don't have to check ExecCGI
56  * in ScriptAliased directories, which means we need to know if this
57  * request came through ScriptAlias or not... so the Alias module
58  * leaves a note for us.
59  */
60
61 #if 0
62 static int is_scriptaliased(request_rec *r)
63 {
64     const char *t = apr_table_get(r->notes, "alias-forced-type");
65     return t && (!strcasecmp(t, "cgi-script"));
66 }
67 #endif
68
69 /* Configuration stuff */
70
71 #define HMLREADMAX      2048
72 #define DEFAULT_LOGBYTES 10385760
73 #define DEFAULT_BUFBYTES 1024
74
75 typedef struct {
76     const char *logname;
77     long        logbytes;
78     apr_size_t  bufbytes;
79 } hml_server_conf;
80
81 typedef struct hml_dir_conf {
82     char*  hmldir;
83     char*  hmlsubpath;
84 //    apr_table_t*  env;
85     char*  searchpath;
86     char*  dataroot;
87 }  hml_dir_conf;
88
89 typedef struct {
90     apr_int32_t          in_pipe;
91     apr_int32_t          out_pipe;
92     apr_int32_t          err_pipe;
93     int                  process_hml;
94     apr_cmdtype_e        cmd_type;
95     apr_int32_t          detached;
96 //    prog_types           prog_type;
97     apr_bucket_brigade **bb;
98 //    include_ctx_t       *ctx;
99     ap_filter_t         *next;
100     apr_int32_t          addrspace;
101     hml_dir_conf*  dirconf;
102 } hml_exec_info_t;
103
104 static void*  create_hml_dir_config (apr_pool_t* p, char* dir) {
105     hml_dir_conf*  conf = apr_pcalloc (p, sizeof (hml_dir_conf));
106     return conf;
107 }
108
109 static void*  merge_hml_dir_config (apr_pool_t* p, void* base_conf, void* new_conf) {
110     hml_dir_conf*  bconf = (hml_dir_conf*)base_conf;
111     hml_dir_conf*  nconf = (hml_dir_conf*)new_conf;
112     if (nconf->hmldir == NULL) nconf->hmldir = bconf->hmldir;
113     if (nconf->hmlsubpath == NULL) nconf->hmlsubpath = bconf->hmlsubpath;
114 #if 0
115     if (nconf->env == NULL) {
116         nconf->env = bconf->env;
117     } else if (bconf->env) {
118         const apr_array_header_t*  arr = apr_table_elts (bconf->env);
119         const apr_table_entry_t*  elts;
120         int  i;
121
122         if (arr) {
123             elts = (const apr_table_entry_t *)arr->elts;
124             for (i = 0; i < arr->nelts; i ++) {
125                 apr_table_setn (nconf->env, elts[i].key, elts[i].val);
126             }
127         }
128         
129     }
130 #endif
131     if (nconf->searchpath == NULL) nconf->searchpath = bconf->searchpath;
132     if (nconf->dataroot == NULL) nconf->dataroot = bconf->dataroot;
133     return nconf;
134 }
135
136 static const char*  set_subpath (cmd_parms* cmd, void* vconf, const char* value) {
137     hml_dir_conf*  conf = (hml_dir_conf*)vconf;
138     const char*  p;
139     int  c;
140
141     for (p = value; *p; p ++) {
142         c = *p;
143         if (isalnum (c) || c == '-' || c == '_') {
144         } else {
145             return apr_pstrcat (cmd->pool, "Invalid directory path ", value, NULL);
146         }
147     }
148     conf->hmlsubpath = value;
149
150     return NULL;
151 }
152
153 //static const char* set_searchpath (cmd_parms* cmd, void* vconf, const char* name, const char* value) {
154 static const char* set_searchpath (cmd_parms* cmd, void* vconf, const char* value) {
155     hml_dir_conf*  conf = (hml_dir_conf*)vconf;
156
157     if (ap_os_is_path_absolute (cmd->pool, value)) {
158         goto err;
159     } else {
160         if (cmd->path) {
161             char*  path;
162             char*  p;
163             path = ap_make_full_path (cmd->pool, cmd->path, value);
164             for (p = path; *p; p ++) {
165                 if ((*p == '/' && p[1] == '/')
166                     || (*p == '.' && p[1] == '.')) {
167                     goto err;
168                 }
169             }
170 //          if (conf->env == NULL)
171 //              conf->env = apr_table_make (cmd->pool, 4);
172 //          apr_table_setn (conf->env, name, path);
173             conf->searchpath = path;
174         }
175     }
176
177  err:
178     return apr_pstrcat (cmd->pool, "Invalid directory path ", value, NULL);
179 }
180
181 static void *create_hml_config(apr_pool_t *p, server_rec *s)
182 {
183     hml_server_conf *c =
184         (hml_server_conf *) apr_pcalloc(p, sizeof(hml_server_conf));
185
186     c->logname = NULL;
187     c->logbytes = DEFAULT_LOGBYTES;
188     c->bufbytes = DEFAULT_BUFBYTES;
189
190     return c;
191 }
192
193 static void *merge_hml_config(apr_pool_t *p, void *basev, void *overridesv)
194 {
195     hml_server_conf *base = (hml_server_conf *) basev,
196                     *overrides = (hml_server_conf *) overridesv;
197
198     return overrides->logname ? overrides : base;
199 }
200
201 static const char *set_scriptlog(cmd_parms *cmd, void *dummy, const char *arg)
202 {
203     server_rec *s = cmd->server;
204     hml_server_conf *conf = ap_get_module_config(s->module_config,
205                                                  &hml_module);
206
207     conf->logname = ap_server_root_relative(cmd->pool, arg);
208
209     if (!conf->logname) {
210         return apr_pstrcat(cmd->pool, "Invalid HmlScriptLog path ",
211                            arg, NULL);
212     }
213
214     return NULL;
215 }
216
217 static const char *set_scriptlog_length(cmd_parms *cmd, void *dummy,
218                                         const char *arg)
219 {
220     server_rec *s = cmd->server;
221     hml_server_conf *conf = ap_get_module_config(s->module_config,
222                                                  &hml_module);
223
224     conf->logbytes = atol(arg);
225     return NULL;
226 }
227
228 static const char *set_scriptlog_buffer(cmd_parms *cmd, void *dummy,
229                                         const char *arg)
230 {
231     server_rec *s = cmd->server;
232     hml_server_conf *conf = ap_get_module_config(s->module_config,
233                                                  &hml_module);
234
235     conf->bufbytes = atoi(arg);
236     return NULL;
237 }
238
239 static const command_rec hml_cmds[] =
240 {
241     AP_INIT_TAKE1 ("HmlDir", ap_set_file_slot, (void*)APR_OFFSETOF (hml_dir_conf, hmldir), RSRC_CONF | ACCESS_CONF, "interpreter command directory"),
242     AP_INIT_TAKE1 ("HmlSubPath", set_subpath, NULL, OR_FILEINFO | ACCESS_CONF, "subdirectory of HmlDir"),
243 //    AP_INIT_TAKE2 ("HmlSearchPath", set_searchpath, NULL, OR_FILEINFO, "set HMLSEARCHPATH env. variable"),
244     AP_INIT_TAKE1 ("HmlSearchPath", set_searchpath, NULL, OR_FILEINFO, "set HTMLSEARCHPATH env. variable"),
245     AP_INIT_TAKE1 ("HmlDataRoot", ap_set_file_slot, (void*)APR_OFFSETOF (hml_dir_conf, dataroot), RSRC_CONF | ACCESS_CONF, "top directory of data"),
246     AP_INIT_TAKE1("HmlScriptLog", set_scriptlog, NULL, RSRC_CONF, "the name of a log for script debugging info"),
247     AP_INIT_TAKE1("HmlScriptLogLength", set_scriptlog_length, NULL, RSRC_CONF, "the maximum length (in bytes) of the script debug log"),
248     AP_INIT_TAKE1("HmlScriptLogBuffer", set_scriptlog_buffer, NULL, RSRC_CONF, "the maximum size (in bytes) to record of a POST request"),
249     {NULL}
250 };
251
252 static int log_scripterror(request_rec *r, hml_server_conf * conf, int ret,
253                            apr_status_t rv, char *error)
254 {
255     apr_file_t *f = NULL;
256     apr_finfo_t finfo;
257     char time_str[APR_CTIME_LEN];
258     int log_flags = rv ? APLOG_ERR : APLOG_ERR;
259
260     ap_log_rerror(APLOG_MARK, log_flags, rv, r,
261                   "%s: %s", error, r->filename);
262
263     /* XXX Very expensive mainline case! Open, then getfileinfo! */
264     if (!conf->logname ||
265         ((apr_stat(&finfo, conf->logname,
266                    APR_FINFO_SIZE, r->pool) == APR_SUCCESS) &&
267          (finfo.size > conf->logbytes)) ||
268         (apr_file_open(&f, conf->logname,
269                        APR_APPEND|APR_WRITE|APR_CREATE, APR_OS_DEFAULT,
270                        r->pool) != APR_SUCCESS)) {
271         return ret;
272     }
273
274     /* "%% [Wed Jun 19 10:53:21 1996] GET /cgi-bin/printenv HTTP/1.0" */
275     apr_ctime(time_str, apr_time_now());
276     apr_file_printf(f, "%%%% [%s] %s %s%s%s %s\n", time_str, r->method, r->uri,
277                     r->args ? "?" : "", r->args ? r->args : "", r->protocol);
278     /* "%% 500 /usr/local/apache/cgi-bin */
279     apr_file_printf(f, "%%%% %d %s\n", ret, r->filename);
280
281     apr_file_printf(f, "%%error\n%s\n", error);
282
283     apr_file_close(f);
284     return ret;
285 }
286
287 /* Soak up stderr from a script and redirect it to the error log.
288  */
289 static apr_status_t log_script_err(request_rec *r, apr_file_t *script_err)
290 {
291     char argsbuffer[HUGE_STRING_LEN];
292     char *newline;
293     apr_status_t rv;
294
295     while ((rv = apr_file_gets(argsbuffer, HUGE_STRING_LEN,
296                                script_err)) == APR_SUCCESS) {
297 //        newline = strchr(argsbuffer, '\n');
298 //        if (newline) {
299 //            *newline = '\0';
300 //        }
301 //        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
302 //                      "%s", argsbuffer);
303         if (r->server->error_log) {
304             apr_file_puts (argsbuffer, r->server->error_log);
305         }
306     }
307     if (r->server->error_log) {
308         apr_file_flush (r->server->error_log);
309     }
310
311     return rv;
312 }
313
314 static int log_script(request_rec *r, hml_server_conf * conf, int ret,
315                       char *dbuf, const char *sbuf, apr_bucket_brigade *bb,
316                       apr_file_t *script_err)
317 {
318     const apr_array_header_t *hdrs_arr = apr_table_elts(r->headers_in);
319     const apr_table_entry_t *hdrs = (const apr_table_entry_t *) hdrs_arr->elts;
320     char argsbuffer[HUGE_STRING_LEN];
321     apr_file_t *f = NULL;
322     apr_bucket *e;
323     const char *buf;
324     apr_size_t len;
325     apr_status_t rv;
326     int first;
327     int i;
328     apr_finfo_t finfo;
329     char time_str[APR_CTIME_LEN];
330
331     /* XXX Very expensive mainline case! Open, then getfileinfo! */
332     if (!conf->logname ||
333         ((apr_stat(&finfo, conf->logname,
334                    APR_FINFO_SIZE, r->pool) == APR_SUCCESS) &&
335          (finfo.size > conf->logbytes)) ||
336         (apr_file_open(&f, conf->logname,
337                        APR_APPEND|APR_WRITE|APR_CREATE, APR_OS_DEFAULT,
338                        r->pool) != APR_SUCCESS)) {
339         /* Soak up script output */
340         discard_script_output(bb);
341         log_script_err(r, script_err);
342         return ret;
343     }
344
345     /* "%% [Wed Jun 19 10:53:21 1996] GET /cgi-bin/printenv HTTP/1.0" */
346     apr_ctime(time_str, apr_time_now());
347     apr_file_printf(f, "%%%% [%s] %s %s%s%s %s\n", time_str, r->method, r->uri,
348                     r->args ? "?" : "", r->args ? r->args : "", r->protocol);
349     /* "%% 500 /usr/local/apache/cgi-bin" */
350     apr_file_printf(f, "%%%% %d %s\n", ret, r->filename);
351
352     apr_file_puts("%request\n", f);
353     for (i = 0; i < hdrs_arr->nelts; ++i) {
354         if (!hdrs[i].key)
355             continue;
356         apr_file_printf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val);
357     }
358     if ((r->method_number == M_POST || r->method_number == M_PUT) &&
359         *dbuf) {
360         apr_file_printf(f, "\n%s\n", dbuf);
361     }
362
363     apr_file_puts("%response\n", f);
364     hdrs_arr = apr_table_elts(r->err_headers_out);
365     hdrs = (const apr_table_entry_t *) hdrs_arr->elts;
366
367     for (i = 0; i < hdrs_arr->nelts; ++i) {
368         if (!hdrs[i].key)
369             continue;
370         apr_file_printf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val);
371     }
372
373     if (sbuf && *sbuf)
374         apr_file_printf(f, "%s\n", sbuf);
375
376     first = 1;
377     for (e = APR_BRIGADE_FIRST(bb);
378          e != APR_BRIGADE_SENTINEL(bb);
379          e = APR_BUCKET_NEXT(e))
380     {
381         if (APR_BUCKET_IS_EOS(e)) {
382             break;
383         }
384         rv = apr_bucket_read(e, &buf, &len, APR_BLOCK_READ);
385         if (rv != APR_SUCCESS || (len == 0)) {
386             break;
387         }
388         if (first) {
389             apr_file_puts("%stdout\n", f);
390             first = 0;
391         }
392         apr_file_write(f, buf, &len);
393         apr_file_puts("\n", f);
394     }
395
396     if (apr_file_gets(argsbuffer, HUGE_STRING_LEN, script_err) == APR_SUCCESS) {
397         apr_file_puts("%stderr\n", f);
398         apr_file_puts(argsbuffer, f);
399         while (apr_file_gets(argsbuffer, HUGE_STRING_LEN,
400                              script_err) == APR_SUCCESS) {
401             apr_file_puts(argsbuffer, f);
402         }
403         apr_file_puts("\n", f);
404     }
405
406     apr_brigade_destroy(bb);
407     apr_file_close(script_err);
408
409     apr_file_close(f);
410     return ret;
411 }
412
413
414 #if 0
415 /* This is the special environment used for running the "exec cmd="
416  *   variety of SSI directives.
417  */
418 static void add_ssi_vars(request_rec *r)
419 {
420     apr_table_t *e = r->subprocess_env;
421
422     if (r->path_info && r->path_info[0] != '\0') {
423         request_rec *pa_req;
424
425         apr_table_setn(e, "PATH_INFO", ap_escape_shell_cmd(r->pool,
426                                                            r->path_info));
427
428         pa_req = ap_sub_req_lookup_uri(ap_escape_uri(r->pool, r->path_info),
429                                        r, NULL);
430         if (pa_req->filename) {
431             apr_table_setn(e, "PATH_TRANSLATED",
432                            apr_pstrcat(r->pool, pa_req->filename,
433                                        pa_req->path_info, NULL));
434         }
435         ap_destroy_sub_req(pa_req);
436     }
437
438     if (r->args) {
439         char *arg_copy = apr_pstrdup(r->pool, r->args);
440
441         apr_table_setn(e, "QUERY_STRING", r->args);
442         ap_unescape_url(arg_copy);
443         apr_table_setn(e, "QUERY_STRING_UNESCAPED",
444                        ap_escape_shell_cmd(r->pool, arg_copy));
445     }
446 }
447 #endif
448
449 static void hml_child_errfn(apr_pool_t *pool, apr_status_t err,
450                             const char *description)
451 {
452     apr_file_t *stderr_log;
453     char errbuf[200];
454
455     apr_file_open_stderr(&stderr_log, pool);
456     /* Escape the logged string because it may be something that
457      * came in over the network.
458      */
459     apr_file_printf(stderr_log,
460                     "(%d)%s: %s\n",
461                     err,
462                     apr_strerror(err, errbuf, sizeof(errbuf)),
463 #ifndef AP_UNSAFE_ERROR_LOG_UNESCAPED
464                     ap_escape_logitem(pool,
465 #endif
466                     description
467 #ifndef AP_UNSAFE_ERROR_LOG_UNESCAPED
468                     )
469 #endif
470                     );
471 }
472
473 static apr_status_t run_hml_child(apr_file_t **script_out,
474                                   apr_file_t **script_in,
475                                   apr_file_t **script_err,
476                                   const char *command,
477                                   const char * const argv[],
478                                   request_rec *r,
479                                   apr_pool_t *p,
480                                   hml_exec_info_t *e_info)
481 {
482     const char * const *env;
483     apr_procattr_t *procattr;
484     apr_proc_t *procnew;
485     apr_status_t rc = APR_SUCCESS;
486
487 #if defined(RLIMIT_CPU)  || defined(RLIMIT_NPROC) || \
488     defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined (RLIMIT_AS)
489
490     core_dir_config *conf = ap_get_module_config(r->per_dir_config,
491                                                  &core_module);
492 #endif
493
494 #ifdef DEBUG_CGI
495 #ifdef OS2
496     /* Under OS/2 need to use device con. */
497     FILE *dbg = fopen("con", "w");
498 #else
499     FILE *dbg = fopen("/dev/tty", "w");
500 #endif
501     int i;
502 #endif
503
504     RAISE_SIGSTOP(CGI_CHILD);
505 #ifdef DEBUG_CGI
506     fprintf(dbg, "Attempting to exec %s as CGI child (argv0 = %s)\n",
507             r->filename, argv[0]);
508 #endif
509
510     env = (const char * const *)ap_create_environment(p, r->subprocess_env);
511
512 #ifdef DEBUG_CGI
513     fprintf(dbg, "Environment: \n");
514     for (i = 0; env[i]; ++i)
515         fprintf(dbg, "'%s'\n", env[i]);
516 #endif
517
518     /* Transmute ourselves into the script.
519      * NB only ISINDEX scripts get decoded arguments.
520      */
521     if (((rc = apr_procattr_create(&procattr, p)) != APR_SUCCESS) ||
522         ((rc = apr_procattr_io_set(procattr,
523                                    e_info->in_pipe,
524                                    e_info->out_pipe,
525                                    e_info->err_pipe)) != APR_SUCCESS) ||
526         ((rc = apr_procattr_dir_set(procattr,
527                         ap_make_dirstr_parent(r->pool,
528                                               r->filename))) != APR_SUCCESS) ||
529 #ifdef RLIMIT_CPU
530         ((rc = apr_procattr_limit_set(procattr, APR_LIMIT_CPU,
531                                       conf->limit_cpu)) != APR_SUCCESS) ||
532 #endif
533 #if defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
534         ((rc = apr_procattr_limit_set(procattr, APR_LIMIT_MEM,
535                                       conf->limit_mem)) != APR_SUCCESS) ||
536 #endif
537 #ifdef RLIMIT_NPROC
538         ((rc = apr_procattr_limit_set(procattr, APR_LIMIT_NPROC,
539                                       conf->limit_nproc)) != APR_SUCCESS) ||
540 #endif
541         ((rc = apr_procattr_cmdtype_set(procattr,
542                                         e_info->cmd_type)) != APR_SUCCESS) ||
543
544         ((rc = apr_procattr_detach_set(procattr,
545                                         e_info->detached)) != APR_SUCCESS) ||
546         ((rc = apr_procattr_addrspace_set(procattr,
547                                         e_info->addrspace)) != APR_SUCCESS) ||
548         ((rc = apr_procattr_child_errfn_set(procattr, hml_child_errfn)) != APR_SUCCESS)) {
549         /* Something bad happened, tell the world. */
550         ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r,
551                       "couldn't set child process attributes: %s", r->filename);
552     }
553     else {
554         procnew = apr_pcalloc(p, sizeof(*procnew));
555         rc = ap_os_create_privileged_process(r, procnew, command, argv, env,
556                                              procattr, p);
557
558         if (rc != APR_SUCCESS) {
559             /* Bad things happened. Everyone should have cleaned up. */
560             ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_TOCLIENT, rc, r,
561                           "couldn't create child process: %d: %s", rc,
562                           apr_filepath_name_get(r->filename));
563         }
564         else {
565             apr_pool_note_subprocess(p, procnew, APR_KILL_AFTER_TIMEOUT);
566
567             *script_in = procnew->out;
568             if (!*script_in)
569                 return APR_EBADF;
570             apr_file_pipe_timeout_set(*script_in, r->server->timeout);
571
572 //            if (e_info->prog_type == RUN_AS_CGI) {
573             {
574                 *script_out = procnew->in;
575                 if (!*script_out)
576                     return APR_EBADF;
577                 apr_file_pipe_timeout_set(*script_out, r->server->timeout);
578
579                 *script_err = procnew->err;
580                 if (!*script_err)
581                     return APR_EBADF;
582                 apr_file_pipe_timeout_set(*script_err, r->server->timeout);
583             }
584         }
585     }
586 #ifdef DEBUG_CGI
587     fclose(dbg);
588 #endif
589     return (rc);
590 }
591
592
593 static apr_status_t hml_build_command(const char **cmd, const char ***argv,
594                                           request_rec *r, apr_pool_t *p,
595                                           hml_exec_info_t *e_info)
596 {
597     apr_status_t  rc;
598     apr_file_t*  f = NULL;
599     apr_finfo_t  finfo;
600     apr_size_t  size;
601     char*  b;
602     int  i, n, start;
603     int  st;
604     int  c;
605     const char*  argv0;
606     const char*  a;
607
608     if ((rc = apr_file_open (&f, r->filename, APR_READ, APR_OS_DEFAULT, p)) != APR_SUCCESS) {
609         ap_log_rerror (APLOG_MARK, APLOG_ERR, rc, r, "file not found or unable to read");
610         return rc;
611     }
612     apr_file_info_get (&finfo, 0, f);
613     if (finfo.size > HMLREADMAX - 1) {
614         size = HMLREADMAX - 1;
615     } else {
616         size = finfo.size;
617     }
618     b = apr_palloc (p, size + 1);
619     if (size > 0) {
620         rc = apr_file_read (f, b, &size);
621         b[size] = 0;
622     } else {
623         goto Err1;
624     }
625     apr_file_close (f);
626
627     start = 0;
628     if (size >= 3 && memcmp (b, "\xef\xbb\xbf", 3) == 0)
629         start = 3;
630     n = 0;
631     st = 0;
632     for (i = start; i < size; i ++) {
633         c = b[i];
634         switch (st) {
635         case 0:                 /* init, space */
636             if (apr_isspace (c)) {
637 //              st = 0;
638             } else if (' ' < c && c < 0x7f) {
639                 st = 2;
640                 n ++;
641             } else {
642                 b[i] = 0;
643                 i = size;
644             }
645             break;
646         case 2:                 /* ascii */
647             if (apr_isspace (c)) {
648                 st = 0;
649                 if (n == APACHE_ARG_MAX - 1) {
650                     b[i] = 0;
651                     i = size;
652                 }
653             } else if (' ' < c && c < 0x7f) {
654 //              st = 2;
655             } else {
656                 b[i] = 0;
657                 i = size;
658             }
659             break;
660         }
661     }
662     *argv = apr_palloc (p, sizeof (char*) * n + 1);
663     n = 0;
664     st = 0;
665     for (i = start; i < size && b[i]; i ++) {
666         c = b[i];
667         switch (st) {
668         case 0:                 /* init, space */
669             if (apr_isspace (c)) {
670 //              st = 0;
671             } else if (' ' < c && c < 0x7f) {
672                 st = 2;
673                 (*argv)[n] = &b[i];
674                 n ++;
675             } else {
676                 b[i] = 0;
677                 i = size;
678             }
679             break;
680         case 2:                 /* ascii */
681             if (apr_isspace (c)) {
682                 st = 0;
683                 b[i] = 0;
684                 if (n == APACHE_ARG_MAX - 1) {
685                     i = size;
686                 }
687             } else if (' ' < c && c < 0x7f) {
688 //              st = 2;
689             } else {
690                 b[i] = 0;
691                 i = size;
692             }
693             break;
694         }
695     }
696     (*argv)[n] = NULL;
697     if (n == 0) {
698         goto Err1;
699     }
700     argv0 = (*argv)[0];
701     if (argv0 == 0 || argv0[0] == 0 || argv0[0] == '/' || argv0[0] == '.') {
702         goto Err2;
703     }
704     for (a = argv0; *a; a ++) {
705         if ((*a == '.' && *(a + 1) == '.')
706             || (*a == '/' && (*(a + 1) == '/' || *(a + 1) == '.'))) {
707             goto Err2;
708         }
709     }
710     if (e_info->dirconf->hmlsubpath) {
711         *cmd = apr_pstrcat (p, e_info->dirconf->hmldir, "/", e_info->dirconf->hmlsubpath, "/", argv0, NULL);
712     } else {
713         *cmd = apr_pstrcat (p, e_info->dirconf->hmldir, "/", argv0, NULL);
714     }
715
716 #if 0    /*DEBUG*/
717     for (i = 0; (*argv)[i]; i ++) {
718         ap_log_rerror (APLOG_MARK, APLOG_ERR, 0, r, "%s", (*argv)[i]);
719     }
720 #endif
721
722     return APR_SUCCESS;
723
724  Err1:
725     ap_log_rerror (APLOG_MARK, APLOG_ERR, 0, r, "empty hml file");
726     return APR_EGENERAL;
727  Err2:
728     ap_log_rerror (APLOG_MARK, APLOG_ERR, 0, r, "bad command '%s'", argv0);
729     return APR_EGENERAL;
730
731
732
733 #if 0
734     int numwords, x, idx;
735     char *w;
736     const char *args = NULL;
737
738     if (e_info->process_hml) {
739         *cmd = r->filename;
740         /* Do not process r->args if they contain an '=' assignment
741          */
742         if (r->args && r->args[0] && !ap_strchr_c(r->args, '=')) {
743             args = r->args;
744         }
745     }
746
747     if (!args) {
748         numwords = 1;
749     }
750     else {
751         /* count the number of keywords */
752         for (x = 0, numwords = 2; args[x]; x++) {
753             if (args[x] == '+') {
754                 ++numwords;
755             }
756         }
757     }
758     /* Everything is - 1 to account for the first parameter
759      * which is the program name.
760      */
761     if (numwords > APACHE_ARG_MAX - 1) {
762         numwords = APACHE_ARG_MAX - 1;    /* Truncate args to prevent overrun */
763     }
764     *argv = apr_palloc(p, (numwords + 2) * sizeof(char *));
765     (*argv)[0] = *cmd;
766     for (x = 1, idx = 1; x < numwords; x++) {
767         w = ap_getword_nulls(p, &args, '+');
768         ap_unescape_url(w);
769         (*argv)[idx++] = ap_escape_shell_cmd(p, w);
770     }
771     (*argv)[idx] = NULL;
772
773     return APR_SUCCESS;
774 #endif
775 }
776
777 static void discard_script_output(apr_bucket_brigade *bb)
778 {
779     apr_bucket *e;
780     const char *buf;
781     apr_size_t len;
782     apr_status_t rv;
783
784     for (e = APR_BRIGADE_FIRST(bb);
785          e != APR_BRIGADE_SENTINEL(bb);
786          e = APR_BUCKET_NEXT(e))
787     {
788         if (APR_BUCKET_IS_EOS(e)) {
789             break;
790         }
791         rv = apr_bucket_read(e, &buf, &len, APR_BLOCK_READ);
792         if (rv != APR_SUCCESS) {
793             break;
794         }
795     }
796 }
797
798 #if APR_FILES_AS_SOCKETS
799
800 /* A CGI bucket type is needed to catch any output to stderr from the
801  * script; see PR 22030. */
802 static const apr_bucket_type_t bucket_type_hml;
803
804 struct hml_bucket_data {
805     apr_pollset_t *pollset;
806     request_rec *r;
807 };
808
809 /* Create a CGI bucket using pipes from script stdout 'out'
810  * and stderr 'err', for request 'r'. */
811 static apr_bucket *hml_bucket_create(request_rec *r,
812                                      apr_file_t *out, apr_file_t *err,
813                                      apr_bucket_alloc_t *list)
814 {
815     apr_bucket *b = apr_bucket_alloc(sizeof(*b), list);
816     apr_status_t rv;
817     apr_pollfd_t fd;
818     struct hml_bucket_data *data = apr_palloc(r->pool, sizeof *data);
819
820     APR_BUCKET_INIT(b);
821     b->free = apr_bucket_free;
822     b->list = list;
823     b->type = &bucket_type_hml;
824     b->length = (apr_size_t)(-1);
825     b->start = -1;
826
827     /* Create the pollset */
828     rv = apr_pollset_create(&data->pollset, 2, r->pool, 0);
829     AP_DEBUG_ASSERT(rv == APR_SUCCESS);
830
831     fd.desc_type = APR_POLL_FILE;
832     fd.reqevents = APR_POLLIN;
833     fd.p = r->pool;
834     fd.desc.f = out; /* script's stdout */
835     fd.client_data = (void *)1;
836     rv = apr_pollset_add(data->pollset, &fd);
837     AP_DEBUG_ASSERT(rv == APR_SUCCESS);
838
839     fd.desc.f = err; /* script's stderr */
840     fd.client_data = (void *)2;
841     rv = apr_pollset_add(data->pollset, &fd);
842     AP_DEBUG_ASSERT(rv == APR_SUCCESS);
843
844     data->r = r;
845     b->data = data;
846     return b;
847 }
848
849 /* Create a duplicate CGI bucket using given bucket data */
850 static apr_bucket *hml_bucket_dup(struct hml_bucket_data *data,
851                                   apr_bucket_alloc_t *list)
852 {
853     apr_bucket *b = apr_bucket_alloc(sizeof(*b), list);
854     APR_BUCKET_INIT(b);
855     b->free = apr_bucket_free;
856     b->list = list;
857     b->type = &bucket_type_hml;
858     b->length = (apr_size_t)(-1);
859     b->start = -1;
860     b->data = data;
861     return b;
862 }
863
864 /* Handle stdout from CGI child.  Duplicate of logic from the _read
865  * method of the real APR pipe bucket implementation. */
866 static apr_status_t hml_read_stdout(apr_bucket *a, apr_file_t *out,
867                                     const char **str, apr_size_t *len)
868 {
869     char *buf;
870     apr_status_t rv;
871
872     *str = NULL;
873     *len = APR_BUCKET_BUFF_SIZE;
874     buf = apr_bucket_alloc(*len, a->list); /* XXX: check for failure? */
875
876     rv = apr_file_read(out, buf, len);
877
878     if (rv != APR_SUCCESS && rv != APR_EOF) {
879         apr_bucket_free(buf);
880         return rv;
881     }
882
883     if (*len > 0) {
884         struct hml_bucket_data *data = a->data;
885         apr_bucket_heap *h;
886
887         /* Change the current bucket to refer to what we read */
888         a = apr_bucket_heap_make(a, buf, *len, apr_bucket_free);
889         h = a->data;
890         h->alloc_len = APR_BUCKET_BUFF_SIZE; /* note the real buffer size */
891         *str = buf;
892         APR_BUCKET_INSERT_AFTER(a, hml_bucket_dup(data, a->list));
893     }
894     else {
895         apr_bucket_free(buf);
896         a = apr_bucket_immortal_make(a, "", 0);
897         *str = a->data;
898     }
899     return rv;
900 }
901
902 /* Read method of CGI bucket: polls on stderr and stdout of the child,
903  * sending any stderr output immediately away to the error log. */
904 static apr_status_t hml_bucket_read(apr_bucket *b, const char **str,
905                                     apr_size_t *len, apr_read_type_e block)
906 {
907     struct hml_bucket_data *data = b->data;
908     apr_interval_time_t timeout;
909     apr_status_t rv;
910     int gotdata = 0;
911
912     timeout = block == APR_NONBLOCK_READ ? 0 : data->r->server->timeout;
913
914     do {
915         const apr_pollfd_t *results;
916         apr_int32_t num;
917
918         rv = apr_pollset_poll(data->pollset, timeout, &num, &results);
919         if (APR_STATUS_IS_TIMEUP(rv)) {
920             if (timeout) {
921                 ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, data->r,
922                               "Timeout waiting for output from CGI script %s",
923                               data->r->filename);
924                 return rv;
925             }
926             else {
927                 return APR_EAGAIN;
928             }
929         }
930         else if (APR_STATUS_IS_EINTR(rv)) {
931             continue;
932         }
933         else if (rv != APR_SUCCESS) {
934             ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, data->r,
935                           "poll failed waiting for CGI child");
936             return rv;
937         }
938
939         for (; num; num--, results++) {
940             if (results[0].client_data == (void *)1) {
941                 /* stdout */
942                 rv = hml_read_stdout(b, results[0].desc.f, str, len);
943                 if (APR_STATUS_IS_EOF(rv)) {
944                     rv = APR_SUCCESS;
945                 }
946                 gotdata = 1;
947             } else {
948                 /* stderr */
949                 apr_status_t rv2 = log_script_err(data->r, results[0].desc.f);
950                 if (APR_STATUS_IS_EOF(rv2)) {
951                     apr_pollset_remove(data->pollset, &results[0]);
952                 }
953             }
954         }
955
956     } while (!gotdata);
957
958     return rv;
959 }
960
961 static const apr_bucket_type_t bucket_type_hml = {
962     "HML", 5, APR_BUCKET_DATA,
963     apr_bucket_destroy_noop,
964     hml_bucket_read,
965     apr_bucket_setaside_notimpl,
966     apr_bucket_split_notimpl,
967     apr_bucket_copy_notimpl
968 };
969
970 #endif
971
972 static void  add_hml_vars (request_rec* r, hml_dir_conf* dirconf, const char* root) {
973     static const char*  key = "HMLSEARCHPATH";
974     size_t  s;
975
976     if (dirconf->searchpath) {
977         s = strlen (root);
978         if (s > 0 && root[s - 1] == '/')
979             s --;
980         if (apr_table_get (r->subprocess_env, key) == NULL) {
981             if (memcmp (root, dirconf->searchpath, s) == 0) {
982                 apr_table_setn (r->subprocess_env, key, dirconf->searchpath + s);
983             }
984         }
985     }
986 }
987
988 static int hml_handler(request_rec *r)
989 {
990     apr_size_t dbpos = 0;
991     const char *argv0;
992     const char *command;
993     const char **argv;
994     char *dbuf = NULL;
995     apr_file_t *script_out = NULL, *script_in = NULL, *script_err = NULL;
996     apr_bucket_brigade *bb;
997     apr_bucket *b;
998 //    int is_included;
999     int seen_eos, child_stopped_reading;
1000     apr_pool_t *p;
1001     hml_server_conf *conf;
1002     apr_status_t rv;
1003     hml_exec_info_t e_info;
1004     conn_rec *c = r->connection;
1005     hml_dir_conf*  dirconf;
1006     const char*  root;
1007
1008     if (strcmp(r->handler, "hml-handler")) {
1009         return DECLINED;
1010     }
1011
1012     p = r->main ? r->main->pool : r->pool;
1013
1014     argv0 = apr_filepath_name_get(r->filename);
1015     conf = ap_get_module_config(r->server->module_config, &hml_module);
1016     dirconf = ap_get_module_config (r->per_dir_config, &hml_module);
1017
1018     if (dirconf->hmldir == NULL) {
1019         ap_log_rerror (APLOG_MARK, APLOG_ERR, 0, r, "HmlDir is not defined");
1020         return HTTP_INTERNAL_SERVER_ERROR;
1021     }
1022     if (r->finfo.filetype == 0)
1023         return log_scripterror(r, conf, HTTP_NOT_FOUND, 0,
1024                                "script not found or unable to stat");
1025     if (r->finfo.filetype == APR_DIR)
1026         return log_scripterror(r, conf, HTTP_FORBIDDEN, 0,
1027                                "attempt to invoke directory as script");
1028
1029     ap_add_common_vars(r);
1030     ap_add_cgi_vars(r);
1031 //    hml_document_root (r);
1032 //    root = apr_table_get (r->subprocess_env, "DOCUMENT_ROOT");
1033     root = ap_document_root (r);
1034     add_hml_vars (r, dirconf, root);
1035
1036     e_info.process_hml = 1;
1037     e_info.cmd_type    = APR_PROGRAM;
1038     e_info.detached    = 0;
1039     e_info.in_pipe     = APR_CHILD_BLOCK;
1040     e_info.out_pipe    = APR_CHILD_BLOCK;
1041     e_info.err_pipe    = APR_CHILD_BLOCK;
1042 //    e_info.prog_type   = RUN_AS_CGI;
1043     e_info.bb          = NULL;
1044 //    e_info.ctx         = NULL;
1045     e_info.next        = NULL;
1046     e_info.addrspace   = 0;
1047     e_info.dirconf     = dirconf;
1048
1049     /* build the command line */
1050     if ((rv = hml_build_command(&command, &argv, r, p, &e_info)) != APR_SUCCESS) {
1051         ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1052                       "don't know how to spawn child process: %s",
1053                       r->filename);
1054         return HTTP_INTERNAL_SERVER_ERROR;
1055     }
1056
1057     /* run the script in its own process */
1058     if ((rv = run_hml_child(&script_out, &script_in, &script_err,
1059                             command, argv, r, p, &e_info)) != APR_SUCCESS) {
1060         ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1061                       "couldn't spawn child process: %s", r->filename);
1062         return HTTP_INTERNAL_SERVER_ERROR;
1063     }
1064
1065     /* Transfer any put/post args, CERN style...
1066      * Note that we already ignore SIGPIPE in the core server.
1067      */
1068     bb = apr_brigade_create(r->pool, c->bucket_alloc);
1069     seen_eos = 0;
1070     child_stopped_reading = 0;
1071     if (conf->logname) {
1072         dbuf = apr_palloc(r->pool, conf->bufbytes + 1);
1073         dbpos = 0;
1074     }
1075     do {
1076         apr_bucket *bucket;
1077
1078         rv = ap_get_brigade(r->input_filters, bb, AP_MODE_READBYTES,
1079                             APR_BLOCK_READ, HUGE_STRING_LEN);
1080
1081         if (rv != APR_SUCCESS) {
1082             ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1083                           "Error reading request entity data");
1084             return HTTP_INTERNAL_SERVER_ERROR;
1085         }
1086
1087         for (bucket = APR_BRIGADE_FIRST(bb);
1088              bucket != APR_BRIGADE_SENTINEL(bb);
1089              bucket = APR_BUCKET_NEXT(bucket))
1090         {
1091             const char *data;
1092             apr_size_t len;
1093
1094             if (APR_BUCKET_IS_EOS(bucket)) {
1095                 seen_eos = 1;
1096                 break;
1097             }
1098
1099             /* We can't do much with this. */
1100             if (APR_BUCKET_IS_FLUSH(bucket)) {
1101                 continue;
1102             }
1103
1104             /* If the child stopped, we still must read to EOS. */
1105             if (child_stopped_reading) {
1106                 continue;
1107             }
1108
1109             /* read */
1110             apr_bucket_read(bucket, &data, &len, APR_BLOCK_READ);
1111
1112             if (conf->logname && dbpos < conf->bufbytes) {
1113                 int cursize;
1114
1115                 if ((dbpos + len) > conf->bufbytes) {
1116                     cursize = conf->bufbytes - dbpos;
1117                 }
1118                 else {
1119                     cursize = len;
1120                 }
1121                 memcpy(dbuf + dbpos, data, cursize);
1122                 dbpos += cursize;
1123             }
1124
1125             /* Keep writing data to the child until done or too much time
1126              * elapses with no progress or an error occurs.
1127              */
1128             rv = apr_file_write_full(script_out, data, len, NULL);
1129
1130             if (rv != APR_SUCCESS) {
1131                 /* silly script stopped reading, soak up remaining message */
1132                 child_stopped_reading = 1;
1133             }
1134         }
1135         apr_brigade_cleanup(bb);
1136     }
1137     while (!seen_eos);
1138
1139     if (conf->logname) {
1140         dbuf[dbpos] = '\0';
1141     }
1142     /* Is this flush really needed? */
1143     apr_file_flush(script_out);
1144     apr_file_close(script_out);
1145
1146     AP_DEBUG_ASSERT(script_in != NULL);
1147
1148     apr_brigade_cleanup(bb);
1149
1150 #if APR_FILES_AS_SOCKETS
1151     apr_file_pipe_timeout_set(script_in, 0);
1152     apr_file_pipe_timeout_set(script_err, 0);
1153
1154     b = hml_bucket_create(r, script_in, script_err, c->bucket_alloc);
1155 #else
1156     b = apr_bucket_pipe_create(script_in, c->bucket_alloc);
1157 #endif
1158     APR_BRIGADE_INSERT_TAIL(bb, b);
1159     b = apr_bucket_eos_create(c->bucket_alloc);
1160     APR_BRIGADE_INSERT_TAIL(bb, b);
1161
1162     /* Handle script return... */
1163 //    if (!nph) {
1164     {
1165         const char *location;
1166         char sbuf[MAX_STRING_LEN];
1167         int ret;
1168
1169         if ((ret = ap_scan_script_header_err_brigade(r, bb, sbuf))) {
1170             ret = log_script(r, conf, ret, dbuf, sbuf, bb, script_err);
1171
1172             /*
1173              * ret could be HTTP_NOT_MODIFIED in the case that the CGI script
1174              * does not set an explicit status and ap_meets_conditions, which
1175              * is called by ap_scan_script_header_err_brigade, detects that
1176              * the conditions of the requests are met and the response is
1177              * not modified.
1178              * In this case set r->status and return OK in order to prevent
1179              * running through the error processing stack as this would
1180              * break with mod_cache, if the conditions had been set by
1181              * mod_cache itself to validate a stale entity.
1182              * BTW: We circumvent the error processing stack anyway if the
1183              * CGI script set an explicit status code (whatever it is) and
1184              * the only possible values for ret here are:
1185              *
1186              * HTTP_NOT_MODIFIED          (set by ap_meets_conditions)
1187              * HTTP_PRECONDITION_FAILED   (set by ap_meets_conditions)
1188              * HTTP_INTERNAL_SERVER_ERROR (if something went wrong during the
1189              * processing of the response of the CGI script, e.g broken headers
1190              * or a crashed CGI process).
1191              */
1192             if (ret == HTTP_NOT_MODIFIED) {
1193                 r->status = ret;
1194                 return OK;
1195             }
1196
1197             return ret;
1198         }
1199
1200         location = apr_table_get(r->headers_out, "Location");
1201
1202         if (location && r->status == 200) {
1203             /* For a redirect whether internal or not, discard any
1204              * remaining stdout from the script, and log any remaining
1205              * stderr output, as normal. */
1206             discard_script_output(bb);
1207             apr_brigade_destroy(bb);
1208             apr_file_pipe_timeout_set(script_err, r->server->timeout);
1209             log_script_err(r, script_err);
1210         }
1211
1212         if (location && location[0] == '/' && r->status == 200) {
1213             /* This redirect needs to be a GET no matter what the original
1214              * method was.
1215              */
1216             r->method = apr_pstrdup(r->pool, "GET");
1217             r->method_number = M_GET;
1218
1219             /* We already read the message body (if any), so don't allow
1220              * the redirected request to think it has one.  We can ignore
1221              * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR.
1222              */
1223             apr_table_unset(r->headers_in, "Content-Length");
1224
1225             ap_internal_redirect_handler(location, r);
1226             return OK;
1227         }
1228         else if (location && r->status == 200) {
1229             /* XX Note that if a script wants to produce its own Redirect
1230              * body, it now has to explicitly *say* "Status: 302"
1231              */
1232             return HTTP_MOVED_TEMPORARILY;
1233         }
1234
1235         rv = ap_pass_brigade(r->output_filters, bb);
1236     }
1237
1238     /* don't soak up script output if errors occurred writing it
1239      * out...  otherwise, we prolong the life of the script when the
1240      * connection drops or we stopped sending output for some other
1241      * reason */
1242     if (rv == APR_SUCCESS && !r->connection->aborted) {
1243         apr_file_pipe_timeout_set(script_err, r->server->timeout);
1244         log_script_err(r, script_err);
1245     }
1246
1247     apr_file_close(script_err);
1248
1249     return OK;                      /* NOT r->status, even if it has changed. */
1250 }
1251
1252
1253 static void hml_register_hooks(apr_pool_t *p)
1254 {
1255     ap_hook_handler(hml_handler, NULL, NULL, APR_HOOK_MIDDLE);
1256 }
1257
1258 module AP_MODULE_DECLARE_DATA hml_module =
1259 {
1260     STANDARD20_MODULE_STUFF,
1261     create_hml_dir_config,      /* create per-dir    config structures */
1262     merge_hml_dir_config,       /* merge  per-dir    config structures */
1263     create_hml_config,           /* server config */
1264     merge_hml_config,            /* merge server config */
1265     hml_cmds,                    /* command apr_table_t */
1266     hml_register_hooks               /* register hooks */
1267 };