]> granicus.if.org Git - apache/blob - modules/generators/mod_cgid.c
438817f27f483bf191232b3bfa59d8747c7c0f15
[apache] / modules / generators / mod_cgid.c
1 /* ====================================================================
2  * The Apache Software License, Version 1.1
3  *
4  * Copyright (c) 2000-2002 The Apache Software Foundation.  All rights
5  * reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  *
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in
16  *    the documentation and/or other materials provided with the
17  *    distribution.
18  *
19  * 3. The end-user documentation included with the redistribution,
20  *    if any, must include the following acknowledgment:
21  *       "This product includes software developed by the
22  *        Apache Software Foundation (http://www.apache.org/)."
23  *    Alternately, this acknowledgment may appear in the software itself,
24  *    if and wherever such third-party acknowledgments normally appear.
25  *
26  * 4. The names "Apache" and "Apache Software Foundation" must
27  *    not be used to endorse or promote products derived from this
28  *    software without prior written permission. For written
29  *    permission, please contact apache@apache.org.
30  *
31  * 5. Products derived from this software may not be called "Apache",
32  *    nor may "Apache" appear in their name, without prior written
33  *    permission of the Apache Software Foundation.
34  *
35  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38  * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
39  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
46  * SUCH DAMAGE.
47  * ====================================================================
48  *
49  * This software consists of voluntary contributions made by many
50  * individuals on behalf of the Apache Software Foundation.  For more
51  * information on the Apache Software Foundation, please see
52  * <http://www.apache.org/>.
53  *
54  * Portions of this software are based upon public domain software
55  * originally written at the National Center for Supercomputing Applications,
56  * University of Illinois, Urbana-Champaign.
57  */
58
59 /* 
60  * http_script: keeps all script-related ramblings together. 
61  * 
62  * Compliant to cgi/1.1 spec 
63  * 
64  * Adapted by rst from original NCSA code by Rob McCool 
65  * 
66  * Apache adds some new env vars; REDIRECT_URL and REDIRECT_QUERY_STRING for 
67  * custom error responses, and DOCUMENT_ROOT because we found it useful. 
68  * It also adds SERVER_ADMIN - useful for scripts to know who to mail when 
69  * they fail. 
70  */ 
71
72 #include "apr_lib.h"
73 #include "apr_strings.h"
74 #include "apr_general.h"
75 #include "apr_file_io.h"
76 #include "apr_portable.h"
77 #include "apr_buckets.h"
78 #include "apr_optional.h"
79 #include "apr_signal.h"
80
81 #define APR_WANT_STRFUNC
82 #include "apr_want.h"
83
84 #if APR_HAVE_SYS_SOCKET_H
85 #include <sys/socket.h>
86 #endif
87 #if APR_HAVE_UNISTD_H
88 #include <unistd.h>
89 #endif
90 #if APR_HAVE_SYS_TYPES_H
91 #include <sys/types.h>
92 #endif
93
94 #define CORE_PRIVATE 
95
96 #include "util_filter.h"
97 #include "httpd.h" 
98 #include "http_config.h" 
99 #include "http_request.h" 
100 #include "http_core.h" 
101 #include "http_protocol.h" 
102 #include "http_main.h" 
103 #include "http_log.h" 
104 #include "util_script.h" 
105 #include "ap_mpm.h"
106 #include "unixd.h"
107 #include "mod_suexec.h"
108 #include "../filters/mod_include.h"
109
110 #include "mod_core.h"
111
112
113 /* ### should be tossed in favor of APR */
114 #include <sys/stat.h>
115 #include <sys/un.h> /* for sockaddr_un */
116
117
118 module AP_MODULE_DECLARE_DATA cgid_module; 
119
120 static int cgid_init(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *main_server); 
121 static int handle_exec(include_ctx_t *ctx, apr_bucket_brigade **bb, request_rec *r,
122                        ap_filter_t *f, apr_bucket *head_ptr, apr_bucket **inserted_head);
123
124 static APR_OPTIONAL_FN_TYPE(ap_register_include_handler) *cgid_pfn_reg_with_ssi;
125 static APR_OPTIONAL_FN_TYPE(ap_ssi_get_tag_and_value) *cgid_pfn_gtv;
126 static APR_OPTIONAL_FN_TYPE(ap_ssi_parse_string) *cgid_pfn_ps;
127
128 static apr_pool_t *pcgi; 
129 static int total_modules = 0;
130 static pid_t daemon_pid;
131 static int daemon_should_exit = 0;
132
133 /* Read and discard the data in the brigade produced by a CGI script */
134 static void discard_script_output(apr_bucket_brigade *bb);
135
136 /* KLUDGE --- for back-combatibility, we don't have to check ExecCGI
137  * in ScriptAliased directories, which means we need to know if this 
138  * request came through ScriptAlias or not... so the Alias module 
139  * leaves a note for us. 
140  */ 
141
142 static int is_scriptaliased(request_rec *r) 
143
144     const char *t = apr_table_get(r->notes, "alias-forced-type"); 
145     return t && (!strcasecmp(t, "cgi-script")); 
146
147
148 /* Configuration stuff */ 
149
150 #define DEFAULT_LOGBYTES 10385760 
151 #define DEFAULT_BUFBYTES 1024 
152 #define DEFAULT_SOCKET  DEFAULT_REL_RUNTIMEDIR "/cgisock"
153
154 #define CGI_REQ    1
155 #define SSI_REQ    2
156 #define GETPID_REQ 3 /* get the pid of script created for prior request */
157
158 /* DEFAULT_CGID_LISTENBACKLOG controls the max depth on the unix socket's
159  * pending connection queue.  If a bunch of cgi requests arrive at about
160  * the same time, connections from httpd threads/processes will back up
161  * in the queue while the cgid process slowly forks off a child to process
162  * each connection on the unix socket.  If the queue is too short, the
163  * httpd process will get ECONNREFUSED when trying to connect.
164  */
165 #ifndef DEFAULT_CGID_LISTENBACKLOG
166 #define DEFAULT_CGID_LISTENBACKLOG 100
167 #endif
168
169 /* DEFAULT_CONNECT_ATTEMPTS controls how many times we'll try to connect
170  * to the cgi daemon from the thread/process handling the cgi request.
171  * Generally we want to retry when we get ECONNREFUSED since it is
172  * probably because the listen queue is full.  We need to try harder so
173  * the client doesn't see it as a 503 error.
174  *
175  * Set this to 0 to continually retry until the connect works or Apache
176  * terminates.
177  */
178 #ifndef DEFAULT_CONNECT_ATTEMPTS
179 #define DEFAULT_CONNECT_ATTEMPTS  15
180 #endif
181
182 typedef struct { 
183     const char *sockname;
184     const char *logname; 
185     long logbytes; 
186     int bufbytes; 
187 } cgid_server_conf; 
188
189 typedef struct {
190     int req_type; /* request type (CGI_REQ, SSI_REQ, etc.) */
191     unsigned long conn_id; /* connection id; daemon uses this as a hash value
192                             * to find the script pid when it is time for that
193                             * process to be cleaned up
194                             */
195     int core_module_index;
196     int have_suexec;
197     int suexec_module_index;
198     suexec_config_t suexec_cfg;
199     int env_count;
200     apr_size_t filename_len;
201     apr_size_t argv0_len;
202     apr_size_t uri_len;
203     apr_size_t args_len;
204     apr_size_t mod_userdir_user_len;
205 } cgid_req_t;
206
207 /* If a request includes query info in the URL (stuff after "?"), and
208  * the query info does not contain "=" (indicative of a FORM submission),
209  * then this routine is called to create the argument list to be passed
210  * to the CGI script.  When suexec is enabled, the suexec path, user, and
211  * group are the first three arguments to be passed; if not, all three
212  * must be NULL.  The query info is split into separate arguments, where
213  * "+" is the separator between keyword arguments.
214  */
215 static char **create_argv(apr_pool_t *p, char *path, char *user, char *group,
216                           char *av0, const char *args)
217 {
218     int x, numwords;
219     char **av;
220     char *w;
221     int idx = 0;
222
223     /* count the number of keywords */
224
225     for (x = 0, numwords = 1; args[x]; x++) {
226         if (args[x] == '+') {
227             ++numwords;
228         }
229     }
230
231     if (numwords > APACHE_ARG_MAX - 5) {
232         numwords = APACHE_ARG_MAX - 5;  /* Truncate args to prevent overrun */
233     }
234     av = (char **) apr_pcalloc(p, (numwords + 5) * sizeof(char *));
235
236     if (path) {
237         av[idx++] = path;
238     }
239     if (user) {
240         av[idx++] = user;
241     }
242     if (group) {
243         av[idx++] = group;
244     }
245
246     av[idx++] = apr_pstrdup(p, av0);
247
248     for (x = 1; x <= numwords; x++) {
249         w = ap_getword_nulls(p, &args, '+');
250         if (strcmp(w, "")) {
251             ap_unescape_url(w);
252             av[idx++] = ap_escape_shell_cmd(p, w);
253         }
254     }
255     av[idx] = NULL;
256     return av;
257 }
258
259 #if APR_HAS_OTHER_CHILD
260 static void cgid_maint(int reason, void *data, apr_wait_t status)
261 {
262     pid_t *sd = data;
263
264     switch (reason) {
265         case APR_OC_REASON_DEATH:
266         case APR_OC_REASON_RESTART:
267             /* don't do anything; server is stopping or restarting */
268             apr_proc_other_child_unregister(data);
269             break;
270         case APR_OC_REASON_LOST:
271             /* it would be better to restart just the cgid child
272              * process but for now we'll gracefully restart the entire 
273              * server by sending AP_SIG_GRACEFUL to ourself, the httpd 
274              * parent process
275              */
276             kill(getpid(), AP_SIG_GRACEFUL);
277             break;
278         case APR_OC_REASON_UNREGISTER:
279             /* we get here when pcgi is cleaned up; pcgi gets cleaned
280              * up when pconf gets cleaned up
281              */
282             kill(*sd, SIGHUP); /* send signal to daemon telling it to die */
283             break;
284     }
285 }
286 #endif
287
288 /* deal with incomplete reads and signals
289  * assume you really have to read buf_size bytes
290  */
291 static apr_status_t sock_read(int fd, void *vbuf, size_t buf_size)
292 {
293     char *buf = vbuf;
294     int rc;
295     size_t bytes_read = 0;
296
297     do {
298         do {
299             rc = read(fd, buf + bytes_read, buf_size - bytes_read);
300         } while (rc < 0 && errno == EINTR);
301         switch(rc) {
302         case -1:
303             return errno;
304         case 0: /* unexpected */
305             return ECONNRESET;
306         default:
307             bytes_read += rc;
308         }
309     } while (bytes_read < buf_size);
310
311     return APR_SUCCESS;
312 }
313
314 /* deal with signals
315  */
316 static apr_status_t sock_write(int fd, const void *buf, size_t buf_size)
317 {
318     int rc;
319
320     do {
321         rc = write(fd, buf, buf_size);
322     } while (rc < 0 && errno == EINTR);
323     if (rc < 0) {
324         return errno;
325     }
326
327     return APR_SUCCESS;
328 }
329
330 static apr_status_t get_req(int fd, request_rec *r, char **argv0, char ***env, 
331                             cgid_req_t *req)
332
333     int i; 
334     char *user;
335     char **environ; 
336     core_dir_config *temp_core; 
337     void **dconf;
338     apr_status_t stat;
339
340     r->server = apr_pcalloc(r->pool, sizeof(server_rec)); 
341
342     /* read the request header */
343     stat = sock_read(fd, req, sizeof(*req));
344     if (stat != APR_SUCCESS) {
345         return stat;
346     }
347     if (req->req_type == GETPID_REQ) {
348         /* no more data sent for this request */
349         return APR_SUCCESS;
350     }
351
352     /* handle module indexes and such */
353     dconf = (void **) apr_pcalloc(r->pool, sizeof(void *) * (total_modules + DYNAMIC_MODULE_LIMIT));
354
355     temp_core = (core_dir_config *)apr_palloc(r->pool, sizeof(core_module)); 
356     dconf[req->core_module_index] = (void *)temp_core;
357
358     if (req->have_suexec) {
359         dconf[req->suexec_module_index] = &req->suexec_cfg;
360     }
361
362     r->per_dir_config = (ap_conf_vector_t *)dconf; 
363
364     /* Read the filename, argv0, uri, and args */
365     r->filename = apr_pcalloc(r->pool, req->filename_len + 1);
366     *argv0 = apr_pcalloc(r->pool, req->argv0_len + 1);
367     r->uri = apr_pcalloc(r->pool, req->uri_len + 1);
368     if ((stat = sock_read(fd, r->filename, req->filename_len)) != APR_SUCCESS ||
369         (stat = sock_read(fd, *argv0, req->argv0_len)) != APR_SUCCESS ||
370         (stat = sock_read(fd, r->uri, req->uri_len)) != APR_SUCCESS) {
371         return stat;
372     }
373
374     r->args = apr_pcalloc(r->pool, req->args_len + 1); /* empty string if no args */
375     if (req->args_len) {
376         if ((stat = sock_read(fd, r->args, req->args_len)) != APR_SUCCESS) {
377             return stat;
378         }
379     }
380
381     /* read the environment variables */
382     environ = apr_pcalloc(r->pool, (req->env_count + 2) *sizeof(char *));
383     for (i = 0; i < req->env_count; i++) {
384         apr_size_t curlen;
385
386         if ((stat = sock_read(fd, &curlen, sizeof(curlen))) != APR_SUCCESS) {
387             return stat;
388         }
389         environ[i] = apr_pcalloc(r->pool, curlen + 1);
390         if ((stat = sock_read(fd, environ[i], curlen)) != APR_SUCCESS) {
391             return stat;
392         }
393     }
394     *env = environ;
395
396     /* basic notes table to avoid segfaults */
397     r->notes = apr_table_make(r->pool, 1);
398
399     /* mod_userdir requires the mod_userdir_user note */
400     if (req->mod_userdir_user_len) {
401         user = apr_pcalloc(r->pool, req->mod_userdir_user_len + 1); /* last byte is '\0' */
402         stat = sock_read(fd, user, req->mod_userdir_user_len);
403         if (stat != APR_SUCCESS) {
404             return stat;
405         }
406         apr_table_set(r->notes, "mod_userdir_user", (const char *)user);
407     }
408
409 #if 0
410 #ifdef RLIMIT_CPU 
411     sock_read(fd, &j, sizeof(int)); 
412     if (j) { 
413         temp_core->limit_cpu = (struct rlimit *)apr_palloc (sizeof(struct rlimit)); 
414         sock_read(fd, temp_core->limit_cpu, sizeof(struct rlimit)); 
415     } 
416     else { 
417         temp_core->limit_cpu = NULL; 
418     } 
419 #endif 
420
421 #if defined (RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS) 
422     sock_read(fd, &j, sizeof(int)); 
423     if (j) { 
424         temp_core->limit_mem = (struct rlimit *)apr_palloc(r->pool, sizeof(struct rlimit)); 
425         sock_read(fd, temp_core->limit_mem, sizeof(struct rlimit)); 
426     } 
427     else { 
428         temp_core->limit_mem = NULL; 
429     } 
430 #endif 
431
432 #ifdef RLIMIT_NPROC 
433     sock_read(fd, &j, sizeof(int)); 
434     if (j) { 
435         temp_core->limit_nproc = (struct rlimit *)apr_palloc(r->pool, sizeof(struct rlimit)); 
436         sock_read(fd, temp_core->limit_nproc, sizeof(struct rlimit)); 
437     } 
438     else { 
439         temp_core->limit_nproc = NULL; 
440     } 
441 #endif 
442 #endif
443
444     return APR_SUCCESS;
445
446
447 static apr_status_t send_req(int fd, request_rec *r, char *argv0, char **env, 
448                              int req_type) 
449
450     int i;
451     const char *user;
452     module *suexec_mod = ap_find_linked_module("mod_suexec.c");
453     cgid_req_t req = {0};
454     suexec_config_t *suexec_cfg;
455     apr_status_t stat;
456
457     req.req_type = req_type;
458     req.conn_id = r->connection->id;
459     req.core_module_index = core_module.module_index;
460     if (suexec_mod) {
461         req.have_suexec = 1;
462         req.suexec_module_index = suexec_mod->module_index;
463         suexec_cfg = ap_get_module_config(r->per_dir_config,
464                                           suexec_mod);
465         req.suexec_cfg = *suexec_cfg;
466     }
467     for (req.env_count = 0; env[req.env_count]; req.env_count++) {
468         continue; 
469     }
470     req.filename_len = strlen(r->filename);
471     req.argv0_len = strlen(argv0);
472     req.uri_len = strlen(r->uri);
473     req.args_len = r->args ? strlen(r->args) : 0;
474     user = (const char *)apr_table_get(r->notes, "mod_userdir_user");
475     if (user != NULL) {
476         req.mod_userdir_user_len = strlen(user);
477     }
478
479     /* Write the request header */
480     if ((stat = sock_write(fd, &req, sizeof(req))) != APR_SUCCESS) {
481         return stat;
482     }
483
484     /* Write filename, argv0, uri, and args */
485     if ((stat = sock_write(fd, r->filename, req.filename_len)) != APR_SUCCESS ||
486         (stat = sock_write(fd, argv0, req.argv0_len)) != APR_SUCCESS ||
487         (stat = sock_write(fd, r->uri, req.uri_len)) != APR_SUCCESS) {
488         return stat;
489     }
490     if (req.args_len) {
491         if ((stat = sock_write(fd, r->args, req.args_len)) != APR_SUCCESS) {
492             return stat;
493         }
494     }
495
496     /* write the environment variables */
497     for (i = 0; i < req.env_count; i++) {
498         apr_size_t curlen = strlen(env[i]);
499
500         if ((stat = sock_write(fd, &curlen, sizeof(curlen))) != APR_SUCCESS) {
501             return stat;
502         }
503             
504         if ((stat = sock_write(fd, env[i], curlen)) != APR_SUCCESS) {
505             return stat;
506         }
507     }
508
509     /* send a minimal notes table */
510     if (user) {
511         if ((stat = sock_write(fd, user, req.mod_userdir_user_len)) != APR_SUCCESS) {
512             return stat;
513         }
514     }
515
516 #if 0
517 #ifdef RLIMIT_CPU 
518     if (conf->limit_cpu) { 
519         len = 1; 
520         stat = sock_write(fd, &len, sizeof(int)); 
521         stat = sock_write(fd, conf->limit_cpu, sizeof(struct rlimit)); 
522     } 
523     else { 
524         len = 0; 
525         stat = sock_write(fd, &len, sizeof(int)); 
526     } 
527 #endif 
528
529 #if defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS) 
530     if (conf->limit_mem) { 
531         len = 1; 
532         stat = sock_write(fd, &len, sizeof(int)); 
533         stat = sock_write(fd, conf->limit_mem, sizeof(struct rlimit)); 
534     } 
535     else { 
536         len = 0; 
537         stat = sock_write(fd, &len, sizeof(int)); 
538     } 
539 #endif 
540   
541 #ifdef RLIMIT_NPROC 
542     if (conf->limit_nproc) { 
543         len = 1; 
544         stat = sock_write(fd, &len, sizeof(int)); 
545         stat = sock_write(fd, conf->limit_nproc, sizeof(struct rlimit)); 
546     } 
547     else { 
548         len = 0; 
549         stat = sock_write(fd, &len, sizeof(int)); 
550     } 
551 #endif
552 #endif
553     return APR_SUCCESS;
554
555
556 static void daemon_signal_handler(int sig)
557 {
558     if (sig == SIGHUP) {
559         ++daemon_should_exit;
560     }
561 }
562
563 static int cgid_server(void *data) 
564
565     struct sockaddr_un unix_addr;
566     int sd, sd2, rc;
567     mode_t omask;
568     apr_socklen_t len;
569     apr_pool_t *ptrans;
570     server_rec *main_server = data;
571     cgid_server_conf *sconf = ap_get_module_config(main_server->module_config,
572                                                    &cgid_module); 
573     apr_hash_t *script_hash = apr_hash_make(pcgi);
574
575     apr_pool_create(&ptrans, pcgi); 
576
577     apr_signal(SIGCHLD, SIG_IGN); 
578     apr_signal(SIGHUP, daemon_signal_handler);
579
580     if (unlink(sconf->sockname) < 0 && errno != ENOENT) {
581         ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
582                      "Couldn't unlink unix domain socket %s",
583                      sconf->sockname);
584         /* just a warning; don't bail out */
585     }
586
587     if ((sd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
588         ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server, 
589                      "Couldn't create unix domain socket");
590         return errno;
591     } 
592
593     memset(&unix_addr, 0, sizeof(unix_addr));
594     unix_addr.sun_family = AF_UNIX;
595     strcpy(unix_addr.sun_path, sconf->sockname);
596
597     omask = umask(0077); /* so that only Apache can use socket */
598     rc = bind(sd, (struct sockaddr *)&unix_addr, sizeof(unix_addr));
599     umask(omask); /* can't fail, so can't clobber errno */
600     if (rc < 0) {
601         ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server, 
602                      "Couldn't bind unix domain socket %s",
603                      sconf->sockname); 
604         return errno;
605     } 
606
607     if (listen(sd, DEFAULT_CGID_LISTENBACKLOG) < 0) {
608         ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server, 
609                      "Couldn't listen on unix domain socket"); 
610         return errno;
611     } 
612
613     if (!geteuid()) {
614         if (chown(sconf->sockname, unixd_config.user_id, -1) < 0) {
615             ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server, 
616                          "Couldn't change owner of unix domain socket %s",
617                          sconf->sockname); 
618             return errno;
619         }
620     }
621     
622     unixd_setup_child(); /* if running as root, switch to configured user/group */
623
624     while (!daemon_should_exit) {
625         int errfileno = STDERR_FILENO;
626         char *argv0; 
627         char **env; 
628         const char * const *argv; 
629         apr_int32_t in_pipe;
630         apr_int32_t out_pipe;
631         apr_int32_t err_pipe;
632         apr_cmdtype_e cmd_type;
633         request_rec *r;
634         apr_procattr_t *procattr = NULL;
635         apr_proc_t *procnew = NULL;
636         apr_file_t *inout;
637         cgid_req_t cgid_req;
638         apr_status_t stat;
639
640         apr_pool_clear(ptrans);
641
642         len = sizeof(unix_addr);
643         sd2 = accept(sd, (struct sockaddr *)&unix_addr, &len);
644         if (sd2 < 0) {
645             if (errno != EINTR) {
646                 ap_log_error(APLOG_MARK, APLOG_ERR, errno, 
647                              (server_rec *)data,
648                              "Error accepting on cgid socket");
649             }
650             continue;
651         }
652        
653         r = apr_pcalloc(ptrans, sizeof(request_rec)); 
654         procnew = apr_pcalloc(ptrans, sizeof(*procnew));
655         r->pool = ptrans; 
656         stat = get_req(sd2, r, &argv0, &env, &cgid_req); 
657         if (stat != APR_SUCCESS) {
658             ap_log_error(APLOG_MARK, APLOG_ERR, stat,
659                          main_server,
660                          "Error reading request on cgid socket");
661             close(sd2);
662             continue;
663         }
664
665         if (cgid_req.req_type == GETPID_REQ) {
666             pid_t pid;
667
668             pid = (pid_t)apr_hash_get(script_hash, &cgid_req.conn_id, sizeof(cgid_req.conn_id));
669             if (write(sd2, &pid, sizeof(pid)) != sizeof(pid)) {
670                 ap_log_error(APLOG_MARK, APLOG_ERR, 0,
671                              main_server,
672                              "Error writing pid %" APR_PID_T_FMT " to handler", pid);
673             }
674             close(sd2);
675             continue;
676         }
677
678         apr_os_file_put(&r->server->error_log, &errfileno, 0, r->pool);
679         apr_os_file_put(&inout, &sd2, 0, r->pool);
680
681         if (cgid_req.req_type == SSI_REQ) {
682             in_pipe  = APR_NO_PIPE;
683             out_pipe = APR_FULL_BLOCK;
684             err_pipe = APR_NO_PIPE;
685             cmd_type = APR_SHELLCMD;
686         }
687         else {
688             in_pipe  = APR_CHILD_BLOCK;
689             out_pipe = APR_CHILD_BLOCK;
690             err_pipe = APR_CHILD_BLOCK;
691             cmd_type = APR_PROGRAM;
692         }
693
694         if (((rc = apr_procattr_create(&procattr, ptrans)) != APR_SUCCESS) ||
695             ((cgid_req.req_type == CGI_REQ) && 
696              (((rc = apr_procattr_io_set(procattr,
697                                         in_pipe,
698                                         out_pipe,
699                                         err_pipe)) != APR_SUCCESS) ||
700               /* XXX apr_procattr_child_*_set() is creating an unnecessary 
701                * pipe between this process and the child being created...
702                * It is cleaned up with the temporary pool for this request.
703                */
704               ((rc = apr_procattr_child_err_set(procattr, r->server->error_log, NULL)) != APR_SUCCESS) ||
705               ((rc = apr_procattr_child_in_set(procattr, inout, NULL)) != APR_SUCCESS))) ||
706             ((rc = apr_procattr_child_out_set(procattr, inout, NULL)) != APR_SUCCESS) ||
707             ((rc = apr_procattr_dir_set(procattr,
708                                   ap_make_dirstr_parent(r->pool, r->filename))) != APR_SUCCESS) ||
709             ((rc = apr_procattr_cmdtype_set(procattr, cmd_type)) != APR_SUCCESS)) {
710             /* Something bad happened, tell the world. */
711             ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r,
712                       "couldn't set child process attributes: %s", r->filename);
713         }
714         else {
715             argv = (const char * const *)create_argv(r->pool, NULL, NULL, NULL, argv0, r->args);
716
717            /* We want to close sd2 for the new CGI process too.
718             * If it is left open it'll make ap_pass_brigade() block
719             * waiting for EOF if CGI forked something running long.
720             * close(sd2) here should be okay, as CGI channel
721             * is already dup()ed by apr_procattr_child_{in,out}_set()
722             * above.
723             */
724             close(sd2);
725
726             rc = ap_os_create_privileged_process(r, procnew, argv0, argv, 
727                                                  (const char * const *)env, 
728                                                  procattr, ptrans);
729
730             if (rc != APR_SUCCESS) {
731                 /* Bad things happened. Everyone should have cleaned up. */
732                 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_TOCLIENT, rc, r,
733                               "couldn't create child process: %d: %s", rc, 
734                               apr_filename_of_pathname(r->filename));
735             }
736             else {
737                 apr_hash_set(script_hash, &cgid_req.conn_id, sizeof(cgid_req.conn_id), 
738                              (void *)procnew->pid);
739             }
740         }
741     } 
742     return -1; 
743
744
745 static int cgid_init(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, 
746                       server_rec *main_server) 
747
748     apr_proc_t *procnew;
749     void *data;
750     int first_time = 0;
751     const char *userdata_key = "cgid_init";
752     module **m;
753
754     apr_pool_userdata_get(&data, userdata_key, main_server->process->pool);
755     if (!data) {
756         first_time = 1;
757         apr_pool_userdata_set((const void *)1, userdata_key,
758                          apr_pool_cleanup_null, main_server->process->pool);
759     }
760
761     if (!first_time) {
762         total_modules = 0;
763         for (m = ap_preloaded_modules; *m != NULL; m++)
764             total_modules++;
765
766         daemon_should_exit = 0; /* clear setting from previous generation */
767         if ((daemon_pid = fork()) < 0) {
768             ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server, 
769                          "mod_cgid: Couldn't spawn cgid daemon process"); 
770             return DECLINED;
771         }
772         else if (daemon_pid == 0) {
773             apr_pool_create(&pcgi, p); 
774             cgid_server(main_server);
775             exit(-1);
776         } 
777         procnew = apr_pcalloc(p, sizeof(*procnew));
778         procnew->pid = daemon_pid;
779         procnew->err = procnew->in = procnew->out = NULL;
780         apr_pool_note_subprocess(p, procnew, APR_KILL_AFTER_TIMEOUT);
781 #if APR_HAS_OTHER_CHILD
782         apr_proc_other_child_register(procnew, cgid_maint, &procnew->pid, NULL, p);
783 #endif
784
785         cgid_pfn_reg_with_ssi = APR_RETRIEVE_OPTIONAL_FN(ap_register_include_handler);
786         cgid_pfn_gtv          = APR_RETRIEVE_OPTIONAL_FN(ap_ssi_get_tag_and_value);
787         cgid_pfn_ps           = APR_RETRIEVE_OPTIONAL_FN(ap_ssi_parse_string);
788
789         if ((cgid_pfn_reg_with_ssi) && (cgid_pfn_gtv) && (cgid_pfn_ps)) {
790             /* Required by mod_include filter. This is how mod_cgid registers
791              *   with mod_include to provide processing of the exec directive.
792              */
793             cgid_pfn_reg_with_ssi("exec", handle_exec);
794         }
795     }
796     return OK;
797
798
799 static void *create_cgid_config(apr_pool_t *p, server_rec *s) 
800
801     cgid_server_conf *c = 
802     (cgid_server_conf *) apr_pcalloc(p, sizeof(cgid_server_conf)); 
803
804     c->logname = NULL; 
805     c->logbytes = DEFAULT_LOGBYTES; 
806     c->bufbytes = DEFAULT_BUFBYTES; 
807     c->sockname = ap_server_root_relative(p, DEFAULT_SOCKET); 
808     return c; 
809
810
811 static void *merge_cgid_config(apr_pool_t *p, void *basev, void *overridesv) 
812
813     cgid_server_conf *base = (cgid_server_conf *) basev, *overrides = (cgid_server_conf *) overridesv; 
814
815     return overrides->logname ? overrides : base; 
816
817
818 static const char *set_scriptlog(cmd_parms *cmd, void *dummy, const char *arg) 
819
820     server_rec *s = cmd->server; 
821     cgid_server_conf *conf = ap_get_module_config(s->module_config,
822                                                   &cgid_module); 
823
824     conf->logname = ap_server_root_relative(cmd->pool, arg);
825
826     if (!conf->logname) {
827         return apr_pstrcat(cmd->pool, "Invalid ScriptLog path ",
828                            arg, NULL);
829     }
830     return NULL; 
831
832
833 static const char *set_scriptlog_length(cmd_parms *cmd, void *dummy, const char *arg) 
834
835     server_rec *s = cmd->server; 
836     cgid_server_conf *conf = ap_get_module_config(s->module_config,
837                                                   &cgid_module); 
838
839     conf->logbytes = atol(arg); 
840     return NULL; 
841
842
843 static const char *set_scriptlog_buffer(cmd_parms *cmd, void *dummy, const char *arg) 
844
845     server_rec *s = cmd->server; 
846     cgid_server_conf *conf = ap_get_module_config(s->module_config,
847                                                   &cgid_module); 
848
849     conf->bufbytes = atoi(arg); 
850     return NULL; 
851
852
853 static const char *set_script_socket(cmd_parms *cmd, void *dummy, const char *arg) 
854
855     server_rec *s = cmd->server; 
856     cgid_server_conf *conf = ap_get_module_config(s->module_config,
857                                                   &cgid_module); 
858
859     conf->sockname = ap_server_root_relative(cmd->pool, arg); 
860
861     if (!conf->sockname) {
862         return apr_pstrcat(cmd->pool, "Invalid Scriptsock path ",
863                            arg, NULL);
864     }
865
866     return NULL; 
867
868
869 static const command_rec cgid_cmds[] = 
870
871     AP_INIT_TAKE1("ScriptLog", set_scriptlog, NULL, RSRC_CONF,
872                   "the name of a log for script debugging info"), 
873     AP_INIT_TAKE1("ScriptLogLength", set_scriptlog_length, NULL, RSRC_CONF,
874                   "the maximum length (in bytes) of the script debug log"), 
875     AP_INIT_TAKE1("ScriptLogBuffer", set_scriptlog_buffer, NULL, RSRC_CONF,
876                   "the maximum size (in bytes) to record of a POST request"), 
877     AP_INIT_TAKE1("Scriptsock", set_script_socket, NULL, RSRC_CONF,
878                   "the name of the socket to use for communication with "
879                   "the cgi daemon."), 
880     {NULL} 
881 }; 
882
883 static int log_scripterror(request_rec *r, cgid_server_conf * conf, int ret, 
884                            apr_status_t rv, char *error) 
885
886     apr_file_t *f = NULL; 
887     struct stat finfo; 
888     char time_str[APR_CTIME_LEN];
889     int log_flags = rv ? APLOG_ERR : APLOG_ERR;
890
891     ap_log_rerror(APLOG_MARK, log_flags, rv, r, 
892                 "%s: %s", error, r->filename); 
893
894     /* XXX Very expensive mainline case! Open, then getfileinfo! */
895     if (!conf->logname || 
896         ((stat(conf->logname, &finfo) == 0) 
897          && (finfo.st_size > conf->logbytes)) || 
898          (apr_file_open(&f, conf->logname,
899                   APR_APPEND|APR_WRITE|APR_CREATE, APR_OS_DEFAULT, r->pool) != APR_SUCCESS)) { 
900         return ret; 
901     } 
902
903     /* "%% [Wed Jun 19 10:53:21 1996] GET /cgid-bin/printenv HTTP/1.0" */ 
904     apr_ctime(time_str, apr_time_now());
905     apr_file_printf(f, "%%%% [%s] %s %s%s%s %s\n", time_str, r->method, r->uri, 
906             r->args ? "?" : "", r->args ? r->args : "", r->protocol); 
907     /* "%% 500 /usr/local/apache/cgid-bin */ 
908     apr_file_printf(f, "%%%% %d %s\n", ret, r->filename); 
909
910     apr_file_printf(f, "%%error\n%s\n", error); 
911
912     apr_file_close(f); 
913     return ret; 
914
915
916 static int log_script(request_rec *r, cgid_server_conf * conf, int ret, 
917                       char *dbuf, const char *sbuf, apr_bucket_brigade *bb,
918                       apr_file_t *script_err) 
919
920     const apr_array_header_t *hdrs_arr = apr_table_elts(r->headers_in); 
921     const apr_table_entry_t *hdrs = (apr_table_entry_t *) hdrs_arr->elts; 
922     char argsbuffer[HUGE_STRING_LEN]; 
923     apr_file_t *f = NULL; 
924     apr_bucket *e;
925     const char *buf;
926     apr_size_t len;
927     apr_status_t rv;
928     int first;
929     int i; 
930     struct stat finfo; 
931     char time_str[APR_CTIME_LEN];
932
933     /* XXX Very expensive mainline case! Open, then getfileinfo! */
934     if (!conf->logname || 
935         ((stat(conf->logname, &finfo) == 0) 
936          && (finfo.st_size > conf->logbytes)) || 
937          (apr_file_open(&f, conf->logname, 
938                   APR_APPEND|APR_WRITE|APR_CREATE, APR_OS_DEFAULT, r->pool) != APR_SUCCESS)) { 
939         /* Soak up script output */ 
940         discard_script_output(bb);
941         if (script_err) {
942             while (apr_file_gets(argsbuffer, HUGE_STRING_LEN, 
943                                  script_err) == APR_SUCCESS) 
944                 continue; 
945         }
946         return ret; 
947     } 
948
949     /* "%% [Wed Jun 19 10:53:21 1996] GET /cgid-bin/printenv HTTP/1.0" */ 
950     apr_ctime(time_str, apr_time_now());
951     apr_file_printf(f, "%%%% [%s] %s %s%s%s %s\n", time_str, r->method, r->uri, 
952             r->args ? "?" : "", r->args ? r->args : "", r->protocol); 
953     /* "%% 500 /usr/local/apache/cgid-bin" */ 
954     apr_file_printf(f, "%%%% %d %s\n", ret, r->filename); 
955
956     apr_file_puts("%request\n", f); 
957     for (i = 0; i < hdrs_arr->nelts; ++i) { 
958         if (!hdrs[i].key) 
959             continue; 
960         apr_file_printf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val); 
961     } 
962     if ((r->method_number == M_POST || r->method_number == M_PUT) 
963         && *dbuf) { 
964         apr_file_printf(f, "\n%s\n", dbuf); 
965     } 
966
967     apr_file_puts("%response\n", f); 
968     hdrs_arr = apr_table_elts(r->err_headers_out); 
969     hdrs = (const apr_table_entry_t *) hdrs_arr->elts; 
970
971     for (i = 0; i < hdrs_arr->nelts; ++i) { 
972         if (!hdrs[i].key) 
973             continue; 
974         apr_file_printf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val); 
975     } 
976
977     if (sbuf && *sbuf) 
978         apr_file_printf(f, "%s\n", sbuf); 
979
980     first = 1;
981     APR_BRIGADE_FOREACH(e, bb) {
982         if (APR_BUCKET_IS_EOS(e)) {
983             break;
984         }
985         rv = apr_bucket_read(e, &buf, &len, APR_BLOCK_READ);
986         if (!APR_STATUS_IS_SUCCESS(rv) || (len == 0)) {
987             break;
988         }
989         if (first) {
990             apr_file_puts("%stdout\n", f);
991             first = 0;
992         }
993         apr_file_write(f, buf, &len);
994         apr_file_puts("\n", f);
995     }
996
997     if (script_err) {
998         if (apr_file_gets(argsbuffer, HUGE_STRING_LEN, 
999                           script_err) == APR_SUCCESS) { 
1000             apr_file_puts("%stderr\n", f); 
1001             apr_file_puts(argsbuffer, f); 
1002             while (apr_file_gets(argsbuffer, HUGE_STRING_LEN, 
1003                                  script_err) == APR_SUCCESS) 
1004                 apr_file_puts(argsbuffer, f); 
1005             apr_file_puts("\n", f); 
1006         } 
1007     }
1008
1009     if (script_err) {
1010         apr_file_close(script_err); 
1011     }
1012
1013     apr_file_close(f); 
1014     return ret; 
1015
1016
1017 static apr_status_t close_unix_socket(void *thefd)
1018 {
1019     int fd = (int)thefd;
1020     
1021     return close(fd);
1022 }
1023
1024 static int connect_to_daemon(int *sdptr, request_rec *r,
1025                              cgid_server_conf *conf)
1026 {
1027     struct sockaddr_un unix_addr;
1028     int sd;
1029     int connect_tries;
1030     apr_interval_time_t sliding_timer;
1031
1032     memset(&unix_addr, 0, sizeof(unix_addr));
1033     unix_addr.sun_family = AF_UNIX;
1034     strcpy(unix_addr.sun_path, conf->sockname);
1035
1036     connect_tries = 0;
1037     sliding_timer = 100000; /* 100 milliseconds */
1038     while (1) {
1039         ++connect_tries;
1040         if ((sd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
1041             return log_scripterror(r, conf, HTTP_INTERNAL_SERVER_ERROR, errno, 
1042                                    "unable to create socket to cgi daemon");
1043         }
1044         if (connect(sd, (struct sockaddr *)&unix_addr, sizeof(unix_addr)) < 0) {
1045             if (errno == ECONNREFUSED && connect_tries < DEFAULT_CONNECT_ATTEMPTS) {
1046                 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, errno, r,
1047                               "connect #%d to cgi daemon failed, sleeping before retry",
1048                               connect_tries);
1049                 close(sd);
1050                 apr_sleep(sliding_timer);
1051                 if (sliding_timer < apr_time_from_sec(2)) {
1052                     sliding_timer *= 2;
1053                 }
1054             }
1055             else {
1056                 close(sd);
1057                 return log_scripterror(r, conf, HTTP_SERVICE_UNAVAILABLE, errno, 
1058                                        "unable to connect to cgi daemon after multiple tries");
1059             }
1060         }
1061         else {
1062             apr_pool_cleanup_register(r->pool, (void *)sd, close_unix_socket,
1063                                       apr_pool_cleanup_null);
1064             break; /* we got connected! */
1065         }
1066         /* gotta try again, but make sure the cgid daemon is still around */
1067         if (kill(daemon_pid, 0) != 0) {
1068             return log_scripterror(r, conf, HTTP_SERVICE_UNAVAILABLE, errno,
1069                                    "cgid daemon is gone; is Apache terminating?");
1070         }
1071     }
1072     *sdptr = sd;
1073     return OK;
1074 }
1075
1076 static void discard_script_output(apr_bucket_brigade *bb)
1077 {
1078     apr_bucket *e;
1079     const char *buf;
1080     apr_size_t len;
1081     apr_status_t rv;
1082     APR_BRIGADE_FOREACH(e, bb) {
1083         if (APR_BUCKET_IS_EOS(e)) {
1084             break;
1085         }
1086         rv = apr_bucket_read(e, &buf, &len, APR_BLOCK_READ);
1087         if (!APR_STATUS_IS_SUCCESS(rv)) {
1088             break;
1089         }
1090     }
1091 }
1092
1093 /**************************************************************** 
1094  * 
1095  * Actual cgid handling... 
1096  */ 
1097
1098 struct cleanup_script_info {
1099     request_rec *r;
1100     unsigned long conn_id;
1101     cgid_server_conf *conf;
1102 };
1103
1104 static apr_status_t dead_yet(pid_t pid, apr_interval_time_t max_wait)
1105 {
1106     apr_interval_time_t interval = 10000; /* 10 ms */
1107     apr_interval_time_t total = 0;
1108
1109     do {
1110         if (kill(pid, 0) < 0) {
1111             return APR_SUCCESS;
1112         }
1113         apr_sleep(interval);
1114         total = total + interval;
1115         if (interval < 500000) {
1116             interval *= 2;
1117         }
1118     } while (total < max_wait);
1119     return APR_EGENERAL;
1120 }
1121
1122 static apr_status_t cleanup_nonchild_process(request_rec *r, pid_t pid)
1123 {
1124     kill(pid, SIGTERM); /* in case it isn't dead yet */
1125     if (dead_yet(pid, apr_time_from_sec(3)) == APR_SUCCESS) {
1126         return APR_SUCCESS;
1127     }
1128     ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1129                   "CGI process %" APR_PID_T_FMT " didn't exit, sending SIGKILL",
1130                   pid);
1131     kill(pid, SIGKILL);
1132     if (dead_yet(pid, apr_time_from_sec(3)) == APR_SUCCESS) {
1133         return APR_SUCCESS;
1134     }
1135     ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1136                   "CGI process %" APR_PID_T_FMT " didn't exit, sending SIGKILL again",
1137                   pid);
1138     kill(pid, SIGKILL);
1139
1140     return APR_EGENERAL;
1141 }
1142
1143 static apr_status_t cleanup_script(void *vptr)
1144 {
1145     struct cleanup_script_info *info = vptr;
1146     int sd;
1147     int rc;
1148     cgid_req_t req = {0};
1149     pid_t pid;
1150     apr_status_t stat;
1151
1152     rc = connect_to_daemon(&sd, info->r, info->conf);
1153     if (rc != OK) {
1154         return APR_EGENERAL;
1155     }
1156
1157     req.req_type = GETPID_REQ;
1158     req.conn_id = info->r->connection->id;
1159
1160     stat = sock_write(sd, &req, sizeof(req));
1161     if (stat != APR_SUCCESS) {
1162         close(sd);
1163         return stat;
1164     }
1165
1166     /* wait for pid of script */
1167     stat = sock_read(sd, &pid, sizeof(pid));
1168     if (stat != APR_SUCCESS) {
1169         close(sd);
1170         return stat;
1171     }
1172     close(sd);
1173
1174     if (pid == 0) {
1175         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, info->r,
1176                       "daemon couldn't find CGI process for connection %lu",
1177                       info->conn_id);
1178         return APR_EGENERAL;
1179     }
1180     return cleanup_nonchild_process(info->r, pid);
1181 }
1182
1183 static int cgid_handler(request_rec *r) 
1184
1185     conn_rec *c = r->connection;
1186     int retval, nph, dbpos = 0; 
1187     char *argv0, *dbuf = NULL; 
1188     apr_bucket_brigade *bb;
1189     apr_bucket *b;
1190     cgid_server_conf *conf;
1191     int is_included;
1192     int seen_eos, child_stopped_reading;
1193     int sd;
1194     char **env; 
1195     apr_file_t *tempsock;
1196     struct cleanup_script_info *info;
1197     apr_status_t rv;
1198
1199     if (strcmp(r->handler,CGI_MAGIC_TYPE) && strcmp(r->handler,"cgi-script"))
1200         return DECLINED;
1201
1202     if (r->method_number == M_OPTIONS) { 
1203         /* 99 out of 100 cgid scripts, this is all they support */ 
1204         r->allowed |= (AP_METHOD_BIT << M_GET); 
1205         r->allowed |= (AP_METHOD_BIT << M_POST); 
1206         return DECLINED; 
1207     } 
1208
1209     conf = ap_get_module_config(r->server->module_config, &cgid_module); 
1210     is_included = !strcmp(r->protocol, "INCLUDED"); 
1211
1212     if ((argv0 = strrchr(r->filename, '/')) != NULL)
1213         argv0++;
1214     else
1215         argv0 = r->filename;
1216  
1217     nph = !(strncmp(argv0, "nph-", 4)); 
1218
1219     if ((argv0 = strrchr(r->filename, '/')) != NULL) 
1220         argv0++; 
1221     else 
1222         argv0 = r->filename; 
1223
1224     if (!(ap_allow_options(r) & OPT_EXECCGI) && !is_scriptaliased(r)) 
1225         return log_scripterror(r, conf, HTTP_FORBIDDEN, 0, 
1226                                "Options ExecCGI is off in this directory"); 
1227     if (nph && is_included) 
1228         return log_scripterror(r, conf, HTTP_FORBIDDEN, 0, 
1229                                "attempt to include NPH CGI script"); 
1230
1231 #if defined(OS2) || defined(WIN32)
1232 #error mod_cgid does not work on this platform.  If you teach it to, look 
1233 #error at mod_cgi.c for required code in this path.
1234 #else 
1235     if (r->finfo.filetype == 0) 
1236         return log_scripterror(r, conf, HTTP_NOT_FOUND, 0, 
1237                                "script not found or unable to stat"); 
1238 #endif 
1239     if (r->finfo.filetype == APR_DIR) 
1240         return log_scripterror(r, conf, HTTP_FORBIDDEN, 0, 
1241                                "attempt to invoke directory as script"); 
1242
1243     if ((r->used_path_info == AP_REQ_REJECT_PATH_INFO) &&
1244         r->path_info && *r->path_info)
1245     {
1246         /* default to accept */
1247         return log_scripterror(r, conf, HTTP_NOT_FOUND, 0,
1248                                "AcceptPathInfo off disallows user's path");
1249     }
1250 /*
1251     if (!ap_suexec_enabled) { 
1252         if (!ap_can_exec(&r->finfo)) 
1253             return log_scripterror(r, conf, HTTP_FORBIDDEN, 0, 
1254                                    "file permissions deny server execution"); 
1255     } 
1256 */
1257     ap_add_common_vars(r); 
1258     ap_add_cgi_vars(r); 
1259     env = ap_create_environment(r->pool, r->subprocess_env); 
1260
1261     if ((retval = connect_to_daemon(&sd, r, conf)) != OK) {
1262         return retval;
1263     }
1264
1265     rv = send_req(sd, r, argv0, env, CGI_REQ); 
1266     if (rv != APR_SUCCESS) {
1267         ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1268                      "write to cgi daemon process");
1269     }
1270
1271     info = apr_palloc(r->pool, sizeof(struct cleanup_script_info));
1272     info->r = r;
1273     info->conn_id = r->connection->id;
1274     info->conf = conf;
1275     apr_pool_cleanup_register(r->pool, info,
1276                               cleanup_script,
1277                               apr_pool_cleanup_null);
1278     /* We are putting the socket discriptor into an apr_file_t so that we can
1279      * use a pipe bucket to send the data to the client.
1280      * Note that this does not register a cleanup for the socket.  We did
1281      * that explicitly right after we created the socket.
1282      */
1283     apr_os_pipe_put(&tempsock, &sd, r->pool);
1284
1285     if ((argv0 = strrchr(r->filename, '/')) != NULL) 
1286         argv0++; 
1287     else 
1288         argv0 = r->filename; 
1289
1290     /* Transfer any put/post args, CERN style... 
1291      * Note that we already ignore SIGPIPE in the core server. 
1292      */ 
1293     bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
1294     seen_eos = 0;
1295     child_stopped_reading = 0;
1296     if (conf->logname) {
1297         dbuf = apr_palloc(r->pool, conf->bufbytes + 1);
1298         dbpos = 0;
1299     }
1300     do {
1301         apr_bucket *bucket;
1302
1303         rv = ap_get_brigade(r->input_filters, bb, AP_MODE_READBYTES,
1304                             APR_BLOCK_READ, HUGE_STRING_LEN);
1305        
1306         if (rv != APR_SUCCESS) {
1307             return rv;
1308         }
1309  
1310         APR_BRIGADE_FOREACH(bucket, bb) {
1311             const char *data;
1312             apr_size_t len;
1313
1314             if (APR_BUCKET_IS_EOS(bucket)) {
1315                 seen_eos = 1;
1316                 break;
1317             }
1318
1319             /* We can't do much with this. */
1320             if (APR_BUCKET_IS_FLUSH(bucket)) {
1321                 continue;
1322             }
1323
1324             /* If the child stopped, we still must read to EOS. */
1325             if (child_stopped_reading) {
1326                 continue;
1327             } 
1328
1329             /* read */
1330             apr_bucket_read(bucket, &data, &len, APR_BLOCK_READ);
1331             
1332             if (conf->logname && dbpos < conf->bufbytes) {
1333                 int cursize;
1334
1335                 if ((dbpos + len) > conf->bufbytes) {
1336                     cursize = conf->bufbytes - dbpos;
1337                 }
1338                 else {
1339                     cursize = len;
1340                 }
1341                 memcpy(dbuf + dbpos, data, cursize);
1342                 dbpos += cursize;
1343             }
1344
1345             /* Keep writing data to the child until done or too much time
1346              * elapses with no progress or an error occurs.
1347              */
1348             rv = apr_file_write_full(tempsock, data, len, NULL);
1349
1350             if (rv != APR_SUCCESS) {
1351                 /* silly script stopped reading, soak up remaining message */
1352                 child_stopped_reading = 1;
1353             }
1354         }
1355         apr_brigade_cleanup(bb);
1356     }
1357     while (!seen_eos);
1358  
1359     if (conf->logname) {
1360         dbuf[dbpos] = '\0';
1361     }
1362
1363     /* we're done writing, or maybe we didn't write at all;
1364      * force EOF on child's stdin so that the cgi detects end (or
1365      * absence) of data
1366      */
1367     shutdown(sd, 1);
1368
1369     /* Handle script return... */ 
1370     if (!nph) { 
1371         const char *location; 
1372         char sbuf[MAX_STRING_LEN]; 
1373         int ret; 
1374
1375         bb = apr_brigade_create(r->pool, c->bucket_alloc);
1376         b = apr_bucket_pipe_create(tempsock, c->bucket_alloc);
1377         APR_BRIGADE_INSERT_TAIL(bb, b);
1378         b = apr_bucket_eos_create(c->bucket_alloc);
1379         APR_BRIGADE_INSERT_TAIL(bb, b);
1380
1381         if ((ret = ap_scan_script_header_err_brigade(r, bb, sbuf))) { 
1382             return log_script(r, conf, ret, dbuf, sbuf, bb, NULL); 
1383         } 
1384
1385         location = apr_table_get(r->headers_out, "Location"); 
1386
1387         if (location && location[0] == '/' && r->status == 200) { 
1388
1389             /* Soak up all the script output */
1390             discard_script_output(bb);
1391             apr_brigade_destroy(bb);
1392             /* This redirect needs to be a GET no matter what the original 
1393              * method was. 
1394              */ 
1395             r->method = apr_pstrdup(r->pool, "GET"); 
1396             r->method_number = M_GET; 
1397
1398             /* We already read the message body (if any), so don't allow 
1399              * the redirected request to think it has one. We can ignore 
1400              * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR. 
1401              */ 
1402             apr_table_unset(r->headers_in, "Content-Length"); 
1403
1404             ap_internal_redirect_handler(location, r); 
1405             return OK; 
1406         } 
1407         else if (location && r->status == 200) { 
1408             /* XX Note that if a script wants to produce its own Redirect 
1409              * body, it now has to explicitly *say* "Status: 302" 
1410              */ 
1411             discard_script_output(bb);
1412             apr_brigade_destroy(bb);
1413             return HTTP_MOVED_TEMPORARILY; 
1414         } 
1415
1416         /* Passing our socket down the filter chain in a pipe bucket
1417          * gives up the responsibility of closing the socket, so
1418          * get rid of the cleanup.
1419          */
1420         apr_pool_cleanup_kill(r->pool, (void *)sd, close_unix_socket);
1421
1422         ap_pass_brigade(r->output_filters, bb);
1423     } 
1424
1425     if (nph) {
1426         struct ap_filter_t *cur;
1427         
1428         /* Passing our socket down the filter chain in a pipe bucket
1429          * gives up the responsibility of closing the socket, so
1430          * get rid of the cleanup.
1431          */
1432         apr_pool_cleanup_kill(r->pool, (void *)sd, close_unix_socket);
1433
1434         /* get rid of all filters up through protocol...  since we
1435          * haven't parsed off the headers, there is no way they can
1436          * work
1437          */
1438
1439         cur = r->proto_output_filters;
1440         while (cur && cur->frec->ftype < AP_FTYPE_CONNECTION) {
1441             cur = cur->next;
1442         }
1443         r->output_filters = r->proto_output_filters = cur;
1444
1445         bb = apr_brigade_create(r->pool, c->bucket_alloc);
1446         b = apr_bucket_pipe_create(tempsock, c->bucket_alloc);
1447         APR_BRIGADE_INSERT_TAIL(bb, b);
1448         b = apr_bucket_eos_create(c->bucket_alloc);
1449         APR_BRIGADE_INSERT_TAIL(bb, b);
1450         ap_pass_brigade(r->output_filters, bb);
1451     } 
1452
1453     return OK; /* NOT r->status, even if it has changed. */ 
1454
1455
1456
1457
1458
1459 /*============================================================================
1460  *============================================================================
1461  * This is the beginning of the cgi filter code moved from mod_include. This
1462  *   is the code required to handle the "exec" SSI directive.
1463  *============================================================================
1464  *============================================================================*/
1465 static int include_cgi(char *s, request_rec *r, ap_filter_t *next,
1466                        apr_bucket *head_ptr, apr_bucket **inserted_head)
1467 {
1468     request_rec *rr = ap_sub_req_lookup_uri(s, r, next);
1469     int rr_status;
1470     apr_bucket  *tmp_buck, *tmp2_buck;
1471
1472     if (rr->status != HTTP_OK) {
1473         ap_destroy_sub_req(rr);
1474         return -1;
1475     }
1476
1477     /* No hardwired path info or query allowed */
1478
1479     if ((rr->path_info && rr->path_info[0]) || rr->args) {
1480         ap_destroy_sub_req(rr);
1481         return -1;
1482     }
1483     if (rr->finfo.filetype != APR_REG) {
1484         ap_destroy_sub_req(rr);
1485         return -1;
1486     }
1487
1488     /* Script gets parameters of the *document*, for back compatibility */
1489
1490     rr->path_info = r->path_info;       /* hard to get right; see mod_cgi.c */
1491     rr->args = r->args;
1492
1493     /* Force sub_req to be treated as a CGI request, even if ordinary
1494      * typing rules would have called it something else.
1495      */
1496     ap_set_content_type(rr, CGI_MAGIC_TYPE);
1497
1498     /* Run it. */
1499
1500     rr_status = ap_run_sub_req(rr);
1501     if (ap_is_HTTP_REDIRECT(rr_status)) {
1502         apr_size_t len_loc;
1503         const char *location = apr_table_get(rr->headers_out, "Location");
1504         conn_rec *c = r->connection;
1505
1506         location = ap_escape_html(rr->pool, location);
1507         len_loc = strlen(location);
1508
1509         /* XXX: if most of this stuff is going to get copied anyway,
1510          * it'd be more efficient to pstrcat it into a single pool buffer
1511          * and a single pool bucket */
1512
1513         tmp_buck = apr_bucket_immortal_create("<A HREF=\"",
1514                                               sizeof("<A HREF=\"") - 1,
1515                                               c->bucket_alloc);
1516         APR_BUCKET_INSERT_BEFORE(head_ptr, tmp_buck);
1517         tmp2_buck = apr_bucket_heap_create(location, len_loc, NULL,
1518                                            c->bucket_alloc);
1519         APR_BUCKET_INSERT_BEFORE(head_ptr, tmp2_buck);
1520         tmp2_buck = apr_bucket_immortal_create("\">", sizeof("\">") - 1,
1521                                                c->bucket_alloc);
1522         APR_BUCKET_INSERT_BEFORE(head_ptr, tmp2_buck);
1523         tmp2_buck = apr_bucket_heap_create(location, len_loc, NULL,
1524                                            c->bucket_alloc);
1525         APR_BUCKET_INSERT_BEFORE(head_ptr, tmp2_buck);
1526         tmp2_buck = apr_bucket_immortal_create("</A>", sizeof("</A>") - 1,
1527                                                c->bucket_alloc);
1528         APR_BUCKET_INSERT_BEFORE(head_ptr, tmp2_buck);
1529
1530         if (*inserted_head == NULL) {
1531             *inserted_head = tmp_buck;
1532         }
1533     }
1534
1535     ap_destroy_sub_req(rr);
1536
1537     return 0;
1538 }
1539
1540
1541 /* This is the special environment used for running the "exec cmd="
1542  *   variety of SSI directives.
1543  */
1544 static void add_ssi_vars(request_rec *r, ap_filter_t *next)
1545 {
1546     apr_table_t *e = r->subprocess_env;
1547
1548     if (r->path_info && r->path_info[0] != '\0') {
1549         request_rec *pa_req;
1550
1551         apr_table_setn(e, "PATH_INFO", ap_escape_shell_cmd(r->pool, r->path_info));
1552
1553         pa_req = ap_sub_req_lookup_uri(ap_escape_uri(r->pool, r->path_info), r, NULL);
1554         if (pa_req->filename) {
1555             apr_table_setn(e, "PATH_TRANSLATED",
1556                            apr_pstrcat(r->pool, pa_req->filename, pa_req->path_info, NULL));
1557         }
1558         ap_destroy_sub_req(pa_req);
1559     }
1560
1561     if (r->args) {
1562         char *arg_copy = apr_pstrdup(r->pool, r->args);
1563
1564         apr_table_setn(e, "QUERY_STRING", r->args);
1565         ap_unescape_url(arg_copy);
1566         apr_table_setn(e, "QUERY_STRING_UNESCAPED", ap_escape_shell_cmd(r->pool, arg_copy));
1567     }
1568 }
1569
1570 static int include_cmd(include_ctx_t *ctx, apr_bucket_brigade **bb, char *command,
1571                        request_rec *r, ap_filter_t *f)
1572 {
1573     char **env; 
1574     const char *location; 
1575     int sd;
1576     apr_status_t rc = APR_SUCCESS; 
1577     int retval;
1578     apr_bucket_brigade *bcgi;
1579     apr_bucket *b;
1580     apr_file_t *tempsock = NULL;
1581     cgid_server_conf *conf = ap_get_module_config(r->server->module_config,
1582                                                   &cgid_module); 
1583     struct cleanup_script_info *info;
1584
1585     add_ssi_vars(r, f->next);
1586     env = ap_create_environment(r->pool, r->subprocess_env);
1587
1588     if ((retval = connect_to_daemon(&sd, r, conf)) != OK) {
1589         return retval;
1590     }
1591
1592     SPLIT_AND_PASS_PRETAG_BUCKETS(*bb, ctx, f->next, rc);
1593     if (rc != APR_SUCCESS) {
1594         return rc;
1595     }
1596
1597     send_req(sd, r, command, env, SSI_REQ); 
1598
1599     info = apr_palloc(r->pool, sizeof(struct cleanup_script_info));
1600     info->r = r;
1601     info->conn_id = r->connection->id;
1602     info->conf = conf;
1603     /* for this type of request, the script is invoked through an
1604      * intermediate shell process...  cleanup_script is only able 
1605      * to knock out the shell process, not the actual script
1606      */
1607     apr_pool_cleanup_register(r->pool, info,
1608                               cleanup_script,
1609                               apr_pool_cleanup_null);
1610     /* We are putting the socket discriptor into an apr_file_t so that we can
1611      * use a pipe bucket to send the data to the client.
1612      * Note that this does not register a cleanup for the socket.  We did
1613      * that explicitly right after we created the socket.
1614      */
1615     apr_os_pipe_put(&tempsock, &sd, r->pool);
1616
1617     if ((retval = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR))) 
1618         return retval; 
1619     
1620     location = apr_table_get(r->headers_out, "Location"); 
1621
1622     if (location && location[0] == '/' && r->status == 200) { 
1623         char argsbuffer[HUGE_STRING_LEN]; 
1624
1625         /* Soak up all the script output */ 
1626         while (apr_file_gets(argsbuffer, HUGE_STRING_LEN, 
1627                              tempsock) == APR_SUCCESS) { 
1628             continue; 
1629         } 
1630         /* This redirect needs to be a GET no matter what the original 
1631          * method was. 
1632          */ 
1633         r->method = apr_pstrdup(r->pool, "GET"); 
1634         r->method_number = M_GET; 
1635
1636         /* We already read the message body (if any), so don't allow 
1637          * the redirected request to think it has one. We can ignore 
1638          * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR. 
1639          */ 
1640         apr_table_unset(r->headers_in, "Content-Length"); 
1641
1642         ap_internal_redirect_handler(location, r); 
1643         return OK; 
1644     } 
1645     else if (location && r->status == 200) { 
1646         /* XX Note that if a script wants to produce its own Redirect 
1647          * body, it now has to explicitly *say* "Status: 302" 
1648          */ 
1649         return HTTP_MOVED_TEMPORARILY; 
1650     } 
1651
1652     if (!r->header_only) { 
1653         /* Passing our socket down the filter chain in a pipe bucket
1654          * gives up the responsibility of closing the socket, so
1655          * get rid of the cleanup.
1656          */
1657         apr_pool_cleanup_kill(r->pool, (void *)sd, close_unix_socket);
1658
1659         bcgi = apr_brigade_create(r->pool, r->connection->bucket_alloc);
1660         b    = apr_bucket_pipe_create(tempsock, r->connection->bucket_alloc);
1661         APR_BRIGADE_INSERT_TAIL(bcgi, b);
1662         ap_pass_brigade(f->next, bcgi);
1663     } 
1664
1665     return 0;
1666 }
1667
1668 static int handle_exec(include_ctx_t *ctx, apr_bucket_brigade **bb, request_rec *r,
1669                        ap_filter_t *f, apr_bucket *head_ptr, apr_bucket **inserted_head)
1670 {
1671     char *tag     = NULL;
1672     char *tag_val = NULL;
1673     char *file = r->filename;
1674     apr_bucket  *tmp_buck;
1675     char parsed_string[MAX_STRING_LEN];
1676
1677     *inserted_head = NULL;
1678     if (ctx->flags & FLAG_PRINTING) {
1679         if (ctx->flags & FLAG_NO_EXEC) {
1680             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1681                       "exec used but not allowed in %s", r->filename);
1682             CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, *inserted_head);
1683         }
1684         else {
1685             while (1) {
1686                 cgid_pfn_gtv(ctx, &tag, &tag_val, 1);
1687                 if (tag_val == NULL) {
1688                     if (tag == NULL) {
1689                         return (0);
1690                     }
1691                     else {
1692                         return 1;
1693                     }
1694                 }
1695                 if (!strcmp(tag, "cmd")) {
1696                     cgid_pfn_ps(r, ctx, tag_val, parsed_string, sizeof(parsed_string), 1);
1697                     if (include_cmd(ctx, bb, parsed_string, r, f) == -1) {
1698                         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1699                                     "execution failure for parameter \"%s\" "
1700                                     "to tag exec in file %s", tag, r->filename);
1701                         CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, *inserted_head);
1702                     }
1703                     /* just in case some stooge changed directories */
1704                 }
1705                 else if (!strcmp(tag, "cgi")) {
1706                     apr_status_t retval = APR_SUCCESS;
1707
1708                     cgid_pfn_ps(r, ctx, tag_val, parsed_string, sizeof(parsed_string), 0);
1709                     SPLIT_AND_PASS_PRETAG_BUCKETS(*bb, ctx, f->next, retval);
1710                     if (retval != APR_SUCCESS) {
1711                         return retval;
1712                     }
1713
1714                     if (include_cgi(parsed_string, r, f->next, head_ptr, inserted_head) == -1) {
1715                         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1716                                     "invalid CGI ref \"%s\" in %s", tag_val, file);
1717                         CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, *inserted_head);
1718                     }
1719                 }
1720                 else {
1721                     ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1722                                 "unknown parameter \"%s\" to tag exec in %s", tag, file);
1723                     CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, *inserted_head);
1724                 }
1725             }
1726         }
1727     }
1728     return 0;
1729 }
1730 /*============================================================================
1731  *============================================================================
1732  * This is the end of the cgi filter code moved from mod_include.
1733  *============================================================================
1734  *============================================================================*/
1735
1736
1737 static void register_hook(apr_pool_t *p)
1738 {
1739     static const char * const aszPre[] = { "mod_include.c", NULL };
1740
1741     ap_hook_post_config(cgid_init, aszPre, NULL, APR_HOOK_MIDDLE);
1742     ap_hook_handler(cgid_handler, NULL, NULL, APR_HOOK_MIDDLE);
1743 }
1744
1745 module AP_MODULE_DECLARE_DATA cgid_module = { 
1746     STANDARD20_MODULE_STUFF, 
1747     NULL, /* dir config creater */ 
1748     NULL, /* dir merger --- default is to override */ 
1749     create_cgid_config, /* server config */ 
1750     merge_cgid_config, /* merge server config */ 
1751     cgid_cmds, /* command table */ 
1752     register_hook /* register_handlers */ 
1753 }; 
1754