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