1 /* ====================================================================
2 * The Apache Software License, Version 1.1
4 * Copyright (c) 2000-2001 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);
171 static const char *set_scriptlog_length(cmd_parms *cmd, void *dummy,
174 server_rec *s = cmd->server;
175 cgi_server_conf *conf = ap_get_module_config(s->module_config,
178 conf->logbytes = atol(arg);
182 static const char *set_scriptlog_buffer(cmd_parms *cmd, void *dummy,
185 server_rec *s = cmd->server;
186 cgi_server_conf *conf = ap_get_module_config(s->module_config,
189 conf->bufbytes = atoi(arg);
193 static const command_rec cgi_cmds[] =
195 AP_INIT_TAKE1("ScriptLog", set_scriptlog, NULL, RSRC_CONF,
196 "the name of a log for script debugging info"),
197 AP_INIT_TAKE1("ScriptLogLength", set_scriptlog_length, NULL, RSRC_CONF,
198 "the maximum length (in bytes) of the script debug log"),
199 AP_INIT_TAKE1("ScriptLogBuffer", set_scriptlog_buffer, NULL, RSRC_CONF,
200 "the maximum size (in bytes) to record of a POST request"),
204 static int log_scripterror(request_rec *r, cgi_server_conf * conf, int ret,
205 apr_status_t rv, char *error)
207 apr_file_t *f = NULL;
209 char time_str[APR_CTIME_LEN];
210 int log_flags = rv ? APLOG_ERR : APLOG_NOERRNO | APLOG_ERR;
212 ap_log_rerror(APLOG_MARK, log_flags, rv, r,
213 "%s: %s", error, r->filename);
215 /* XXX Very expensive mainline case! Open, then getfileinfo! */
216 if (!conf->logname ||
217 ((apr_stat(&finfo, conf->logname,
218 APR_FINFO_SIZE, r->pool) == APR_SUCCESS)
219 && (finfo.size > conf->logbytes)) ||
220 (apr_file_open(&f, conf->logname,
221 APR_APPEND|APR_WRITE|APR_CREATE, APR_OS_DEFAULT, r->pool)
226 /* "%% [Wed Jun 19 10:53:21 1996] GET /cgi-bin/printenv HTTP/1.0" */
227 apr_ctime(time_str, apr_time_now());
228 apr_file_printf(f, "%%%% [%s] %s %s%s%s %s\n", time_str, r->method, r->uri,
229 r->args ? "?" : "", r->args ? r->args : "", r->protocol);
230 /* "%% 500 /usr/local/apache/cgi-bin */
231 apr_file_printf(f, "%%%% %d %s\n", ret, r->filename);
233 apr_file_printf(f, "%%error\n%s\n", error);
239 /* Soak up stderr from a script and redirect it to the error log.
241 static void log_script_err(request_rec *r, apr_file_t *script_err)
243 char argsbuffer[HUGE_STRING_LEN];
246 while (apr_file_gets(argsbuffer, HUGE_STRING_LEN, script_err) == 0) {
247 newline = strchr(argsbuffer, '\n');
251 ap_log_rerror(APLOG_MARK, APLOG_ERR | APLOG_NOERRNO, 0, r,
256 static int log_script(request_rec *r, cgi_server_conf * conf, int ret,
257 char *dbuf, const char *sbuf, apr_file_t *script_in,
258 apr_file_t *script_err)
260 const apr_array_header_t *hdrs_arr = apr_table_elts(r->headers_in);
261 const apr_table_entry_t *hdrs = (const apr_table_entry_t *) hdrs_arr->elts;
262 char argsbuffer[HUGE_STRING_LEN];
263 apr_file_t *f = NULL;
266 char time_str[APR_CTIME_LEN];
268 /* XXX Very expensive mainline case! Open, then getfileinfo! */
269 if (!conf->logname ||
270 ((apr_stat(&finfo, conf->logname,
271 APR_FINFO_SIZE, r->pool) == APR_SUCCESS)
272 && (finfo.size > conf->logbytes)) ||
273 (apr_file_open(&f, conf->logname,
274 APR_APPEND|APR_WRITE|APR_CREATE, APR_OS_DEFAULT, r->pool) != APR_SUCCESS)) {
275 /* Soak up script output */
276 while (apr_file_gets(argsbuffer, HUGE_STRING_LEN, script_in) == 0)
279 log_script_err(r, script_err);
283 /* "%% [Wed Jun 19 10:53:21 1996] GET /cgi-bin/printenv HTTP/1.0" */
284 apr_ctime(time_str, apr_time_now());
285 apr_file_printf(f, "%%%% [%s] %s %s%s%s %s\n", time_str, r->method, r->uri,
286 r->args ? "?" : "", r->args ? r->args : "", r->protocol);
287 /* "%% 500 /usr/local/apache/cgi-bin" */
288 apr_file_printf(f, "%%%% %d %s\n", ret, r->filename);
290 apr_file_puts("%request\n", f);
291 for (i = 0; i < hdrs_arr->nelts; ++i) {
294 apr_file_printf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val);
296 if ((r->method_number == M_POST || r->method_number == M_PUT)
298 apr_file_printf(f, "\n%s\n", dbuf);
301 apr_file_puts("%response\n", f);
302 hdrs_arr = apr_table_elts(r->err_headers_out);
303 hdrs = (const apr_table_entry_t *) hdrs_arr->elts;
305 for (i = 0; i < hdrs_arr->nelts; ++i) {
308 apr_file_printf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val);
312 apr_file_printf(f, "%s\n", sbuf);
314 if (apr_file_gets(argsbuffer, HUGE_STRING_LEN, script_in) == 0) {
315 apr_file_puts("%stdout\n", f);
316 apr_file_puts(argsbuffer, f);
317 while (apr_file_gets(argsbuffer, HUGE_STRING_LEN, script_in) == 0)
318 apr_file_puts(argsbuffer, f);
319 apr_file_puts("\n", f);
322 if (apr_file_gets(argsbuffer, HUGE_STRING_LEN, script_err) == 0) {
323 apr_file_puts("%stderr\n", f);
324 apr_file_puts(argsbuffer, f);
325 while (apr_file_gets(argsbuffer, HUGE_STRING_LEN, script_err) == 0)
326 apr_file_puts(argsbuffer, f);
327 apr_file_puts("\n", f);
330 apr_file_close(script_in);
331 apr_file_close(script_err);
338 /* This is the special environment used for running the "exec cmd="
339 * variety of SSI directives.
341 static void add_ssi_vars(request_rec *r, ap_filter_t *next)
343 apr_table_t *e = r->subprocess_env;
345 if (r->path_info && r->path_info[0] != '\0') {
348 apr_table_setn(e, "PATH_INFO", ap_escape_shell_cmd(r->pool, r->path_info));
350 pa_req = ap_sub_req_lookup_uri(ap_escape_uri(r->pool, r->path_info), r, next);
351 if (pa_req->filename) {
352 apr_table_setn(e, "PATH_TRANSLATED",
353 apr_pstrcat(r->pool, pa_req->filename, pa_req->path_info, NULL));
355 ap_destroy_sub_req(pa_req);
359 char *arg_copy = apr_pstrdup(r->pool, r->args);
361 apr_table_setn(e, "QUERY_STRING", r->args);
362 ap_unescape_url(arg_copy);
363 apr_table_setn(e, "QUERY_STRING_UNESCAPED", ap_escape_shell_cmd(r->pool, arg_copy));
367 static apr_status_t run_cgi_child(apr_file_t **script_out,
368 apr_file_t **script_in,
369 apr_file_t **script_err,
371 const char * const argv[],
376 const char * const *env;
377 apr_procattr_t *procattr;
379 apr_status_t rc = APR_SUCCESS;
381 #if defined(RLIMIT_CPU) || defined(RLIMIT_NPROC) || \
382 defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined (RLIMIT_AS)
384 core_dir_config *conf = ap_get_module_config(r->per_dir_config,
391 /* Under OS/2 need to use device con. */
392 FILE *dbg = fopen("con", "w");
394 FILE *dbg = fopen("/dev/tty", "w");
399 RAISE_SIGSTOP(CGI_CHILD);
401 fprintf(dbg, "Attempting to exec %s as %sCGI child (argv0 = %s)\n",
402 r->filename, cld->nph ? "NPH " : "", argv0);
405 if (e_info->prog_type == RUN_AS_CGI) {
408 else /* SSIs want a controlled environment and a special path. */
410 add_ssi_vars(r, e_info->next);
412 env = (const char * const *)ap_create_environment(p, r->subprocess_env);
415 fprintf(dbg, "Environment: \n");
416 for (i = 0; env[i]; ++i)
417 fprintf(dbg, "'%s'\n", env[i]);
420 /* Transmute ourselves into the script.
421 * NB only ISINDEX scripts get decoded arguments.
423 if (((rc = apr_procattr_create(&procattr, p)) != APR_SUCCESS) ||
424 ((rc = apr_procattr_io_set(procattr,
427 e_info->err_pipe)) != APR_SUCCESS) ||
428 ((rc = apr_procattr_dir_set(procattr,
429 ap_make_dirstr_parent(r->pool, r->filename))) != APR_SUCCESS) ||
431 ((rc = apr_procattr_limit_set(procattr, APR_LIMIT_CPU, conf->limit_cpu)) != APR_SUCCESS) ||
433 #if defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
434 ((rc = apr_procattr_limit_set(procattr, APR_LIMIT_MEM, conf->limit_mem)) != APR_SUCCESS) ||
437 ((rc = apr_procattr_limit_set(procattr, APR_LIMIT_NPROC, conf->limit_nproc)) != APR_SUCCESS) ||
439 ((rc = apr_procattr_cmdtype_set(procattr, e_info->cmd_type)) != APR_SUCCESS)) {
440 /* Something bad happened, tell the world. */
441 ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r,
442 "couldn't set child process attributes: %s", r->filename);
445 procnew = apr_pcalloc(p, sizeof(*procnew));
446 if (e_info->prog_type == RUN_AS_SSI) {
447 SPLIT_AND_PASS_PRETAG_BUCKETS(*(e_info->bb), e_info->ctx, e_info->next, rc);
448 if (rc != APR_SUCCESS) {
453 rc = ap_os_create_privileged_process(r, procnew, command, argv, env, procattr, p);
455 if (rc != APR_SUCCESS) {
456 /* Bad things happened. Everyone should have cleaned up. */
457 ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r,
458 "couldn't create child process: %d: %s", rc, r->filename);
461 apr_pool_note_subprocess(p, procnew, kill_after_timeout);
463 *script_in = procnew->out;
466 apr_file_pipe_timeout_set(*script_in, (int)(r->server->timeout * APR_USEC_PER_SEC));
468 if (e_info->prog_type == RUN_AS_CGI) {
469 *script_out = procnew->in;
472 apr_file_pipe_timeout_set(*script_out, (int)(r->server->timeout * APR_USEC_PER_SEC));
474 *script_err = procnew->err;
477 apr_file_pipe_timeout_set(*script_err, (int)(r->server->timeout * APR_USEC_PER_SEC));
485 static apr_status_t default_build_command(const char **cmd, const char ***argv,
486 request_rec *r, apr_pool_t *p)
488 int numwords, x, idx;
490 const char *args = r->args;
493 /* Allow suexec's "/" check to succeed */
494 if ((argv0 = strrchr(r->filename, '/')) != NULL)
500 if (!args || !args[0] || ap_strchr_c(args, '=')) {
504 /* count the number of keywords */
505 for (x = 0, numwords = 2; args[x]; x++) {
506 if (args[x] == '+') {
511 /* Everything is - 1 to account for the first parameter
512 * which is the program name.
514 if (numwords > APACHE_ARG_MAX - 1) {
515 numwords = APACHE_ARG_MAX - 1; /* Truncate args to prevent overrun */
517 *argv = apr_palloc(p, (numwords + 2) * sizeof(char *));
519 for (x = 1, idx = 1; x < numwords; x++) {
520 w = ap_getword_nulls(p, &args, '+');
522 (*argv)[idx++] = ap_escape_shell_cmd(p, w);
530 static int cgi_handler(request_rec *r)
532 int retval, nph, dbpos = 0;
537 apr_file_t *script_out = NULL, *script_in = NULL, *script_err = NULL;
538 apr_bucket_brigade *bb;
540 char argsbuffer[HUGE_STRING_LEN];
541 int is_included = !strcmp(r->protocol, "INCLUDED");
543 cgi_server_conf *conf;
547 if(strcmp(r->handler,CGI_MAGIC_TYPE) && strcmp(r->handler,"cgi-script"))
550 p = r->main ? r->main->pool : r->pool;
552 if (r->method_number == M_OPTIONS) {
553 /* 99 out of 100 CGI scripts, this is all they support */
554 r->allowed |= (AP_METHOD_BIT << M_GET);
555 r->allowed |= (AP_METHOD_BIT << M_POST);
559 argv0 = apr_filename_of_pathname(r->filename);
560 nph = !(strncmp(argv0, "nph-", 4));
561 conf = ap_get_module_config(r->server->module_config, &cgi_module);
563 if (!(ap_allow_options(r) & OPT_EXECCGI) && !is_scriptaliased(r))
564 return log_scripterror(r, conf, HTTP_FORBIDDEN, 0,
565 "Options ExecCGI is off in this directory");
566 if (nph && is_included)
567 return log_scripterror(r, conf, HTTP_FORBIDDEN, 0,
568 "attempt to include NPH CGI script");
570 if (r->finfo.filetype == 0)
571 return log_scripterror(r, conf, HTTP_NOT_FOUND, 0,
572 "script not found or unable to stat");
573 if (r->finfo.filetype == APR_DIR)
574 return log_scripterror(r, conf, HTTP_FORBIDDEN, 0,
575 "attempt to invoke directory as script");
578 if (!ap_suexec_enabled) {
579 if (!ap_can_exec(&r->finfo))
580 return log_scripterror(r, conf, HTTP_FORBIDDEN, 0,
581 "file permissions deny server execution");
585 if ((retval = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR)))
588 ap_add_common_vars(r);
590 /* build the command line */
591 if ((rv = cgi_build_command(&command, &argv, r, p)) != APR_SUCCESS) {
592 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
593 "don't know how to spawn child process: %s",
595 return HTTP_INTERNAL_SERVER_ERROR;
598 e_info.cmd_type = APR_PROGRAM;
599 e_info.in_pipe = APR_CHILD_BLOCK;
600 e_info.out_pipe = APR_CHILD_BLOCK;
601 e_info.err_pipe = APR_CHILD_BLOCK;
602 e_info.prog_type = RUN_AS_CGI;
607 /* run the script in its own process */
608 if ((rv = run_cgi_child(&script_out, &script_in, &script_err,
609 command, argv, r, p, &e_info)) != APR_SUCCESS) {
610 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
611 "couldn't spawn child process: %s", r->filename);
612 return HTTP_INTERNAL_SERVER_ERROR;
615 /* Transfer any put/post args, CERN style...
616 * Note that we already ignore SIGPIPE in the core server.
618 if (ap_should_client_block(r)) {
619 int len_read, dbsize;
620 apr_size_t bytes_written, bytes_to_write;
624 dbuf = apr_pcalloc(r->pool, conf->bufbytes + 1);
629 ap_get_client_block(r, argsbuffer, HUGE_STRING_LEN)) > 0) {
631 if ((dbpos + len_read) > conf->bufbytes) {
632 dbsize = conf->bufbytes - dbpos;
637 memcpy(dbuf + dbpos, argsbuffer, dbsize);
640 /* Keep writing data to the child until done or too much time
641 * elapses with no progress or an error occurs.
645 bytes_to_write = len_read - bytes_written;
646 rv = apr_file_write(script_out, argsbuffer + bytes_written,
648 bytes_written += bytes_to_write;
649 } while (rv == APR_SUCCESS
650 && bytes_written < (apr_size_t)len_read);
651 if (rv != APR_SUCCESS || bytes_written < (apr_size_t)len_read) {
652 /* silly script stopped reading, soak up remaining message */
653 while (ap_get_client_block(r, argsbuffer, HUGE_STRING_LEN) > 0) {
659 apr_file_flush(script_out);
662 apr_file_close(script_out);
664 /* Handle script return... */
665 if (script_in && !nph) {
666 const char *location;
667 char sbuf[MAX_STRING_LEN];
670 if ((ret = ap_scan_script_header_err(r, script_in, sbuf))) {
671 return log_script(r, conf, ret, dbuf, sbuf, script_in, script_err);
674 location = apr_table_get(r->headers_out, "Location");
676 if (location && location[0] == '/' && r->status == 200) {
678 /* Soak up all the script output */
679 while (apr_file_gets(argsbuffer, HUGE_STRING_LEN, script_in) == 0) {
682 log_script_err(r, script_err);
683 /* This redirect needs to be a GET no matter what the original
686 r->method = apr_pstrdup(r->pool, "GET");
687 r->method_number = M_GET;
689 /* We already read the message body (if any), so don't allow
690 * the redirected request to think it has one. We can ignore
691 * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR.
693 apr_table_unset(r->headers_in, "Content-Length");
695 ap_internal_redirect_handler(location, r);
698 else if (location && r->status == 200) {
699 /* XX Note that if a script wants to produce its own Redirect
700 * body, it now has to explicitly *say* "Status: 302"
702 return HTTP_MOVED_TEMPORARILY;
705 if (!r->header_only) {
706 bb = apr_brigade_create(r->pool);
707 b = apr_bucket_pipe_create(script_in);
708 APR_BRIGADE_INSERT_TAIL(bb, b);
709 b = apr_bucket_eos_create();
710 APR_BRIGADE_INSERT_TAIL(bb, b);
711 ap_pass_brigade(r->output_filters, bb);
714 log_script_err(r, script_err);
715 apr_file_close(script_err);
718 if (script_in && nph) {
719 bb = apr_brigade_create(r->pool);
720 b = apr_bucket_pipe_create(script_in);
721 APR_BRIGADE_INSERT_TAIL(bb, b);
722 b = apr_bucket_eos_create();
723 APR_BRIGADE_INSERT_TAIL(bb, b);
724 ap_pass_brigade(r->output_filters, bb);
727 return OK; /* NOT r->status, even if it has changed. */
730 /*============================================================================
731 *============================================================================
732 * This is the beginning of the cgi filter code moved from mod_include. This
733 * is the code required to handle the "exec" SSI directive.
734 *============================================================================
735 *============================================================================*/
736 static int include_cgi(char *s, request_rec *r, ap_filter_t *next,
737 apr_bucket *head_ptr, apr_bucket **inserted_head)
739 request_rec *rr = ap_sub_req_lookup_uri(s, r, next);
741 apr_bucket *tmp_buck, *tmp2_buck;
743 if (rr->status != HTTP_OK) {
744 ap_destroy_sub_req(rr);
748 /* No hardwired path info or query allowed */
750 if ((rr->path_info && rr->path_info[0]) || rr->args) {
751 ap_destroy_sub_req(rr);
754 if (rr->finfo.filetype != APR_REG) {
755 ap_destroy_sub_req(rr);
759 /* Script gets parameters of the *document*, for back compatibility */
761 rr->path_info = r->path_info; /* hard to get right; see mod_cgi.c */
764 /* Force sub_req to be treated as a CGI request, even if ordinary
765 * typing rules would have called it something else.
768 rr->content_type = CGI_MAGIC_TYPE;
772 rr_status = ap_run_sub_req(rr);
773 if (ap_is_HTTP_REDIRECT(rr_status)) {
774 apr_size_t len_loc, h_wrt;
775 const char *location = apr_table_get(rr->headers_out, "Location");
777 location = ap_escape_html(rr->pool, location);
778 len_loc = strlen(location);
780 tmp_buck = apr_bucket_immortal_create("<A HREF=\"", sizeof("<A HREF=\""));
781 APR_BUCKET_INSERT_BEFORE(head_ptr, tmp_buck);
782 tmp2_buck = apr_bucket_heap_create(location, len_loc, 1, &h_wrt);
783 APR_BUCKET_INSERT_BEFORE(head_ptr, tmp2_buck);
784 tmp2_buck = apr_bucket_immortal_create("\">", sizeof("\">"));
785 APR_BUCKET_INSERT_BEFORE(head_ptr, tmp2_buck);
786 tmp2_buck = apr_bucket_heap_create(location, len_loc, 1, &h_wrt);
787 APR_BUCKET_INSERT_BEFORE(head_ptr, tmp2_buck);
788 tmp2_buck = apr_bucket_immortal_create("</A>", sizeof("</A>"));
789 APR_BUCKET_INSERT_BEFORE(head_ptr, tmp2_buck);
791 if (*inserted_head == NULL) {
792 *inserted_head = tmp_buck;
796 ap_destroy_sub_req(rr);
802 static int include_cmd(include_ctx_t *ctx, apr_bucket_brigade **bb,
803 const char *command, request_rec *r, ap_filter_t *f)
807 apr_file_t *script_out = NULL, *script_in = NULL, *script_err = NULL;
808 apr_bucket_brigade *bcgi;
812 if ((rv = cgi_build_command(&command, &argv, r, r->pool)) != APR_SUCCESS) {
813 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
814 "don't know how to spawn cmd child process: %s",
816 return HTTP_INTERNAL_SERVER_ERROR;
819 e_info.cmd_type = APR_SHELLCMD;
820 e_info.in_pipe = APR_NO_PIPE;
821 e_info.out_pipe = APR_FULL_BLOCK;
822 e_info.err_pipe = APR_NO_PIPE;
823 e_info.prog_type = RUN_AS_SSI;
826 e_info.next = f->next;
828 /* run the script in its own process */
829 if ((rv = run_cgi_child(&script_out, &script_in, &script_err,
830 command, argv, r, r->pool, &e_info)) != APR_SUCCESS) {
831 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
832 "couldn't spawn child process: %s", r->filename);
833 return HTTP_INTERNAL_SERVER_ERROR;
836 bcgi = apr_brigade_create(r->pool);
837 b = apr_bucket_pipe_create(script_in);
838 APR_BRIGADE_INSERT_TAIL(bcgi, b);
839 ap_pass_brigade(f->next, bcgi);
841 /* We can't close the pipe here, because we may return before the
842 * full CGI has been sent to the network. That's okay though,
843 * because we can rely on the pool to close the pipe for us.
849 static int handle_exec(include_ctx_t *ctx, apr_bucket_brigade **bb, request_rec *r,
850 ap_filter_t *f, apr_bucket *head_ptr, apr_bucket **inserted_head)
853 char *tag_val = NULL;
854 char *file = r->filename;
855 apr_bucket *tmp_buck;
856 char parsed_string[MAX_STRING_LEN];
858 *inserted_head = NULL;
859 if (ctx->flags & FLAG_PRINTING) {
860 if (ctx->flags & FLAG_NO_EXEC) {
861 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
862 "exec used but not allowed in %s", r->filename);
863 CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, *inserted_head);
867 cgi_pfn_gtv(ctx, &tag, &tag_val, 1);
868 if (tag_val == NULL) {
876 if (!strcmp(tag, "cmd")) {
877 cgi_pfn_ps(r, tag_val, parsed_string, sizeof(parsed_string), 1);
878 if (include_cmd(ctx, bb, parsed_string, r, f) == -1) {
879 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
880 "execution failure for parameter \"%s\" "
881 "to tag exec in file %s", tag, r->filename);
882 CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, *inserted_head);
885 else if (!strcmp(tag, "cgi")) {
886 apr_status_t retval = APR_SUCCESS;
888 cgi_pfn_ps(r, tag_val, parsed_string, sizeof(parsed_string), 0);
889 SPLIT_AND_PASS_PRETAG_BUCKETS(*bb, ctx, f->next, retval);
890 if (retval != APR_SUCCESS) {
894 if (include_cgi(parsed_string, r, f->next, head_ptr, inserted_head) == -1) {
895 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
896 "invalid CGI ref \"%s\" in %s", tag_val, file);
897 CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, *inserted_head);
901 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
902 "unknown parameter \"%s\" to tag exec in %s", tag, file);
903 CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, *inserted_head);
912 /*============================================================================
913 *============================================================================
914 * This is the end of the cgi filter code moved from mod_include.
915 *============================================================================
916 *============================================================================*/
919 static void cgi_post_config(apr_pool_t *p, apr_pool_t *plog,
920 apr_pool_t *ptemp, server_rec *s)
922 cgi_pfn_reg_with_ssi = APR_RETRIEVE_OPTIONAL_FN(ap_register_include_handler);
923 cgi_pfn_gtv = APR_RETRIEVE_OPTIONAL_FN(ap_ssi_get_tag_and_value);
924 cgi_pfn_ps = APR_RETRIEVE_OPTIONAL_FN(ap_ssi_parse_string);
926 if ((cgi_pfn_reg_with_ssi) && (cgi_pfn_gtv) && (cgi_pfn_ps)) {
927 /* Required by mod_include filter. This is how mod_cgi registers
928 * with mod_include to provide processing of the exec directive.
930 cgi_pfn_reg_with_ssi("exec", handle_exec);
933 /* This is the means by which unusual (non-unix) os's may find alternate
934 * means to run a given command (e.g. shebang/registry parsing on Win32)
936 cgi_build_command = APR_RETRIEVE_OPTIONAL_FN(ap_cgi_build_command);
937 if (!cgi_build_command) {
938 cgi_build_command = default_build_command;
942 static void register_hooks(apr_pool_t *p)
944 static const char * const aszPre[] = { "mod_include.c", NULL };
945 ap_hook_handler(cgi_handler, NULL, NULL, APR_HOOK_MIDDLE);
946 ap_hook_post_config(cgi_post_config, aszPre, NULL, APR_HOOK_REALLY_FIRST);
949 module AP_MODULE_DECLARE_DATA cgi_module =
951 STANDARD20_MODULE_STUFF,
952 NULL, /* dir config creater */
953 NULL, /* dir merger --- default is to override */
954 create_cgi_config, /* server config */
955 merge_cgi_config, /* merge server config */
956 cgi_cmds, /* command apr_table_t */
957 register_hooks /* register hooks */