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