]> granicus.if.org Git - apache/blob - modules/generators/mod_cgid.c
Fix for mod_include. Ryan's patch to check error
[apache] / modules / generators / mod_cgid.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_lib.h"
73 #include "apr_strings.h"
74 #include "apr_general.h"
75 #include "apr_file_io.h"
76 #include "apr_portable.h"
77 #include "apr_buckets.h"
78 #include "apr_optional.h"
79 #include "apr_signal.h"
80
81 #define APR_WANT_STRFUNC
82 #include "apr_want.h"
83
84 #if APR_HAVE_SYS_SOCKET_H
85 #include <sys/socket.h>
86 #endif
87 #if APR_HAVE_UNISTD_H
88 #include <unistd.h>
89 #endif
90 #if APR_HAVE_SYS_TYPES_H
91 #include <sys/types.h>
92 #endif
93
94 #define CORE_PRIVATE 
95
96 #include "util_filter.h"
97 #include "httpd.h" 
98 #include "http_config.h" 
99 #include "http_request.h" 
100 #include "http_core.h" 
101 #include "http_protocol.h" 
102 #include "http_main.h" 
103 #include "http_log.h" 
104 #include "util_script.h" 
105 #include "ap_mpm.h"
106 #include "unixd.h"
107 #include "mod_suexec.h"
108 #include "../filters/mod_include.h"
109
110 #include "mod_core.h"
111
112
113 /* ### should be tossed in favor of APR */
114 #include <sys/stat.h>
115 #include <sys/un.h> /* for sockaddr_un */
116
117
118 module AP_MODULE_DECLARE_DATA cgid_module; 
119
120 static void cgid_init(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *main_server); 
121 static int handle_exec(include_ctx_t *ctx, apr_bucket_brigade **bb, request_rec *r,
122                        ap_filter_t *f, apr_bucket *head_ptr, apr_bucket **inserted_head);
123
124 static APR_OPTIONAL_FN_TYPE(ap_register_include_handler) *cgid_pfn_reg_with_ssi;
125 static APR_OPTIONAL_FN_TYPE(ap_ssi_get_tag_and_value) *cgid_pfn_gtv;
126 static APR_OPTIONAL_FN_TYPE(ap_ssi_parse_string) *cgid_pfn_ps;
127
128 static apr_pool_t *pcgi; 
129 static int total_modules = 0;
130
131 /* KLUDGE --- for back-combatibility, we don't have to check Execcgid 
132  * in ScriptAliased directories, which means we need to know if this 
133  * request came through ScriptAlias or not... so the Alias module 
134  * leaves a note for us. 
135  */ 
136
137 static int is_scriptaliased(request_rec *r) 
138
139     const char *t = apr_table_get(r->notes, "alias-forced-type"); 
140     return t && (!strcasecmp(t, "cgi-script")); 
141
142
143 /* Configuration stuff */ 
144
145 #define DEFAULT_LOGBYTES 10385760 
146 #define DEFAULT_BUFBYTES 1024 
147 #define DEFAULT_SOCKET "logs/cgisock"
148
149 #define SHELL_PATH "/bin/sh"
150
151 #define CGI_REQ 1
152 #define SSI_REQ 2
153
154 /* DEFAULT_CGID_LISTENBACKLOG controls the max depth on the unix socket's
155  * pending connection queue.  If a bunch of cgi requests arrive at about
156  * the same time, connections from httpd threads/processes will back up
157  * in the queue while the cgid process slowly forks off a child to process
158  * each connection on the unix socket.  If the queue is too short, the
159  * httpd process will get ECONNREFUSED when trying to connect.
160  */
161 #ifndef DEFAULT_CGID_LISTENBACKLOG
162 #define DEFAULT_CGID_LISTENBACKLOG 100
163 #endif
164
165 typedef struct { 
166     const char *sockname;
167     const char *logname; 
168     long logbytes; 
169     int bufbytes; 
170 } cgid_server_conf; 
171
172 /* This function is used to split the brigade at the beginning of
173  *   the tag and forward the pretag buckets before any substitution
174  *   work is performed on the tag. This maintains proper ordering.
175  */
176 static int split_and_pass_pretag_buckets(apr_bucket_brigade **brgd, 
177                                          include_ctx_t *cntxt, 
178                                          ap_filter_t *next)
179 {
180     apr_bucket_brigade *tag_plus;
181     int rv;
182
183     if ((APR_BRIGADE_EMPTY(cntxt->ssi_tag_brigade)) &&
184         (cntxt->head_start_bucket != NULL)) {
185         tag_plus = apr_brigade_split(*brgd, cntxt->head_start_bucket);
186         rv = ap_pass_brigade(next, *brgd);
187         cntxt->bytes_parsed = 0;
188         *brgd = tag_plus;
189         if (rv != APR_SUCCESS) {
190             return rv;
191         }
192     }
193 }
194
195 /* If a request includes query info in the URL (stuff after "?"), and
196  * the query info does not contain "=" (indicative of a FORM submission),
197  * then this routine is called to create the argument list to be passed
198  * to the CGI script.  When suexec is enabled, the suexec path, user, and
199  * group are the first three arguments to be passed; if not, all three
200  * must be NULL.  The query info is split into separate arguments, where
201  * "+" is the separator between keyword arguments.
202  *
203  * XXXX: note that the WIN32 code uses one of the suexec strings
204  * to pass an interpreter name.  Remember this if changing the way they
205  * are handled in create_argv.
206  *
207  */
208 static char **create_argv(apr_pool_t *p, char *path, char *user, char *group,
209                           char *av0, const char *args)
210 {
211     int x, numwords;
212     char **av;
213     char *w;
214     int idx = 0;
215
216     /* count the number of keywords */
217
218     for (x = 0, numwords = 1; args[x]; x++) {
219         if (args[x] == '+') {
220             ++numwords;
221         }
222     }
223
224     if (numwords > APACHE_ARG_MAX - 5) {
225         numwords = APACHE_ARG_MAX - 5;  /* Truncate args to prevent overrun */
226     }
227     av = (char **) apr_pcalloc(p, (numwords + 5) * sizeof(char *));
228
229     if (path) {
230         av[idx++] = path;
231     }
232     if (user) {
233         av[idx++] = user;
234     }
235     if (group) {
236         av[idx++] = group;
237     }
238
239     av[idx++] = apr_pstrdup(p, av0);
240
241     for (x = 1; x <= numwords; x++) {
242         w = ap_getword_nulls(p, &args, '+');
243         if (strcmp(w, "")) {
244             ap_unescape_url(w);
245             av[idx++] = ap_escape_shell_cmd(p, w);
246         }
247     }
248     av[idx] = NULL;
249     return av;
250 }
251
252 #if APR_HAS_OTHER_CHILD
253 static void cgid_maint(int reason, void *data, apr_wait_t status)
254 {
255     pid_t *sd = data;
256
257     switch (reason) {
258         case APR_OC_REASON_DEATH:
259             /* don't do anything; server is stopping or restarting */
260             break;
261         case APR_OC_REASON_LOST:
262             /* it would be better to restart just the cgid child
263              * process but for now we'll gracefully restart the entire 
264              * server by sending SIGWINCH to ourself, the httpd parent
265              * process
266              */
267             kill(getpid(), SIGWINCH);
268             break;
269         case APR_OC_REASON_RESTART:
270             apr_proc_other_child_unregister(data);
271             break;
272         case APR_OC_REASON_UNREGISTER:
273             /* we get here when pcgi is cleaned up; pcgi gets cleaned
274              * up when pconf gets cleaned up
275              */
276             kill(*sd, SIGHUP);
277             break;
278     }
279 }
280 #endif
281
282 static void get_req(int fd, request_rec *r, char **argv0, char ***env, int *req_type) 
283
284     int i, len, j; 
285     unsigned char *data; 
286     char **environ; 
287     core_dir_config *temp_core; 
288     void **dconf; 
289     module *suexec_mod = ap_find_linked_module("mod_suexec.c");
290
291     r->server = apr_pcalloc(r->pool, sizeof(server_rec)); 
292
293     read(fd, req_type, sizeof(int));
294     read(fd, &j, sizeof(int)); 
295     read(fd, &len, sizeof(int)); 
296     data = apr_pcalloc(r->pool, len + 1); /* get a cleared byte for final '\0' */
297     i = read(fd, data, len); 
298
299     r->filename = ap_getword(r->pool, (const char **)&data, '\n'); 
300     *argv0 = ap_getword(r->pool, (const char **)&data, '\n'); 
301
302     r->uri = ap_getword(r->pool, (const char **)&data, '\n'); 
303     
304     environ = apr_pcalloc(r->pool, (j + 2) *sizeof(char *)); 
305     i = 0; 
306     for (i = 0; i < j; i++) { 
307         environ[i] = ap_getword(r->pool, (const char **)&data, '\n'); 
308     } 
309     *env = environ; 
310     r->args = ap_getword(r->pool, (const char **)&data, '\n'); 
311   
312     read(fd, &i, sizeof(int)); 
313      
314     /* add 1, so that if i == 0, we still malloc something. */ 
315
316     dconf = (void **) apr_pcalloc(r->pool, sizeof(void *) * (total_modules + DYNAMIC_MODULE_LIMIT));
317
318     temp_core = (core_dir_config *)apr_palloc(r->pool, sizeof(core_module)); 
319
320     dconf[i] = (void *)temp_core; 
321
322     if (suexec_mod) {
323         suexec_config_t *suexec_cfg = apr_pcalloc(r->pool, sizeof(*suexec_cfg));
324
325         read(fd, &i, sizeof(int));
326         read(fd, &suexec_cfg->ugid.uid, sizeof(uid_t));
327         read(fd, &suexec_cfg->ugid.gid, sizeof(gid_t));
328         read(fd, &suexec_cfg->active, sizeof(int));
329         dconf[i] = (void *)suexec_cfg;
330     }
331
332     r->per_dir_config = (ap_conf_vector_t *)dconf; 
333 #if 0
334 #ifdef RLIMIT_CPU 
335     read(fd, &j, sizeof(int)); 
336     if (j) { 
337         temp_core->limit_cpu = (struct rlimit *)apr_palloc (sizeof(struct rlimit)); 
338         read(fd, temp_core->limit_cpu, sizeof(struct rlimit)); 
339     } 
340     else { 
341         temp_core->limit_cpu = NULL; 
342     } 
343 #endif 
344
345 #if defined (RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS) 
346     read(fd, &j, sizeof(int)); 
347     if (j) { 
348         temp_core->limit_mem = (struct rlimit *)apr_palloc(r->pool, sizeof(struct rlimit)); 
349         read(fd, temp_core->limit_mem, sizeof(struct rlimit)); 
350     } 
351     else { 
352         temp_core->limit_mem = NULL; 
353     } 
354 #endif 
355
356 #ifdef RLIMIT_NPROC 
357     read(fd, &j, sizeof(int)); 
358     if (j) { 
359         temp_core->limit_nproc = (struct rlimit *)apr_palloc(r->pool, sizeof(struct rlimit)); 
360         read(fd, temp_core->limit_nproc, sizeof(struct rlimit)); 
361     } 
362     else { 
363         temp_core->limit_nproc = NULL; 
364     } 
365 #endif 
366 #endif
367     /* For right now, just make the notes table.  At some point we will need
368      * to actually fill this out, but for now we just don't want suexec to
369      * seg fault.
370      */
371     r->notes = apr_table_make(r->pool, 1);
372
373
374
375
376 static void send_req(int fd, request_rec *r, char *argv0, char **env, int req_type) 
377
378     int len, r_type = req_type; 
379     int i = 0; 
380     char *data; 
381     module *suexec_mod = ap_find_linked_module("mod_suexec.c");
382
383     data = apr_pstrcat(r->pool, r->filename, "\n", argv0, "\n", r->uri, "\n", 
384                      NULL); 
385
386     for (i =0; env[i]; i++) { 
387         continue; 
388     } 
389
390     /* Write the request type (SSI "exec cmd" or cgi). */
391     if (write(fd, &r_type, sizeof(int)) < 0) {
392         ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r,
393                      "write to cgi daemon process");
394     }
395
396     /* Write the number of entries in the environment. */
397     if (write(fd, &i, sizeof(int)) < 0) {
398         ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r, 
399                      "write to cgi daemon process"); 
400         }     
401
402     for (i = 0; env[i]; i++) { 
403         data = apr_pstrcat(r->pool, data, env[i], "\n", NULL); 
404     } 
405     data = apr_pstrcat(r->pool, data, r->args, NULL); 
406     len = strlen(data); 
407     /* Write the length of the concatenated env string. */
408     if (write(fd, &len, sizeof(int)) < 0) { 
409         ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r, 
410                      "write to cgi daemon process"); 
411     }
412     /* Write the concatted env string. */     
413     if (write(fd, data, len) < 0) {
414         ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r, 
415                      "write to cgi daemon process"); 
416     }
417     /* Write module_index id value. */     
418     if (write(fd, &core_module.module_index, sizeof(int)) < 0) { 
419         ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r, 
420                      "write to cgi daemon process"); 
421     }     
422     if (suexec_mod) {
423         suexec_config_t *suexec_cfg = ap_get_module_config(r->per_dir_config,
424                                                            suexec_mod);
425
426         write(fd, &suexec_mod->module_index, sizeof(int));
427         write(fd, &suexec_cfg->ugid.uid, sizeof(uid_t));
428         write(fd, &suexec_cfg->ugid.gid, sizeof(gid_t));
429         write(fd, &suexec_cfg->active, sizeof(int));
430     }
431
432 #if 0
433 #ifdef RLIMIT_CPU 
434     if (conf->limit_cpu) { 
435         len = 1; 
436         write(fd, &len, sizeof(int)); 
437         write(fd, conf->limit_cpu, sizeof(struct rlimit)); 
438     } 
439     else { 
440         len = 0; 
441         write(fd, &len, sizeof(int)); 
442     } 
443 #endif 
444
445 #if defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS) 
446     if (conf->limit_mem) { 
447         len = 1; 
448         write(fd, &len, sizeof(int)); 
449         write(fd, conf->limit_mem, sizeof(struct rlimit)); 
450     } 
451     else { 
452         len = 0; 
453         write(fd, &len, sizeof(int)); 
454     } 
455 #endif 
456   
457 #ifdef RLIMIT_NPROC 
458     if (conf->limit_nproc) { 
459         len = 1; 
460         write(fd, &len, sizeof(int)); 
461         write(fd, conf->limit_nproc, sizeof(struct rlimit)); 
462     } 
463     else { 
464         len = 0; 
465         write(fd, &len, sizeof(int)); 
466     } 
467 #endif
468 #endif 
469
470
471 static int cgid_server(void *data) 
472
473     struct sockaddr_un unix_addr;
474     int sd, sd2, rc, req_type;
475     mode_t omask;
476     apr_socklen_t len;
477     apr_pool_t *ptrans;
478     server_rec *main_server = data;
479     cgid_server_conf *sconf = ap_get_module_config(main_server->module_config,
480                                                    &cgid_module); 
481
482     apr_pool_create(&ptrans, pcgi); 
483
484     apr_signal(SIGCHLD, SIG_IGN); 
485     if (unlink(sconf->sockname) < 0 && errno != ENOENT) {
486         ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
487                      "Couldn't unlink unix domain socket %s",
488                      sconf->sockname);
489         /* just a warning; don't bail out */
490     }
491
492     if ((sd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
493         ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server, 
494                      "Couldn't create unix domain socket");
495         return errno;
496     } 
497
498     memset(&unix_addr, 0, sizeof(unix_addr));
499     unix_addr.sun_family = AF_UNIX;
500     strcpy(unix_addr.sun_path, sconf->sockname);
501
502     omask = umask(0077); /* so that only Apache can use socket */
503     rc = bind(sd, (struct sockaddr *)&unix_addr, sizeof(unix_addr));
504     umask(omask); /* can't fail, so can't clobber errno */
505     if (rc < 0) {
506         ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server, 
507                      "Couldn't bind unix domain socket %s",
508                      sconf->sockname); 
509         return errno;
510     } 
511
512     if (listen(sd, DEFAULT_CGID_LISTENBACKLOG) < 0) {
513         ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server, 
514                      "Couldn't listen on unix domain socket"); 
515         return errno;
516     } 
517
518     if (!geteuid()) {
519         if (chown(sconf->sockname, unixd_config.user_id, -1) < 0) {
520             ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server, 
521                          "Couldn't change owner of unix domain socket %s",
522                          sconf->sockname); 
523             return errno;
524         }
525     }
526     
527     unixd_setup_child(); /* if running as root, switch to configured user/group */
528     while (1) {
529         int errfileno = STDERR_FILENO;
530         char *argv0; 
531         char **env; 
532         const char * const *argv; 
533         apr_int32_t   in_pipe  = APR_CHILD_BLOCK;
534         apr_int32_t   out_pipe = APR_CHILD_BLOCK;
535         apr_int32_t   err_pipe = APR_CHILD_BLOCK;
536         apr_cmdtype_e cmd_type = APR_PROGRAM;
537         request_rec *r; 
538         apr_procattr_t *procattr = NULL;
539         apr_proc_t *procnew = NULL;
540         apr_file_t *inout;
541
542         apr_pool_clear(ptrans);
543
544         len = sizeof(unix_addr);
545         sd2 = accept(sd, (struct sockaddr *)&unix_addr, &len);
546         if (sd2 < 0) {
547             if (errno != EINTR) {
548                 ap_log_error(APLOG_MARK, APLOG_ERR, errno, 
549                              (server_rec *)data,
550                              "Error accepting on cgid socket.");
551             }
552             continue;
553         }
554        
555         r = apr_pcalloc(ptrans, sizeof(request_rec)); 
556         procnew = apr_pcalloc(ptrans, sizeof(*procnew));
557         r->pool = ptrans; 
558         get_req(sd2, r, &argv0, &env, &req_type); 
559         apr_os_file_put(&r->server->error_log, &errfileno, r->pool);
560         apr_os_file_put(&inout, &sd2, r->pool);
561
562         if (req_type == SSI_REQ) {
563             in_pipe  = APR_NO_PIPE;
564             out_pipe = APR_FULL_BLOCK;
565             err_pipe = APR_NO_PIPE;
566             cmd_type = APR_SHELLCMD;
567         }
568
569         if (((rc = apr_procattr_create(&procattr, ptrans)) != APR_SUCCESS) ||
570             ((req_type == CGI_REQ) && 
571              (((rc = apr_procattr_io_set(procattr,
572                                         in_pipe,
573                                         out_pipe,
574                                         err_pipe)) != APR_SUCCESS) ||
575               /* XXX apr_procattr_child_*_set() is creating an unnecessary 
576                * pipe between this process and the child being created...
577                * It is cleaned up with the temporary pool for this request.
578                */
579               ((rc = apr_procattr_child_err_set(procattr, r->server->error_log, NULL)) != APR_SUCCESS) ||
580               ((rc = apr_procattr_child_in_set(procattr, inout, NULL)) != APR_SUCCESS))) ||
581             ((rc = apr_procattr_child_out_set(procattr, inout, NULL)) != APR_SUCCESS) ||
582             ((rc = apr_procattr_dir_set(procattr,
583                                   ap_make_dirstr_parent(r->pool, r->filename))) != APR_SUCCESS) ||
584             ((rc = apr_procattr_cmdtype_set(procattr, cmd_type)) != APR_SUCCESS)) {
585             /* Something bad happened, tell the world. */
586             ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r,
587                       "couldn't set child process attributes: %s", r->filename);
588         }
589         else {
590             argv = (const char * const *)create_argv(r->pool, NULL, NULL, NULL, argv0, r->args);
591
592            /* We want to sd2 close for new CGI process too.
593             * If it's remained open it'll make ap_pass_brigade() block
594             * waiting for EOF if CGI forked something running long.
595             * close(sd2) here should be okay, as CGI channel
596             * is already dup()ed by apr_procattr_child_{in,out}_set()
597             * above.
598             */
599             close(sd2);
600
601             rc = ap_os_create_privileged_process(r, procnew, argv0, argv, 
602                                                  (const char * const *)env, 
603                                                  procattr, ptrans);
604
605             if (rc != APR_SUCCESS) {
606                 /* Bad things happened. Everyone should have cleaned up. */
607                 ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r,
608                         "couldn't create child process: %d: %s", rc, r->filename);
609             }
610         }
611     } 
612     return -1; 
613
614
615 static void cgid_init(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, 
616                       server_rec *main_server) 
617
618     pid_t pid; 
619     apr_proc_t *procnew;
620     void *data;
621     int first_time = 0;
622     const char *userdata_key = "cgid_init";
623     module **m;
624
625     apr_pool_userdata_get(&data, userdata_key, main_server->process->pool);
626     if (!data) {
627         first_time = 1;
628         apr_pool_userdata_set((const void *)1, userdata_key,
629                          apr_pool_cleanup_null, main_server->process->pool);
630     }
631
632     if (!first_time) {
633         total_modules = 0;
634         for (m = ap_preloaded_modules; *m != NULL; m++)
635             total_modules++;
636
637
638         if ((pid = fork()) < 0) {
639             ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server, 
640                          "Couldn't spawn cgid daemon process"); 
641         }
642         else if (pid == 0) {
643             apr_pool_create(&pcgi, p); 
644             cgid_server(main_server);
645             exit(-1);
646         } 
647         procnew = apr_pcalloc(p, sizeof(*procnew));
648         procnew->pid = pid;
649         procnew->err = procnew->in = procnew->out = NULL;
650         apr_pool_note_subprocess(p, procnew, kill_after_timeout);
651 #if APR_HAS_OTHER_CHILD
652         apr_proc_other_child_register(procnew, cgid_maint, &procnew->pid, NULL, p);
653 #endif
654
655         cgid_pfn_reg_with_ssi = APR_RETRIEVE_OPTIONAL_FN(ap_register_include_handler);
656         cgid_pfn_gtv          = APR_RETRIEVE_OPTIONAL_FN(ap_ssi_get_tag_and_value);
657         cgid_pfn_ps           = APR_RETRIEVE_OPTIONAL_FN(ap_ssi_parse_string);
658
659         if ((cgid_pfn_reg_with_ssi) && (cgid_pfn_gtv) && (cgid_pfn_ps)) {
660             /* Required by mod_include filter. This is how mod_cgid registers
661              *   with mod_include to provide processing of the exec directive.
662              */
663             cgid_pfn_reg_with_ssi("exec", handle_exec);
664         }
665     }
666
667
668 static void *create_cgid_config(apr_pool_t *p, server_rec *s) 
669
670     cgid_server_conf *c = 
671     (cgid_server_conf *) apr_pcalloc(p, sizeof(cgid_server_conf)); 
672
673     c->logname = NULL; 
674     c->logbytes = DEFAULT_LOGBYTES; 
675     c->bufbytes = DEFAULT_BUFBYTES; 
676     c->sockname = ap_server_root_relative(p, DEFAULT_SOCKET); 
677     return c; 
678
679
680 static void *merge_cgid_config(apr_pool_t *p, void *basev, void *overridesv) 
681
682     cgid_server_conf *base = (cgid_server_conf *) basev, *overrides = (cgid_server_conf *) overridesv; 
683
684     return overrides->logname ? overrides : base; 
685
686
687 static const char *set_scriptlog(cmd_parms *cmd, void *dummy, const char *arg) 
688
689     server_rec *s = cmd->server; 
690     cgid_server_conf *conf = ap_get_module_config(s->module_config,
691                                                   &cgid_module); 
692
693     conf->logname = arg; 
694     return NULL; 
695
696
697 static const char *set_scriptlog_length(cmd_parms *cmd, void *dummy, const char *arg) 
698
699     server_rec *s = cmd->server; 
700     cgid_server_conf *conf = ap_get_module_config(s->module_config,
701                                                   &cgid_module); 
702
703     conf->logbytes = atol(arg); 
704     return NULL; 
705
706
707 static const char *set_scriptlog_buffer(cmd_parms *cmd, void *dummy, const char *arg) 
708
709     server_rec *s = cmd->server; 
710     cgid_server_conf *conf = ap_get_module_config(s->module_config,
711                                                   &cgid_module); 
712
713     conf->bufbytes = atoi(arg); 
714     return NULL; 
715
716
717 static const char *set_script_socket(cmd_parms *cmd, void *dummy, const char *arg) 
718
719     server_rec *s = cmd->server; 
720     cgid_server_conf *conf = ap_get_module_config(s->module_config,
721                                                   &cgid_module); 
722
723     conf->sockname = ap_server_root_relative(cmd->pool, arg); 
724     return NULL; 
725
726
727 static const command_rec cgid_cmds[] = 
728
729     AP_INIT_TAKE1("ScriptLog", set_scriptlog, NULL, RSRC_CONF,
730                   "the name of a log for script debugging info"), 
731     AP_INIT_TAKE1("ScriptLogLength", set_scriptlog_length, NULL, RSRC_CONF,
732                   "the maximum length (in bytes) of the script debug log"), 
733     AP_INIT_TAKE1("ScriptLogBuffer", set_scriptlog_buffer, NULL, RSRC_CONF,
734                   "the maximum size (in bytes) to record of a POST request"), 
735     AP_INIT_TAKE1("Scriptsock", set_script_socket, NULL, RSRC_CONF,
736                   "the name of the socket to use for communication with "
737                   "the cgi daemon."), 
738     {NULL} 
739 }; 
740
741 static int log_scripterror(request_rec *r, cgid_server_conf * conf, int ret, 
742                            apr_status_t rv, char *error) 
743
744     apr_file_t *f = NULL; 
745     struct stat finfo; 
746     char time_str[APR_CTIME_LEN];
747     int log_flags = rv ? APLOG_ERR : APLOG_NOERRNO | APLOG_ERR;
748
749     ap_log_rerror(APLOG_MARK, log_flags, rv, r, 
750                 "%s: %s", error, r->filename); 
751
752     if (!conf->logname || 
753         ((stat(ap_server_root_relative(r->pool, conf->logname), &finfo) == 0) 
754          && (finfo.st_size > conf->logbytes)) || 
755          (apr_file_open(&f, ap_server_root_relative(r->pool, conf->logname),
756                   APR_APPEND|APR_WRITE|APR_CREATE, APR_OS_DEFAULT, r->pool) != APR_SUCCESS)) { 
757         return ret; 
758     } 
759
760     /* "%% [Wed Jun 19 10:53:21 1996] GET /cgid-bin/printenv HTTP/1.0" */ 
761     apr_ctime(time_str, apr_time_now());
762     apr_file_printf(f, "%%%% [%s] %s %s%s%s %s\n", time_str, r->method, r->uri, 
763             r->args ? "?" : "", r->args ? r->args : "", r->protocol); 
764     /* "%% 500 /usr/local/apache/cgid-bin */ 
765     apr_file_printf(f, "%%%% %d %s\n", ret, r->filename); 
766
767     apr_file_printf(f, "%%error\n%s\n", error); 
768
769     apr_file_close(f); 
770     return ret; 
771
772
773 static int log_script(request_rec *r, cgid_server_conf * conf, int ret, 
774                   char *dbuf, const char *sbuf, apr_file_t *script_in, apr_file_t *script_err) 
775
776     apr_array_header_t *hdrs_arr = apr_table_elts(r->headers_in); 
777     apr_table_entry_t *hdrs = (apr_table_entry_t *) hdrs_arr->elts; 
778     char argsbuffer[HUGE_STRING_LEN]; 
779     apr_file_t *f = NULL; 
780     int i; 
781     struct stat finfo; 
782     char time_str[APR_CTIME_LEN];
783
784     if (!conf->logname || 
785         ((stat(ap_server_root_relative(r->pool, conf->logname), &finfo) == 0) 
786          && (finfo.st_size > conf->logbytes)) || 
787          (apr_file_open(&f, ap_server_root_relative(r->pool, conf->logname), 
788                   APR_APPEND|APR_WRITE|APR_CREATE, APR_OS_DEFAULT, r->pool) != APR_SUCCESS)) { 
789         /* Soak up script output */ 
790         while (apr_file_gets(argsbuffer, HUGE_STRING_LEN, script_in) == 0) 
791             continue; 
792         if (script_err) {
793             while (apr_file_gets(argsbuffer, HUGE_STRING_LEN, script_err) == 0) 
794                 continue; 
795         }
796         return ret; 
797     } 
798
799     /* "%% [Wed Jun 19 10:53:21 1996] GET /cgid-bin/printenv HTTP/1.0" */ 
800     apr_ctime(time_str, apr_time_now());
801     apr_file_printf(f, "%%%% [%s] %s %s%s%s %s\n", time_str, r->method, r->uri, 
802             r->args ? "?" : "", r->args ? r->args : "", r->protocol); 
803     /* "%% 500 /usr/local/apache/cgid-bin" */ 
804     apr_file_printf(f, "%%%% %d %s\n", ret, r->filename); 
805
806     apr_file_puts("%request\n", f); 
807     for (i = 0; i < hdrs_arr->nelts; ++i) { 
808         if (!hdrs[i].key) 
809             continue; 
810         apr_file_printf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val); 
811     } 
812     if ((r->method_number == M_POST || r->method_number == M_PUT) 
813         && *dbuf) { 
814         apr_file_printf(f, "\n%s\n", dbuf); 
815     } 
816
817     apr_file_puts("%response\n", f); 
818     hdrs_arr = apr_table_elts(r->err_headers_out); 
819     hdrs = (apr_table_entry_t *) hdrs_arr->elts; 
820
821     for (i = 0; i < hdrs_arr->nelts; ++i) { 
822         if (!hdrs[i].key) 
823             continue; 
824         apr_file_printf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val); 
825     } 
826
827     if (sbuf && *sbuf) 
828         apr_file_printf(f, "%s\n", sbuf); 
829
830     if (apr_file_gets(argsbuffer, HUGE_STRING_LEN, script_in) == 0) { 
831         apr_file_puts("%stdout\n", f); 
832         apr_file_puts(argsbuffer, f); 
833         while (apr_file_gets(argsbuffer, HUGE_STRING_LEN, script_in) == 0) 
834             apr_file_puts(argsbuffer, f); 
835         apr_file_puts("\n", f); 
836     } 
837
838     if (script_err) {
839         if (apr_file_gets(argsbuffer, HUGE_STRING_LEN, script_err) == 0) { 
840             apr_file_puts("%stderr\n", f); 
841             apr_file_puts(argsbuffer, f); 
842             while (apr_file_gets(argsbuffer, HUGE_STRING_LEN, script_err) == 0) 
843                 apr_file_puts(argsbuffer, f); 
844             apr_file_puts("\n", f); 
845         } 
846     }
847
848     apr_file_close(script_in); 
849     if (script_err) {
850         apr_file_close(script_err); 
851     }
852
853     apr_file_close(f); 
854     return ret; 
855
856
857
858
859 /**************************************************************** 
860  * 
861  * Actual cgid handling... 
862  */ 
863 static int cgid_handler(request_rec *r) 
864
865     int retval, nph, dbpos = 0; 
866     char *argv0, *dbuf = NULL; 
867     apr_bucket_brigade *bb;
868     apr_bucket *b;
869     char argsbuffer[HUGE_STRING_LEN]; 
870     cgid_server_conf *conf;
871     int is_included;
872     int sd;
873     char **env; 
874     struct sockaddr_un unix_addr;
875     apr_file_t *tempsock;
876     apr_size_t nbytes;
877
878     if(strcmp(r->handler,CGI_MAGIC_TYPE) && strcmp(r->handler,"cgi-script"))
879         return DECLINED;
880
881     if (r->method_number == M_OPTIONS) { 
882         /* 99 out of 100 cgid scripts, this is all they support */ 
883         r->allowed |= (AP_METHOD_BIT << M_GET); 
884         r->allowed |= (AP_METHOD_BIT << M_POST); 
885         return DECLINED; 
886     } 
887
888     conf = ap_get_module_config(r->server->module_config, &cgid_module); 
889     is_included = !strcmp(r->protocol, "INCLUDED"); 
890
891     if ((argv0 = strrchr(r->filename, '/')) != NULL)
892         argv0++;
893     else
894         argv0 = r->filename;
895  
896     nph = !(strncmp(argv0, "nph-", 4)); 
897
898     if ((argv0 = strrchr(r->filename, '/')) != NULL) 
899         argv0++; 
900     else 
901         argv0 = r->filename; 
902
903     if (!(ap_allow_options(r) & OPT_EXECCGI) && !is_scriptaliased(r)) 
904         return log_scripterror(r, conf, HTTP_FORBIDDEN, 0, 
905                                "Options ExecCGI is off in this directory"); 
906     if (nph && is_included) 
907         return log_scripterror(r, conf, HTTP_FORBIDDEN, 0, 
908                                "attempt to include NPH CGI script"); 
909
910 #if defined(OS2) || defined(WIN32)
911 #error mod_cgid does not work on this platform.  If you teach it to, look 
912 #error at mod_cgi.c for required code in this path.
913 #else 
914     if (r->finfo.filetype == 0) 
915         return log_scripterror(r, conf, HTTP_NOT_FOUND, 0, 
916                                "script not found or unable to stat"); 
917 #endif 
918     if (r->finfo.filetype == APR_DIR) 
919         return log_scripterror(r, conf, HTTP_FORBIDDEN, 0, 
920                                "attempt to invoke directory as script"); 
921 /*
922     if (!ap_suexec_enabled) { 
923         if (!ap_can_exec(&r->finfo)) 
924             return log_scripterror(r, conf, HTTP_FORBIDDEN, 0, 
925                                    "file permissions deny server execution"); 
926     } 
927 */
928     ap_add_common_vars(r); 
929     ap_add_cgi_vars(r); 
930     env = ap_create_environment(r->pool, r->subprocess_env); 
931
932     if ((sd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
933             return log_scripterror(r, conf, HTTP_INTERNAL_SERVER_ERROR, errno, 
934                                    "unable to create socket to cgi daemon");
935     } 
936     memset(&unix_addr, 0, sizeof(unix_addr));
937     unix_addr.sun_family = AF_UNIX;
938     strcpy(unix_addr.sun_path, conf->sockname);
939
940     if (connect(sd, (struct sockaddr *)&unix_addr, sizeof(unix_addr)) < 0) {
941             return log_scripterror(r, conf, HTTP_INTERNAL_SERVER_ERROR, errno, 
942                                    "unable to connect to cgi daemon");
943     } 
944
945     send_req(sd, r, argv0, env, CGI_REQ); 
946
947     /* We are putting the tempsock variable into a file so that we can use
948      * a pipe bucket to send the data to the client.
949      */
950     apr_os_file_put(&tempsock, &sd, r->pool);
951
952     if ((retval = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR))) 
953         return retval; 
954      
955     if ((argv0 = strrchr(r->filename, '/')) != NULL) 
956         argv0++; 
957     else 
958         argv0 = r->filename; 
959
960     /* Transfer any put/post args, CERN style... 
961      * Note that we already ignore SIGPIPE in the core server. 
962      */ 
963
964     if (ap_should_client_block(r)) { 
965         int dbsize, len_read; 
966
967         if (conf->logname) { 
968             dbuf = apr_pcalloc(r->pool, conf->bufbytes + 1); 
969             dbpos = 0; 
970         } 
971
972         while ((len_read = 
973                 ap_get_client_block(r, argsbuffer, HUGE_STRING_LEN)) > 0) { 
974             if (conf->logname) { 
975                 if ((dbpos + len_read) > conf->bufbytes) { 
976                     dbsize = conf->bufbytes - dbpos; 
977                 } 
978                 else { 
979                     dbsize = len_read; 
980                 } 
981                 memcpy(dbuf + dbpos, argsbuffer, dbsize); 
982                 dbpos += dbsize; 
983             } 
984             nbytes = len_read;
985             apr_file_write(tempsock, argsbuffer, &nbytes);
986             if (nbytes < len_read) { 
987                 /* silly script stopped reading, soak up remaining message */ 
988                 while (ap_get_client_block(r, argsbuffer, HUGE_STRING_LEN) > 0) { 
989                     /* dump it */ 
990                 } 
991                 break; 
992             } 
993         } 
994     } 
995     /* we're done writing, or maybe we didn't write at all;
996      * force EOF on child's stdin so that the cgi detects end (or
997      * absence) of data
998      */
999     shutdown(sd, 1);
1000
1001     /* Handle script return... */ 
1002     if (!nph) { 
1003         const char *location; 
1004         char sbuf[MAX_STRING_LEN]; 
1005         int ret; 
1006
1007         if ((ret = ap_scan_script_header_err(r, tempsock, sbuf))) { 
1008             return log_script(r, conf, ret, dbuf, sbuf, tempsock, NULL); 
1009         } 
1010
1011         location = apr_table_get(r->headers_out, "Location"); 
1012
1013         if (location && location[0] == '/' && r->status == 200) { 
1014
1015             /* Soak up all the script output */ 
1016             while (apr_file_gets(argsbuffer, HUGE_STRING_LEN, tempsock) > 0) { 
1017                 continue; 
1018             } 
1019             /* This redirect needs to be a GET no matter what the original 
1020              * method was. 
1021              */ 
1022             r->method = apr_pstrdup(r->pool, "GET"); 
1023             r->method_number = M_GET; 
1024
1025             /* We already read the message body (if any), so don't allow 
1026              * the redirected request to think it has one. We can ignore 
1027              * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR. 
1028              */ 
1029             apr_table_unset(r->headers_in, "Content-Length"); 
1030
1031             ap_internal_redirect_handler(location, r); 
1032             return OK; 
1033         } 
1034         else if (location && r->status == 200) { 
1035             /* XX Note that if a script wants to produce its own Redirect 
1036              * body, it now has to explicitly *say* "Status: 302" 
1037              */ 
1038             return HTTP_MOVED_TEMPORARILY; 
1039         } 
1040
1041         if (!r->header_only) { 
1042             bb = apr_brigade_create(r->pool);
1043             b = apr_bucket_pipe_create(tempsock);
1044             APR_BRIGADE_INSERT_TAIL(bb, b);
1045             b = apr_bucket_eos_create();
1046             APR_BRIGADE_INSERT_TAIL(bb, b);
1047             ap_pass_brigade(r->output_filters, bb);
1048         } 
1049     } 
1050
1051     if (nph) {
1052         bb = apr_brigade_create(r->pool);
1053         b = apr_bucket_pipe_create(tempsock);
1054         APR_BRIGADE_INSERT_TAIL(bb, b);
1055         b = apr_bucket_eos_create();
1056         APR_BRIGADE_INSERT_TAIL(bb, b);
1057         ap_pass_brigade(r->output_filters, bb);
1058     } 
1059
1060     apr_file_close(tempsock);
1061
1062     return OK; /* NOT r->status, even if it has changed. */ 
1063
1064
1065
1066
1067
1068 /*============================================================================
1069  *============================================================================
1070  * This is the beginning of the cgi filter code moved from mod_include. This
1071  *   is the code required to handle the "exec" SSI directive.
1072  *============================================================================
1073  *============================================================================*/
1074 static int include_cgi(char *s, request_rec *r, ap_filter_t *next,
1075                        apr_bucket *head_ptr, apr_bucket **inserted_head)
1076 {
1077     request_rec *rr = ap_sub_req_lookup_uri(s, r, next);
1078     int rr_status;
1079     apr_bucket  *tmp_buck, *tmp2_buck;
1080
1081     if (rr->status != HTTP_OK) {
1082         ap_destroy_sub_req(rr);
1083         return -1;
1084     }
1085
1086     /* No hardwired path info or query allowed */
1087
1088     if ((rr->path_info && rr->path_info[0]) || rr->args) {
1089         ap_destroy_sub_req(rr);
1090         return -1;
1091     }
1092     if (rr->finfo.filetype != APR_REG) {
1093         ap_destroy_sub_req(rr);
1094         return -1;
1095     }
1096
1097     /* Script gets parameters of the *document*, for back compatibility */
1098
1099     rr->path_info = r->path_info;       /* hard to get right; see mod_cgi.c */
1100     rr->args = r->args;
1101
1102     /* Force sub_req to be treated as a CGI request, even if ordinary
1103      * typing rules would have called it something else.
1104      */
1105
1106     rr->content_type = CGI_MAGIC_TYPE;
1107
1108     /* Run it. */
1109
1110     rr_status = ap_run_sub_req(rr);
1111     if (ap_is_HTTP_REDIRECT(rr_status)) {
1112         apr_size_t len_loc, h_wrt;
1113         const char *location = apr_table_get(rr->headers_out, "Location");
1114
1115         location = ap_escape_html(rr->pool, location);
1116         len_loc = strlen(location);
1117
1118         tmp_buck = apr_bucket_immortal_create("<A HREF=\"", sizeof("<A HREF=\""));
1119         APR_BUCKET_INSERT_BEFORE(head_ptr, tmp_buck);
1120         tmp2_buck = apr_bucket_heap_create(location, len_loc, 1, &h_wrt);
1121         APR_BUCKET_INSERT_BEFORE(head_ptr, tmp2_buck);
1122         tmp2_buck = apr_bucket_immortal_create("\">", sizeof("\">"));
1123         APR_BUCKET_INSERT_BEFORE(head_ptr, tmp2_buck);
1124         tmp2_buck = apr_bucket_heap_create(location, len_loc, 1, &h_wrt);
1125         APR_BUCKET_INSERT_BEFORE(head_ptr, tmp2_buck);
1126         tmp2_buck = apr_bucket_immortal_create("</A>", sizeof("</A>"));
1127         APR_BUCKET_INSERT_BEFORE(head_ptr, tmp2_buck);
1128
1129         if (*inserted_head == NULL) {
1130             *inserted_head = tmp_buck;
1131         }
1132     }
1133
1134     ap_destroy_sub_req(rr);
1135
1136     return 0;
1137 }
1138
1139
1140 /* This is the special environment used for running the "exec cmd="
1141  *   variety of SSI directives.
1142  */
1143 static void add_ssi_vars(request_rec *r, ap_filter_t *next)
1144 {
1145     apr_table_t *e = r->subprocess_env;
1146
1147     if (r->path_info && r->path_info[0] != '\0') {
1148         request_rec *pa_req;
1149
1150         apr_table_setn(e, "PATH_INFO", ap_escape_shell_cmd(r->pool, r->path_info));
1151
1152         pa_req = ap_sub_req_lookup_uri(ap_escape_uri(r->pool, r->path_info), r, next);
1153         if (pa_req->filename) {
1154             apr_table_setn(e, "PATH_TRANSLATED",
1155                            apr_pstrcat(r->pool, pa_req->filename, pa_req->path_info, NULL));
1156         }
1157         ap_destroy_sub_req(pa_req);
1158     }
1159
1160     if (r->args) {
1161         char *arg_copy = apr_pstrdup(r->pool, r->args);
1162
1163         apr_table_setn(e, "QUERY_STRING", r->args);
1164         ap_unescape_url(arg_copy);
1165         apr_table_setn(e, "QUERY_STRING_UNESCAPED", ap_escape_shell_cmd(r->pool, arg_copy));
1166     }
1167 }
1168
1169 static int include_cmd(include_ctx_t *ctx, apr_bucket_brigade **bb, char *command,
1170                        request_rec *r, ap_filter_t *f)
1171 {
1172     char **env; 
1173     const char *location; 
1174     int sd;
1175     int retval; 
1176     apr_bucket_brigade *bcgi;
1177     apr_bucket *b;
1178     struct sockaddr_un unix_addr;
1179     apr_file_t *tempsock = NULL;
1180     cgid_server_conf *conf = ap_get_module_config(r->server->module_config,
1181                                                   &cgid_module); 
1182
1183     add_ssi_vars(r, f->next);
1184     env = ap_create_environment(r->pool, r->subprocess_env);
1185
1186     if ((sd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
1187             return log_scripterror(r, conf, HTTP_INTERNAL_SERVER_ERROR, 0, 
1188                                    "unable to create socket to cgi daemon");
1189     }
1190
1191     memset(&unix_addr, 0, sizeof(unix_addr));
1192     unix_addr.sun_family = AF_UNIX;
1193     strcpy(unix_addr.sun_path, conf->sockname);
1194
1195     if (connect(sd, (struct sockaddr *)&unix_addr, sizeof(unix_addr)) < 0) {
1196             return log_scripterror(r, conf, HTTP_INTERNAL_SERVER_ERROR, 0, 
1197                                    "unable to connect to cgi daemon");
1198     } 
1199
1200     retval = split_and_pass_pretag_buckets(bb, ctx, f->next);
1201     if (retval != APR_SUCCESS) {
1202         return retval;
1203     }
1204
1205     send_req(sd, r, command, env, SSI_REQ); 
1206
1207     /* We are putting the tempsock variable into a file so that we can use
1208      * a pipe bucket to send the data to the client.
1209      */
1210     apr_os_file_put(&tempsock, &sd, r->pool);
1211
1212     if ((retval = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR))) 
1213         return retval; 
1214     
1215     location = apr_table_get(r->headers_out, "Location"); 
1216
1217     if (location && location[0] == '/' && r->status == 200) { 
1218         char argsbuffer[HUGE_STRING_LEN]; 
1219
1220         /* Soak up all the script output */ 
1221         while (apr_file_gets(argsbuffer, HUGE_STRING_LEN, tempsock) > 0) { 
1222             continue; 
1223         } 
1224         /* This redirect needs to be a GET no matter what the original 
1225          * method was. 
1226          */ 
1227         r->method = apr_pstrdup(r->pool, "GET"); 
1228         r->method_number = M_GET; 
1229
1230         /* We already read the message body (if any), so don't allow 
1231          * the redirected request to think it has one. We can ignore 
1232          * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR. 
1233          */ 
1234         apr_table_unset(r->headers_in, "Content-Length"); 
1235
1236         ap_internal_redirect_handler(location, r); 
1237         return OK; 
1238     } 
1239     else if (location && r->status == 200) { 
1240         /* XX Note that if a script wants to produce its own Redirect 
1241          * body, it now has to explicitly *say* "Status: 302" 
1242          */ 
1243         return HTTP_MOVED_TEMPORARILY; 
1244     } 
1245
1246     if (!r->header_only) { 
1247         bcgi = apr_brigade_create(r->pool);
1248         b    = apr_bucket_pipe_create(tempsock);
1249         APR_BRIGADE_INSERT_TAIL(bcgi, b);
1250         ap_pass_brigade(f->next, bcgi);
1251     } 
1252
1253     return 0;
1254 }
1255
1256 static int handle_exec(include_ctx_t *ctx, apr_bucket_brigade **bb, request_rec *r,
1257                        ap_filter_t *f, apr_bucket *head_ptr, apr_bucket **inserted_head)
1258 {
1259     char *tag     = NULL;
1260     char *tag_val = NULL;
1261     char *file = r->filename;
1262     apr_bucket  *tmp_buck;
1263     char parsed_string[MAX_STRING_LEN];
1264     int retval;
1265
1266     *inserted_head = NULL;
1267     if (ctx->flags & FLAG_PRINTING) {
1268         if (ctx->flags & FLAG_NO_EXEC) {
1269             ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1270                       "exec used but not allowed in %s", r->filename);
1271             CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, *inserted_head);
1272         }
1273         else {
1274             while (1) {
1275                 cgid_pfn_gtv(ctx, &tag, &tag_val, 1);
1276                 if (tag_val == NULL) {
1277                     if (tag == NULL) {
1278                         return (0);
1279                     }
1280                     else {
1281                         return 1;
1282                     }
1283                 }
1284                 if (!strcmp(tag, "cmd")) {
1285                     cgid_pfn_ps(r, tag_val, parsed_string, sizeof(parsed_string), 1);
1286                     if (include_cmd(ctx, bb, parsed_string, r, f) == -1) {
1287                         ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1288                                     "execution failure for parameter \"%s\" "
1289                                     "to tag exec in file %s", tag, r->filename);
1290                         CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, *inserted_head);
1291                     }
1292                     /* just in case some stooge changed directories */
1293                 }
1294                 else if (!strcmp(tag, "cgi")) {
1295                     cgid_pfn_ps(r, tag_val, parsed_string, sizeof(parsed_string), 0);
1296                     retval = split_and_pass_pretag_buckets(bb, ctx, f->next);
1297                     if (retval != APR_SUCCESS) {
1298                         return retval;
1299                     }
1300
1301                     if (include_cgi(parsed_string, r, f->next, head_ptr, inserted_head) == -1) {
1302                         ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1303                                     "invalid CGI ref \"%s\" in %s", tag_val, file);
1304                         CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, *inserted_head);
1305                     }
1306                 }
1307                 else {
1308                     ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1309                                 "unknown parameter \"%s\" to tag exec in %s", tag, file);
1310                     CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, *inserted_head);
1311                 }
1312             }
1313         }
1314     }
1315     return 0;
1316 }
1317 /*============================================================================
1318  *============================================================================
1319  * This is the end of the cgi filter code moved from mod_include.
1320  *============================================================================
1321  *============================================================================*/
1322
1323
1324 static void register_hook(apr_pool_t *p)
1325 {
1326     static const char * const aszPre[] = { "mod_include.c", NULL };
1327
1328     ap_hook_post_config(cgid_init, aszPre, NULL, APR_HOOK_MIDDLE);
1329     ap_hook_handler(cgid_handler, NULL, NULL, APR_HOOK_MIDDLE);
1330 }
1331
1332 module AP_MODULE_DECLARE_DATA cgid_module = { 
1333     STANDARD20_MODULE_STUFF, 
1334     NULL, /* dir config creater */ 
1335     NULL, /* dir merger --- default is to override */ 
1336     create_cgid_config, /* server config */ 
1337     merge_cgid_config, /* merge server config */ 
1338     cgid_cmds, /* command table */ 
1339     register_hook /* register_handlers */ 
1340 }; 
1341