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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 #include "apr_strings.h"
19 #include "apr_thread_proc.h" /* for RLIMIT stuff */
20 #include "apr_optional.h"
21 #include "apr_buckets.h"
25 #define APR_WANT_STRFUNC
26 #define APR_WANT_MEMFUNC
31 #include "util_filter.h"
32 #include "ap_config.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"
40 #include "util_script.h"
43 //#include "mod_hml.h"
45 module AP_MODULE_DECLARE_DATA hml_module;
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;
52 /* Read and discard the data in the brigade produced by a CGI script */
53 static void discard_script_output(apr_bucket_brigade *bb);
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.
62 static int is_scriptaliased(request_rec *r)
64 const char *t = apr_table_get(r->notes, "alias-forced-type");
65 return t && (!strcasecmp(t, "cgi-script"));
69 /* Configuration stuff */
71 #define HMLREADMAX 2048
72 #define DEFAULT_LOGBYTES 10385760
73 #define DEFAULT_BUFBYTES 1024
81 typedef struct hml_dir_conf {
94 apr_cmdtype_e cmd_type;
96 // prog_types prog_type;
97 apr_bucket_brigade **bb;
98 // include_ctx_t *ctx;
100 apr_int32_t addrspace;
101 hml_dir_conf* dirconf;
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));
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;
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;
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);
131 if (nconf->searchpath == NULL) nconf->searchpath = bconf->searchpath;
132 if (nconf->dataroot == NULL) nconf->dataroot = bconf->dataroot;
136 static const char* set_subpath (cmd_parms* cmd, void* vconf, const char* value) {
137 hml_dir_conf* conf = (hml_dir_conf*)vconf;
141 for (p = value; *p; p ++) {
143 if (isalnum (c) || c == '-' || c == '_') {
145 return apr_pstrcat (cmd->pool, "Invalid directory path ", value, NULL);
148 conf->hmlsubpath = value;
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;
157 if (ap_os_is_path_absolute (cmd->pool, value)) {
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] == '.')) {
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;
178 return apr_pstrcat (cmd->pool, "Invalid directory path ", value, NULL);
181 static void *create_hml_config(apr_pool_t *p, server_rec *s)
184 (hml_server_conf *) apr_pcalloc(p, sizeof(hml_server_conf));
187 c->logbytes = DEFAULT_LOGBYTES;
188 c->bufbytes = DEFAULT_BUFBYTES;
193 static void *merge_hml_config(apr_pool_t *p, void *basev, void *overridesv)
195 hml_server_conf *base = (hml_server_conf *) basev,
196 *overrides = (hml_server_conf *) overridesv;
198 return overrides->logname ? overrides : base;
201 static const char *set_scriptlog(cmd_parms *cmd, void *dummy, const char *arg)
203 server_rec *s = cmd->server;
204 hml_server_conf *conf = ap_get_module_config(s->module_config,
207 conf->logname = ap_server_root_relative(cmd->pool, arg);
209 if (!conf->logname) {
210 return apr_pstrcat(cmd->pool, "Invalid HmlScriptLog path ",
217 static const char *set_scriptlog_length(cmd_parms *cmd, void *dummy,
220 server_rec *s = cmd->server;
221 hml_server_conf *conf = ap_get_module_config(s->module_config,
224 conf->logbytes = atol(arg);
228 static const char *set_scriptlog_buffer(cmd_parms *cmd, void *dummy,
231 server_rec *s = cmd->server;
232 hml_server_conf *conf = ap_get_module_config(s->module_config,
235 conf->bufbytes = atoi(arg);
239 static const command_rec hml_cmds[] =
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"),
252 static int log_scripterror(request_rec *r, hml_server_conf * conf, int ret,
253 apr_status_t rv, char *error)
255 apr_file_t *f = NULL;
257 char time_str[APR_CTIME_LEN];
258 int log_flags = rv ? APLOG_ERR : APLOG_ERR;
260 ap_log_rerror(APLOG_MARK, log_flags, rv, r,
261 "%s: %s", error, r->filename);
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)) {
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);
281 apr_file_printf(f, "%%error\n%s\n", error);
287 /* Soak up stderr from a script and redirect it to the error log.
289 static apr_status_t log_script_err(request_rec *r, apr_file_t *script_err)
291 char argsbuffer[HUGE_STRING_LEN];
295 while ((rv = apr_file_gets(argsbuffer, HUGE_STRING_LEN,
296 script_err)) == APR_SUCCESS) {
297 // newline = strchr(argsbuffer, '\n');
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);
307 if (r->server->error_log) {
308 apr_file_flush (r->server->error_log);
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)
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;
329 char time_str[APR_CTIME_LEN];
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);
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);
352 apr_file_puts("%request\n", f);
353 for (i = 0; i < hdrs_arr->nelts; ++i) {
356 apr_file_printf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val);
358 if ((r->method_number == M_POST || r->method_number == M_PUT) &&
360 apr_file_printf(f, "\n%s\n", dbuf);
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;
367 for (i = 0; i < hdrs_arr->nelts; ++i) {
370 apr_file_printf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val);
374 apr_file_printf(f, "%s\n", sbuf);
377 for (e = APR_BRIGADE_FIRST(bb);
378 e != APR_BRIGADE_SENTINEL(bb);
379 e = APR_BUCKET_NEXT(e))
381 if (APR_BUCKET_IS_EOS(e)) {
384 rv = apr_bucket_read(e, &buf, &len, APR_BLOCK_READ);
385 if (rv != APR_SUCCESS || (len == 0)) {
389 apr_file_puts("%stdout\n", f);
392 apr_file_write(f, buf, &len);
393 apr_file_puts("\n", f);
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);
403 apr_file_puts("\n", f);
406 apr_brigade_destroy(bb);
407 apr_file_close(script_err);
415 /* This is the special environment used for running the "exec cmd="
416 * variety of SSI directives.
418 static void add_ssi_vars(request_rec *r)
420 apr_table_t *e = r->subprocess_env;
422 if (r->path_info && r->path_info[0] != '\0') {
425 apr_table_setn(e, "PATH_INFO", ap_escape_shell_cmd(r->pool,
428 pa_req = ap_sub_req_lookup_uri(ap_escape_uri(r->pool, r->path_info),
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));
435 ap_destroy_sub_req(pa_req);
439 char *arg_copy = apr_pstrdup(r->pool, r->args);
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));
449 static void hml_child_errfn(apr_pool_t *pool, apr_status_t err,
450 const char *description)
452 apr_file_t *stderr_log;
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.
459 apr_file_printf(stderr_log,
462 apr_strerror(err, errbuf, sizeof(errbuf)),
463 #ifndef AP_UNSAFE_ERROR_LOG_UNESCAPED
464 ap_escape_logitem(pool,
467 #ifndef AP_UNSAFE_ERROR_LOG_UNESCAPED
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,
477 const char * const argv[],
480 hml_exec_info_t *e_info)
482 const char * const *env;
483 apr_procattr_t *procattr;
485 apr_status_t rc = APR_SUCCESS;
487 #if defined(RLIMIT_CPU) || defined(RLIMIT_NPROC) || \
488 defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined (RLIMIT_AS)
490 core_dir_config *conf = ap_get_module_config(r->per_dir_config,
496 /* Under OS/2 need to use device con. */
497 FILE *dbg = fopen("con", "w");
499 FILE *dbg = fopen("/dev/tty", "w");
504 RAISE_SIGSTOP(CGI_CHILD);
506 fprintf(dbg, "Attempting to exec %s as CGI child (argv0 = %s)\n",
507 r->filename, argv[0]);
510 env = (const char * const *)ap_create_environment(p, r->subprocess_env);
513 fprintf(dbg, "Environment: \n");
514 for (i = 0; env[i]; ++i)
515 fprintf(dbg, "'%s'\n", env[i]);
518 /* Transmute ourselves into the script.
519 * NB only ISINDEX scripts get decoded arguments.
521 if (((rc = apr_procattr_create(&procattr, p)) != APR_SUCCESS) ||
522 ((rc = apr_procattr_io_set(procattr,
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) ||
530 ((rc = apr_procattr_limit_set(procattr, APR_LIMIT_CPU,
531 conf->limit_cpu)) != APR_SUCCESS) ||
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) ||
538 ((rc = apr_procattr_limit_set(procattr, APR_LIMIT_NPROC,
539 conf->limit_nproc)) != APR_SUCCESS) ||
541 ((rc = apr_procattr_cmdtype_set(procattr,
542 e_info->cmd_type)) != APR_SUCCESS) ||
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);
554 procnew = apr_pcalloc(p, sizeof(*procnew));
555 rc = ap_os_create_privileged_process(r, procnew, command, argv, env,
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));
565 apr_pool_note_subprocess(p, procnew, APR_KILL_AFTER_TIMEOUT);
567 *script_in = procnew->out;
570 apr_file_pipe_timeout_set(*script_in, r->server->timeout);
572 // if (e_info->prog_type == RUN_AS_CGI) {
574 *script_out = procnew->in;
577 apr_file_pipe_timeout_set(*script_out, r->server->timeout);
579 *script_err = procnew->err;
582 apr_file_pipe_timeout_set(*script_err, r->server->timeout);
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)
598 apr_file_t* f = NULL;
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");
612 apr_file_info_get (&finfo, 0, f);
613 if (finfo.size > HMLREADMAX - 1) {
614 size = HMLREADMAX - 1;
618 b = apr_palloc (p, size + 1);
620 rc = apr_file_read (f, b, &size);
628 if (size >= 3 && memcmp (b, "\xef\xbb\xbf", 3) == 0)
632 for (i = start; i < size; i ++) {
635 case 0: /* init, space */
636 if (apr_isspace (c)) {
638 } else if (' ' < c && c < 0x7f) {
647 if (apr_isspace (c)) {
649 if (n == APACHE_ARG_MAX - 1) {
653 } else if (' ' < c && c < 0x7f) {
662 *argv = apr_palloc (p, sizeof (char*) * n + 1);
665 for (i = start; i < size && b[i]; i ++) {
668 case 0: /* init, space */
669 if (apr_isspace (c)) {
671 } else if (' ' < c && c < 0x7f) {
681 if (apr_isspace (c)) {
684 if (n == APACHE_ARG_MAX - 1) {
687 } else if (' ' < c && c < 0x7f) {
701 if (argv0 == 0 || argv0[0] == 0 || argv0[0] == '/' || argv0[0] == '.') {
704 for (a = argv0; *a; a ++) {
705 if ((*a == '.' && *(a + 1) == '.')
706 || (*a == '/' && (*(a + 1) == '/' || *(a + 1) == '.'))) {
710 if (e_info->dirconf->hmlsubpath) {
711 *cmd = apr_pstrcat (p, e_info->dirconf->hmldir, "/", e_info->dirconf->hmlsubpath, "/", argv0, NULL);
713 *cmd = apr_pstrcat (p, e_info->dirconf->hmldir, "/", argv0, NULL);
717 for (i = 0; (*argv)[i]; i ++) {
718 ap_log_rerror (APLOG_MARK, APLOG_ERR, 0, r, "%s", (*argv)[i]);
725 ap_log_rerror (APLOG_MARK, APLOG_ERR, 0, r, "empty hml file");
728 ap_log_rerror (APLOG_MARK, APLOG_ERR, 0, r, "bad command '%s'", argv0);
734 int numwords, x, idx;
736 const char *args = NULL;
738 if (e_info->process_hml) {
740 /* Do not process r->args if they contain an '=' assignment
742 if (r->args && r->args[0] && !ap_strchr_c(r->args, '=')) {
751 /* count the number of keywords */
752 for (x = 0, numwords = 2; args[x]; x++) {
753 if (args[x] == '+') {
758 /* Everything is - 1 to account for the first parameter
759 * which is the program name.
761 if (numwords > APACHE_ARG_MAX - 1) {
762 numwords = APACHE_ARG_MAX - 1; /* Truncate args to prevent overrun */
764 *argv = apr_palloc(p, (numwords + 2) * sizeof(char *));
766 for (x = 1, idx = 1; x < numwords; x++) {
767 w = ap_getword_nulls(p, &args, '+');
769 (*argv)[idx++] = ap_escape_shell_cmd(p, w);
777 static void discard_script_output(apr_bucket_brigade *bb)
784 for (e = APR_BRIGADE_FIRST(bb);
785 e != APR_BRIGADE_SENTINEL(bb);
786 e = APR_BUCKET_NEXT(e))
788 if (APR_BUCKET_IS_EOS(e)) {
791 rv = apr_bucket_read(e, &buf, &len, APR_BLOCK_READ);
792 if (rv != APR_SUCCESS) {
798 #if APR_FILES_AS_SOCKETS
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;
804 struct hml_bucket_data {
805 apr_pollset_t *pollset;
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)
815 apr_bucket *b = apr_bucket_alloc(sizeof(*b), list);
818 struct hml_bucket_data *data = apr_palloc(r->pool, sizeof *data);
821 b->free = apr_bucket_free;
823 b->type = &bucket_type_hml;
824 b->length = (apr_size_t)(-1);
827 /* Create the pollset */
828 rv = apr_pollset_create(&data->pollset, 2, r->pool, 0);
829 AP_DEBUG_ASSERT(rv == APR_SUCCESS);
831 fd.desc_type = APR_POLL_FILE;
832 fd.reqevents = APR_POLLIN;
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);
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);
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)
853 apr_bucket *b = apr_bucket_alloc(sizeof(*b), list);
855 b->free = apr_bucket_free;
857 b->type = &bucket_type_hml;
858 b->length = (apr_size_t)(-1);
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)
873 *len = APR_BUCKET_BUFF_SIZE;
874 buf = apr_bucket_alloc(*len, a->list); /* XXX: check for failure? */
876 rv = apr_file_read(out, buf, len);
878 if (rv != APR_SUCCESS && rv != APR_EOF) {
879 apr_bucket_free(buf);
884 struct hml_bucket_data *data = a->data;
887 /* Change the current bucket to refer to what we read */
888 a = apr_bucket_heap_make(a, buf, *len, apr_bucket_free);
890 h->alloc_len = APR_BUCKET_BUFF_SIZE; /* note the real buffer size */
892 APR_BUCKET_INSERT_AFTER(a, hml_bucket_dup(data, a->list));
895 apr_bucket_free(buf);
896 a = apr_bucket_immortal_make(a, "", 0);
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)
907 struct hml_bucket_data *data = b->data;
908 apr_interval_time_t timeout;
912 timeout = block == APR_NONBLOCK_READ ? 0 : data->r->server->timeout;
915 const apr_pollfd_t *results;
918 rv = apr_pollset_poll(data->pollset, timeout, &num, &results);
919 if (APR_STATUS_IS_TIMEUP(rv)) {
921 ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, data->r,
922 "Timeout waiting for output from CGI script %s",
930 else if (APR_STATUS_IS_EINTR(rv)) {
933 else if (rv != APR_SUCCESS) {
934 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, data->r,
935 "poll failed waiting for CGI child");
939 for (; num; num--, results++) {
940 if (results[0].client_data == (void *)1) {
942 rv = hml_read_stdout(b, results[0].desc.f, str, len);
943 if (APR_STATUS_IS_EOF(rv)) {
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]);
961 static const apr_bucket_type_t bucket_type_hml = {
962 "HML", 5, APR_BUCKET_DATA,
963 apr_bucket_destroy_noop,
965 apr_bucket_setaside_notimpl,
966 apr_bucket_split_notimpl,
967 apr_bucket_copy_notimpl
972 static void add_hml_vars (request_rec* r, hml_dir_conf* dirconf, const char* root) {
973 static const char* key = "HMLSEARCHPATH";
976 if (dirconf->searchpath) {
978 if (s > 0 && root[s - 1] == '/')
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);
988 static int hml_handler(request_rec *r)
990 apr_size_t dbpos = 0;
995 apr_file_t *script_out = NULL, *script_in = NULL, *script_err = NULL;
996 apr_bucket_brigade *bb;
999 int seen_eos, child_stopped_reading;
1001 hml_server_conf *conf;
1003 hml_exec_info_t e_info;
1004 conn_rec *c = r->connection;
1005 hml_dir_conf* dirconf;
1008 if (strcmp(r->handler, "hml-handler")) {
1012 p = r->main ? r->main->pool : r->pool;
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);
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;
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");
1029 ap_add_common_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);
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;
1044 // e_info.ctx = NULL;
1046 e_info.addrspace = 0;
1047 e_info.dirconf = dirconf;
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",
1054 return HTTP_INTERNAL_SERVER_ERROR;
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;
1065 /* Transfer any put/post args, CERN style...
1066 * Note that we already ignore SIGPIPE in the core server.
1068 bb = apr_brigade_create(r->pool, c->bucket_alloc);
1070 child_stopped_reading = 0;
1071 if (conf->logname) {
1072 dbuf = apr_palloc(r->pool, conf->bufbytes + 1);
1078 rv = ap_get_brigade(r->input_filters, bb, AP_MODE_READBYTES,
1079 APR_BLOCK_READ, HUGE_STRING_LEN);
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;
1087 for (bucket = APR_BRIGADE_FIRST(bb);
1088 bucket != APR_BRIGADE_SENTINEL(bb);
1089 bucket = APR_BUCKET_NEXT(bucket))
1094 if (APR_BUCKET_IS_EOS(bucket)) {
1099 /* We can't do much with this. */
1100 if (APR_BUCKET_IS_FLUSH(bucket)) {
1104 /* If the child stopped, we still must read to EOS. */
1105 if (child_stopped_reading) {
1110 apr_bucket_read(bucket, &data, &len, APR_BLOCK_READ);
1112 if (conf->logname && dbpos < conf->bufbytes) {
1115 if ((dbpos + len) > conf->bufbytes) {
1116 cursize = conf->bufbytes - dbpos;
1121 memcpy(dbuf + dbpos, data, cursize);
1125 /* Keep writing data to the child until done or too much time
1126 * elapses with no progress or an error occurs.
1128 rv = apr_file_write_full(script_out, data, len, NULL);
1130 if (rv != APR_SUCCESS) {
1131 /* silly script stopped reading, soak up remaining message */
1132 child_stopped_reading = 1;
1135 apr_brigade_cleanup(bb);
1139 if (conf->logname) {
1142 /* Is this flush really needed? */
1143 apr_file_flush(script_out);
1144 apr_file_close(script_out);
1146 AP_DEBUG_ASSERT(script_in != NULL);
1148 apr_brigade_cleanup(bb);
1150 #if APR_FILES_AS_SOCKETS
1151 apr_file_pipe_timeout_set(script_in, 0);
1152 apr_file_pipe_timeout_set(script_err, 0);
1154 b = hml_bucket_create(r, script_in, script_err, c->bucket_alloc);
1156 b = apr_bucket_pipe_create(script_in, c->bucket_alloc);
1158 APR_BRIGADE_INSERT_TAIL(bb, b);
1159 b = apr_bucket_eos_create(c->bucket_alloc);
1160 APR_BRIGADE_INSERT_TAIL(bb, b);
1162 /* Handle script return... */
1165 const char *location;
1166 char sbuf[MAX_STRING_LEN];
1169 if ((ret = ap_scan_script_header_err_brigade(r, bb, sbuf))) {
1170 ret = log_script(r, conf, ret, dbuf, sbuf, bb, script_err);
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
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:
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).
1192 if (ret == HTTP_NOT_MODIFIED) {
1200 location = apr_table_get(r->headers_out, "Location");
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);
1212 if (location && location[0] == '/' && r->status == 200) {
1213 /* This redirect needs to be a GET no matter what the original
1216 r->method = apr_pstrdup(r->pool, "GET");
1217 r->method_number = M_GET;
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.
1223 apr_table_unset(r->headers_in, "Content-Length");
1225 ap_internal_redirect_handler(location, r);
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"
1232 return HTTP_MOVED_TEMPORARILY;
1235 rv = ap_pass_brigade(r->output_filters, bb);
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
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);
1247 apr_file_close(script_err);
1249 return OK; /* NOT r->status, even if it has changed. */
1253 static void hml_register_hooks(apr_pool_t *p)
1255 ap_hook_handler(hml_handler, NULL, NULL, APR_HOOK_MIDDLE);
1258 module AP_MODULE_DECLARE_DATA hml_module =
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 */