]> granicus.if.org Git - apache/blob - modules/generators/mod_cgid.c
ef88ce0dd614645d1df18bd8e57c4170b95f01b0
[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 "ap_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 <sys/stat.h>
95 #ifdef HAVE_SYS_SOCKET_H
96 #include <sys/socket.h>
97 #endif
98 #ifdef HAVE_UNISTD_H
99 #include <unistd.h>
100 #endif
101 #ifdef HAVE_STRINGS_H
102 #include <strings.h>
103 #endif
104 #include <sys/un.h> /* for sockaddr_un */
105 #include <sys/types.h>
106
107 module AP_MODULE_DECLARE_DATA cgid_module; 
108
109 static void cgid_init(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *main_server); 
110
111 static apr_pool_t *pcgi; 
112
113 /* KLUDGE --- for back-combatibility, we don't have to check Execcgid 
114  * in ScriptAliased directories, which means we need to know if this 
115  * request came through ScriptAlias or not... so the Alias module 
116  * leaves a note for us. 
117  */ 
118
119 static int is_scriptaliased(request_rec *r) 
120
121     const char *t = apr_table_get(r->notes, "alias-forced-type"); 
122     return t && (!strcasecmp(t, "cgi-script")); 
123
124
125 /* Configuration stuff */ 
126
127 #define DEFAULT_LOGBYTES 10385760 
128 #define DEFAULT_BUFBYTES 1024 
129 #define DEFAULT_SOCKET "logs/cgisock"
130
131 #define SHELL_PATH "/bin/sh"
132
133 /* DEFAULT_CGID_LISTENBACKLOG controls the max depth on the unix socket's
134  * pending connection queue.  If a bunch of cgi requests arrive at about
135  * the same time, connections from httpd threads/processes will back up
136  * in the queue while the cgid process slowly forks off a child to process
137  * each connection on the unix socket.  If the queue is too short, the
138  * httpd process will get ECONNREFUSED when trying to connect.
139  */
140 #ifndef DEFAULT_CGID_LISTENBACKLOG
141 #define DEFAULT_CGID_LISTENBACKLOG 100
142 #endif
143
144 typedef struct { 
145     const char *sockname;
146     const char *logname; 
147     long logbytes; 
148     int bufbytes; 
149 } cgid_server_conf; 
150
151 /* If a request includes query info in the URL (stuff after "?"), and
152  * the query info does not contain "=" (indicative of a FORM submission),
153  * then this routine is called to create the argument list to be passed
154  * to the CGI script.  When suexec is enabled, the suexec path, user, and
155  * group are the first three arguments to be passed; if not, all three
156  * must be NULL.  The query info is split into separate arguments, where
157  * "+" is the separator between keyword arguments.
158  *
159  * XXXX: note that the WIN32 code uses one of the suexec strings
160  * to pass an interpreter name.  Remember this if changing the way they
161  * are handled in create_argv.
162  *
163  */
164 static char **create_argv(apr_pool_t *p, char *path, char *user, char *group,
165                           char *av0, const char *args)
166 {
167     int x, numwords;
168     char **av;
169     char *w;
170     int idx = 0;
171
172     /* count the number of keywords */
173
174     for (x = 0, numwords = 1; args[x]; x++) {
175         if (args[x] == '+') {
176             ++numwords;
177         }
178     }
179
180     if (numwords > APACHE_ARG_MAX - 5) {
181         numwords = APACHE_ARG_MAX - 5;  /* Truncate args to prevent overrun */
182     }
183     av = (char **) apr_palloc(p, (numwords + 5) * sizeof(char *));
184
185     if (path) {
186         av[idx++] = path;
187     }
188     if (user) {
189         av[idx++] = user;
190     }
191     if (group) {
192         av[idx++] = group;
193      }
194
195     av[idx++] = av0;
196
197     for (x = 1; x <= numwords; x++) {
198         w = ap_getword_nulls(p, &args, '+');
199         ap_unescape_url(w);
200         av[idx++] = ap_escape_shell_cmd(p, w);
201     }
202     av[idx] = NULL;
203     return av;
204 }
205
206 static void cgid_maint(int reason, void *data, apr_wait_t status)
207 {
208 #if APR_HAS_OTHER_CHILD
209     int *sd = data;
210     switch (reason) {
211         case APR_OC_REASON_DEATH:
212         case APR_OC_REASON_LOST:
213             /* stop gap to make sure everything else works.  In the end,
214              * we'll just restart the cgid server. */
215             apr_destroy_pool(pcgi);
216             kill(getppid(), SIGWINCH);
217             break;
218         case APR_OC_REASON_RESTART:
219         case APR_OC_REASON_UNREGISTER:
220             apr_destroy_pool(pcgi);
221             kill(*sd, SIGHUP);
222             break;
223     }
224 #endif
225 }
226
227 static void get_req(int fd, request_rec *r, char **filename, char **argv0, char ***env) 
228
229     int i, len, j; 
230     unsigned char *data; 
231     char **environ; 
232     core_dir_config *temp_core; 
233     void **dconf; 
234
235     r->server = apr_pcalloc(r->pool, sizeof(server_rec)); 
236
237     read(fd, &j, sizeof(int)); 
238     read(fd, &len, sizeof(int)); 
239     data = apr_pcalloc(r->pool, len + 1); /* get a cleared byte for final '\0' */
240     i = read(fd, data, len); 
241
242     r->filename = ap_getword(r->pool, (const char **)&data, '\n'); 
243     *argv0 = ap_getword(r->pool, (const char **)&data, '\n'); 
244
245     r->uri = ap_getword(r->pool, (const char **)&data, '\n'); 
246     
247     environ = apr_pcalloc(r->pool, (j + 2) *sizeof(char *)); 
248     i = 0; 
249     for (i = 0; i < j; i++) { 
250         environ[i] = ap_getword(r->pool, (const char **)&data, '\n'); 
251     } 
252     *env = environ; 
253     r->args = ap_getword(r->pool, (const char **)&data, '\n'); 
254   
255     read(fd, &i, sizeof(int)); 
256      
257     /* add 1, so that if i == 0, we still malloc something. */ 
258     dconf = (void **)apr_palloc(r->pool, sizeof(void *) * i + 1); 
259     temp_core = (core_dir_config *)apr_palloc(r->pool, sizeof(core_module)); 
260
261     dconf[i] = (void *)temp_core; 
262     r->per_dir_config = dconf; 
263
264 #if 0
265 #ifdef RLIMIT_CPU 
266     read(fd, &j, sizeof(int)); 
267     if (j) { 
268         temp_core->limit_cpu = (struct rlimit *)apr_palloc (sizeof(struct rlimit)); 
269         read(fd, temp_core->limit_cpu, sizeof(struct rlimit)); 
270     } 
271     else { 
272         temp_core->limit_cpu = NULL; 
273     } 
274 #endif 
275
276 #if defined (RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS) 
277     read(fd, &j, sizeof(int)); 
278     if (j) { 
279         temp_core->limit_mem = (struct rlimit *)apr_palloc(r->pool, sizeof(struct rlimit)); 
280         read(fd, temp_core->limit_mem, sizeof(struct rlimit)); 
281     } 
282     else { 
283         temp_core->limit_mem = NULL; 
284     } 
285 #endif 
286
287 #ifdef RLIMIT_NPROC 
288     read(fd, &j, sizeof(int)); 
289     if (j) { 
290         temp_core->limit_nproc = (struct rlimit *)apr_palloc(r->pool, sizeof(struct rlimit)); 
291         read(fd, temp_core->limit_nproc, sizeof(struct rlimit)); 
292     } 
293     else { 
294         temp_core->limit_nproc = NULL; 
295     } 
296 #endif 
297 #endif
298     /* For right now, just make the notes table.  At some point we will need
299      * to actually fill this out, but for now we just don't want suexec to
300      * seg fault.
301      */
302     r->notes = apr_make_table(r->pool, 1);
303
304
305
306
307 static void send_req(int fd, request_rec *r, char *argv0, char **env) 
308
309     int len; 
310     int i = 0; 
311     char *data; 
312
313     data = apr_pstrcat(r->pool, r->filename, "\n", argv0, "\n", r->uri, "\n", 
314                      NULL); 
315
316     for (i =0; env[i]; i++) { 
317         continue; 
318     } 
319
320     if (write(fd, &i, sizeof(int)) < 0) {
321         ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r, 
322                      "write to cgi daemon process"); 
323         }     
324
325     for (i = 0; env[i]; i++) { 
326         data = apr_pstrcat(r->pool, data, env[i], "\n", NULL); 
327     } 
328     data = apr_pstrcat(r->pool, data, r->args, NULL); 
329     len = strlen(data); 
330     if (write(fd, &len, sizeof(int)) < 0) { 
331         ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r, 
332                      "write to cgi daemon process"); 
333         }     
334     if (write(fd, data, len) < 0) {
335         ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r, 
336                      "write to cgi daemon process"); 
337         }     
338     if (write(fd, &core_module.module_index, sizeof(int)) < 0) { 
339         ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r, 
340                      "write to cgi daemon process"); 
341         }     
342 #if 0
343 #ifdef RLIMIT_CPU 
344     if (conf->limit_cpu) { 
345         len = 1; 
346         write(fd, &len, sizeof(int)); 
347         write(fd, conf->limit_cpu, sizeof(struct rlimit)); 
348     } 
349     else { 
350         len = 0; 
351         write(fd, &len, sizeof(int)); 
352     } 
353 #endif 
354
355 #if defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS) 
356     if (conf->limit_mem) { 
357         len = 1; 
358         write(fd, &len, sizeof(int)); 
359         write(fd, conf->limit_mem, sizeof(struct rlimit)); 
360     } 
361     else { 
362         len = 0; 
363         write(fd, &len, sizeof(int)); 
364     } 
365 #endif 
366   
367 #ifdef RLIMIT_NPROC 
368     if (conf->limit_nproc) { 
369         len = 1; 
370         write(fd, &len, sizeof(int)); 
371         write(fd, conf->limit_nproc, sizeof(struct rlimit)); 
372     } 
373     else { 
374         len = 0; 
375         write(fd, &len, sizeof(int)); 
376     } 
377 #endif
378 #endif 
379
380
381 static int cgid_server(void *data) 
382
383     struct sockaddr_un unix_addr;
384     int sd, sd2, rc;
385     mode_t omask;
386     apr_socklen_t len;
387     server_rec *main_server = data;
388     cgid_server_conf *sconf = (cgid_server_conf *)ap_get_module_config( 
389                        main_server->module_config, &cgid_module); 
390
391     apr_signal(SIGCHLD, SIG_IGN); 
392     if (unlink(sconf->sockname) < 0 && errno != ENOENT) {
393         ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
394                      "Couldn't unlink unix domain socket %s",
395                      sconf->sockname);
396         /* just a warning; don't bail out */
397     }
398
399     if ((sd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
400         ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server, 
401                      "Couldn't create unix domain socket");
402         return errno;
403     } 
404
405     memset(&unix_addr, 0, sizeof(unix_addr));
406     unix_addr.sun_family = AF_UNIX;
407     strcpy(unix_addr.sun_path, sconf->sockname);
408
409     omask = umask(0077); /* so that only Apache can use socket */
410     rc = bind(sd, (struct sockaddr *)&unix_addr, sizeof(unix_addr));
411     umask(omask); /* can't fail, so can't clobber errno */
412     if (rc < 0) {
413         ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server, 
414                      "Couldn't bind unix domain socket %s",
415                      sconf->sockname); 
416         return errno;
417     } 
418
419     if (listen(sd, DEFAULT_CGID_LISTENBACKLOG) < 0) {
420         ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server, 
421                      "Couldn't listen on unix domain socket"); 
422         return errno;
423     } 
424
425     if (!geteuid()) {
426         if (chown(sconf->sockname, unixd_config.user_id, -1) < 0) {
427             ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server, 
428                          "Couldn't change owner of unix domain socket %s",
429                          sconf->sockname); 
430             return errno;
431         }
432     }
433     
434     unixd_setup_child(); /* if running as root, switch to configured user/group */
435
436     while (1) {
437         int errfileno = STDERR_FILENO;
438         char *argv0; 
439         char *filename; 
440         char **env; 
441         const char * const *argv; 
442         apr_pool_t *p; 
443         request_rec *r; 
444         apr_procattr_t *procattr = NULL;
445         apr_proc_t *procnew = NULL;
446         apr_file_t *inout = NULL;
447
448
449         len = sizeof(unix_addr);
450         sd2 = accept(sd, (struct sockaddr *)&unix_addr, &len);
451         if (sd2 < 0) {
452             if (errno != EINTR) {
453                 ap_log_error(APLOG_MARK, APLOG_ERR, errno, 
454                              (server_rec *)data,
455                              "Error accepting on cgid socket.");
456             }
457             continue;
458         }
459        
460         apr_create_pool(&p, pcgi); 
461
462         r = apr_pcalloc(p, sizeof(request_rec)); 
463         procnew = apr_pcalloc(p, sizeof(*procnew));
464         r->pool = p; 
465         get_req(sd2, r, &filename, &argv0, &env); 
466         apr_put_os_file(&r->server->error_log, &errfileno, r->pool);
467         apr_put_os_file(&inout, &sd2, r->pool);
468
469         if (((rc = apr_createprocattr_init(&procattr, p)) != APR_SUCCESS) ||
470             ((rc = apr_setprocattr_io(procattr,
471                                      APR_CHILD_BLOCK,
472                                      APR_CHILD_BLOCK,
473                                      APR_CHILD_BLOCK)) != APR_SUCCESS) ||
474             ((rc = apr_setprocattr_childin(procattr, inout, NULL)) != APR_SUCCESS) ||
475             ((rc = apr_setprocattr_childout(procattr, inout, NULL)) != APR_SUCCESS) ||
476             ((rc = apr_setprocattr_childerr(procattr, r->server->error_log, NULL)) != APR_SUCCESS) ||
477             ((rc = apr_setprocattr_dir(procattr,
478                                   ap_make_dirstr_parent(r->pool, r->filename))) != APR_SUCCESS) ||
479             ((rc = apr_setprocattr_cmdtype(procattr, APR_PROGRAM)) != APR_SUCCESS)) {
480             /* Something bad happened, tell the world. */
481             ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r,
482                       "couldn't set child process attributes: %s", r->filename);
483         }
484         else {
485             argv = (const char * const *)create_argv(r->pool, NULL, NULL, NULL, argv0, r->args);
486             rc = ap_os_create_privileged_process(r, procnew, argv0, argv, 
487                                                  (const char * const *)env, 
488                                                  procattr, p);
489
490             close(sd2);
491             if (rc != APR_SUCCESS) {
492                 /* Bad things happened. Everyone should have cleaned up. */
493                 ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r,
494                         "couldn't create child process: %d: %s", rc, r->filename);
495             }
496         }
497     } 
498     return -1; 
499
500
501 static void cgid_init(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, 
502                       server_rec *main_server) 
503
504     pid_t pid; 
505     apr_proc_t *procnew;
506     void *data;
507     int first_time = 0;
508     const char *userdata_key = "cgid_init";
509
510     apr_get_userdata(&data, userdata_key, main_server->process->pool);
511     if (!data) {
512         first_time = 1;
513         apr_set_userdata((const void *)1, userdata_key,
514                          apr_null_cleanup, main_server->process->pool);
515     }
516
517     if (!first_time) {
518         apr_create_pool(&pcgi, p); 
519
520         if ((pid = fork()) < 0) {
521             ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server, 
522                          "Couldn't spawn cgid daemon process"); 
523         }
524         else if (pid == 0) {
525             cgid_server(main_server);
526             exit(-1);
527         } 
528         procnew = apr_pcalloc(p, sizeof(*procnew));        
529         procnew->pid = pid;
530         procnew->err = procnew->in = procnew->out = NULL;
531         apr_note_subprocess(p, procnew, kill_after_timeout);
532 #if APR_HAS_OTHER_CHILD
533         apr_register_other_child(procnew, cgid_maint, NULL, NULL, p);
534 #endif
535     }
536
537
538 static void *create_cgid_config(apr_pool_t *p, server_rec *s) 
539
540     cgid_server_conf *c = 
541     (cgid_server_conf *) apr_pcalloc(p, sizeof(cgid_server_conf)); 
542
543     c->logname = NULL; 
544     c->logbytes = DEFAULT_LOGBYTES; 
545     c->bufbytes = DEFAULT_BUFBYTES; 
546     c->sockname = ap_server_root_relative(p, DEFAULT_SOCKET); 
547     return c; 
548
549
550 static void *merge_cgid_config(apr_pool_t *p, void *basev, void *overridesv) 
551
552     cgid_server_conf *base = (cgid_server_conf *) basev, *overrides = (cgid_server_conf *) overridesv; 
553
554     return overrides->logname ? overrides : base; 
555
556
557 static const char *set_scriptlog(cmd_parms *cmd, void *dummy, const char *arg) 
558
559     server_rec *s = cmd->server; 
560     cgid_server_conf *conf = 
561     (cgid_server_conf *) ap_get_module_config(s->module_config, &cgid_module); 
562
563     conf->logname = arg; 
564     return NULL; 
565
566
567 static const char *set_scriptlog_length(cmd_parms *cmd, void *dummy, const char *arg) 
568
569     server_rec *s = cmd->server; 
570     cgid_server_conf *conf = 
571     (cgid_server_conf *) ap_get_module_config(s->module_config, &cgid_module); 
572
573     conf->logbytes = atol(arg); 
574     return NULL; 
575
576
577 static const char *set_scriptlog_buffer(cmd_parms *cmd, void *dummy, const char *arg) 
578
579     server_rec *s = cmd->server; 
580     cgid_server_conf *conf = 
581     (cgid_server_conf *) ap_get_module_config(s->module_config, &cgid_module); 
582
583     conf->bufbytes = atoi(arg); 
584     return NULL; 
585
586
587 static const char *set_script_socket(cmd_parms *cmd, void *dummy, const char *arg) 
588
589     server_rec *s = cmd->server; 
590     cgid_server_conf *conf = 
591     (cgid_server_conf *) ap_get_module_config(s->module_config, &cgid_module); 
592
593     conf->sockname = ap_server_root_relative(cmd->pool, arg); 
594     return NULL; 
595
596
597 static const command_rec cgid_cmds[] = 
598
599     AP_INIT_TAKE1("ScriptLog", set_scriptlog, NULL, RSRC_CONF,
600                   "the name of a log for script debugging info"), 
601     AP_INIT_TAKE1("ScriptLogLength", set_scriptlog_length, NULL, RSRC_CONF,
602                   "the maximum length (in bytes) of the script debug log"), 
603     AP_INIT_TAKE1("ScriptLogBuffer", set_scriptlog_buffer, NULL, RSRC_CONF,
604                   "the maximum size (in bytes) to record of a POST request"), 
605     AP_INIT_TAKE1("Scriptsock", set_script_socket, NULL, RSRC_CONF,
606                   "the name of the socket to use for communication with "
607                   "the cgi daemon."), 
608     {NULL} 
609 }; 
610
611 static int log_scripterror(request_rec *r, cgid_server_conf * conf, int ret, 
612                            apr_status_t rv, char *error) 
613
614     apr_file_t *f = NULL; 
615     struct stat finfo; 
616     char time_str[APR_CTIME_LEN];
617     int log_flags = rv ? APLOG_ERR : APLOG_NOERRNO | APLOG_ERR;
618
619     ap_log_rerror(APLOG_MARK, log_flags, rv, r, 
620                 "%s: %s", error, r->filename); 
621
622     if (!conf->logname || 
623         ((stat(ap_server_root_relative(r->pool, conf->logname), &finfo) == 0) 
624          && (finfo.st_size > conf->logbytes)) || 
625          (apr_open(&f, ap_server_root_relative(r->pool, conf->logname),
626                   APR_APPEND|APR_WRITE|APR_CREATE, APR_OS_DEFAULT, r->pool) != APR_SUCCESS)) { 
627         return ret; 
628     } 
629
630     /* "%% [Wed Jun 19 10:53:21 1996] GET /cgid-bin/printenv HTTP/1.0" */ 
631     apr_ctime(time_str, apr_now());
632     apr_fprintf(f, "%%%% [%s] %s %s%s%s %s\n", time_str, r->method, r->uri, 
633             r->args ? "?" : "", r->args ? r->args : "", r->protocol); 
634     /* "%% 500 /usr/local/apache/cgid-bin */ 
635     apr_fprintf(f, "%%%% %d %s\n", ret, r->filename); 
636
637     apr_fprintf(f, "%%error\n%s\n", error); 
638
639     apr_close(f); 
640     return ret; 
641
642
643 static int log_script(request_rec *r, cgid_server_conf * conf, int ret, 
644                   char *dbuf, const char *sbuf, apr_file_t *script_in, apr_file_t *script_err) 
645
646     apr_array_header_t *hdrs_arr = apr_table_elts(r->headers_in); 
647     apr_table_entry_t *hdrs = (apr_table_entry_t *) hdrs_arr->elts; 
648     char argsbuffer[HUGE_STRING_LEN]; 
649     apr_file_t *f = NULL; 
650     int i; 
651     struct stat finfo; 
652     char time_str[APR_CTIME_LEN];
653
654     if (!conf->logname || 
655         ((stat(ap_server_root_relative(r->pool, conf->logname), &finfo) == 0) 
656          && (finfo.st_size > conf->logbytes)) || 
657          (apr_open(&f, ap_server_root_relative(r->pool, conf->logname), 
658                   APR_APPEND|APR_WRITE|APR_CREATE, APR_OS_DEFAULT, r->pool) != APR_SUCCESS)) { 
659         /* Soak up script output */ 
660         while (apr_fgets(argsbuffer, HUGE_STRING_LEN, script_in) == 0) 
661             continue; 
662         if (script_err) {
663             while (apr_fgets(argsbuffer, HUGE_STRING_LEN, script_err) == 0) 
664                 continue; 
665         }
666         return ret; 
667     } 
668
669     /* "%% [Wed Jun 19 10:53:21 1996] GET /cgid-bin/printenv HTTP/1.0" */ 
670     apr_ctime(time_str, apr_now());
671     apr_fprintf(f, "%%%% [%s] %s %s%s%s %s\n", time_str, r->method, r->uri, 
672             r->args ? "?" : "", r->args ? r->args : "", r->protocol); 
673     /* "%% 500 /usr/local/apache/cgid-bin" */ 
674     apr_fprintf(f, "%%%% %d %s\n", ret, r->filename); 
675
676     apr_puts("%request\n", f); 
677     for (i = 0; i < hdrs_arr->nelts; ++i) { 
678         if (!hdrs[i].key) 
679             continue; 
680         apr_fprintf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val); 
681     } 
682     if ((r->method_number == M_POST || r->method_number == M_PUT) 
683         && *dbuf) { 
684         apr_fprintf(f, "\n%s\n", dbuf); 
685     } 
686
687     apr_puts("%response\n", f); 
688     hdrs_arr = apr_table_elts(r->err_headers_out); 
689     hdrs = (apr_table_entry_t *) hdrs_arr->elts; 
690
691     for (i = 0; i < hdrs_arr->nelts; ++i) { 
692         if (!hdrs[i].key) 
693             continue; 
694         apr_fprintf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val); 
695     } 
696
697     if (sbuf && *sbuf) 
698         apr_fprintf(f, "%s\n", sbuf); 
699
700     if (apr_fgets(argsbuffer, HUGE_STRING_LEN, script_in) == 0) { 
701         apr_puts("%stdout\n", f); 
702         apr_puts(argsbuffer, f); 
703         while (apr_fgets(argsbuffer, HUGE_STRING_LEN, script_in) == 0) 
704             apr_puts(argsbuffer, f); 
705         apr_puts("\n", f); 
706     } 
707
708     if (script_err) {
709         if (apr_fgets(argsbuffer, HUGE_STRING_LEN, script_err) == 0) { 
710             apr_puts("%stderr\n", f); 
711             apr_puts(argsbuffer, f); 
712             while (apr_fgets(argsbuffer, HUGE_STRING_LEN, script_err) == 0) 
713                 apr_puts(argsbuffer, f); 
714             apr_puts("\n", f); 
715         } 
716     }
717
718     apr_close(script_in); 
719     if (script_err) {
720         apr_close(script_err); 
721     }
722
723     apr_close(f); 
724     return ret; 
725
726
727
728
729 /**************************************************************** 
730  * 
731  * Actual cgid handling... 
732  */ 
733 static int cgid_handler(request_rec *r) 
734
735     int retval, nph, dbpos = 0; 
736     char *argv0, *dbuf = NULL; 
737     ap_bucket_brigade *bb;
738     ap_bucket *b;
739     char argsbuffer[HUGE_STRING_LEN]; 
740     void *sconf = r->server->module_config; 
741     cgid_server_conf *conf = (cgid_server_conf *) ap_get_module_config(sconf, &cgid_module); 
742     int is_included = !strcmp(r->protocol, "INCLUDED"); 
743     int sd;
744     char **env; 
745     struct sockaddr_un unix_addr;
746     apr_file_t *tempsock = NULL;
747     apr_size_t nbytes;
748
749     if (r->method_number == M_OPTIONS) { 
750         /* 99 out of 100 cgid scripts, this is all they support */ 
751         r->allowed |= (1 << M_GET); 
752         r->allowed |= (1 << M_POST); 
753         return DECLINED; 
754     } 
755
756     if ((argv0 = strrchr(r->filename, '/')) != NULL)
757         argv0++;
758     else
759         argv0 = r->filename;
760  
761     nph = !(strncmp(argv0, "nph-", 4)); 
762
763     if ((argv0 = strrchr(r->filename, '/')) != NULL) 
764         argv0++; 
765     else 
766         argv0 = r->filename; 
767
768     if (!(ap_allow_options(r) & OPT_EXECCGI) && !is_scriptaliased(r)) 
769         return log_scripterror(r, conf, HTTP_FORBIDDEN, 0, 
770                                "Options ExecCGI is off in this directory"); 
771     if (nph && is_included) 
772         return log_scripterror(r, conf, HTTP_FORBIDDEN, 0, 
773                                "attempt to include NPH CGI script"); 
774
775 #if defined(OS2) || defined(WIN32)
776 #error mod_cgid does not work on this platform.  If you teach it to, look 
777 #error at mod_cgi.c for required code in this path.
778 #else 
779     if (r->finfo.protection == 0) 
780         return log_scripterror(r, conf, HTTP_NOT_FOUND, 0, 
781                                "script not found or unable to stat"); 
782 #endif 
783     if (r->finfo.filetype == APR_DIR) 
784         return log_scripterror(r, conf, HTTP_FORBIDDEN, 0, 
785                                "attempt to invoke directory as script"); 
786 /*
787     if (!ap_suexec_enabled) { 
788         if (!ap_can_exec(&r->finfo)) 
789             return log_scripterror(r, conf, HTTP_FORBIDDEN, 0, 
790                                    "file permissions deny server execution"); 
791     } 
792 */
793     ap_add_common_vars(r); 
794     ap_add_cgi_vars(r); 
795     env = ap_create_environment(r->pool, r->subprocess_env); 
796
797     if ((sd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
798             return log_scripterror(r, conf, HTTP_INTERNAL_SERVER_ERROR, errno, 
799                                    "unable to create socket to cgi daemon");
800     } 
801     memset(&unix_addr, 0, sizeof(unix_addr));
802     unix_addr.sun_family = AF_UNIX;
803     strcpy(unix_addr.sun_path, conf->sockname);
804
805     if (connect(sd, (struct sockaddr *)&unix_addr, sizeof(unix_addr)) < 0) {
806             return log_scripterror(r, conf, HTTP_INTERNAL_SERVER_ERROR, errno, 
807                                    "unable to connect to cgi daemon");
808     } 
809
810     send_req(sd, r, argv0, env); 
811
812     /* We are putting the tempsock variable into a file so that we can use
813      * a pipe bucket to send the data to the client.
814      */
815     apr_put_os_file(&tempsock, &sd, r->pool);
816
817     if ((retval = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR))) 
818         return retval; 
819      
820     if ((argv0 = strrchr(r->filename, '/')) != NULL) 
821         argv0++; 
822     else 
823         argv0 = r->filename; 
824
825     /* Transfer any put/post args, CERN style... 
826      * Note that we already ignore SIGPIPE in the core server. 
827      */ 
828
829     if (ap_should_client_block(r)) { 
830         int dbsize, len_read; 
831
832         if (conf->logname) { 
833             dbuf = apr_pcalloc(r->pool, conf->bufbytes + 1); 
834             dbpos = 0; 
835         } 
836
837         while ((len_read = 
838                 ap_get_client_block(r, argsbuffer, HUGE_STRING_LEN)) > 0) { 
839             if (conf->logname) { 
840                 if ((dbpos + len_read) > conf->bufbytes) { 
841                     dbsize = conf->bufbytes - dbpos; 
842                 } 
843                 else { 
844                     dbsize = len_read; 
845                 } 
846                 memcpy(dbuf + dbpos, argsbuffer, dbsize); 
847                 dbpos += dbsize; 
848             } 
849             nbytes = len_read;
850             apr_write(tempsock, argsbuffer, &nbytes);
851             if (nbytes < len_read) { 
852                 /* silly script stopped reading, soak up remaining message */ 
853                 while (ap_get_client_block(r, argsbuffer, HUGE_STRING_LEN) > 0) { 
854                     /* dump it */ 
855                 } 
856                 break; 
857             } 
858         } 
859         shutdown(sd, 1); /* done writing; force EOF on child's stdin */
860     } 
861
862     /* Handle script return... */ 
863     if (!nph) { 
864         const char *location; 
865         char sbuf[MAX_STRING_LEN]; 
866         int ret; 
867
868         if ((ret = ap_scan_script_header_err(r, tempsock, sbuf))) { 
869             return log_script(r, conf, ret, dbuf, sbuf, tempsock, NULL); 
870         } 
871
872         location = apr_table_get(r->headers_out, "Location"); 
873
874         if (location && location[0] == '/' && r->status == 200) { 
875
876             /* Soak up all the script output */ 
877             while (apr_fgets(argsbuffer, HUGE_STRING_LEN, tempsock) > 0) { 
878                 continue; 
879             } 
880             /* This redirect needs to be a GET no matter what the original 
881              * method was. 
882              */ 
883             r->method = apr_pstrdup(r->pool, "GET"); 
884             r->method_number = M_GET; 
885
886             /* We already read the message body (if any), so don't allow 
887              * the redirected request to think it has one. We can ignore 
888              * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR. 
889              */ 
890             apr_table_unset(r->headers_in, "Content-Length"); 
891
892             ap_internal_redirect_handler(location, r); 
893             return OK; 
894         } 
895         else if (location && r->status == 200) { 
896             /* XX Note that if a script wants to produce its own Redirect 
897              * body, it now has to explicitly *say* "Status: 302" 
898              */ 
899             return HTTP_MOVED_TEMPORARILY; 
900         } 
901
902         ap_send_http_header(r); 
903         if (!r->header_only) { 
904             bb = ap_brigade_create(r->pool);
905             b = ap_bucket_create_pipe(tempsock);
906             AP_BRIGADE_INSERT_TAIL(bb, b);
907             b = ap_bucket_create_eos();
908             AP_BRIGADE_INSERT_TAIL(bb, b);
909             ap_pass_brigade(r->output_filters, bb);
910         } 
911     } 
912
913     if (nph) {
914         bb = ap_brigade_create(r->pool);
915         b = ap_bucket_create_pipe(tempsock);
916         AP_BRIGADE_INSERT_TAIL(bb, b);
917         b = ap_bucket_create_eos();
918         AP_BRIGADE_INSERT_TAIL(bb, b);
919         ap_pass_brigade(r->output_filters, bb);
920     } 
921
922     apr_close(tempsock);
923
924     return OK; /* NOT r->status, even if it has changed. */ 
925
926
927 static const handler_rec cgid_handlers[] = 
928
929     {CGI_MAGIC_TYPE, cgid_handler}, 
930     {"cgi-script", cgid_handler}, 
931     {NULL} 
932 };
933
934 static void register_hook(void)
935 {
936     ap_hook_post_config(cgid_init, NULL, NULL, AP_HOOK_MIDDLE);
937 }
938
939 module AP_MODULE_DECLARE_DATA cgid_module = { 
940     STANDARD20_MODULE_STUFF, 
941     NULL, /* dir config creater */ 
942     NULL, /* dir merger --- default is to override */ 
943     create_cgid_config, /* server config */ 
944     merge_cgid_config, /* merge server config */ 
945     cgid_cmds, /* command table */ 
946     cgid_handlers, /* handlers */ 
947     register_hook /* register_handlers */ 
948 }; 
949