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