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 * http_script: keeps all script-related ramblings together.
20 * Compliant to CGI/1.1 spec
22 * Adapted by rst from original NCSA code by Rob McCool
24 * Apache adds some new env vars; REDIRECT_URL and REDIRECT_QUERY_STRING for
25 * custom error responses, and DOCUMENT_ROOT because we found it useful.
26 * It also adds SERVER_ADMIN - useful for scripts to know who to mail when
31 #include "apr_strings.h"
32 #include "apr_thread_proc.h" /* for RLIMIT stuff */
33 #include "apr_optional.h"
34 #include "apr_buckets.h"
38 #define APR_WANT_STRFUNC
39 #define APR_WANT_MEMFUNC
42 #include "util_filter.h"
43 #include "ap_config.h"
45 #include "http_config.h"
46 #include "http_request.h"
47 #include "http_core.h"
48 #include "http_protocol.h"
49 #include "http_main.h"
51 #include "util_script.h"
56 #if APR_HAVE_STRUCT_RLIMIT
57 #if defined (RLIMIT_CPU) || defined (RLIMIT_NPROC) || defined (RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
58 #define AP_CGI_USE_RLIMIT
62 module AP_MODULE_DECLARE_DATA cgi_module;
64 static APR_OPTIONAL_FN_TYPE(ap_register_include_handler) *cgi_pfn_reg_with_ssi;
65 static APR_OPTIONAL_FN_TYPE(ap_ssi_get_tag_and_value) *cgi_pfn_gtv;
66 static APR_OPTIONAL_FN_TYPE(ap_ssi_parse_string) *cgi_pfn_ps;
67 static APR_OPTIONAL_FN_TYPE(ap_cgi_build_command) *cgi_build_command;
69 /* Read and discard the data in the brigade produced by a CGI script */
70 static void discard_script_output(apr_bucket_brigade *bb);
72 /* KLUDGE --- for back-combatibility, we don't have to check ExecCGI
73 * in ScriptAliased directories, which means we need to know if this
74 * request came through ScriptAlias or not... so the Alias module
75 * leaves a note for us.
78 static int is_scriptaliased(request_rec *r)
80 const char *t = apr_table_get(r->notes, "alias-forced-type");
81 return t && (!strcasecmp(t, "cgi-script"));
84 /* Configuration stuff */
86 #define DEFAULT_LOGBYTES 10385760
87 #define DEFAULT_BUFBYTES 1024
95 static void *create_cgi_config(apr_pool_t *p, server_rec *s)
98 (cgi_server_conf *) apr_pcalloc(p, sizeof(cgi_server_conf));
101 c->logbytes = DEFAULT_LOGBYTES;
102 c->bufbytes = DEFAULT_BUFBYTES;
107 static void *merge_cgi_config(apr_pool_t *p, void *basev, void *overridesv)
109 cgi_server_conf *base = (cgi_server_conf *) basev,
110 *overrides = (cgi_server_conf *) overridesv;
112 return overrides->logname ? overrides : base;
115 static const char *set_scriptlog(cmd_parms *cmd, void *dummy, const char *arg)
117 server_rec *s = cmd->server;
118 cgi_server_conf *conf = ap_get_module_config(s->module_config,
121 conf->logname = ap_server_root_relative(cmd->pool, arg);
123 if (!conf->logname) {
124 return apr_pstrcat(cmd->pool, "Invalid ScriptLog path ",
131 static const char *set_scriptlog_length(cmd_parms *cmd, void *dummy,
134 server_rec *s = cmd->server;
135 cgi_server_conf *conf = ap_get_module_config(s->module_config,
138 conf->logbytes = atol(arg);
142 static const char *set_scriptlog_buffer(cmd_parms *cmd, void *dummy,
145 server_rec *s = cmd->server;
146 cgi_server_conf *conf = ap_get_module_config(s->module_config,
149 conf->bufbytes = atoi(arg);
153 static const command_rec cgi_cmds[] =
155 AP_INIT_TAKE1("ScriptLog", set_scriptlog, NULL, RSRC_CONF,
156 "the name of a log for script debugging info"),
157 AP_INIT_TAKE1("ScriptLogLength", set_scriptlog_length, NULL, RSRC_CONF,
158 "the maximum length (in bytes) of the script debug log"),
159 AP_INIT_TAKE1("ScriptLogBuffer", set_scriptlog_buffer, NULL, RSRC_CONF,
160 "the maximum size (in bytes) to record of a POST request"),
164 static int log_scripterror(request_rec *r, cgi_server_conf * conf, int ret,
165 apr_status_t rv, char *error)
167 apr_file_t *f = NULL;
169 char time_str[APR_CTIME_LEN];
170 int log_flags = rv ? APLOG_ERR : APLOG_ERR;
172 ap_log_rerror(APLOG_MARK, log_flags, rv, r,
173 "%s: %s", error, r->filename);
175 /* XXX Very expensive mainline case! Open, then getfileinfo! */
176 if (!conf->logname ||
177 ((apr_stat(&finfo, conf->logname,
178 APR_FINFO_SIZE, r->pool) == APR_SUCCESS) &&
179 (finfo.size > conf->logbytes)) ||
180 (apr_file_open(&f, conf->logname,
181 APR_APPEND|APR_WRITE|APR_CREATE, APR_OS_DEFAULT,
182 r->pool) != APR_SUCCESS)) {
186 /* "%% [Wed Jun 19 10:53:21 1996] GET /cgi-bin/printenv HTTP/1.0" */
187 apr_ctime(time_str, apr_time_now());
188 apr_file_printf(f, "%%%% [%s] %s %s%s%s %s\n", time_str, r->method, r->uri,
189 r->args ? "?" : "", r->args ? r->args : "", r->protocol);
190 /* "%% 500 /usr/local/apache/cgi-bin */
191 apr_file_printf(f, "%%%% %d %s\n", ret, r->filename);
193 apr_file_printf(f, "%%error\n%s\n", error);
199 /* Soak up stderr from a script and redirect it to the error log.
201 static apr_status_t log_script_err(request_rec *r, apr_file_t *script_err)
203 char argsbuffer[HUGE_STRING_LEN];
207 while ((rv = apr_file_gets(argsbuffer, HUGE_STRING_LEN,
208 script_err)) == APR_SUCCESS) {
209 newline = strchr(argsbuffer, '\n');
213 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01215)
220 static int log_script(request_rec *r, cgi_server_conf * conf, int ret,
221 char *dbuf, const char *sbuf, apr_bucket_brigade *bb,
222 apr_file_t *script_err)
224 const apr_array_header_t *hdrs_arr = apr_table_elts(r->headers_in);
225 const apr_table_entry_t *hdrs = (const apr_table_entry_t *) hdrs_arr->elts;
226 char argsbuffer[HUGE_STRING_LEN];
227 apr_file_t *f = NULL;
235 char time_str[APR_CTIME_LEN];
237 /* XXX Very expensive mainline case! Open, then getfileinfo! */
238 if (!conf->logname ||
239 ((apr_stat(&finfo, conf->logname,
240 APR_FINFO_SIZE, r->pool) == APR_SUCCESS) &&
241 (finfo.size > conf->logbytes)) ||
242 (apr_file_open(&f, conf->logname,
243 APR_APPEND|APR_WRITE|APR_CREATE, APR_OS_DEFAULT,
244 r->pool) != APR_SUCCESS)) {
245 /* Soak up script output */
246 discard_script_output(bb);
247 log_script_err(r, script_err);
251 /* "%% [Wed Jun 19 10:53:21 1996] GET /cgi-bin/printenv HTTP/1.0" */
252 apr_ctime(time_str, apr_time_now());
253 apr_file_printf(f, "%%%% [%s] %s %s%s%s %s\n", time_str, r->method, r->uri,
254 r->args ? "?" : "", r->args ? r->args : "", r->protocol);
255 /* "%% 500 /usr/local/apache/cgi-bin" */
256 apr_file_printf(f, "%%%% %d %s\n", ret, r->filename);
258 apr_file_puts("%request\n", f);
259 for (i = 0; i < hdrs_arr->nelts; ++i) {
262 apr_file_printf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val);
264 if ((r->method_number == M_POST || r->method_number == M_PUT) &&
266 apr_file_printf(f, "\n%s\n", dbuf);
269 apr_file_puts("%response\n", f);
270 hdrs_arr = apr_table_elts(r->err_headers_out);
271 hdrs = (const apr_table_entry_t *) hdrs_arr->elts;
273 for (i = 0; i < hdrs_arr->nelts; ++i) {
276 apr_file_printf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val);
280 apr_file_printf(f, "%s\n", sbuf);
283 for (e = APR_BRIGADE_FIRST(bb);
284 e != APR_BRIGADE_SENTINEL(bb);
285 e = APR_BUCKET_NEXT(e))
287 if (APR_BUCKET_IS_EOS(e)) {
290 rv = apr_bucket_read(e, &buf, &len, APR_BLOCK_READ);
291 if (rv != APR_SUCCESS || (len == 0)) {
295 apr_file_puts("%stdout\n", f);
298 apr_file_write(f, buf, &len);
299 apr_file_puts("\n", f);
302 if (apr_file_gets(argsbuffer, HUGE_STRING_LEN, script_err) == APR_SUCCESS) {
303 apr_file_puts("%stderr\n", f);
304 apr_file_puts(argsbuffer, f);
305 while (apr_file_gets(argsbuffer, HUGE_STRING_LEN,
306 script_err) == APR_SUCCESS) {
307 apr_file_puts(argsbuffer, f);
309 apr_file_puts("\n", f);
312 apr_brigade_destroy(bb);
313 apr_file_close(script_err);
320 /* This is the special environment used for running the "exec cmd="
321 * variety of SSI directives.
323 static void add_ssi_vars(request_rec *r)
325 apr_table_t *e = r->subprocess_env;
327 if (r->path_info && r->path_info[0] != '\0') {
330 apr_table_setn(e, "PATH_INFO", ap_escape_shell_cmd(r->pool,
333 pa_req = ap_sub_req_lookup_uri(ap_escape_uri(r->pool, r->path_info),
335 if (pa_req->filename) {
336 apr_table_setn(e, "PATH_TRANSLATED",
337 apr_pstrcat(r->pool, pa_req->filename,
338 pa_req->path_info, NULL));
340 ap_destroy_sub_req(pa_req);
344 char *arg_copy = apr_pstrdup(r->pool, r->args);
346 apr_table_setn(e, "QUERY_STRING", r->args);
347 ap_unescape_url(arg_copy);
348 apr_table_setn(e, "QUERY_STRING_UNESCAPED",
349 ap_escape_shell_cmd(r->pool, arg_copy));
353 static void cgi_child_errfn(apr_pool_t *pool, apr_status_t err,
354 const char *description)
356 apr_file_t *stderr_log;
359 apr_file_open_stderr(&stderr_log, pool);
360 /* Escape the logged string because it may be something that
361 * came in over the network.
363 apr_file_printf(stderr_log,
366 apr_strerror(err, errbuf, sizeof(errbuf)),
367 #ifndef AP_UNSAFE_ERROR_LOG_UNESCAPED
368 ap_escape_logitem(pool,
371 #ifndef AP_UNSAFE_ERROR_LOG_UNESCAPED
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[],
384 cgi_exec_info_t *e_info)
386 const char * const *env;
387 apr_procattr_t *procattr;
389 apr_status_t rc = APR_SUCCESS;
391 #ifdef AP_CGI_USE_RLIMIT
392 core_dir_config *conf = ap_get_core_module_config(r->per_dir_config);
397 /* Under OS/2 need to use device con. */
398 FILE *dbg = fopen("con", "w");
400 FILE *dbg = fopen("/dev/tty", "w");
405 RAISE_SIGSTOP(CGI_CHILD);
407 fprintf(dbg, "Attempting to exec %s as CGI child (argv0 = %s)\n",
408 r->filename, argv[0]);
411 env = (const char * const *)ap_create_environment(p, r->subprocess_env);
414 fprintf(dbg, "Environment: \n");
415 for (i = 0; env[i]; ++i)
416 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,
430 r->filename))) != APR_SUCCESS) ||
431 #if defined(RLIMIT_CPU) && defined(AP_CGI_USE_RLIMIT)
432 ((rc = apr_procattr_limit_set(procattr, APR_LIMIT_CPU,
433 conf->limit_cpu)) != APR_SUCCESS) ||
435 #if defined(AP_CGI_USE_RLIMIT) && (defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS))
436 ((rc = apr_procattr_limit_set(procattr, APR_LIMIT_MEM,
437 conf->limit_mem)) != APR_SUCCESS) ||
439 #if RLIMIT_NPROC && defined(AP_CGI_USE_RLIMIT)
440 ((rc = apr_procattr_limit_set(procattr, APR_LIMIT_NPROC,
441 conf->limit_nproc)) != APR_SUCCESS) ||
443 ((rc = apr_procattr_cmdtype_set(procattr,
444 e_info->cmd_type)) != APR_SUCCESS) ||
446 ((rc = apr_procattr_detach_set(procattr,
447 e_info->detached)) != APR_SUCCESS) ||
448 ((rc = apr_procattr_addrspace_set(procattr,
449 e_info->addrspace)) != APR_SUCCESS) ||
450 ((rc = apr_procattr_child_errfn_set(procattr, cgi_child_errfn)) != APR_SUCCESS)) {
451 /* Something bad happened, tell the world. */
452 ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r, APLOGNO(01216)
453 "couldn't set child process attributes: %s", r->filename);
456 procnew = apr_pcalloc(p, sizeof(*procnew));
457 rc = ap_os_create_privileged_process(r, procnew, command, argv, env,
460 if (rc != APR_SUCCESS) {
461 /* Bad things happened. Everyone should have cleaned up. */
462 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_TOCLIENT, rc, r,
463 "couldn't create child process: %d: %s", rc,
464 apr_filepath_name_get(r->filename));
467 apr_pool_note_subprocess(p, procnew, APR_KILL_AFTER_TIMEOUT);
469 *script_in = procnew->out;
472 apr_file_pipe_timeout_set(*script_in, r->server->timeout);
474 if (e_info->prog_type == RUN_AS_CGI) {
475 *script_out = procnew->in;
478 apr_file_pipe_timeout_set(*script_out, r->server->timeout);
480 *script_err = procnew->err;
483 apr_file_pipe_timeout_set(*script_err, r->server->timeout);
491 static apr_status_t default_build_command(const char **cmd, const char ***argv,
492 request_rec *r, apr_pool_t *p,
493 cgi_exec_info_t *e_info)
495 int numwords, x, idx;
497 const char *args = NULL;
499 if (e_info->process_cgi) {
501 /* Do not process r->args if they contain an '=' assignment
503 if (r->args && r->args[0] && !ap_strchr_c(r->args, '=')) {
512 /* count the number of keywords */
513 for (x = 0, numwords = 2; args[x]; x++) {
514 if (args[x] == '+') {
519 /* Everything is - 1 to account for the first parameter
520 * which is the program name.
522 if (numwords > APACHE_ARG_MAX - 1) {
523 numwords = APACHE_ARG_MAX - 1; /* Truncate args to prevent overrun */
525 *argv = apr_palloc(p, (numwords + 2) * sizeof(char *));
527 for (x = 1, idx = 1; x < numwords; x++) {
528 w = ap_getword_nulls(p, &args, '+');
530 (*argv)[idx++] = ap_escape_shell_cmd(p, w);
537 static void discard_script_output(apr_bucket_brigade *bb)
544 for (e = APR_BRIGADE_FIRST(bb);
545 e != APR_BRIGADE_SENTINEL(bb);
546 e = APR_BUCKET_NEXT(e))
548 if (APR_BUCKET_IS_EOS(e)) {
551 rv = apr_bucket_read(e, &buf, &len, APR_BLOCK_READ);
552 if (rv != APR_SUCCESS) {
558 #if APR_FILES_AS_SOCKETS
560 /* A CGI bucket type is needed to catch any output to stderr from the
561 * script; see PR 22030. */
562 static const apr_bucket_type_t bucket_type_cgi;
564 struct cgi_bucket_data {
565 apr_pollset_t *pollset;
569 /* Create a CGI bucket using pipes from script stdout 'out'
570 * and stderr 'err', for request 'r'. */
571 static apr_bucket *cgi_bucket_create(request_rec *r,
572 apr_file_t *out, apr_file_t *err,
573 apr_bucket_alloc_t *list)
575 apr_bucket *b = apr_bucket_alloc(sizeof(*b), list);
578 struct cgi_bucket_data *data = apr_palloc(r->pool, sizeof *data);
581 b->free = apr_bucket_free;
583 b->type = &bucket_type_cgi;
584 b->length = (apr_size_t)(-1);
587 /* Create the pollset */
588 rv = apr_pollset_create(&data->pollset, 2, r->pool, 0);
589 if (rv != APR_SUCCESS) {
590 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(01217)
591 "apr_pollset_create(); check system or user limits");
595 fd.desc_type = APR_POLL_FILE;
596 fd.reqevents = APR_POLLIN;
598 fd.desc.f = out; /* script's stdout */
599 fd.client_data = (void *)1;
600 rv = apr_pollset_add(data->pollset, &fd);
601 if (rv != APR_SUCCESS) {
602 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(01218)
603 "apr_pollset_add(); check system or user limits");
607 fd.desc.f = err; /* script's stderr */
608 fd.client_data = (void *)2;
609 rv = apr_pollset_add(data->pollset, &fd);
610 if (rv != APR_SUCCESS) {
611 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(01219)
612 "apr_pollset_add(); check system or user limits");
621 /* Create a duplicate CGI bucket using given bucket data */
622 static apr_bucket *cgi_bucket_dup(struct cgi_bucket_data *data,
623 apr_bucket_alloc_t *list)
625 apr_bucket *b = apr_bucket_alloc(sizeof(*b), list);
627 b->free = apr_bucket_free;
629 b->type = &bucket_type_cgi;
630 b->length = (apr_size_t)(-1);
636 /* Handle stdout from CGI child. Duplicate of logic from the _read
637 * method of the real APR pipe bucket implementation. */
638 static apr_status_t cgi_read_stdout(apr_bucket *a, apr_file_t *out,
639 const char **str, apr_size_t *len)
645 *len = APR_BUCKET_BUFF_SIZE;
646 buf = apr_bucket_alloc(*len, a->list); /* XXX: check for failure? */
648 rv = apr_file_read(out, buf, len);
650 if (rv != APR_SUCCESS && rv != APR_EOF) {
651 apr_bucket_free(buf);
656 struct cgi_bucket_data *data = a->data;
659 /* Change the current bucket to refer to what we read */
660 a = apr_bucket_heap_make(a, buf, *len, apr_bucket_free);
662 h->alloc_len = APR_BUCKET_BUFF_SIZE; /* note the real buffer size */
664 APR_BUCKET_INSERT_AFTER(a, cgi_bucket_dup(data, a->list));
667 apr_bucket_free(buf);
668 a = apr_bucket_immortal_make(a, "", 0);
674 /* Read method of CGI bucket: polls on stderr and stdout of the child,
675 * sending any stderr output immediately away to the error log. */
676 static apr_status_t cgi_bucket_read(apr_bucket *b, const char **str,
677 apr_size_t *len, apr_read_type_e block)
679 struct cgi_bucket_data *data = b->data;
680 apr_interval_time_t timeout;
684 timeout = block == APR_NONBLOCK_READ ? 0 : data->r->server->timeout;
687 const apr_pollfd_t *results;
690 rv = apr_pollset_poll(data->pollset, timeout, &num, &results);
691 if (APR_STATUS_IS_TIMEUP(rv)) {
693 ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, data->r, APLOGNO(01220)
694 "Timeout waiting for output from CGI script %s",
702 else if (APR_STATUS_IS_EINTR(rv)) {
705 else if (rv != APR_SUCCESS) {
706 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, data->r, APLOGNO(01221)
707 "poll failed waiting for CGI child");
711 for (; num; num--, results++) {
712 if (results[0].client_data == (void *)1) {
714 rv = cgi_read_stdout(b, results[0].desc.f, str, len);
715 if (APR_STATUS_IS_EOF(rv)) {
721 apr_status_t rv2 = log_script_err(data->r, results[0].desc.f);
722 if (APR_STATUS_IS_EOF(rv2)) {
723 apr_pollset_remove(data->pollset, &results[0]);
733 static const apr_bucket_type_t bucket_type_cgi = {
734 "CGI", 5, APR_BUCKET_DATA,
735 apr_bucket_destroy_noop,
737 apr_bucket_setaside_notimpl,
738 apr_bucket_split_notimpl,
739 apr_bucket_copy_notimpl
744 static int cgi_handler(request_rec *r)
747 apr_size_t dbpos = 0;
752 apr_file_t *script_out = NULL, *script_in = NULL, *script_err = NULL;
753 apr_bucket_brigade *bb;
756 int seen_eos, child_stopped_reading;
758 cgi_server_conf *conf;
760 cgi_exec_info_t e_info;
763 if (strcmp(r->handler, CGI_MAGIC_TYPE) && strcmp(r->handler, "cgi-script")) {
769 is_included = !strcmp(r->protocol, "INCLUDED");
771 p = r->main ? r->main->pool : r->pool;
773 argv0 = apr_filepath_name_get(r->filename);
774 nph = !(strncmp(argv0, "nph-", 4));
775 conf = ap_get_module_config(r->server->module_config, &cgi_module);
777 if (!(ap_allow_options(r) & OPT_EXECCGI) && !is_scriptaliased(r))
778 return log_scripterror(r, conf, HTTP_FORBIDDEN, 0,
779 "Options ExecCGI is off in this directory");
780 if (nph && is_included)
781 return log_scripterror(r, conf, HTTP_FORBIDDEN, 0,
782 "attempt to include NPH CGI script");
784 if (r->finfo.filetype == APR_NOFILE)
785 return log_scripterror(r, conf, HTTP_NOT_FOUND, 0,
786 "script not found or unable to stat");
787 if (r->finfo.filetype == APR_DIR)
788 return log_scripterror(r, conf, HTTP_FORBIDDEN, 0,
789 "attempt to invoke directory as script");
791 if ((r->used_path_info == AP_REQ_REJECT_PATH_INFO) &&
792 r->path_info && *r->path_info)
794 /* default to accept */
795 return log_scripterror(r, conf, HTTP_NOT_FOUND, 0,
796 "AcceptPathInfo off disallows user's path");
799 if (!ap_suexec_enabled) {
800 if (!ap_can_exec(&r->finfo))
801 return log_scripterror(r, conf, HTTP_FORBIDDEN, 0,
802 "file permissions deny server execution");
806 ap_add_common_vars(r);
809 e_info.process_cgi = 1;
810 e_info.cmd_type = APR_PROGRAM;
812 e_info.in_pipe = APR_CHILD_BLOCK;
813 e_info.out_pipe = APR_CHILD_BLOCK;
814 e_info.err_pipe = APR_CHILD_BLOCK;
815 e_info.prog_type = RUN_AS_CGI;
819 e_info.addrspace = 0;
821 /* build the command line */
822 if ((rv = cgi_build_command(&command, &argv, r, p, &e_info)) != APR_SUCCESS) {
823 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(01222)
824 "don't know how to spawn child process: %s",
826 return HTTP_INTERNAL_SERVER_ERROR;
829 /* run the script in its own process */
830 if ((rv = run_cgi_child(&script_out, &script_in, &script_err,
831 command, argv, r, p, &e_info)) != APR_SUCCESS) {
832 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(01223)
833 "couldn't spawn child process: %s", r->filename);
834 return HTTP_INTERNAL_SERVER_ERROR;
837 /* Transfer any put/post args, CERN style...
838 * Note that we already ignore SIGPIPE in the core server.
840 bb = apr_brigade_create(r->pool, c->bucket_alloc);
842 child_stopped_reading = 0;
844 dbuf = apr_palloc(r->pool, conf->bufbytes + 1);
850 rv = ap_get_brigade(r->input_filters, bb, AP_MODE_READBYTES,
851 APR_BLOCK_READ, HUGE_STRING_LEN);
853 if (rv != APR_SUCCESS) {
854 if (APR_STATUS_IS_TIMEUP(rv)) {
855 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(01224)
856 "Timeout during reading request entity data");
857 return HTTP_REQUEST_TIME_OUT;
859 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(01225)
860 "Error reading request entity data");
861 return HTTP_INTERNAL_SERVER_ERROR;
864 for (bucket = APR_BRIGADE_FIRST(bb);
865 bucket != APR_BRIGADE_SENTINEL(bb);
866 bucket = APR_BUCKET_NEXT(bucket))
871 if (APR_BUCKET_IS_EOS(bucket)) {
876 /* We can't do much with this. */
877 if (APR_BUCKET_IS_FLUSH(bucket)) {
881 /* If the child stopped, we still must read to EOS. */
882 if (child_stopped_reading) {
887 apr_bucket_read(bucket, &data, &len, APR_BLOCK_READ);
889 if (conf->logname && dbpos < conf->bufbytes) {
892 if ((dbpos + len) > conf->bufbytes) {
893 cursize = conf->bufbytes - dbpos;
898 memcpy(dbuf + dbpos, data, cursize);
902 /* Keep writing data to the child until done or too much time
903 * elapses with no progress or an error occurs.
905 rv = apr_file_write_full(script_out, data, len, NULL);
907 if (rv != APR_SUCCESS) {
908 /* silly script stopped reading, soak up remaining message */
909 child_stopped_reading = 1;
912 apr_brigade_cleanup(bb);
919 /* Is this flush really needed? */
920 apr_file_flush(script_out);
921 apr_file_close(script_out);
923 AP_DEBUG_ASSERT(script_in != NULL);
925 apr_brigade_cleanup(bb);
927 #if APR_FILES_AS_SOCKETS
928 apr_file_pipe_timeout_set(script_in, 0);
929 apr_file_pipe_timeout_set(script_err, 0);
931 b = cgi_bucket_create(r, script_in, script_err, c->bucket_alloc);
933 return HTTP_INTERNAL_SERVER_ERROR;
935 b = apr_bucket_pipe_create(script_in, c->bucket_alloc);
937 APR_BRIGADE_INSERT_TAIL(bb, b);
938 b = apr_bucket_eos_create(c->bucket_alloc);
939 APR_BRIGADE_INSERT_TAIL(bb, b);
941 /* Handle script return... */
943 const char *location;
944 char sbuf[MAX_STRING_LEN];
947 if ((ret = ap_scan_script_header_err_brigade_ex(r, bb, sbuf,
948 APLOG_MODULE_INDEX)))
950 ret = log_script(r, conf, ret, dbuf, sbuf, bb, script_err);
953 * ret could be HTTP_NOT_MODIFIED in the case that the CGI script
954 * does not set an explicit status and ap_meets_conditions, which
955 * is called by ap_scan_script_header_err_brigade, detects that
956 * the conditions of the requests are met and the response is
958 * In this case set r->status and return OK in order to prevent
959 * running through the error processing stack as this would
960 * break with mod_cache, if the conditions had been set by
961 * mod_cache itself to validate a stale entity.
962 * BTW: We circumvent the error processing stack anyway if the
963 * CGI script set an explicit status code (whatever it is) and
964 * the only possible values for ret here are:
966 * HTTP_NOT_MODIFIED (set by ap_meets_conditions)
967 * HTTP_PRECONDITION_FAILED (set by ap_meets_conditions)
968 * HTTP_INTERNAL_SERVER_ERROR (if something went wrong during the
969 * processing of the response of the CGI script, e.g broken headers
970 * or a crashed CGI process).
972 if (ret == HTTP_NOT_MODIFIED) {
980 location = apr_table_get(r->headers_out, "Location");
982 if (location && r->status == 200) {
983 /* For a redirect whether internal or not, discard any
984 * remaining stdout from the script, and log any remaining
985 * stderr output, as normal. */
986 discard_script_output(bb);
987 apr_brigade_destroy(bb);
988 apr_file_pipe_timeout_set(script_err, r->server->timeout);
989 log_script_err(r, script_err);
992 if (location && location[0] == '/' && r->status == 200) {
993 /* This redirect needs to be a GET no matter what the original
996 r->method = apr_pstrdup(r->pool, "GET");
997 r->method_number = M_GET;
999 /* We already read the message body (if any), so don't allow
1000 * the redirected request to think it has one. We can ignore
1001 * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR.
1003 apr_table_unset(r->headers_in, "Content-Length");
1005 ap_internal_redirect_handler(location, r);
1008 else if (location && r->status == 200) {
1009 /* XXX: Note that if a script wants to produce its own Redirect
1010 * body, it now has to explicitly *say* "Status: 302"
1012 return HTTP_MOVED_TEMPORARILY;
1015 rv = ap_pass_brigade(r->output_filters, bb);
1018 struct ap_filter_t *cur;
1020 /* get rid of all filters up through protocol... since we
1021 * haven't parsed off the headers, there is no way they can
1025 cur = r->proto_output_filters;
1026 while (cur && cur->frec->ftype < AP_FTYPE_CONNECTION) {
1029 r->output_filters = r->proto_output_filters = cur;
1031 rv = ap_pass_brigade(r->output_filters, bb);
1034 /* don't soak up script output if errors occurred writing it
1035 * out... otherwise, we prolong the life of the script when the
1036 * connection drops or we stopped sending output for some other
1038 if (rv == APR_SUCCESS && !r->connection->aborted) {
1039 apr_file_pipe_timeout_set(script_err, r->server->timeout);
1040 log_script_err(r, script_err);
1043 apr_file_close(script_err);
1045 return OK; /* NOT r->status, even if it has changed. */
1048 /*============================================================================
1049 *============================================================================
1050 * This is the beginning of the cgi filter code moved from mod_include. This
1051 * is the code required to handle the "exec" SSI directive.
1052 *============================================================================
1053 *============================================================================*/
1054 static apr_status_t include_cgi(include_ctx_t *ctx, ap_filter_t *f,
1055 apr_bucket_brigade *bb, char *s)
1057 request_rec *r = f->r;
1058 request_rec *rr = ap_sub_req_lookup_uri(s, r, f->next);
1061 if (rr->status != HTTP_OK) {
1062 ap_destroy_sub_req(rr);
1063 return APR_EGENERAL;
1066 /* No hardwired path info or query allowed */
1067 if ((rr->path_info && rr->path_info[0]) || rr->args) {
1068 ap_destroy_sub_req(rr);
1069 return APR_EGENERAL;
1071 if (rr->finfo.filetype != APR_REG) {
1072 ap_destroy_sub_req(rr);
1073 return APR_EGENERAL;
1076 /* Script gets parameters of the *document*, for back compatibility */
1077 rr->path_info = r->path_info; /* hard to get right; see mod_cgi.c */
1080 /* Force sub_req to be treated as a CGI request, even if ordinary
1081 * typing rules would have called it something else.
1083 ap_set_content_type(rr, CGI_MAGIC_TYPE);
1086 rr_status = ap_run_sub_req(rr);
1087 if (ap_is_HTTP_REDIRECT(rr_status)) {
1088 const char *location = apr_table_get(rr->headers_out, "Location");
1093 location = ap_escape_html(rr->pool, location);
1094 buffer = apr_pstrcat(ctx->pool, "<a href=\"", location, "\">",
1095 location, "</a>", NULL);
1097 APR_BRIGADE_INSERT_TAIL(bb, apr_bucket_pool_create(buffer,
1098 strlen(buffer), ctx->pool,
1099 f->c->bucket_alloc));
1103 ap_destroy_sub_req(rr);
1108 static apr_status_t include_cmd(include_ctx_t *ctx, ap_filter_t *f,
1109 apr_bucket_brigade *bb, const char *command)
1111 cgi_exec_info_t e_info;
1113 apr_file_t *script_out = NULL, *script_in = NULL, *script_err = NULL;
1115 request_rec *r = f->r;
1119 e_info.process_cgi = 0;
1120 e_info.cmd_type = APR_SHELLCMD;
1121 e_info.detached = 0;
1122 e_info.in_pipe = APR_NO_PIPE;
1123 e_info.out_pipe = APR_FULL_BLOCK;
1124 e_info.err_pipe = APR_NO_PIPE;
1125 e_info.prog_type = RUN_AS_SSI;
1128 e_info.next = f->next;
1129 e_info.addrspace = 0;
1131 if ((rv = cgi_build_command(&command, &argv, r, r->pool,
1132 &e_info)) != APR_SUCCESS) {
1133 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(01226)
1134 "don't know how to spawn cmd child process: %s",
1139 /* run the script in its own process */
1140 if ((rv = run_cgi_child(&script_out, &script_in, &script_err,
1141 command, argv, r, r->pool,
1142 &e_info)) != APR_SUCCESS) {
1143 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(01227)
1144 "couldn't spawn child process: %s", r->filename);
1148 APR_BRIGADE_INSERT_TAIL(bb, apr_bucket_pipe_create(script_in,
1149 f->c->bucket_alloc));
1152 /* We can't close the pipe here, because we may return before the
1153 * full CGI has been sent to the network. That's okay though,
1154 * because we can rely on the pool to close the pipe for us.
1159 static apr_status_t handle_exec(include_ctx_t *ctx, ap_filter_t *f,
1160 apr_bucket_brigade *bb)
1163 char *tag_val = NULL;
1164 request_rec *r = f->r;
1165 char *file = r->filename;
1166 char parsed_string[MAX_STRING_LEN];
1169 ap_log_rerror(APLOG_MARK,
1170 (ctx->flags & SSI_FLAG_PRINTING)
1171 ? APLOG_ERR : APLOG_WARNING,
1172 0, r, "missing argument for exec element in %s",
1176 if (!(ctx->flags & SSI_FLAG_PRINTING)) {
1181 SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
1185 if (ctx->flags & SSI_FLAG_NO_EXEC) {
1186 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01228) "exec used but not allowed "
1187 "in %s", r->filename);
1188 SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
1193 cgi_pfn_gtv(ctx, &tag, &tag_val, SSI_VALUE_DECODED);
1194 if (!tag || !tag_val) {
1198 if (!strcmp(tag, "cmd")) {
1201 cgi_pfn_ps(ctx, tag_val, parsed_string, sizeof(parsed_string),
1202 SSI_EXPAND_LEAVE_NAME);
1204 rv = include_cmd(ctx, f, bb, parsed_string);
1205 if (rv != APR_SUCCESS) {
1206 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01229) "execution failure "
1207 "for parameter \"%s\" to tag exec in file %s",
1209 SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
1213 else if (!strcmp(tag, "cgi")) {
1216 cgi_pfn_ps(ctx, tag_val, parsed_string, sizeof(parsed_string),
1217 SSI_EXPAND_DROP_NAME);
1219 rv = include_cgi(ctx, f, bb, parsed_string);
1220 if (rv != APR_SUCCESS) {
1221 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01230) "invalid CGI ref "
1222 "\"%s\" in %s", tag_val, file);
1223 SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
1228 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01231) "unknown parameter "
1229 "\"%s\" to tag exec in %s", tag, file);
1230 SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
1239 /*============================================================================
1240 *============================================================================
1241 * This is the end of the cgi filter code moved from mod_include.
1242 *============================================================================
1243 *============================================================================*/
1246 static int cgi_post_config(apr_pool_t *p, apr_pool_t *plog,
1247 apr_pool_t *ptemp, server_rec *s)
1249 cgi_pfn_reg_with_ssi = APR_RETRIEVE_OPTIONAL_FN(ap_register_include_handler);
1250 cgi_pfn_gtv = APR_RETRIEVE_OPTIONAL_FN(ap_ssi_get_tag_and_value);
1251 cgi_pfn_ps = APR_RETRIEVE_OPTIONAL_FN(ap_ssi_parse_string);
1253 if ((cgi_pfn_reg_with_ssi) && (cgi_pfn_gtv) && (cgi_pfn_ps)) {
1254 /* Required by mod_include filter. This is how mod_cgi registers
1255 * with mod_include to provide processing of the exec directive.
1257 cgi_pfn_reg_with_ssi("exec", handle_exec);
1260 /* This is the means by which unusual (non-unix) os's may find alternate
1261 * means to run a given command (e.g. shebang/registry parsing on Win32)
1263 cgi_build_command = APR_RETRIEVE_OPTIONAL_FN(ap_cgi_build_command);
1264 if (!cgi_build_command) {
1265 cgi_build_command = default_build_command;
1270 static void register_hooks(apr_pool_t *p)
1272 static const char * const aszPre[] = { "mod_include.c", NULL };
1273 ap_hook_handler(cgi_handler, NULL, NULL, APR_HOOK_MIDDLE);
1274 ap_hook_post_config(cgi_post_config, aszPre, NULL, APR_HOOK_REALLY_FIRST);
1277 AP_DECLARE_MODULE(cgi) =
1279 STANDARD20_MODULE_STUFF,
1280 NULL, /* dir config creater */
1281 NULL, /* dir merger --- default is to override */
1282 create_cgi_config, /* server config */
1283 merge_cgi_config, /* merge server config */
1284 cgi_cmds, /* command apr_table_t */
1285 register_hooks /* register hooks */