]> granicus.if.org Git - apache/blob - modules/generators/mod_cgi.c
Trace the invoked command when we use CreateProcess()-style emulation
[apache] / modules / generators / mod_cgi.c
1 /* ====================================================================
2  * The Apache Software License, Version 1.1
3  *
4  * Copyright (c) 2000-2002 The Apache Software Foundation.  All rights
5  * reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  *
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
17  *    distribution.
18  *
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.
25  *
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.
30  *
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.
34  *
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
46  * SUCH DAMAGE.
47  * ====================================================================
48  *
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/>.
53  *
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.
57  */
58
59 /*
60  * http_script: keeps all script-related ramblings together.
61  * 
62  * Compliant to CGI/1.1 spec
63  * 
64  * Adapted by rst from original NCSA code by Rob McCool
65  *
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 
69  * they fail.
70  */
71
72 #include "apr.h"
73 #include "apr_strings.h"
74 #include "apr_thread_proc.h"    /* for RLIMIT stuff */
75 #include "apr_optional.h"
76 #include "apr_buckets.h"
77 #include "apr_lib.h"
78
79 #define APR_WANT_STRFUNC
80 #include "apr_want.h"
81
82 #define CORE_PRIVATE
83
84 #include "util_filter.h"
85 #include "ap_config.h"
86 #include "httpd.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"
92 #include "http_log.h"
93 #include "util_script.h"
94 #include "ap_mpm.h"
95 #include "mod_core.h"
96 #include "../filters/mod_include.h"
97 #include "mod_cgi.h"
98
99 module AP_MODULE_DECLARE_DATA cgi_module;
100
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;
105
106 typedef enum {RUN_AS_SSI, RUN_AS_CGI} prog_types;
107
108 typedef struct {
109     apr_int32_t          in_pipe;
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;
115     include_ctx_t       *ctx;
116     ap_filter_t         *next;
117 } exec_info;
118
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.
123  */
124
125 static int is_scriptaliased(request_rec *r)
126 {
127     const char *t = apr_table_get(r->notes, "alias-forced-type");
128     return t && (!strcasecmp(t, "cgi-script"));
129 }
130
131 /* Configuration stuff */
132
133 #define DEFAULT_LOGBYTES 10385760
134 #define DEFAULT_BUFBYTES 1024
135
136 typedef struct {
137     const char *logname;
138     long logbytes;
139     int bufbytes;
140 } cgi_server_conf;
141
142 static void *create_cgi_config(apr_pool_t *p, server_rec *s)
143 {
144     cgi_server_conf *c =
145     (cgi_server_conf *) apr_pcalloc(p, sizeof(cgi_server_conf));
146
147     c->logname = NULL;
148     c->logbytes = DEFAULT_LOGBYTES;
149     c->bufbytes = DEFAULT_BUFBYTES;
150
151     return c;
152 }
153
154 static void *merge_cgi_config(apr_pool_t *p, void *basev, void *overridesv)
155 {
156     cgi_server_conf *base = (cgi_server_conf *) basev, *overrides = (cgi_server_conf *) overridesv;
157
158     return overrides->logname ? overrides : base;
159 }
160
161 static const char *set_scriptlog(cmd_parms *cmd, void *dummy, const char *arg)
162 {
163     server_rec *s = cmd->server;
164     cgi_server_conf *conf = ap_get_module_config(s->module_config,
165                                                  &cgi_module);
166
167     conf->logname = ap_server_root_relative(cmd->pool, arg);
168
169     if (!conf->logname) {
170         return apr_pstrcat(cmd->pool, "Invalid ScriptLog path ",
171                            arg, NULL);
172     }
173
174     return NULL;
175 }
176
177 static const char *set_scriptlog_length(cmd_parms *cmd, void *dummy,
178                                         const char *arg)
179 {
180     server_rec *s = cmd->server;
181     cgi_server_conf *conf = ap_get_module_config(s->module_config,
182                                                  &cgi_module);
183
184     conf->logbytes = atol(arg);
185     return NULL;
186 }
187
188 static const char *set_scriptlog_buffer(cmd_parms *cmd, void *dummy,
189                                         const char *arg)
190 {
191     server_rec *s = cmd->server;
192     cgi_server_conf *conf = ap_get_module_config(s->module_config,
193                                                  &cgi_module);
194
195     conf->bufbytes = atoi(arg);
196     return NULL;
197 }
198
199 static const command_rec cgi_cmds[] =
200 {
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"),
207     {NULL}
208 };
209
210 static int log_scripterror(request_rec *r, cgi_server_conf * conf, int ret,
211                            apr_status_t rv, char *error)
212 {
213     apr_file_t *f = NULL;
214     apr_finfo_t finfo;
215     char time_str[APR_CTIME_LEN];
216     int log_flags = rv ? APLOG_ERR : APLOG_NOERRNO | APLOG_ERR;
217
218     ap_log_rerror(APLOG_MARK, log_flags, rv, r, 
219                   "%s: %s", error, r->filename);
220
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)
228               != APR_SUCCESS)) {
229         return ret;
230     }
231
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);
238
239     apr_file_printf(f, "%%error\n%s\n", error);
240
241     apr_file_close(f);
242     return ret;
243 }
244
245 /* Soak up stderr from a script and redirect it to the error log. 
246  */
247 static void log_script_err(request_rec *r, apr_file_t *script_err)
248 {
249     char argsbuffer[HUGE_STRING_LEN];
250     char *newline;
251
252     while (apr_file_gets(argsbuffer, HUGE_STRING_LEN,
253                          script_err) == APR_SUCCESS) {
254         newline = strchr(argsbuffer, '\n');
255         if (newline) {
256             *newline = '\0';
257         }
258         ap_log_rerror(APLOG_MARK, APLOG_ERR | APLOG_NOERRNO, 0, r, 
259                       "%s", argsbuffer);            
260     }
261 }
262
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)
266 {
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;
271     int i;
272     apr_finfo_t finfo;
273     char time_str[APR_CTIME_LEN];
274
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)
285             continue;
286
287         log_script_err(r, script_err);
288         return ret;
289     }
290
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);
297
298     apr_file_puts("%request\n", f);
299     for (i = 0; i < hdrs_arr->nelts; ++i) {
300         if (!hdrs[i].key)
301             continue;
302         apr_file_printf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val);
303     }
304     if ((r->method_number == M_POST || r->method_number == M_PUT)
305         && *dbuf) {
306         apr_file_printf(f, "\n%s\n", dbuf);
307     }
308
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;
312
313     for (i = 0; i < hdrs_arr->nelts; ++i) {
314         if (!hdrs[i].key)
315             continue;
316         apr_file_printf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val);
317     }
318
319     if (sbuf && *sbuf)
320         apr_file_printf(f, "%s\n", sbuf);
321
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);
329     }
330
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);
338     }
339
340     apr_file_close(script_in);
341     apr_file_close(script_err);
342
343     apr_file_close(f);
344     return ret;
345 }
346
347
348 /* This is the special environment used for running the "exec cmd="
349  *   variety of SSI directives.
350  */
351 static void add_ssi_vars(request_rec *r, ap_filter_t *next)
352 {
353     apr_table_t *e = r->subprocess_env;
354
355     if (r->path_info && r->path_info[0] != '\0') {
356         request_rec *pa_req;
357
358         apr_table_setn(e, "PATH_INFO", ap_escape_shell_cmd(r->pool, r->path_info));
359
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));
364         }
365         ap_destroy_sub_req(pa_req);
366     }
367
368     if (r->args) {
369         char *arg_copy = apr_pstrdup(r->pool, r->args);
370
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));
374     }
375 }
376
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, 
380                                   const char *command,
381                                   const char * const argv[],
382                                   request_rec *r,
383                                   apr_pool_t *p,
384                                   exec_info *e_info)
385 {
386     const char * const *env;
387     apr_procattr_t *procattr;
388     apr_proc_t *procnew;
389     apr_status_t rc = APR_SUCCESS;
390
391 #if defined(RLIMIT_CPU)  || defined(RLIMIT_NPROC) || \
392     defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined (RLIMIT_AS)
393
394     core_dir_config *conf = ap_get_module_config(r->per_dir_config,
395                                                  &core_module);
396 #endif
397
398
399 #ifdef DEBUG_CGI
400 #ifdef OS2
401     /* Under OS/2 need to use device con. */
402     FILE *dbg = fopen("con", "w");
403 #else
404     FILE *dbg = fopen("/dev/tty", "w");
405 #endif
406     int i;
407 #endif
408
409     RAISE_SIGSTOP(CGI_CHILD);
410 #ifdef DEBUG_CGI
411     fprintf(dbg, "Attempting to exec %s as CGI child (argv0 = %s)\n",
412             r->filename, argv[0]);
413 #endif
414
415     if (e_info->prog_type == RUN_AS_CGI) {
416         ap_add_cgi_vars(r);
417     }
418     else /* SSIs want a controlled environment and a special path. */
419     {
420         add_ssi_vars(r, e_info->next);
421     }
422     env = (const char * const *)ap_create_environment(p, r->subprocess_env);
423
424 #ifdef DEBUG_CGI
425     fprintf(dbg, "Environment: \n");
426     for (i = 0; env[i]; ++i)
427         fprintf(dbg, "'%s'\n", env[i]);
428 #endif
429
430     /* Transmute ourselves into the script.
431      * NB only ISINDEX scripts get decoded arguments.
432      */
433     if (((rc = apr_procattr_create(&procattr, p)) != APR_SUCCESS) ||
434         ((rc = apr_procattr_io_set(procattr,
435                                   e_info->in_pipe,
436                                   e_info->out_pipe,
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) ||
440 #ifdef RLIMIT_CPU
441         ((rc = apr_procattr_limit_set(procattr, APR_LIMIT_CPU, conf->limit_cpu)) != APR_SUCCESS) ||
442 #endif
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) ||
445 #endif
446 #ifdef RLIMIT_NPROC
447         ((rc = apr_procattr_limit_set(procattr, APR_LIMIT_NPROC, conf->limit_nproc)) != APR_SUCCESS) ||
448 #endif
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);
453     }
454     else {
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) {
459                 return rc;
460             }
461         }
462
463         rc = ap_os_create_privileged_process(r, procnew, command, argv, env, procattr, p);
464     
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", 
471                               procnew->invoked);
472             }
473             else
474 #endif
475             ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r,
476                           "mod_cgi: couldn't create child process: %s",
477                           r->filename);
478         }
479         else {
480             apr_pool_note_subprocess(p, procnew, APR_KILL_AFTER_TIMEOUT);
481
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", 
486                               procnew->invoked);
487             }
488 #endif
489
490             *script_in = procnew->out;
491             if (!*script_in)
492                 return APR_EBADF;
493             apr_file_pipe_timeout_set(*script_in, (int)(r->server->timeout * APR_USEC_PER_SEC));
494
495             if (e_info->prog_type == RUN_AS_CGI) {
496                 *script_out = procnew->in;
497                 if (!*script_out)
498                     return APR_EBADF;
499                 apr_file_pipe_timeout_set(*script_out, (int)(r->server->timeout * APR_USEC_PER_SEC));
500
501                 *script_err = procnew->err;
502                 if (!*script_err)
503                     return APR_EBADF;
504                 apr_file_pipe_timeout_set(*script_err, (int)(r->server->timeout * APR_USEC_PER_SEC));
505             }
506         }
507     }
508 #ifdef DEBUG_CGI
509     fclose(dbg);
510 #endif
511     return (rc);
512 }
513
514
515 static apr_status_t default_build_command(const char **cmd, const char ***argv,
516                                           request_rec *r, apr_pool_t *p,
517                                           int replace_cmd)
518 {
519     int numwords, x, idx;
520     char *w;
521     const char *args = r->args;
522     const char *argv0;
523
524     if (replace_cmd) {
525         /* Allow suexec's "/" check to succeed */
526         if ((argv0 = strrchr(r->filename, '/')) != NULL)
527             argv0++;
528         else
529             argv0 = r->filename;
530         *cmd = argv0;
531     }
532
533     if (!args || !args[0] || ap_strchr_c(args, '=')) {
534         numwords = 1;
535     }
536     else {
537         /* count the number of keywords */
538         for (x = 0, numwords = 2; args[x]; x++) {
539             if (args[x] == '+') {
540                 ++numwords;
541             }
542         }
543     }
544     /* Everything is - 1 to account for the first parameter 
545      * which is the program name.
546      */ 
547     if (numwords > APACHE_ARG_MAX - 1) {
548         numwords = APACHE_ARG_MAX - 1;  /* Truncate args to prevent overrun */
549     }
550     *argv = apr_palloc(p, (numwords + 2) * sizeof(char *));
551     (*argv)[0] = *cmd;
552     for (x = 1, idx = 1; x < numwords; x++) {
553         w = ap_getword_nulls(p, &args, '+');
554         ap_unescape_url(w);
555         (*argv)[idx++] = ap_escape_shell_cmd(p, w);
556     }
557     (*argv)[idx] = NULL;
558
559     return APR_SUCCESS;
560 }
561
562
563 static int cgi_handler(request_rec *r)
564 {
565     int retval, nph, dbpos = 0;
566     const char *argv0;
567     const char *command;
568     const char **argv;
569     char *dbuf = NULL;
570     apr_file_t *script_out = NULL, *script_in = NULL, *script_err = NULL;
571     apr_bucket_brigade *bb;
572     apr_bucket *b;
573     char argsbuffer[HUGE_STRING_LEN];
574     int is_included;
575     apr_pool_t *p;
576     cgi_server_conf *conf;
577     apr_status_t rv;
578     exec_info e_info;
579
580     if(strcmp(r->handler,CGI_MAGIC_TYPE) && strcmp(r->handler,"cgi-script"))
581         return DECLINED;
582
583     is_included = !strcmp(r->protocol, "INCLUDED");
584
585     p = r->main ? r->main->pool : r->pool;
586
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);
591         return DECLINED;
592     }
593
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);
597
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");
604
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");
611
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");
615     }
616 /*
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");
621     }
622
623 */
624     if ((retval = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR)))
625         return retval;
626
627     ap_add_common_vars(r);
628
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", 
633                       r->filename);
634         return HTTP_INTERNAL_SERVER_ERROR;
635     }
636
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;
642     e_info.bb        = NULL;
643     e_info.ctx       = NULL;
644     e_info.next      = NULL;
645
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;
652     }
653
654     /* Transfer any put/post args, CERN style...
655      * Note that we already ignore SIGPIPE in the core server.
656      */
657     if (ap_should_client_block(r)) {
658         int len_read, dbsize;
659         apr_size_t bytes_written, bytes_to_write;
660         apr_status_t rv;
661
662         if (conf->logname) {
663             dbuf = apr_pcalloc(r->pool, conf->bufbytes + 1);
664             dbpos = 0;
665         }
666
667         while ((len_read =
668                 ap_get_client_block(r, argsbuffer, HUGE_STRING_LEN)) > 0) {
669             if (conf->logname) {
670                 if ((dbpos + len_read) > conf->bufbytes) {
671                     dbsize = conf->bufbytes - dbpos;
672                 }
673                 else {
674                     dbsize = len_read;
675                 }
676                 memcpy(dbuf + dbpos, argsbuffer, dbsize);
677                 dbpos += dbsize;
678             }
679             /* Keep writing data to the child until done or too much time
680              * elapses with no progress or an error occurs.
681              */
682             bytes_written = 0;
683             do {
684                 bytes_to_write = len_read - bytes_written;
685                 rv = apr_file_write(script_out, argsbuffer + bytes_written, 
686                                &bytes_to_write);
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) {
693                     /* dump it */
694                 }
695                 break;
696             }
697         }
698         apr_file_flush(script_out);
699     }
700
701     apr_file_close(script_out);
702
703     /* Handle script return... */
704     if (script_in && !nph) {
705         const char *location;
706         char sbuf[MAX_STRING_LEN];
707         int ret;
708
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);
711         }
712
713         location = apr_table_get(r->headers_out, "Location");
714
715         if (location && location[0] == '/' && r->status == 200) {
716
717             /* Soak up all the script output */
718             while (apr_file_gets(argsbuffer, HUGE_STRING_LEN,
719                                  script_in) == APR_SUCCESS) {
720                 continue;
721             }
722             log_script_err(r, script_err);
723             /* This redirect needs to be a GET no matter what the original
724              * method was.
725              */
726             r->method = apr_pstrdup(r->pool, "GET");
727             r->method_number = M_GET;
728
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.
732              */
733             apr_table_unset(r->headers_in, "Content-Length");
734
735             ap_internal_redirect_handler(location, r);
736             return OK;
737         }
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"
741              */
742             return HTTP_MOVED_TEMPORARILY;
743         }
744
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);
752         }
753
754         log_script_err(r, script_err);
755         apr_file_close(script_err);
756     }
757
758     if (script_in && nph) {
759         struct ap_filter_t *cur;
760         
761         /* get rid of all filters up through protocol...  since we
762          * haven't parsed off the headers, there is no way they can
763          * work
764          */
765
766         cur = r->proto_output_filters;
767         while (cur && cur->frec->ftype < AP_FTYPE_CONNECTION) {
768             cur = cur->next;
769         }
770         r->output_filters = r->proto_output_filters = cur;
771
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);
778     }
779
780     return OK;                  /* NOT r->status, even if it has changed. */
781 }
782
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)
791 {
792     request_rec *rr = ap_sub_req_lookup_uri(s, r, next);
793     int rr_status;
794     apr_bucket  *tmp_buck, *tmp2_buck;
795
796     if (rr->status != HTTP_OK) {
797         ap_destroy_sub_req(rr);
798         return -1;
799     }
800
801     /* No hardwired path info or query allowed */
802
803     if ((rr->path_info && rr->path_info[0]) || rr->args) {
804         ap_destroy_sub_req(rr);
805         return -1;
806     }
807     if (rr->finfo.filetype != APR_REG) {
808         ap_destroy_sub_req(rr);
809         return -1;
810     }
811
812     /* Script gets parameters of the *document*, for back compatibility */
813
814     rr->path_info = r->path_info;       /* hard to get right; see mod_cgi.c */
815     rr->args = r->args;
816
817     /* Force sub_req to be treated as a CGI request, even if ordinary
818      * typing rules would have called it something else.
819      */
820
821     ap_set_content_type(rr, CGI_MAGIC_TYPE);
822
823     /* Run it. */
824
825     rr_status = ap_run_sub_req(rr);
826     if (ap_is_HTTP_REDIRECT(rr_status)) {
827         apr_size_t len_loc;
828         const char *location = apr_table_get(rr->headers_out, "Location");
829
830         location = ap_escape_html(rr->pool, location);
831         len_loc = strlen(location);
832
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 */
836
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);
848
849         if (*inserted_head == NULL) {
850             *inserted_head = tmp_buck;
851         }
852     }
853
854     ap_destroy_sub_req(rr);
855
856     return 0;
857 }
858
859
860 static int include_cmd(include_ctx_t *ctx, apr_bucket_brigade **bb,
861                        const char *command, request_rec *r, ap_filter_t *f)
862 {
863     exec_info      e_info;
864     const char   **argv;
865     apr_file_t    *script_out = NULL, *script_in = NULL, *script_err = NULL;
866     apr_bucket_brigade *bcgi;
867     apr_bucket *b;
868     apr_status_t rv;
869
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", 
873                       r->filename);
874         return HTTP_INTERNAL_SERVER_ERROR;
875     }
876
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;
882     e_info.bb        = bb;
883     e_info.ctx       = ctx;
884     e_info.next      = f->next;
885
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;
892     }
893
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);
898
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.
902      */
903
904     return 0;
905 }
906
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)
909 {
910     char *tag     = NULL;
911     char *tag_val = NULL;
912     char *file = r->filename;
913     apr_bucket  *tmp_buck;
914     char parsed_string[MAX_STRING_LEN];
915
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);
922         }
923         else {
924             while (1) {
925                 cgi_pfn_gtv(ctx, &tag, &tag_val, 1);
926                 if (tag_val == NULL) {
927                     if (tag == NULL) {
928                         return (0);
929                     }
930                     else {
931                         return 1;
932                     }
933                 }
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);
941                     }
942                 }
943                 else if (!strcmp(tag, "cgi")) {
944                     apr_status_t retval = APR_SUCCESS;
945
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) {
949                         return retval;
950                     }
951
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);
956                     }
957                 }
958                 else {
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);
962                 }
963             }
964         }
965     }
966     return 0;
967 }
968
969
970 /*============================================================================
971  *============================================================================
972  * This is the end of the cgi filter code moved from mod_include.
973  *============================================================================
974  *============================================================================*/
975
976
977 static int cgi_post_config(apr_pool_t *p, apr_pool_t *plog,
978                                 apr_pool_t *ptemp, server_rec *s)
979 {
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);
983
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.
987          */
988         cgi_pfn_reg_with_ssi("exec", handle_exec);
989     }
990
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)
993      */
994     cgi_build_command    = APR_RETRIEVE_OPTIONAL_FN(ap_cgi_build_command);
995     if (!cgi_build_command) {
996         cgi_build_command = default_build_command;
997     }
998     return OK;
999 }
1000
1001 static void register_hooks(apr_pool_t *p)
1002 {
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);
1006 }
1007
1008 module AP_MODULE_DECLARE_DATA cgi_module =
1009 {
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 */
1017 };