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