1 /* ====================================================================
2 * The Apache Software License, Version 1.1
4 * Copyright (c) 2000-2002 The Apache Software Foundation. All rights
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in
16 * the documentation and/or other materials provided with the
19 * 3. The end-user documentation included with the redistribution,
20 * if any, must include the following acknowledgment:
21 * "This product includes software developed by the
22 * Apache Software Foundation (http://www.apache.org/)."
23 * Alternately, this acknowledgment may appear in the software itself,
24 * if and wherever such third-party acknowledgments normally appear.
26 * 4. The names "Apache" and "Apache Software Foundation" must
27 * not be used to endorse or promote products derived from this
28 * software without prior written permission. For written
29 * permission, please contact apache@apache.org.
31 * 5. Products derived from this software may not be called "Apache",
32 * nor may "Apache" appear in their name, without prior written
33 * permission of the Apache Software Foundation.
35 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38 * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
39 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47 * ====================================================================
49 * This software consists of voluntary contributions made by many
50 * individuals on behalf of the Apache Software Foundation. For more
51 * information on the Apache Software Foundation, please see
52 * <http://www.apache.org/>.
54 * Portions of this software are based upon public domain software
55 * originally written at the National Center for Supercomputing Applications,
56 * University of Illinois, Urbana-Champaign.
60 * http_script: keeps all script-related ramblings together.
62 * Compliant to CGI/1.1 spec
64 * Adapted by rst from original NCSA code by Rob McCool
66 * Apache adds some new env vars; REDIRECT_URL and REDIRECT_QUERY_STRING for
67 * custom error responses, and DOCUMENT_ROOT because we found it useful.
68 * It also adds SERVER_ADMIN - useful for scripts to know who to mail when
73 #include "apr_strings.h"
74 #include "apr_thread_proc.h" /* for RLIMIT stuff */
75 #include "apr_optional.h"
76 #include "apr_buckets.h"
79 #define APR_WANT_STRFUNC
84 #include "util_filter.h"
85 #include "ap_config.h"
87 #include "http_config.h"
88 #include "http_request.h"
89 #include "http_core.h"
90 #include "http_protocol.h"
91 #include "http_main.h"
93 #include "util_script.h"
96 #include "../filters/mod_include.h"
99 module AP_MODULE_DECLARE_DATA cgi_module;
101 static APR_OPTIONAL_FN_TYPE(ap_register_include_handler) *cgi_pfn_reg_with_ssi;
102 static APR_OPTIONAL_FN_TYPE(ap_ssi_get_tag_and_value) *cgi_pfn_gtv;
103 static APR_OPTIONAL_FN_TYPE(ap_ssi_parse_string) *cgi_pfn_ps;
104 static APR_OPTIONAL_FN_TYPE(ap_cgi_build_command) *cgi_build_command;
106 typedef enum {RUN_AS_SSI, RUN_AS_CGI} prog_types;
110 apr_int32_t out_pipe;
111 apr_int32_t err_pipe;
112 apr_cmdtype_e cmd_type;
113 prog_types prog_type;
114 apr_bucket_brigade **bb;
119 /* KLUDGE --- for back-combatibility, we don't have to check ExecCGI
120 * in ScriptAliased directories, which means we need to know if this
121 * request came through ScriptAlias or not... so the Alias module
122 * leaves a note for us.
125 static int is_scriptaliased(request_rec *r)
127 const char *t = apr_table_get(r->notes, "alias-forced-type");
128 return t && (!strcasecmp(t, "cgi-script"));
131 /* Configuration stuff */
133 #define DEFAULT_LOGBYTES 10385760
134 #define DEFAULT_BUFBYTES 1024
142 static void *create_cgi_config(apr_pool_t *p, server_rec *s)
145 (cgi_server_conf *) apr_pcalloc(p, sizeof(cgi_server_conf));
148 c->logbytes = DEFAULT_LOGBYTES;
149 c->bufbytes = DEFAULT_BUFBYTES;
154 static void *merge_cgi_config(apr_pool_t *p, void *basev, void *overridesv)
156 cgi_server_conf *base = (cgi_server_conf *) basev, *overrides = (cgi_server_conf *) overridesv;
158 return overrides->logname ? overrides : base;
161 static const char *set_scriptlog(cmd_parms *cmd, void *dummy, const char *arg)
163 server_rec *s = cmd->server;
164 cgi_server_conf *conf = ap_get_module_config(s->module_config,
167 conf->logname = ap_server_root_relative(cmd->pool, arg);
169 if (!conf->logname) {
170 return apr_pstrcat(cmd->pool, "Invalid ScriptLog path ",
177 static const char *set_scriptlog_length(cmd_parms *cmd, void *dummy,
180 server_rec *s = cmd->server;
181 cgi_server_conf *conf = ap_get_module_config(s->module_config,
184 conf->logbytes = atol(arg);
188 static const char *set_scriptlog_buffer(cmd_parms *cmd, void *dummy,
191 server_rec *s = cmd->server;
192 cgi_server_conf *conf = ap_get_module_config(s->module_config,
195 conf->bufbytes = atoi(arg);
199 static const command_rec cgi_cmds[] =
201 AP_INIT_TAKE1("ScriptLog", set_scriptlog, NULL, RSRC_CONF,
202 "the name of a log for script debugging info"),
203 AP_INIT_TAKE1("ScriptLogLength", set_scriptlog_length, NULL, RSRC_CONF,
204 "the maximum length (in bytes) of the script debug log"),
205 AP_INIT_TAKE1("ScriptLogBuffer", set_scriptlog_buffer, NULL, RSRC_CONF,
206 "the maximum size (in bytes) to record of a POST request"),
210 static int log_scripterror(request_rec *r, cgi_server_conf * conf, int ret,
211 apr_status_t rv, char *error)
213 apr_file_t *f = NULL;
215 char time_str[APR_CTIME_LEN];
216 int log_flags = rv ? APLOG_ERR : APLOG_NOERRNO | APLOG_ERR;
218 ap_log_rerror(APLOG_MARK, log_flags, rv, r,
219 "%s: %s", error, r->filename);
221 /* XXX Very expensive mainline case! Open, then getfileinfo! */
222 if (!conf->logname ||
223 ((apr_stat(&finfo, conf->logname,
224 APR_FINFO_SIZE, r->pool) == APR_SUCCESS)
225 && (finfo.size > conf->logbytes)) ||
226 (apr_file_open(&f, conf->logname,
227 APR_APPEND|APR_WRITE|APR_CREATE, APR_OS_DEFAULT, r->pool)
232 /* "%% [Wed Jun 19 10:53:21 1996] GET /cgi-bin/printenv HTTP/1.0" */
233 apr_ctime(time_str, apr_time_now());
234 apr_file_printf(f, "%%%% [%s] %s %s%s%s %s\n", time_str, r->method, r->uri,
235 r->args ? "?" : "", r->args ? r->args : "", r->protocol);
236 /* "%% 500 /usr/local/apache/cgi-bin */
237 apr_file_printf(f, "%%%% %d %s\n", ret, r->filename);
239 apr_file_printf(f, "%%error\n%s\n", error);
245 /* Soak up stderr from a script and redirect it to the error log.
247 static void log_script_err(request_rec *r, apr_file_t *script_err)
249 char argsbuffer[HUGE_STRING_LEN];
252 while (apr_file_gets(argsbuffer, HUGE_STRING_LEN,
253 script_err) == APR_SUCCESS) {
254 newline = strchr(argsbuffer, '\n');
258 ap_log_rerror(APLOG_MARK, APLOG_ERR | APLOG_NOERRNO, 0, r,
263 static int log_script(request_rec *r, cgi_server_conf * conf, int ret,
264 char *dbuf, const char *sbuf, apr_file_t *script_in,
265 apr_file_t *script_err)
267 const apr_array_header_t *hdrs_arr = apr_table_elts(r->headers_in);
268 const apr_table_entry_t *hdrs = (const apr_table_entry_t *) hdrs_arr->elts;
269 char argsbuffer[HUGE_STRING_LEN];
270 apr_file_t *f = NULL;
273 char time_str[APR_CTIME_LEN];
275 /* XXX Very expensive mainline case! Open, then getfileinfo! */
276 if (!conf->logname ||
277 ((apr_stat(&finfo, conf->logname,
278 APR_FINFO_SIZE, r->pool) == APR_SUCCESS)
279 && (finfo.size > conf->logbytes)) ||
280 (apr_file_open(&f, conf->logname,
281 APR_APPEND|APR_WRITE|APR_CREATE, APR_OS_DEFAULT, r->pool) != APR_SUCCESS)) {
282 /* Soak up script output */
283 while (apr_file_gets(argsbuffer, HUGE_STRING_LEN,
284 script_in) == APR_SUCCESS)
287 log_script_err(r, script_err);
291 /* "%% [Wed Jun 19 10:53:21 1996] GET /cgi-bin/printenv HTTP/1.0" */
292 apr_ctime(time_str, apr_time_now());
293 apr_file_printf(f, "%%%% [%s] %s %s%s%s %s\n", time_str, r->method, r->uri,
294 r->args ? "?" : "", r->args ? r->args : "", r->protocol);
295 /* "%% 500 /usr/local/apache/cgi-bin" */
296 apr_file_printf(f, "%%%% %d %s\n", ret, r->filename);
298 apr_file_puts("%request\n", f);
299 for (i = 0; i < hdrs_arr->nelts; ++i) {
302 apr_file_printf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val);
304 if ((r->method_number == M_POST || r->method_number == M_PUT)
306 apr_file_printf(f, "\n%s\n", dbuf);
309 apr_file_puts("%response\n", f);
310 hdrs_arr = apr_table_elts(r->err_headers_out);
311 hdrs = (const apr_table_entry_t *) hdrs_arr->elts;
313 for (i = 0; i < hdrs_arr->nelts; ++i) {
316 apr_file_printf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val);
320 apr_file_printf(f, "%s\n", sbuf);
322 if (apr_file_gets(argsbuffer, HUGE_STRING_LEN, script_in) == APR_SUCCESS) {
323 apr_file_puts("%stdout\n", f);
324 apr_file_puts(argsbuffer, f);
325 while (apr_file_gets(argsbuffer, HUGE_STRING_LEN,
326 script_in) == APR_SUCCESS)
327 apr_file_puts(argsbuffer, f);
328 apr_file_puts("\n", f);
331 if (apr_file_gets(argsbuffer, HUGE_STRING_LEN, script_err) == APR_SUCCESS) {
332 apr_file_puts("%stderr\n", f);
333 apr_file_puts(argsbuffer, f);
334 while (apr_file_gets(argsbuffer, HUGE_STRING_LEN,
335 script_err) == APR_SUCCESS)
336 apr_file_puts(argsbuffer, f);
337 apr_file_puts("\n", f);
340 apr_file_close(script_in);
341 apr_file_close(script_err);
348 /* This is the special environment used for running the "exec cmd="
349 * variety of SSI directives.
351 static void add_ssi_vars(request_rec *r, ap_filter_t *next)
353 apr_table_t *e = r->subprocess_env;
355 if (r->path_info && r->path_info[0] != '\0') {
358 apr_table_setn(e, "PATH_INFO", ap_escape_shell_cmd(r->pool, r->path_info));
360 pa_req = ap_sub_req_lookup_uri(ap_escape_uri(r->pool, r->path_info), r, next);
361 if (pa_req->filename) {
362 apr_table_setn(e, "PATH_TRANSLATED",
363 apr_pstrcat(r->pool, pa_req->filename, pa_req->path_info, NULL));
365 ap_destroy_sub_req(pa_req);
369 char *arg_copy = apr_pstrdup(r->pool, r->args);
371 apr_table_setn(e, "QUERY_STRING", r->args);
372 ap_unescape_url(arg_copy);
373 apr_table_setn(e, "QUERY_STRING_UNESCAPED", ap_escape_shell_cmd(r->pool, arg_copy));
377 static apr_status_t run_cgi_child(apr_file_t **script_out,
378 apr_file_t **script_in,
379 apr_file_t **script_err,
381 const char * const argv[],
386 const char * const *env;
387 apr_procattr_t *procattr;
389 apr_status_t rc = APR_SUCCESS;
391 #if defined(RLIMIT_CPU) || defined(RLIMIT_NPROC) || \
392 defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined (RLIMIT_AS)
394 core_dir_config *conf = ap_get_module_config(r->per_dir_config,
401 /* Under OS/2 need to use device con. */
402 FILE *dbg = fopen("con", "w");
404 FILE *dbg = fopen("/dev/tty", "w");
409 RAISE_SIGSTOP(CGI_CHILD);
411 fprintf(dbg, "Attempting to exec %s as CGI child (argv0 = %s)\n",
412 r->filename, argv[0]);
415 if (e_info->prog_type == RUN_AS_CGI) {
418 else /* SSIs want a controlled environment and a special path. */
420 add_ssi_vars(r, e_info->next);
422 env = (const char * const *)ap_create_environment(p, r->subprocess_env);
425 fprintf(dbg, "Environment: \n");
426 for (i = 0; env[i]; ++i)
427 fprintf(dbg, "'%s'\n", env[i]);
430 /* Transmute ourselves into the script.
431 * NB only ISINDEX scripts get decoded arguments.
433 if (((rc = apr_procattr_create(&procattr, p)) != APR_SUCCESS) ||
434 ((rc = apr_procattr_io_set(procattr,
437 e_info->err_pipe)) != APR_SUCCESS) ||
438 ((rc = apr_procattr_dir_set(procattr,
439 ap_make_dirstr_parent(r->pool, r->filename))) != APR_SUCCESS) ||
441 ((rc = apr_procattr_limit_set(procattr, APR_LIMIT_CPU, conf->limit_cpu)) != APR_SUCCESS) ||
443 #if defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
444 ((rc = apr_procattr_limit_set(procattr, APR_LIMIT_MEM, conf->limit_mem)) != APR_SUCCESS) ||
447 ((rc = apr_procattr_limit_set(procattr, APR_LIMIT_NPROC, conf->limit_nproc)) != APR_SUCCESS) ||
449 ((rc = apr_procattr_cmdtype_set(procattr, e_info->cmd_type)) != APR_SUCCESS)) {
450 /* Something bad happened, tell the world. */
451 ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r,
452 "couldn't set child process attributes: %s", r->filename);
455 procnew = apr_pcalloc(p, sizeof(*procnew));
456 if (e_info->prog_type == RUN_AS_SSI) {
457 SPLIT_AND_PASS_PRETAG_BUCKETS(*(e_info->bb), e_info->ctx, e_info->next, rc);
458 if (rc != APR_SUCCESS) {
463 rc = ap_os_create_privileged_process(r, procnew, command, argv, env, procattr, p);
465 if (rc != APR_SUCCESS) {
466 /* Bad things happened. Everyone should have cleaned up. */
467 #if APR_HAS_PROC_INVOKED
468 if (procnew->invoked) {
469 ap_log_rerror(APLOG_MARK, APLOG_INFO, rc, r,
470 "mod_cgi: failed to invoke process: %s",
475 ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r,
476 "mod_cgi: couldn't create child process: %s",
480 apr_pool_note_subprocess(p, procnew, APR_KILL_AFTER_TIMEOUT);
482 #if APR_HAS_PROC_INVOKED
483 if (procnew->invoked) {
484 ap_log_rerror(APLOG_MARK, APLOG_INFO, rc, r,
485 "mod_cgi invoked process: %s",
490 *script_in = procnew->out;
493 apr_file_pipe_timeout_set(*script_in, (int)(r->server->timeout * APR_USEC_PER_SEC));
495 if (e_info->prog_type == RUN_AS_CGI) {
496 *script_out = procnew->in;
499 apr_file_pipe_timeout_set(*script_out, (int)(r->server->timeout * APR_USEC_PER_SEC));
501 *script_err = procnew->err;
504 apr_file_pipe_timeout_set(*script_err, (int)(r->server->timeout * APR_USEC_PER_SEC));
515 static apr_status_t default_build_command(const char **cmd, const char ***argv,
516 request_rec *r, apr_pool_t *p,
519 int numwords, x, idx;
521 const char *args = r->args;
525 /* Allow suexec's "/" check to succeed */
526 if ((argv0 = strrchr(r->filename, '/')) != NULL)
533 if (!args || !args[0] || ap_strchr_c(args, '=')) {
537 /* count the number of keywords */
538 for (x = 0, numwords = 2; args[x]; x++) {
539 if (args[x] == '+') {
544 /* Everything is - 1 to account for the first parameter
545 * which is the program name.
547 if (numwords > APACHE_ARG_MAX - 1) {
548 numwords = APACHE_ARG_MAX - 1; /* Truncate args to prevent overrun */
550 *argv = apr_palloc(p, (numwords + 2) * sizeof(char *));
552 for (x = 1, idx = 1; x < numwords; x++) {
553 w = ap_getword_nulls(p, &args, '+');
555 (*argv)[idx++] = ap_escape_shell_cmd(p, w);
563 static int cgi_handler(request_rec *r)
565 int retval, nph, dbpos = 0;
570 apr_file_t *script_out = NULL, *script_in = NULL, *script_err = NULL;
571 apr_bucket_brigade *bb;
573 char argsbuffer[HUGE_STRING_LEN];
576 cgi_server_conf *conf;
580 if(strcmp(r->handler,CGI_MAGIC_TYPE) && strcmp(r->handler,"cgi-script"))
583 is_included = !strcmp(r->protocol, "INCLUDED");
585 p = r->main ? r->main->pool : r->pool;
587 if (r->method_number == M_OPTIONS) {
588 /* 99 out of 100 CGI scripts, this is all they support */
589 r->allowed |= (AP_METHOD_BIT << M_GET);
590 r->allowed |= (AP_METHOD_BIT << M_POST);
594 argv0 = apr_filename_of_pathname(r->filename);
595 nph = !(strncmp(argv0, "nph-", 4));
596 conf = ap_get_module_config(r->server->module_config, &cgi_module);
598 if (!(ap_allow_options(r) & OPT_EXECCGI) && !is_scriptaliased(r))
599 return log_scripterror(r, conf, HTTP_FORBIDDEN, 0,
600 "Options ExecCGI is off in this directory");
601 if (nph && is_included)
602 return log_scripterror(r, conf, HTTP_FORBIDDEN, 0,
603 "attempt to include NPH CGI script");
605 if (r->finfo.filetype == 0)
606 return log_scripterror(r, conf, HTTP_NOT_FOUND, 0,
607 "script not found or unable to stat");
608 if (r->finfo.filetype == APR_DIR)
609 return log_scripterror(r, conf, HTTP_FORBIDDEN, 0,
610 "attempt to invoke directory as script");
612 if (r->path_info && *r->path_info && !r->used_path_info) {
613 return log_scripterror(r, conf, HTTP_NOT_FOUND, 0,
614 "AcceptPathInfo off disallows user's path");
617 if (!ap_suexec_enabled) {
618 if (!ap_can_exec(&r->finfo))
619 return log_scripterror(r, conf, HTTP_FORBIDDEN, 0,
620 "file permissions deny server execution");
624 if ((retval = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR)))
627 ap_add_common_vars(r);
629 /* build the command line */
630 if ((rv = cgi_build_command(&command, &argv, r, p, 1)) != APR_SUCCESS) {
631 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
632 "don't know how to spawn child process: %s",
634 return HTTP_INTERNAL_SERVER_ERROR;
637 e_info.cmd_type = APR_PROGRAM;
638 e_info.in_pipe = APR_CHILD_BLOCK;
639 e_info.out_pipe = APR_CHILD_BLOCK;
640 e_info.err_pipe = APR_CHILD_BLOCK;
641 e_info.prog_type = RUN_AS_CGI;
646 /* run the script in its own process */
647 if ((rv = run_cgi_child(&script_out, &script_in, &script_err,
648 command, argv, r, p, &e_info)) != APR_SUCCESS) {
649 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
650 "couldn't spawn child process: %s", r->filename);
651 return HTTP_INTERNAL_SERVER_ERROR;
654 /* Transfer any put/post args, CERN style...
655 * Note that we already ignore SIGPIPE in the core server.
657 if (ap_should_client_block(r)) {
658 int len_read, dbsize;
659 apr_size_t bytes_written, bytes_to_write;
663 dbuf = apr_pcalloc(r->pool, conf->bufbytes + 1);
668 ap_get_client_block(r, argsbuffer, HUGE_STRING_LEN)) > 0) {
670 if ((dbpos + len_read) > conf->bufbytes) {
671 dbsize = conf->bufbytes - dbpos;
676 memcpy(dbuf + dbpos, argsbuffer, dbsize);
679 /* Keep writing data to the child until done or too much time
680 * elapses with no progress or an error occurs.
684 bytes_to_write = len_read - bytes_written;
685 rv = apr_file_write(script_out, argsbuffer + bytes_written,
687 bytes_written += bytes_to_write;
688 } while (rv == APR_SUCCESS
689 && bytes_written < (apr_size_t)len_read);
690 if (rv != APR_SUCCESS || bytes_written < (apr_size_t)len_read) {
691 /* silly script stopped reading, soak up remaining message */
692 while (ap_get_client_block(r, argsbuffer, HUGE_STRING_LEN) > 0) {
698 apr_file_flush(script_out);
701 apr_file_close(script_out);
703 /* Handle script return... */
704 if (script_in && !nph) {
705 const char *location;
706 char sbuf[MAX_STRING_LEN];
709 if ((ret = ap_scan_script_header_err(r, script_in, sbuf))) {
710 return log_script(r, conf, ret, dbuf, sbuf, script_in, script_err);
713 location = apr_table_get(r->headers_out, "Location");
715 if (location && location[0] == '/' && r->status == 200) {
717 /* Soak up all the script output */
718 while (apr_file_gets(argsbuffer, HUGE_STRING_LEN,
719 script_in) == APR_SUCCESS) {
722 log_script_err(r, script_err);
723 /* This redirect needs to be a GET no matter what the original
726 r->method = apr_pstrdup(r->pool, "GET");
727 r->method_number = M_GET;
729 /* We already read the message body (if any), so don't allow
730 * the redirected request to think it has one. We can ignore
731 * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR.
733 apr_table_unset(r->headers_in, "Content-Length");
735 ap_internal_redirect_handler(location, r);
738 else if (location && r->status == 200) {
739 /* XX Note that if a script wants to produce its own Redirect
740 * body, it now has to explicitly *say* "Status: 302"
742 return HTTP_MOVED_TEMPORARILY;
745 if (!r->header_only) {
746 bb = apr_brigade_create(r->pool);
747 b = apr_bucket_pipe_create(script_in);
748 APR_BRIGADE_INSERT_TAIL(bb, b);
749 b = apr_bucket_eos_create();
750 APR_BRIGADE_INSERT_TAIL(bb, b);
751 ap_pass_brigade(r->output_filters, bb);
754 log_script_err(r, script_err);
755 apr_file_close(script_err);
758 if (script_in && nph) {
759 struct ap_filter_t *cur;
761 /* get rid of all filters up through protocol... since we
762 * haven't parsed off the headers, there is no way they can
766 cur = r->proto_output_filters;
767 while (cur && cur->frec->ftype < AP_FTYPE_CONNECTION) {
770 r->output_filters = r->proto_output_filters = cur;
772 bb = apr_brigade_create(r->pool);
773 b = apr_bucket_pipe_create(script_in);
774 APR_BRIGADE_INSERT_TAIL(bb, b);
775 b = apr_bucket_eos_create();
776 APR_BRIGADE_INSERT_TAIL(bb, b);
777 ap_pass_brigade(r->output_filters, bb);
780 return OK; /* NOT r->status, even if it has changed. */
783 /*============================================================================
784 *============================================================================
785 * This is the beginning of the cgi filter code moved from mod_include. This
786 * is the code required to handle the "exec" SSI directive.
787 *============================================================================
788 *============================================================================*/
789 static int include_cgi(char *s, request_rec *r, ap_filter_t *next,
790 apr_bucket *head_ptr, apr_bucket **inserted_head)
792 request_rec *rr = ap_sub_req_lookup_uri(s, r, next);
794 apr_bucket *tmp_buck, *tmp2_buck;
796 if (rr->status != HTTP_OK) {
797 ap_destroy_sub_req(rr);
801 /* No hardwired path info or query allowed */
803 if ((rr->path_info && rr->path_info[0]) || rr->args) {
804 ap_destroy_sub_req(rr);
807 if (rr->finfo.filetype != APR_REG) {
808 ap_destroy_sub_req(rr);
812 /* Script gets parameters of the *document*, for back compatibility */
814 rr->path_info = r->path_info; /* hard to get right; see mod_cgi.c */
817 /* Force sub_req to be treated as a CGI request, even if ordinary
818 * typing rules would have called it something else.
821 ap_set_content_type(rr, CGI_MAGIC_TYPE);
825 rr_status = ap_run_sub_req(rr);
826 if (ap_is_HTTP_REDIRECT(rr_status)) {
828 const char *location = apr_table_get(rr->headers_out, "Location");
830 location = ap_escape_html(rr->pool, location);
831 len_loc = strlen(location);
833 /* XXX: if most of this stuff is going to get copied anyway,
834 * it'd be more efficient to pstrcat it into a single pool buffer
835 * and a single pool bucket */
837 tmp_buck = apr_bucket_immortal_create("<A HREF=\"",
838 sizeof("<A HREF=\"") - 1);
839 APR_BUCKET_INSERT_BEFORE(head_ptr, tmp_buck);
840 tmp2_buck = apr_bucket_heap_create(location, len_loc, 1);
841 APR_BUCKET_INSERT_BEFORE(head_ptr, tmp2_buck);
842 tmp2_buck = apr_bucket_immortal_create("\">", sizeof("\">") - 1);
843 APR_BUCKET_INSERT_BEFORE(head_ptr, tmp2_buck);
844 tmp2_buck = apr_bucket_heap_create(location, len_loc, 1);
845 APR_BUCKET_INSERT_BEFORE(head_ptr, tmp2_buck);
846 tmp2_buck = apr_bucket_immortal_create("</A>", sizeof("</A>") - 1);
847 APR_BUCKET_INSERT_BEFORE(head_ptr, tmp2_buck);
849 if (*inserted_head == NULL) {
850 *inserted_head = tmp_buck;
854 ap_destroy_sub_req(rr);
860 static int include_cmd(include_ctx_t *ctx, apr_bucket_brigade **bb,
861 const char *command, request_rec *r, ap_filter_t *f)
865 apr_file_t *script_out = NULL, *script_in = NULL, *script_err = NULL;
866 apr_bucket_brigade *bcgi;
870 if ((rv = cgi_build_command(&command, &argv, r, r->pool, 0)) != APR_SUCCESS) {
871 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
872 "don't know how to spawn cmd child process: %s",
874 return HTTP_INTERNAL_SERVER_ERROR;
877 e_info.cmd_type = APR_SHELLCMD;
878 e_info.in_pipe = APR_NO_PIPE;
879 e_info.out_pipe = APR_FULL_BLOCK;
880 e_info.err_pipe = APR_NO_PIPE;
881 e_info.prog_type = RUN_AS_SSI;
884 e_info.next = f->next;
886 /* run the script in its own process */
887 if ((rv = run_cgi_child(&script_out, &script_in, &script_err,
888 command, argv, r, r->pool, &e_info)) != APR_SUCCESS) {
889 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
890 "couldn't spawn child process: %s", r->filename);
891 return HTTP_INTERNAL_SERVER_ERROR;
894 bcgi = apr_brigade_create(r->pool);
895 b = apr_bucket_pipe_create(script_in);
896 APR_BRIGADE_INSERT_TAIL(bcgi, b);
897 ap_pass_brigade(f->next, bcgi);
899 /* We can't close the pipe here, because we may return before the
900 * full CGI has been sent to the network. That's okay though,
901 * because we can rely on the pool to close the pipe for us.
907 static int handle_exec(include_ctx_t *ctx, apr_bucket_brigade **bb, request_rec *r,
908 ap_filter_t *f, apr_bucket *head_ptr, apr_bucket **inserted_head)
911 char *tag_val = NULL;
912 char *file = r->filename;
913 apr_bucket *tmp_buck;
914 char parsed_string[MAX_STRING_LEN];
916 *inserted_head = NULL;
917 if (ctx->flags & FLAG_PRINTING) {
918 if (ctx->flags & FLAG_NO_EXEC) {
919 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
920 "exec used but not allowed in %s", r->filename);
921 CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, *inserted_head);
925 cgi_pfn_gtv(ctx, &tag, &tag_val, 1);
926 if (tag_val == NULL) {
934 if (!strcmp(tag, "cmd")) {
935 cgi_pfn_ps(r, ctx, tag_val, parsed_string, sizeof(parsed_string), 1);
936 if (include_cmd(ctx, bb, parsed_string, r, f) == -1) {
937 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
938 "execution failure for parameter \"%s\" "
939 "to tag exec in file %s", tag, r->filename);
940 CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, *inserted_head);
943 else if (!strcmp(tag, "cgi")) {
944 apr_status_t retval = APR_SUCCESS;
946 cgi_pfn_ps(r, ctx, tag_val, parsed_string, sizeof(parsed_string), 0);
947 SPLIT_AND_PASS_PRETAG_BUCKETS(*bb, ctx, f->next, retval);
948 if (retval != APR_SUCCESS) {
952 if (include_cgi(parsed_string, r, f->next, head_ptr, inserted_head) == -1) {
953 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
954 "invalid CGI ref \"%s\" in %s", tag_val, file);
955 CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, *inserted_head);
959 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
960 "unknown parameter \"%s\" to tag exec in %s", tag, file);
961 CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, *inserted_head);
970 /*============================================================================
971 *============================================================================
972 * This is the end of the cgi filter code moved from mod_include.
973 *============================================================================
974 *============================================================================*/
977 static int cgi_post_config(apr_pool_t *p, apr_pool_t *plog,
978 apr_pool_t *ptemp, server_rec *s)
980 cgi_pfn_reg_with_ssi = APR_RETRIEVE_OPTIONAL_FN(ap_register_include_handler);
981 cgi_pfn_gtv = APR_RETRIEVE_OPTIONAL_FN(ap_ssi_get_tag_and_value);
982 cgi_pfn_ps = APR_RETRIEVE_OPTIONAL_FN(ap_ssi_parse_string);
984 if ((cgi_pfn_reg_with_ssi) && (cgi_pfn_gtv) && (cgi_pfn_ps)) {
985 /* Required by mod_include filter. This is how mod_cgi registers
986 * with mod_include to provide processing of the exec directive.
988 cgi_pfn_reg_with_ssi("exec", handle_exec);
991 /* This is the means by which unusual (non-unix) os's may find alternate
992 * means to run a given command (e.g. shebang/registry parsing on Win32)
994 cgi_build_command = APR_RETRIEVE_OPTIONAL_FN(ap_cgi_build_command);
995 if (!cgi_build_command) {
996 cgi_build_command = default_build_command;
1001 static void register_hooks(apr_pool_t *p)
1003 static const char * const aszPre[] = { "mod_include.c", NULL };
1004 ap_hook_handler(cgi_handler, NULL, NULL, APR_HOOK_MIDDLE);
1005 ap_hook_post_config(cgi_post_config, aszPre, NULL, APR_HOOK_REALLY_FIRST);
1008 module AP_MODULE_DECLARE_DATA cgi_module =
1010 STANDARD20_MODULE_STUFF,
1011 NULL, /* dir config creater */
1012 NULL, /* dir merger --- default is to override */
1013 create_cgi_config, /* server config */
1014 merge_cgi_config, /* merge server config */
1015 cgi_cmds, /* command apr_table_t */
1016 register_hooks /* register hooks */