]> granicus.if.org Git - apache/blob - modules/generators/mod_cgi.c
This patch changes the apr_table_elts macro so that it provides
[apache] / modules / generators / mod_cgi.c
1 /* ====================================================================
2  * The Apache Software License, Version 1.1
3  *
4  * Copyright (c) 2000-2001 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     return NULL;
169 }
170
171 static const char *set_scriptlog_length(cmd_parms *cmd, void *dummy,
172                                         const char *arg)
173 {
174     server_rec *s = cmd->server;
175     cgi_server_conf *conf = ap_get_module_config(s->module_config,
176                                                  &cgi_module);
177
178     conf->logbytes = atol(arg);
179     return NULL;
180 }
181
182 static const char *set_scriptlog_buffer(cmd_parms *cmd, void *dummy,
183                                         const char *arg)
184 {
185     server_rec *s = cmd->server;
186     cgi_server_conf *conf = ap_get_module_config(s->module_config,
187                                                  &cgi_module);
188
189     conf->bufbytes = atoi(arg);
190     return NULL;
191 }
192
193 static const command_rec cgi_cmds[] =
194 {
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"),
201     {NULL}
202 };
203
204 static int log_scripterror(request_rec *r, cgi_server_conf * conf, int ret,
205                            apr_status_t rv, char *error)
206 {
207     apr_file_t *f = NULL;
208     apr_finfo_t finfo;
209     char time_str[APR_CTIME_LEN];
210     int log_flags = rv ? APLOG_ERR : APLOG_NOERRNO | APLOG_ERR;
211
212     ap_log_rerror(APLOG_MARK, log_flags, rv, r, 
213                   "%s: %s", error, r->filename);
214
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)
222               != APR_SUCCESS)) {
223         return ret;
224     }
225
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);
232
233     apr_file_printf(f, "%%error\n%s\n", error);
234
235     apr_file_close(f);
236     return ret;
237 }
238
239 /* Soak up stderr from a script and redirect it to the error log. 
240  */
241 static void log_script_err(request_rec *r, apr_file_t *script_err)
242 {
243     char argsbuffer[HUGE_STRING_LEN];
244     char *newline;
245
246     while (apr_file_gets(argsbuffer, HUGE_STRING_LEN, script_err) == 0) {
247         newline = strchr(argsbuffer, '\n');
248         if (newline) {
249             *newline = '\0';
250         }
251         ap_log_rerror(APLOG_MARK, APLOG_ERR | APLOG_NOERRNO, 0, r, 
252                       "%s", argsbuffer);            
253     }
254 }
255
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)
259 {
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;
264     int i;
265     apr_finfo_t finfo;
266     char time_str[APR_CTIME_LEN];
267
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)
277             continue;
278
279         log_script_err(r, script_err);
280         return ret;
281     }
282
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);
289
290     apr_file_puts("%request\n", f);
291     for (i = 0; i < hdrs_arr->nelts; ++i) {
292         if (!hdrs[i].key)
293             continue;
294         apr_file_printf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val);
295     }
296     if ((r->method_number == M_POST || r->method_number == M_PUT)
297         && *dbuf) {
298         apr_file_printf(f, "\n%s\n", dbuf);
299     }
300
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;
304
305     for (i = 0; i < hdrs_arr->nelts; ++i) {
306         if (!hdrs[i].key)
307             continue;
308         apr_file_printf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val);
309     }
310
311     if (sbuf && *sbuf)
312         apr_file_printf(f, "%s\n", sbuf);
313
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);
320     }
321
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);
328     }
329
330     apr_file_close(script_in);
331     apr_file_close(script_err);
332
333     apr_file_close(f);
334     return ret;
335 }
336
337
338 /* This is the special environment used for running the "exec cmd="
339  *   variety of SSI directives.
340  */
341 static void add_ssi_vars(request_rec *r, ap_filter_t *next)
342 {
343     apr_table_t *e = r->subprocess_env;
344
345     if (r->path_info && r->path_info[0] != '\0') {
346         request_rec *pa_req;
347
348         apr_table_setn(e, "PATH_INFO", ap_escape_shell_cmd(r->pool, r->path_info));
349
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));
354         }
355         ap_destroy_sub_req(pa_req);
356     }
357
358     if (r->args) {
359         char *arg_copy = apr_pstrdup(r->pool, r->args);
360
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));
364     }
365 }
366
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, 
370                                   const char *command,
371                                   const char * const argv[],
372                                   request_rec *r,
373                                   apr_pool_t *p,
374                                   exec_info *e_info)
375 {
376     const char * const *env;
377     apr_procattr_t *procattr;
378     apr_proc_t *procnew;
379     apr_status_t rc = APR_SUCCESS;
380
381 #if defined(RLIMIT_CPU)  || defined(RLIMIT_NPROC) || \
382     defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined (RLIMIT_AS)
383
384     core_dir_config *conf = ap_get_module_config(r->per_dir_config,
385                                                  &core_module);
386 #endif
387
388
389 #ifdef DEBUG_CGI
390 #ifdef OS2
391     /* Under OS/2 need to use device con. */
392     FILE *dbg = fopen("con", "w");
393 #else
394     FILE *dbg = fopen("/dev/tty", "w");
395 #endif
396     int i;
397 #endif
398
399     RAISE_SIGSTOP(CGI_CHILD);
400 #ifdef DEBUG_CGI
401     fprintf(dbg, "Attempting to exec %s as %sCGI child (argv0 = %s)\n",
402             r->filename, cld->nph ? "NPH " : "", argv0);
403 #endif
404
405     if (e_info->prog_type == RUN_AS_CGI) {
406         ap_add_cgi_vars(r);
407     }
408     else /* SSIs want a controlled environment and a special path. */
409     {
410         add_ssi_vars(r, e_info->next);
411     }
412     env = (const char * const *)ap_create_environment(p, r->subprocess_env);
413
414 #ifdef DEBUG_CGI
415     fprintf(dbg, "Environment: \n");
416     for (i = 0; env[i]; ++i)
417         fprintf(dbg, "'%s'\n", env[i]);
418 #endif
419
420     /* Transmute ourselves into the script.
421      * NB only ISINDEX scripts get decoded arguments.
422      */
423     if (((rc = apr_procattr_create(&procattr, p)) != APR_SUCCESS) ||
424         ((rc = apr_procattr_io_set(procattr,
425                                   e_info->in_pipe,
426                                   e_info->out_pipe,
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) ||
430 #ifdef RLIMIT_CPU
431         ((rc = apr_procattr_limit_set(procattr, APR_LIMIT_CPU, conf->limit_cpu)) != APR_SUCCESS) ||
432 #endif
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) ||
435 #endif
436 #ifdef RLIMIT_NPROC
437         ((rc = apr_procattr_limit_set(procattr, APR_LIMIT_NPROC, conf->limit_nproc)) != APR_SUCCESS) ||
438 #endif
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);
443     }
444     else {
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) {
449                 return rc;
450             }
451         }
452
453         rc = ap_os_create_privileged_process(r, procnew, command, argv, env, procattr, p);
454     
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);
459         }
460         else {
461             apr_pool_note_subprocess(p, procnew, kill_after_timeout);
462
463             *script_in = procnew->out;
464             if (!script_in)
465                 return APR_EBADF;
466             apr_file_pipe_timeout_set(*script_in, (int)(r->server->timeout * APR_USEC_PER_SEC));
467
468             if (e_info->prog_type == RUN_AS_CGI) {
469                 *script_out = procnew->in;
470                 if (!*script_out)
471                     return APR_EBADF;
472                 apr_file_pipe_timeout_set(*script_out, (int)(r->server->timeout * APR_USEC_PER_SEC));
473
474                 *script_err = procnew->err;
475                 if (!*script_err)
476                     return APR_EBADF;
477                 apr_file_pipe_timeout_set(*script_err, (int)(r->server->timeout * APR_USEC_PER_SEC));
478             }
479         }
480     }
481     return (rc);
482 }
483
484
485 static apr_status_t default_build_command(const char **cmd, const char ***argv,
486                                           request_rec *r, apr_pool_t *p)
487 {
488     int numwords, x, idx;
489     char *w;
490     const char *args = r->args;
491     const char *argv0;
492
493     /* Allow suexec's "/" check to succeed */
494     if ((argv0 = strrchr(r->filename, '/')) != NULL)
495         argv0++;
496     else
497         argv0 = r->filename;
498     *cmd = argv0;
499
500     if (!args || !args[0] || ap_strchr_c(args, '=')) {
501         numwords = 1;
502     }
503     else {
504         /* count the number of keywords */
505         for (x = 0, numwords = 2; args[x]; x++) {
506             if (args[x] == '+') {
507                 ++numwords;
508             }
509         }
510     }
511     /* Everything is - 1 to account for the first parameter 
512      * which is the program name.
513      */ 
514     if (numwords > APACHE_ARG_MAX - 1) {
515         numwords = APACHE_ARG_MAX - 1;  /* Truncate args to prevent overrun */
516     }
517     *argv = apr_palloc(p, (numwords + 2) * sizeof(char *));
518     (*argv)[0] = argv0;
519     for (x = 1, idx = 1; x < numwords; x++) {
520         w = ap_getword_nulls(p, &args, '+');
521         ap_unescape_url(w);
522         (*argv)[idx++] = ap_escape_shell_cmd(p, w);
523     }
524     (*argv)[idx] = NULL;
525
526     return APR_SUCCESS;
527 }
528
529
530 static int cgi_handler(request_rec *r)
531 {
532     int retval, nph, dbpos = 0;
533     const char *argv0;
534     const char *command;
535     const char **argv;
536     char *dbuf = NULL;
537     apr_file_t *script_out = NULL, *script_in = NULL, *script_err = NULL;
538     apr_bucket_brigade *bb;
539     apr_bucket *b;
540     char argsbuffer[HUGE_STRING_LEN];
541     int is_included = !strcmp(r->protocol, "INCLUDED");
542     apr_pool_t *p;
543     cgi_server_conf *conf;
544     apr_status_t rv;
545     exec_info e_info;
546
547     if(strcmp(r->handler,CGI_MAGIC_TYPE) && strcmp(r->handler,"cgi-script"))
548         return DECLINED;
549
550     p = r->main ? r->main->pool : r->pool;
551
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);
556         return DECLINED;
557     }
558
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);
562
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");
569
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");
576
577 /*
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");
582     }
583
584 */
585     if ((retval = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR)))
586         return retval;
587
588     ap_add_common_vars(r);
589
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", 
594                       r->filename);
595         return HTTP_INTERNAL_SERVER_ERROR;
596     }
597
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;
603     e_info.bb        = NULL;
604     e_info.ctx       = NULL;
605     e_info.next      = NULL;
606
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;
613     }
614
615     /* Transfer any put/post args, CERN style...
616      * Note that we already ignore SIGPIPE in the core server.
617      */
618     if (ap_should_client_block(r)) {
619         int len_read, dbsize;
620         apr_size_t bytes_written, bytes_to_write;
621         apr_status_t rv;
622
623         if (conf->logname) {
624             dbuf = apr_pcalloc(r->pool, conf->bufbytes + 1);
625             dbpos = 0;
626         }
627
628         while ((len_read =
629                 ap_get_client_block(r, argsbuffer, HUGE_STRING_LEN)) > 0) {
630             if (conf->logname) {
631                 if ((dbpos + len_read) > conf->bufbytes) {
632                     dbsize = conf->bufbytes - dbpos;
633                 }
634                 else {
635                     dbsize = len_read;
636                 }
637                 memcpy(dbuf + dbpos, argsbuffer, dbsize);
638                 dbpos += dbsize;
639             }
640             /* Keep writing data to the child until done or too much time
641              * elapses with no progress or an error occurs.
642              */
643             bytes_written = 0;
644             do {
645                 bytes_to_write = len_read - bytes_written;
646                 rv = apr_file_write(script_out, argsbuffer + bytes_written, 
647                                &bytes_to_write);
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) {
654                     /* dump it */
655                 }
656                 break;
657             }
658         }
659         apr_file_flush(script_out);
660     }
661
662     apr_file_close(script_out);
663
664     /* Handle script return... */
665     if (script_in && !nph) {
666         const char *location;
667         char sbuf[MAX_STRING_LEN];
668         int ret;
669
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);
672         }
673
674         location = apr_table_get(r->headers_out, "Location");
675
676         if (location && location[0] == '/' && r->status == 200) {
677
678             /* Soak up all the script output */
679             while (apr_file_gets(argsbuffer, HUGE_STRING_LEN, script_in) == 0) {
680                 continue;
681             }
682             log_script_err(r, script_err);
683             /* This redirect needs to be a GET no matter what the original
684              * method was.
685              */
686             r->method = apr_pstrdup(r->pool, "GET");
687             r->method_number = M_GET;
688
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.
692              */
693             apr_table_unset(r->headers_in, "Content-Length");
694
695             ap_internal_redirect_handler(location, r);
696             return OK;
697         }
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"
701              */
702             return HTTP_MOVED_TEMPORARILY;
703         }
704
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);
712         }
713
714         log_script_err(r, script_err);
715         apr_file_close(script_err);
716     }
717
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);
725     }
726
727     return OK;                  /* NOT r->status, even if it has changed. */
728 }
729
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)
738 {
739     request_rec *rr = ap_sub_req_lookup_uri(s, r, next);
740     int rr_status;
741     apr_bucket  *tmp_buck, *tmp2_buck;
742
743     if (rr->status != HTTP_OK) {
744         ap_destroy_sub_req(rr);
745         return -1;
746     }
747
748     /* No hardwired path info or query allowed */
749
750     if ((rr->path_info && rr->path_info[0]) || rr->args) {
751         ap_destroy_sub_req(rr);
752         return -1;
753     }
754     if (rr->finfo.filetype != APR_REG) {
755         ap_destroy_sub_req(rr);
756         return -1;
757     }
758
759     /* Script gets parameters of the *document*, for back compatibility */
760
761     rr->path_info = r->path_info;       /* hard to get right; see mod_cgi.c */
762     rr->args = r->args;
763
764     /* Force sub_req to be treated as a CGI request, even if ordinary
765      * typing rules would have called it something else.
766      */
767
768     rr->content_type = CGI_MAGIC_TYPE;
769
770     /* Run it. */
771
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");
776
777         location = ap_escape_html(rr->pool, location);
778         len_loc = strlen(location);
779
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);
790
791         if (*inserted_head == NULL) {
792             *inserted_head = tmp_buck;
793         }
794     }
795
796     ap_destroy_sub_req(rr);
797
798     return 0;
799 }
800
801
802 static int include_cmd(include_ctx_t *ctx, apr_bucket_brigade **bb,
803                        const char *command, request_rec *r, ap_filter_t *f)
804 {
805     exec_info      e_info;
806     const char   **argv;
807     apr_file_t    *script_out = NULL, *script_in = NULL, *script_err = NULL;
808     apr_bucket_brigade *bcgi;
809     apr_bucket *b;
810     apr_status_t rv;
811
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", 
815                       r->filename);
816         return HTTP_INTERNAL_SERVER_ERROR;
817     }
818
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;
824     e_info.bb        = bb;
825     e_info.ctx       = ctx;
826     e_info.next      = f->next;
827
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;
834     }
835
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);
840
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.
844      */
845
846     return 0;
847 }
848
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)
851 {
852     char *tag     = NULL;
853     char *tag_val = NULL;
854     char *file = r->filename;
855     apr_bucket  *tmp_buck;
856     char parsed_string[MAX_STRING_LEN];
857
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);
864         }
865         else {
866             while (1) {
867                 cgi_pfn_gtv(ctx, &tag, &tag_val, 1);
868                 if (tag_val == NULL) {
869                     if (tag == NULL) {
870                         return (0);
871                     }
872                     else {
873                         return 1;
874                     }
875                 }
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);
883                     }
884                 }
885                 else if (!strcmp(tag, "cgi")) {
886                     apr_status_t retval = APR_SUCCESS;
887
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) {
891                         return retval;
892                     }
893
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);
898                     }
899                 }
900                 else {
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);
904                 }
905             }
906         }
907     }
908     return 0;
909 }
910
911
912 /*============================================================================
913  *============================================================================
914  * This is the end of the cgi filter code moved from mod_include.
915  *============================================================================
916  *============================================================================*/
917
918
919 static void cgi_post_config(apr_pool_t *p, apr_pool_t *plog,
920                                 apr_pool_t *ptemp, server_rec *s)
921 {
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);
925
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.
929          */
930         cgi_pfn_reg_with_ssi("exec", handle_exec);
931     }
932
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)
935      */
936     cgi_build_command    = APR_RETRIEVE_OPTIONAL_FN(ap_cgi_build_command);
937     if (!cgi_build_command) {
938         cgi_build_command = default_build_command;
939     }
940 }
941
942 static void register_hooks(apr_pool_t *p)
943 {
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);
947 }
948
949 module AP_MODULE_DECLARE_DATA cgi_module =
950 {
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 */
958 };