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