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