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