]> granicus.if.org Git - apache/blob - modules/generators/mod_cgi.c
* server/util_filter.c (ap_save_brigade): Handle an ENOTIMPL setaside
[apache] / modules / generators / mod_cgi.c
1 /* Copyright 1999-2004 The Apache Software Foundation
2  *
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15
16 /*
17  * http_script: keeps all script-related ramblings together.
18  * 
19  * Compliant to CGI/1.1 spec
20  * 
21  * Adapted by rst from original NCSA code by Rob McCool
22  *
23  * Apache adds some new env vars; REDIRECT_URL and REDIRECT_QUERY_STRING for
24  * custom error responses, and DOCUMENT_ROOT because we found it useful.
25  * It also adds SERVER_ADMIN - useful for scripts to know who to mail when 
26  * they fail.
27  */
28
29 #include "apr.h"
30 #include "apr_strings.h"
31 #include "apr_thread_proc.h"    /* for RLIMIT stuff */
32 #include "apr_optional.h"
33 #include "apr_buckets.h"
34 #include "apr_lib.h"
35 #include "apr_poll.h"
36
37 #define APR_WANT_STRFUNC
38 #define APR_WANT_MEMFUNC
39 #include "apr_want.h"
40
41 #define CORE_PRIVATE
42
43 #include "util_filter.h"
44 #include "ap_config.h"
45 #include "httpd.h"
46 #include "http_config.h"
47 #include "http_request.h"
48 #include "http_core.h"
49 #include "http_protocol.h"
50 #include "http_main.h"
51 #include "http_log.h"
52 #include "util_script.h"
53 #include "ap_mpm.h"
54 #include "mod_core.h"
55 #include "mod_cgi.h"
56
57 module AP_MODULE_DECLARE_DATA cgi_module;
58
59 static APR_OPTIONAL_FN_TYPE(ap_register_include_handler) *cgi_pfn_reg_with_ssi;
60 static APR_OPTIONAL_FN_TYPE(ap_ssi_get_tag_and_value) *cgi_pfn_gtv;
61 static APR_OPTIONAL_FN_TYPE(ap_ssi_parse_string) *cgi_pfn_ps;
62 static APR_OPTIONAL_FN_TYPE(ap_cgi_build_command) *cgi_build_command;
63
64 /* Read and discard the data in the brigade produced by a CGI script */
65 static void discard_script_output(apr_bucket_brigade *bb);
66
67 /* KLUDGE --- for back-combatibility, we don't have to check ExecCGI
68  * in ScriptAliased directories, which means we need to know if this
69  * request came through ScriptAlias or not... so the Alias module
70  * leaves a note for us.
71  */
72
73 static int is_scriptaliased(request_rec *r)
74 {
75     const char *t = apr_table_get(r->notes, "alias-forced-type");
76     return t && (!strcasecmp(t, "cgi-script"));
77 }
78
79 /* Configuration stuff */
80
81 #define DEFAULT_LOGBYTES 10385760
82 #define DEFAULT_BUFBYTES 1024
83
84 typedef struct {
85     const char *logname;
86     long        logbytes;
87     apr_size_t  bufbytes;
88 } cgi_server_conf;
89
90 static void *create_cgi_config(apr_pool_t *p, server_rec *s)
91 {
92     cgi_server_conf *c =
93     (cgi_server_conf *) apr_pcalloc(p, sizeof(cgi_server_conf));
94
95     c->logname = NULL;
96     c->logbytes = DEFAULT_LOGBYTES;
97     c->bufbytes = DEFAULT_BUFBYTES;
98
99     return c;
100 }
101
102 static void *merge_cgi_config(apr_pool_t *p, void *basev, void *overridesv)
103 {
104     cgi_server_conf *base = (cgi_server_conf *) basev,
105                     *overrides = (cgi_server_conf *) overridesv;
106
107     return overrides->logname ? overrides : base;
108 }
109
110 static const char *set_scriptlog(cmd_parms *cmd, void *dummy, const char *arg)
111 {
112     server_rec *s = cmd->server;
113     cgi_server_conf *conf = ap_get_module_config(s->module_config,
114                                                  &cgi_module);
115
116     conf->logname = ap_server_root_relative(cmd->pool, arg);
117
118     if (!conf->logname) {
119         return apr_pstrcat(cmd->pool, "Invalid ScriptLog path ",
120                            arg, NULL);
121     }
122
123     return NULL;
124 }
125
126 static const char *set_scriptlog_length(cmd_parms *cmd, void *dummy,
127                                         const char *arg)
128 {
129     server_rec *s = cmd->server;
130     cgi_server_conf *conf = ap_get_module_config(s->module_config,
131                                                  &cgi_module);
132
133     conf->logbytes = atol(arg);
134     return NULL;
135 }
136
137 static const char *set_scriptlog_buffer(cmd_parms *cmd, void *dummy,
138                                         const char *arg)
139 {
140     server_rec *s = cmd->server;
141     cgi_server_conf *conf = ap_get_module_config(s->module_config,
142                                                  &cgi_module);
143
144     conf->bufbytes = atoi(arg);
145     return NULL;
146 }
147
148 static const command_rec cgi_cmds[] =
149 {
150 AP_INIT_TAKE1("ScriptLog", set_scriptlog, NULL, RSRC_CONF,
151      "the name of a log for script debugging info"),
152 AP_INIT_TAKE1("ScriptLogLength", set_scriptlog_length, NULL, RSRC_CONF,
153      "the maximum length (in bytes) of the script debug log"),
154 AP_INIT_TAKE1("ScriptLogBuffer", set_scriptlog_buffer, NULL, RSRC_CONF,
155      "the maximum size (in bytes) to record of a POST request"),
156     {NULL}
157 };
158
159 static int log_scripterror(request_rec *r, cgi_server_conf * conf, int ret,
160                            apr_status_t rv, char *error)
161 {
162     apr_file_t *f = NULL;
163     apr_finfo_t finfo;
164     char time_str[APR_CTIME_LEN];
165     int log_flags = rv ? APLOG_ERR : APLOG_ERR;
166
167     ap_log_rerror(APLOG_MARK, log_flags, rv, r, 
168                   "%s: %s", error, r->filename);
169
170     /* XXX Very expensive mainline case! Open, then getfileinfo! */
171     if (!conf->logname ||
172         ((apr_stat(&finfo, conf->logname,
173                    APR_FINFO_SIZE, r->pool) == APR_SUCCESS) &&
174          (finfo.size > conf->logbytes)) ||
175         (apr_file_open(&f, conf->logname,
176                        APR_APPEND|APR_WRITE|APR_CREATE, APR_OS_DEFAULT,
177                        r->pool) != APR_SUCCESS)) {
178         return ret;
179     }
180
181     /* "%% [Wed Jun 19 10:53:21 1996] GET /cgi-bin/printenv HTTP/1.0" */
182     apr_ctime(time_str, apr_time_now());
183     apr_file_printf(f, "%%%% [%s] %s %s%s%s %s\n", time_str, r->method, r->uri,
184                     r->args ? "?" : "", r->args ? r->args : "", r->protocol);
185     /* "%% 500 /usr/local/apache/cgi-bin */
186     apr_file_printf(f, "%%%% %d %s\n", ret, r->filename);
187
188     apr_file_printf(f, "%%error\n%s\n", error);
189
190     apr_file_close(f);
191     return ret;
192 }
193
194 /* Soak up stderr from a script and redirect it to the error log. 
195  */
196 static apr_status_t log_script_err(request_rec *r, apr_file_t *script_err)
197 {
198     char argsbuffer[HUGE_STRING_LEN];
199     char *newline;
200     apr_status_t rv;
201
202     while ((rv = apr_file_gets(argsbuffer, HUGE_STRING_LEN,
203                                script_err)) == APR_SUCCESS) {
204         newline = strchr(argsbuffer, '\n');
205         if (newline) {
206             *newline = '\0';
207         }
208         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, 
209                       "%s", argsbuffer);            
210     }
211
212     return rv;
213 }
214
215 static int log_script(request_rec *r, cgi_server_conf * conf, int ret,
216                       char *dbuf, const char *sbuf, apr_bucket_brigade *bb, 
217                       apr_file_t *script_err)
218 {
219     const apr_array_header_t *hdrs_arr = apr_table_elts(r->headers_in);
220     const apr_table_entry_t *hdrs = (const apr_table_entry_t *) hdrs_arr->elts;
221     char argsbuffer[HUGE_STRING_LEN];
222     apr_file_t *f = NULL;
223     apr_bucket *e;
224     const char *buf;
225     apr_size_t len;
226     apr_status_t rv;
227     int first;
228     int i;
229     apr_finfo_t finfo;
230     char time_str[APR_CTIME_LEN];
231
232     /* XXX Very expensive mainline case! Open, then getfileinfo! */
233     if (!conf->logname ||
234         ((apr_stat(&finfo, conf->logname,
235                    APR_FINFO_SIZE, r->pool) == APR_SUCCESS) &&
236          (finfo.size > conf->logbytes)) ||
237         (apr_file_open(&f, conf->logname,
238                        APR_APPEND|APR_WRITE|APR_CREATE, APR_OS_DEFAULT,
239                        r->pool) != APR_SUCCESS)) {
240         /* Soak up script output */
241         discard_script_output(bb);
242         log_script_err(r, script_err);
243         return ret;
244     }
245
246     /* "%% [Wed Jun 19 10:53:21 1996] GET /cgi-bin/printenv HTTP/1.0" */
247     apr_ctime(time_str, apr_time_now());
248     apr_file_printf(f, "%%%% [%s] %s %s%s%s %s\n", time_str, r->method, r->uri,
249                     r->args ? "?" : "", r->args ? r->args : "", r->protocol);
250     /* "%% 500 /usr/local/apache/cgi-bin" */
251     apr_file_printf(f, "%%%% %d %s\n", ret, r->filename);
252
253     apr_file_puts("%request\n", f);
254     for (i = 0; i < hdrs_arr->nelts; ++i) {
255         if (!hdrs[i].key)
256             continue;
257         apr_file_printf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val);
258     }
259     if ((r->method_number == M_POST || r->method_number == M_PUT) &&
260         *dbuf) {
261         apr_file_printf(f, "\n%s\n", dbuf);
262     }
263
264     apr_file_puts("%response\n", f);
265     hdrs_arr = apr_table_elts(r->err_headers_out);
266     hdrs = (const apr_table_entry_t *) hdrs_arr->elts;
267
268     for (i = 0; i < hdrs_arr->nelts; ++i) {
269         if (!hdrs[i].key)
270             continue;
271         apr_file_printf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val);
272     }
273
274     if (sbuf && *sbuf)
275         apr_file_printf(f, "%s\n", sbuf);
276
277     first = 1;
278     for (e = APR_BRIGADE_FIRST(bb);
279          e != APR_BRIGADE_SENTINEL(bb);
280          e = APR_BUCKET_NEXT(e))
281     {
282         if (APR_BUCKET_IS_EOS(e)) {
283             break;
284         }
285         rv = apr_bucket_read(e, &buf, &len, APR_BLOCK_READ);
286         if (rv != APR_SUCCESS || (len == 0)) {
287             break;
288         }
289         if (first) {
290             apr_file_puts("%stdout\n", f);
291             first = 0;
292         }
293         apr_file_write(f, buf, &len);
294         apr_file_puts("\n", f);
295     }
296
297     if (apr_file_gets(argsbuffer, HUGE_STRING_LEN, script_err) == APR_SUCCESS) {
298         apr_file_puts("%stderr\n", f);
299         apr_file_puts(argsbuffer, f);
300         while (apr_file_gets(argsbuffer, HUGE_STRING_LEN,
301                              script_err) == APR_SUCCESS) {
302             apr_file_puts(argsbuffer, f);
303         }
304         apr_file_puts("\n", f);
305     }
306
307     apr_brigade_destroy(bb);
308     apr_file_close(script_err);
309
310     apr_file_close(f);
311     return ret;
312 }
313
314
315 /* This is the special environment used for running the "exec cmd="
316  *   variety of SSI directives.
317  */
318 static void add_ssi_vars(request_rec *r)
319 {
320     apr_table_t *e = r->subprocess_env;
321
322     if (r->path_info && r->path_info[0] != '\0') {
323         request_rec *pa_req;
324
325         apr_table_setn(e, "PATH_INFO", ap_escape_shell_cmd(r->pool,
326                                                            r->path_info));
327
328         pa_req = ap_sub_req_lookup_uri(ap_escape_uri(r->pool, r->path_info),
329                                        r, NULL);
330         if (pa_req->filename) {
331             apr_table_setn(e, "PATH_TRANSLATED",
332                            apr_pstrcat(r->pool, pa_req->filename,
333                                        pa_req->path_info, NULL));
334         }
335         ap_destroy_sub_req(pa_req);
336     }
337
338     if (r->args) {
339         char *arg_copy = apr_pstrdup(r->pool, r->args);
340
341         apr_table_setn(e, "QUERY_STRING", r->args);
342         ap_unescape_url(arg_copy);
343         apr_table_setn(e, "QUERY_STRING_UNESCAPED",
344                        ap_escape_shell_cmd(r->pool, arg_copy));
345     }
346 }
347
348 static void cgi_child_errfn(apr_pool_t *pool, apr_status_t err,
349                             const char *description)
350 {
351     apr_file_t *stderr_log;
352     char errbuf[200];
353
354     apr_file_open_stderr(&stderr_log, pool);
355     /* Escape the logged string because it may be something that
356      * came in over the network.
357      */
358     apr_file_printf(stderr_log,
359                     "(%d)%s: %s\n",
360                     err,
361                     apr_strerror(err, errbuf, sizeof(errbuf)),
362 #ifndef AP_UNSAFE_ERROR_LOG_UNESCAPED
363                     ap_escape_logitem(pool,
364 #endif
365                     description
366 #ifndef AP_UNSAFE_ERROR_LOG_UNESCAPED
367                     )
368 #endif
369                     );
370 }
371
372 static apr_status_t run_cgi_child(apr_file_t **script_out,
373                                   apr_file_t **script_in,
374                                   apr_file_t **script_err, 
375                                   const char *command,
376                                   const char * const argv[],
377                                   request_rec *r,
378                                   apr_pool_t *p,
379                                   cgi_exec_info_t *e_info)
380 {
381     const char * const *env;
382     apr_procattr_t *procattr;
383     apr_proc_t *procnew;
384     apr_status_t rc = APR_SUCCESS;
385
386 #if defined(RLIMIT_CPU)  || defined(RLIMIT_NPROC) || \
387     defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined (RLIMIT_AS)
388
389     core_dir_config *conf = ap_get_module_config(r->per_dir_config,
390                                                  &core_module);
391 #endif
392
393 #ifdef DEBUG_CGI
394 #ifdef OS2
395     /* Under OS/2 need to use device con. */
396     FILE *dbg = fopen("con", "w");
397 #else
398     FILE *dbg = fopen("/dev/tty", "w");
399 #endif
400     int i;
401 #endif
402
403     RAISE_SIGSTOP(CGI_CHILD);
404 #ifdef DEBUG_CGI
405     fprintf(dbg, "Attempting to exec %s as CGI child (argv0 = %s)\n",
406             r->filename, argv[0]);
407 #endif
408
409     env = (const char * const *)ap_create_environment(p, r->subprocess_env);
410
411 #ifdef DEBUG_CGI
412     fprintf(dbg, "Environment: \n");
413     for (i = 0; env[i]; ++i)
414         fprintf(dbg, "'%s'\n", env[i]);
415 #endif
416
417     /* Transmute ourselves into the script.
418      * NB only ISINDEX scripts get decoded arguments.
419      */
420     if (((rc = apr_procattr_create(&procattr, p)) != APR_SUCCESS) ||
421         ((rc = apr_procattr_io_set(procattr,
422                                    e_info->in_pipe,
423                                    e_info->out_pipe,
424                                    e_info->err_pipe)) != APR_SUCCESS) ||
425         ((rc = apr_procattr_dir_set(procattr, 
426                         ap_make_dirstr_parent(r->pool,
427                                               r->filename))) != APR_SUCCESS) ||
428 #ifdef RLIMIT_CPU
429         ((rc = apr_procattr_limit_set(procattr, APR_LIMIT_CPU,
430                                       conf->limit_cpu)) != APR_SUCCESS) ||
431 #endif
432 #if defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
433         ((rc = apr_procattr_limit_set(procattr, APR_LIMIT_MEM,
434                                       conf->limit_mem)) != APR_SUCCESS) ||
435 #endif
436 #ifdef RLIMIT_NPROC
437         ((rc = apr_procattr_limit_set(procattr, APR_LIMIT_NPROC,
438                                       conf->limit_nproc)) != APR_SUCCESS) ||
439 #endif
440         ((rc = apr_procattr_cmdtype_set(procattr,
441                                         e_info->cmd_type)) != APR_SUCCESS) ||
442
443         ((rc = apr_procattr_detach_set(procattr,
444                                         e_info->detached)) != APR_SUCCESS) ||
445         ((rc = apr_procattr_addrspace_set(procattr,
446                                         e_info->addrspace)) != APR_SUCCESS) ||
447         ((rc = apr_procattr_child_errfn_set(procattr, cgi_child_errfn)) != APR_SUCCESS)) {
448         /* Something bad happened, tell the world. */
449         ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r,
450                       "couldn't set child process attributes: %s", r->filename);
451     }
452     else {
453         procnew = apr_pcalloc(p, sizeof(*procnew));
454         rc = ap_os_create_privileged_process(r, procnew, command, argv, env,
455                                              procattr, p);
456     
457         if (rc != APR_SUCCESS) {
458             /* Bad things happened. Everyone should have cleaned up. */
459             ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_TOCLIENT, rc, r,
460                           "couldn't create child process: %d: %s", rc,
461                           apr_filepath_name_get(r->filename));
462         }
463         else {
464             apr_pool_note_subprocess(p, procnew, APR_KILL_AFTER_TIMEOUT);
465
466             *script_in = procnew->out;
467             if (!*script_in)
468                 return APR_EBADF;
469             apr_file_pipe_timeout_set(*script_in, r->server->timeout);
470
471             if (e_info->prog_type == RUN_AS_CGI) {
472                 *script_out = procnew->in;
473                 if (!*script_out)
474                     return APR_EBADF;
475                 apr_file_pipe_timeout_set(*script_out, r->server->timeout);
476
477                 *script_err = procnew->err;
478                 if (!*script_err)
479                     return APR_EBADF;
480                 apr_file_pipe_timeout_set(*script_err, r->server->timeout);
481             }
482         }
483     }
484 #ifdef DEBUG_CGI
485     fclose(dbg);
486 #endif
487     return (rc);
488 }
489
490
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)
494 {
495     int numwords, x, idx;
496     char *w;
497     const char *args = NULL;
498
499     if (e_info->process_cgi) {
500         *cmd = r->filename;
501         /* Do not process r->args if they contain an '=' assignment 
502          */
503         if (r->args && r->args[0] && !ap_strchr_c(r->args, '=')) {
504             args = r->args;
505         }
506     }
507
508     if (!args) {
509         numwords = 1;
510     }
511     else {
512         /* count the number of keywords */
513         for (x = 0, numwords = 2; args[x]; x++) {
514             if (args[x] == '+') {
515                 ++numwords;
516             }
517         }
518     }
519     /* Everything is - 1 to account for the first parameter 
520      * which is the program name.
521      */ 
522     if (numwords > APACHE_ARG_MAX - 1) {
523         numwords = APACHE_ARG_MAX - 1;    /* Truncate args to prevent overrun */
524     }
525     *argv = apr_palloc(p, (numwords + 2) * sizeof(char *));
526     (*argv)[0] = *cmd;
527     for (x = 1, idx = 1; x < numwords; x++) {
528         w = ap_getword_nulls(p, &args, '+');
529         ap_unescape_url(w);
530         (*argv)[idx++] = ap_escape_shell_cmd(p, w);
531     }
532     (*argv)[idx] = NULL;
533
534     return APR_SUCCESS;
535 }
536
537 static void discard_script_output(apr_bucket_brigade *bb)
538 {
539     apr_bucket *e;
540     const char *buf;
541     apr_size_t len;
542     apr_status_t rv;
543
544     for (e = APR_BRIGADE_FIRST(bb);
545          e != APR_BRIGADE_SENTINEL(bb);
546          e = APR_BUCKET_NEXT(e))
547     {
548         if (APR_BUCKET_IS_EOS(e)) {
549             break;
550         }
551         rv = apr_bucket_read(e, &buf, &len, APR_BLOCK_READ);
552         if (rv != APR_SUCCESS) {
553             break;
554         }
555     }
556 }
557
558 #if APR_FILES_AS_SOCKETS
559
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;
563
564 struct cgi_bucket_data {
565     apr_pollset_t *pollset;
566     request_rec *r;
567 };
568
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)
574 {
575     apr_bucket *b = apr_bucket_alloc(sizeof(*b), list);
576     apr_status_t rv;
577     apr_pollfd_t fd;
578     struct cgi_bucket_data *data = apr_palloc(r->pool, sizeof *data);
579     
580     APR_BUCKET_INIT(b);
581     b->free = apr_bucket_free;
582     b->list = list;
583     b->type = &bucket_type_cgi;
584     b->length = (apr_size_t)(-1);
585     b->start = -1;
586
587     /* Create the pollset */
588     rv = apr_pollset_create(&data->pollset, 2, r->pool, 0);
589     AP_DEBUG_ASSERT(rv == APR_SUCCESS);
590
591     fd.desc_type = APR_POLL_FILE;
592     fd.reqevents = APR_POLLIN;
593     fd.p = r->pool;
594     fd.desc.f = out; /* script's stdout */
595     fd.client_data = (void *)1;
596     rv = apr_pollset_add(data->pollset, &fd);
597     AP_DEBUG_ASSERT(rv == APR_SUCCESS);
598     
599     fd.desc.f = err; /* script's stderr */
600     fd.client_data = (void *)2;
601     rv = apr_pollset_add(data->pollset, &fd);
602     AP_DEBUG_ASSERT(rv == APR_SUCCESS);
603     
604     data->r = r;
605     b->data = data;
606     return b;
607 }
608
609 /* Create a duplicate CGI bucket using given bucket data */
610 static apr_bucket *cgi_bucket_dup(struct cgi_bucket_data *data,
611                                   apr_bucket_alloc_t *list)
612 {
613     apr_bucket *b = apr_bucket_alloc(sizeof(*b), list);
614     APR_BUCKET_INIT(b);
615     b->free = apr_bucket_free;
616     b->list = list;
617     b->type = &bucket_type_cgi;
618     b->length = (apr_size_t)(-1);
619     b->start = -1;
620     b->data = data;
621     return b;
622 }
623
624 /* Handle stdout from CGI child.  Duplicate of logic from the _read
625  * method of the real APR pipe bucket implementation. */
626 static apr_status_t cgi_read_stdout(apr_bucket *a, apr_file_t *out,
627                                     const char **str, apr_size_t *len)
628 {
629     char *buf;
630     apr_status_t rv;
631
632     *str = NULL;
633     *len = APR_BUCKET_BUFF_SIZE;
634     buf = apr_bucket_alloc(*len, a->list); /* XXX: check for failure? */
635
636     rv = apr_file_read(out, buf, len);
637
638     if (rv != APR_SUCCESS && rv != APR_EOF) {
639         apr_bucket_free(buf);
640         return rv;
641     }
642
643     if (*len > 0) {
644         struct cgi_bucket_data *data = a->data;
645         apr_bucket_heap *h;
646
647         /* Change the current bucket to refer to what we read */
648         a = apr_bucket_heap_make(a, buf, *len, apr_bucket_free);
649         h = a->data;
650         h->alloc_len = APR_BUCKET_BUFF_SIZE; /* note the real buffer size */
651         *str = buf;
652         APR_BUCKET_INSERT_AFTER(a, cgi_bucket_dup(data, a->list));
653     }
654     else {
655         apr_bucket_free(buf);
656         a = apr_bucket_immortal_make(a, "", 0);
657         *str = a->data;
658     }
659     return rv;
660 }
661
662 /* Read method of CGI bucket: polls on stderr and stdout of the child,
663  * sending any stderr output immediately away to the error log. */
664 static apr_status_t cgi_bucket_read(apr_bucket *b, const char **str,
665                                     apr_size_t *len, apr_read_type_e block)
666 {
667     struct cgi_bucket_data *data = b->data;
668     apr_interval_time_t timeout;
669     apr_status_t rv;
670     int gotdata = 0;
671
672     timeout = block == APR_NONBLOCK_READ ? 0 : data->r->server->timeout;
673
674     do {
675         const apr_pollfd_t *results;
676         apr_int32_t num;
677
678         rv = apr_pollset_poll(data->pollset, timeout, &num, &results);
679         if (APR_STATUS_IS_TIMEUP(rv)) {
680             return timeout == 0 ? APR_EAGAIN : rv;
681         }
682         else if (APR_STATUS_IS_EINTR(rv)) {
683             continue;
684         }
685         else if (rv != APR_SUCCESS) {
686             ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, data->r,
687                           "poll failed waiting for CGI child");
688             return rv;
689         }
690         
691         for (; num; num--, results++) {
692             if (results[0].client_data == (void *)1) {
693                 /* stdout */
694                 rv = cgi_read_stdout(b, results[0].desc.f, str, len);
695                 if (APR_STATUS_IS_EOF(rv)) {
696                     rv = APR_SUCCESS;
697                 }
698                 gotdata = 1;
699             } else {
700                 /* stderr */
701                 apr_status_t rv2 = log_script_err(data->r, results[0].desc.f);
702                 if (APR_STATUS_IS_EOF(rv2)) {
703                     apr_pollset_remove(data->pollset, &results[0]);
704                 }
705             }
706         }
707
708     } while (!gotdata);
709
710     return rv;
711 }
712
713 static const apr_bucket_type_t bucket_type_cgi = {
714     "CGI", 5, APR_BUCKET_DATA,
715     apr_bucket_destroy_noop,
716     cgi_bucket_read,
717     apr_bucket_setaside_notimpl,
718     apr_bucket_split_notimpl,
719     apr_bucket_copy_notimpl
720 };
721
722 #endif
723
724 static int cgi_handler(request_rec *r)
725 {
726     int nph;
727     apr_size_t dbpos = 0;
728     const char *argv0;
729     const char *command;
730     const char **argv;
731     char *dbuf = NULL;
732     apr_file_t *script_out = NULL, *script_in = NULL, *script_err = NULL;
733     apr_bucket_brigade *bb;
734     apr_bucket *b;
735     int is_included;
736     int seen_eos, child_stopped_reading;
737     apr_pool_t *p;
738     cgi_server_conf *conf;
739     apr_status_t rv;
740     cgi_exec_info_t e_info;
741     conn_rec *c = r->connection;
742
743     if(strcmp(r->handler, CGI_MAGIC_TYPE) && strcmp(r->handler, "cgi-script"))
744         return DECLINED;
745
746     is_included = !strcmp(r->protocol, "INCLUDED");
747
748     p = r->main ? r->main->pool : r->pool;
749
750     if (r->method_number == M_OPTIONS) {
751         /* 99 out of 100 CGI scripts, this is all they support */
752         r->allowed |= (AP_METHOD_BIT << M_GET);
753         r->allowed |= (AP_METHOD_BIT << M_POST);
754         return DECLINED;
755     }
756
757     argv0 = apr_filepath_name_get(r->filename);
758     nph = !(strncmp(argv0, "nph-", 4));
759     conf = ap_get_module_config(r->server->module_config, &cgi_module);
760
761     if (!(ap_allow_options(r) & OPT_EXECCGI) && !is_scriptaliased(r))
762         return log_scripterror(r, conf, HTTP_FORBIDDEN, 0,
763                                "Options ExecCGI is off in this directory");
764     if (nph && is_included)
765         return log_scripterror(r, conf, HTTP_FORBIDDEN, 0,
766                                "attempt to include NPH CGI script");
767
768     if (r->finfo.filetype == 0)
769         return log_scripterror(r, conf, HTTP_NOT_FOUND, 0,
770                                "script not found or unable to stat");
771     if (r->finfo.filetype == APR_DIR)
772         return log_scripterror(r, conf, HTTP_FORBIDDEN, 0,
773                                "attempt to invoke directory as script");
774
775     if ((r->used_path_info == AP_REQ_REJECT_PATH_INFO) &&
776         r->path_info && *r->path_info)
777     {
778         /* default to accept */
779         return log_scripterror(r, conf, HTTP_NOT_FOUND, 0,
780                                "AcceptPathInfo off disallows user's path");
781     }
782 /*
783     if (!ap_suexec_enabled) {
784         if (!ap_can_exec(&r->finfo))
785             return log_scripterror(r, conf, HTTP_FORBIDDEN, 0,
786                                    "file permissions deny server execution");
787     }
788
789 */
790     ap_add_common_vars(r);
791     ap_add_cgi_vars(r);
792
793     e_info.process_cgi = 1;
794     e_info.cmd_type    = APR_PROGRAM;
795     e_info.detached    = 0;
796     e_info.in_pipe     = APR_CHILD_BLOCK;
797     e_info.out_pipe    = APR_CHILD_BLOCK;
798     e_info.err_pipe    = APR_CHILD_BLOCK;
799     e_info.prog_type   = RUN_AS_CGI;
800     e_info.bb          = NULL;
801     e_info.ctx         = NULL;
802     e_info.next        = NULL;
803     e_info.addrspace   = 0;
804
805     /* build the command line */
806     if ((rv = cgi_build_command(&command, &argv, r, p, &e_info)) != APR_SUCCESS) {
807         ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
808                       "don't know how to spawn child process: %s", 
809                       r->filename);
810         return HTTP_INTERNAL_SERVER_ERROR;
811     }
812
813     /* run the script in its own process */
814     if ((rv = run_cgi_child(&script_out, &script_in, &script_err,
815                             command, argv, r, p, &e_info)) != APR_SUCCESS) {
816         ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
817                       "couldn't spawn child process: %s", r->filename);
818         return HTTP_INTERNAL_SERVER_ERROR;
819     }
820
821     /* Transfer any put/post args, CERN style...
822      * Note that we already ignore SIGPIPE in the core server.
823      */
824     bb = apr_brigade_create(r->pool, c->bucket_alloc);
825     seen_eos = 0;
826     child_stopped_reading = 0;
827     if (conf->logname) {
828         dbuf = apr_palloc(r->pool, conf->bufbytes + 1);
829         dbpos = 0;
830     }
831     do {
832         apr_bucket *bucket;
833
834         rv = ap_get_brigade(r->input_filters, bb, AP_MODE_READBYTES,
835                             APR_BLOCK_READ, HUGE_STRING_LEN);
836        
837         if (rv != APR_SUCCESS) {
838             return rv;
839         }
840
841         for (bucket = APR_BRIGADE_FIRST(bb);
842              bucket != APR_BRIGADE_SENTINEL(bb);
843              bucket = APR_BUCKET_NEXT(bucket))
844         {
845             const char *data;
846             apr_size_t len;
847
848             if (APR_BUCKET_IS_EOS(bucket)) {
849                 seen_eos = 1;
850                 break;
851             }
852
853             /* We can't do much with this. */
854             if (APR_BUCKET_IS_FLUSH(bucket)) {
855                 continue;
856             }
857
858             /* If the child stopped, we still must read to EOS. */
859             if (child_stopped_reading) {
860                 continue;
861             } 
862
863             /* read */
864             apr_bucket_read(bucket, &data, &len, APR_BLOCK_READ);
865             
866             if (conf->logname && dbpos < conf->bufbytes) {
867                 int cursize;
868
869                 if ((dbpos + len) > conf->bufbytes) {
870                     cursize = conf->bufbytes - dbpos;
871                 }
872                 else {
873                     cursize = len;
874                 }
875                 memcpy(dbuf + dbpos, data, cursize);
876                 dbpos += cursize;
877             }
878
879             /* Keep writing data to the child until done or too much time
880              * elapses with no progress or an error occurs.
881              */
882             rv = apr_file_write_full(script_out, data, len, NULL);
883
884             if (rv != APR_SUCCESS) {
885                 /* silly script stopped reading, soak up remaining message */
886                 child_stopped_reading = 1;
887             }
888         }
889         apr_brigade_cleanup(bb);
890     }
891     while (!seen_eos);
892
893     if (conf->logname) {
894         dbuf[dbpos] = '\0';
895     }
896     /* Is this flush really needed? */
897     apr_file_flush(script_out);
898     apr_file_close(script_out);
899
900     AP_DEBUG_ASSERT(script_in != NULL);
901
902     apr_brigade_cleanup(bb);
903
904 #if APR_FILES_AS_SOCKETS
905     apr_file_pipe_timeout_set(script_in, 0);
906     apr_file_pipe_timeout_set(script_err, 0);
907     
908     b = cgi_bucket_create(r, script_in, script_err, c->bucket_alloc);
909 #else
910     b = apr_bucket_pipe_create(script_in, c->bucket_alloc);
911 #endif
912     APR_BRIGADE_INSERT_TAIL(bb, b);
913     b = apr_bucket_eos_create(c->bucket_alloc);
914     APR_BRIGADE_INSERT_TAIL(bb, b);
915
916     /* Handle script return... */
917     if (!nph) {
918         const char *location;
919         char sbuf[MAX_STRING_LEN];
920         int ret;
921
922         if ((ret = ap_scan_script_header_err_brigade(r, bb, sbuf))) {
923             return log_script(r, conf, ret, dbuf, sbuf, bb, script_err);
924         }
925
926         location = apr_table_get(r->headers_out, "Location");
927
928         if (location && location[0] == '/' && r->status == 200) {
929             discard_script_output(bb);
930             apr_brigade_destroy(bb);
931             apr_file_pipe_timeout_set(script_err, r->server->timeout);
932             log_script_err(r, script_err);
933             /* This redirect needs to be a GET no matter what the original
934              * method was.
935              */
936             r->method = apr_pstrdup(r->pool, "GET");
937             r->method_number = M_GET;
938
939             /* We already read the message body (if any), so don't allow
940              * the redirected request to think it has one.  We can ignore 
941              * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR.
942              */
943             apr_table_unset(r->headers_in, "Content-Length");
944
945             ap_internal_redirect_handler(location, r);
946             return OK;
947         }
948         else if (location && r->status == 200) {
949             /* XX Note that if a script wants to produce its own Redirect
950              * body, it now has to explicitly *say* "Status: 302"
951              */
952             discard_script_output(bb);
953             apr_brigade_destroy(bb);
954             return HTTP_MOVED_TEMPORARILY;
955         }
956
957         rv = ap_pass_brigade(r->output_filters, bb);
958     }
959     else /* nph */ {
960         struct ap_filter_t *cur;
961         
962         /* get rid of all filters up through protocol...  since we
963          * haven't parsed off the headers, there is no way they can
964          * work
965          */
966
967         cur = r->proto_output_filters;
968         while (cur && cur->frec->ftype < AP_FTYPE_CONNECTION) {
969             cur = cur->next;
970         }
971         r->output_filters = r->proto_output_filters = cur;
972
973         rv = ap_pass_brigade(r->output_filters, bb);
974     }
975
976     /* don't soak up script output if errors occurred writing it
977      * out...  otherwise, we prolong the life of the script when the
978      * connection drops or we stopped sending output for some other
979      * reason */
980     if (rv == APR_SUCCESS && !r->connection->aborted) {
981         apr_file_pipe_timeout_set(script_err, r->server->timeout);
982         log_script_err(r, script_err);
983     }
984     
985     apr_file_close(script_err);
986
987     return OK;                      /* NOT r->status, even if it has changed. */
988 }
989
990 /*============================================================================
991  *============================================================================
992  * This is the beginning of the cgi filter code moved from mod_include. This
993  *   is the code required to handle the "exec" SSI directive.
994  *============================================================================
995  *============================================================================*/
996 static apr_status_t include_cgi(include_ctx_t *ctx, ap_filter_t *f,
997                                 apr_bucket_brigade *bb, char *s)
998 {
999     request_rec *r = f->r;
1000     request_rec *rr = ap_sub_req_lookup_uri(s, r, f->next);
1001     int rr_status;
1002
1003     if (rr->status != HTTP_OK) {
1004         ap_destroy_sub_req(rr);
1005         return APR_EGENERAL;
1006     }
1007
1008     /* No hardwired path info or query allowed */
1009     if ((rr->path_info && rr->path_info[0]) || rr->args) {
1010         ap_destroy_sub_req(rr);
1011         return APR_EGENERAL;
1012     }
1013     if (rr->finfo.filetype != APR_REG) {
1014         ap_destroy_sub_req(rr);
1015         return APR_EGENERAL;
1016     }
1017
1018     /* Script gets parameters of the *document*, for back compatibility */
1019     rr->path_info = r->path_info;       /* hard to get right; see mod_cgi.c */
1020     rr->args = r->args;
1021
1022     /* Force sub_req to be treated as a CGI request, even if ordinary
1023      * typing rules would have called it something else.
1024      */
1025     ap_set_content_type(rr, CGI_MAGIC_TYPE);
1026
1027     /* Run it. */
1028     rr_status = ap_run_sub_req(rr);
1029     if (ap_is_HTTP_REDIRECT(rr_status)) {
1030         const char *location = apr_table_get(rr->headers_out, "Location");
1031
1032         if (location) {
1033             char *buffer;
1034
1035             location = ap_escape_html(rr->pool, location);
1036             buffer = apr_pstrcat(ctx->pool, "<a href=\"", location, "\">",
1037                                  location, "</a>", NULL);
1038
1039             APR_BRIGADE_INSERT_TAIL(bb, apr_bucket_pool_create(buffer,
1040                                     strlen(buffer), ctx->pool,
1041                                     f->c->bucket_alloc));
1042         }
1043     }
1044
1045     ap_destroy_sub_req(rr);
1046
1047     return APR_SUCCESS;
1048 }
1049
1050 static apr_status_t include_cmd(include_ctx_t *ctx, ap_filter_t *f,
1051                                 apr_bucket_brigade *bb, const char *command)
1052 {
1053     cgi_exec_info_t  e_info;
1054     const char **argv;
1055     apr_file_t *script_out = NULL, *script_in = NULL, *script_err = NULL;
1056     apr_status_t rv;
1057     request_rec *r = f->r;
1058
1059     add_ssi_vars(r);
1060
1061     e_info.process_cgi = 0;
1062     e_info.cmd_type    = APR_SHELLCMD;
1063     e_info.detached    = 0;
1064     e_info.in_pipe     = APR_NO_PIPE;
1065     e_info.out_pipe    = APR_FULL_BLOCK;
1066     e_info.err_pipe    = APR_NO_PIPE;
1067     e_info.prog_type   = RUN_AS_SSI;
1068     e_info.bb          = &bb;
1069     e_info.ctx         = ctx;
1070     e_info.next        = f->next;
1071     e_info.addrspace   = 0;
1072
1073     if ((rv = cgi_build_command(&command, &argv, r, r->pool,
1074                                 &e_info)) != APR_SUCCESS) {
1075         ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1076                       "don't know how to spawn cmd child process: %s", 
1077                       r->filename);
1078         return rv;
1079     }
1080
1081     /* run the script in its own process */
1082     if ((rv = run_cgi_child(&script_out, &script_in, &script_err,
1083                             command, argv, r, r->pool,
1084                             &e_info)) != APR_SUCCESS) {
1085         ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1086                       "couldn't spawn child process: %s", r->filename);
1087         return rv;
1088     }
1089
1090     APR_BRIGADE_INSERT_TAIL(bb, apr_bucket_pipe_create(script_in,
1091                             f->c->bucket_alloc));
1092     ctx->flush_now = 1;
1093
1094     /* We can't close the pipe here, because we may return before the
1095      * full CGI has been sent to the network.  That's okay though,
1096      * because we can rely on the pool to close the pipe for us.
1097      */
1098     return APR_SUCCESS;
1099 }
1100
1101 static apr_status_t handle_exec(include_ctx_t *ctx, ap_filter_t *f,
1102                                 apr_bucket_brigade *bb)
1103 {
1104     char *tag = NULL;
1105     char *tag_val = NULL;
1106     request_rec *r = f->r;
1107     char *file = r->filename;
1108     char parsed_string[MAX_STRING_LEN];
1109
1110     if (!ctx->argc) {
1111         ap_log_rerror(APLOG_MARK,
1112                       (ctx->flags & SSI_FLAG_PRINTING)
1113                           ? APLOG_ERR : APLOG_WARNING,
1114                       0, r, "missing argument for exec element in %s",
1115                       r->filename);
1116     }
1117
1118     if (!(ctx->flags & SSI_FLAG_PRINTING)) {
1119         return APR_SUCCESS;
1120     }
1121
1122     if (!ctx->argc) {
1123         SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
1124         return APR_SUCCESS;
1125     }
1126
1127     if (ctx->flags & SSI_FLAG_NO_EXEC) {
1128         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "exec used but not allowed "
1129                       "in %s", r->filename);
1130         SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
1131         return APR_SUCCESS;
1132     }
1133
1134     while (1) {
1135         cgi_pfn_gtv(ctx, &tag, &tag_val, SSI_VALUE_DECODED);
1136         if (!tag || !tag_val) {
1137             break;
1138         }
1139
1140         if (!strcmp(tag, "cmd")) {
1141             apr_status_t rv;
1142
1143             cgi_pfn_ps(ctx, tag_val, parsed_string, sizeof(parsed_string),
1144                        SSI_EXPAND_LEAVE_NAME);
1145
1146             rv = include_cmd(ctx, f, bb, parsed_string);
1147             if (rv != APR_SUCCESS) {
1148                 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "execution failure "
1149                               "for parameter \"%s\" to tag exec in file %s",
1150                               tag, r->filename);
1151                 SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
1152                 break;
1153             }
1154         }
1155         else if (!strcmp(tag, "cgi")) {
1156             apr_status_t rv;
1157
1158             cgi_pfn_ps(ctx, tag_val, parsed_string, sizeof(parsed_string),
1159                        SSI_EXPAND_DROP_NAME);
1160
1161             rv = include_cgi(ctx, f, bb, parsed_string);
1162             if (rv != APR_SUCCESS) {
1163                 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "invalid CGI ref "
1164                               "\"%s\" in %s", tag_val, file);
1165                 SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
1166                 break;
1167             }
1168         }
1169         else {
1170             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "unknown parameter "
1171                           "\"%s\" to tag exec in %s", tag, file);
1172             SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
1173             break;
1174         }
1175     }
1176
1177     return APR_SUCCESS;
1178 }
1179
1180
1181 /*============================================================================
1182  *============================================================================
1183  * This is the end of the cgi filter code moved from mod_include.
1184  *============================================================================
1185  *============================================================================*/
1186
1187
1188 static int cgi_post_config(apr_pool_t *p, apr_pool_t *plog,
1189                                 apr_pool_t *ptemp, server_rec *s)
1190 {
1191     cgi_pfn_reg_with_ssi = APR_RETRIEVE_OPTIONAL_FN(ap_register_include_handler);
1192     cgi_pfn_gtv          = APR_RETRIEVE_OPTIONAL_FN(ap_ssi_get_tag_and_value);
1193     cgi_pfn_ps           = APR_RETRIEVE_OPTIONAL_FN(ap_ssi_parse_string);
1194
1195     if ((cgi_pfn_reg_with_ssi) && (cgi_pfn_gtv) && (cgi_pfn_ps)) {
1196         /* Required by mod_include filter. This is how mod_cgi registers
1197          *   with mod_include to provide processing of the exec directive.
1198          */
1199         cgi_pfn_reg_with_ssi("exec", handle_exec);
1200     }
1201
1202     /* This is the means by which unusual (non-unix) os's may find alternate
1203      * means to run a given command (e.g. shebang/registry parsing on Win32)
1204      */
1205     cgi_build_command    = APR_RETRIEVE_OPTIONAL_FN(ap_cgi_build_command);
1206     if (!cgi_build_command) {
1207         cgi_build_command = default_build_command;
1208     }
1209     return OK;
1210 }
1211
1212 static void register_hooks(apr_pool_t *p)
1213 {
1214     static const char * const aszPre[] = { "mod_include.c", NULL };
1215     ap_hook_handler(cgi_handler, NULL, NULL, APR_HOOK_MIDDLE);
1216     ap_hook_post_config(cgi_post_config, aszPre, NULL, APR_HOOK_REALLY_FIRST);
1217 }
1218
1219 module AP_MODULE_DECLARE_DATA cgi_module =
1220 {
1221     STANDARD20_MODULE_STUFF,
1222     NULL,                        /* dir config creater */
1223     NULL,                        /* dir merger --- default is to override */
1224     create_cgi_config,           /* server config */
1225     merge_cgi_config,            /* merge server config */
1226     cgi_cmds,                    /* command apr_table_t */
1227     register_hooks               /* register hooks */
1228 };