]> granicus.if.org Git - apache/blob - modules/generators/mod_cgid.c
Update mod_cgid to work with attach_iol_socket again.
[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_general.h"
78 #include "apr_file_io.h"
79 #include "apr_portable.h"
80 #include "httpd.h" 
81 #include "http_config.h" 
82 #include "http_request.h" 
83 #include "http_core.h" 
84 #include "http_protocol.h" 
85 #include "http_main.h" 
86 #include "http_log.h" 
87 #include "util_script.h" 
88 #include "http_conf_globals.h" 
89 #include "buff.h" 
90 #include "ap_mpm.h"
91 #include "iol_socket.h"
92 #include "unixd.h"
93 #include <sys/stat.h>
94 #ifdef HAVE_SYS_SOCKET_H
95 #include <sys/socket.h>
96 #endif
97 #include <sys/un.h> /* for sockaddr_un */
98 #include <sys/types.h>
99
100 module MODULE_VAR_EXPORT cgid_module; 
101
102 static void cgid_init(ap_pool_t *p, ap_pool_t *plog, ap_pool_t *ptemp, server_rec *main_server); 
103 static int once_through = 0; 
104
105 static ap_pool_t *pcgi; 
106
107 /* KLUDGE --- for back-combatibility, we don't have to check Execcgid 
108  * in ScriptAliased directories, which means we need to know if this 
109  * request came through ScriptAlias or not... so the Alias module 
110  * leaves a note for us. 
111  */ 
112
113 static int is_scriptaliased(request_rec *r) 
114
115     const char *t = ap_table_get(r->notes, "alias-forced-type"); 
116     return t && (!strcasecmp(t, "cgi-script")); 
117
118
119 /* Configuration stuff */ 
120
121 #define DEFAULT_LOGBYTES 10385760 
122 #define DEFAULT_BUFBYTES 1024 
123 #define DEFAULT_SOCKET "logs/cgisock"
124
125 #define SHELL_PATH "/bin/sh"
126
127 typedef struct { 
128     const char *sockname;
129     const char *logname; 
130     long logbytes; 
131     int bufbytes; 
132     BUFF *bin; 
133     BUFF *bout; 
134     BUFF *berror; 
135 } cgid_server_conf; 
136
137 /* If a request includes query info in the URL (stuff after "?"), and
138  * the query info does not contain "=" (indicative of a FORM submission),
139  * then this routine is called to create the argument list to be passed
140  * to the CGI script.  When suexec is enabled, the suexec path, user, and
141  * group are the first three arguments to be passed; if not, all three
142  * must be NULL.  The query info is split into separate arguments, where
143  * "+" is the separator between keyword arguments.
144  *
145  * XXXX: note that the WIN32 code uses one of the suexec strings
146  * to pass an interpreter name.  Remember this if changing the way they
147  * are handled in create_argv.
148  *
149  */
150 static char **create_argv(ap_pool_t *p, char *path, char *user, char *group,
151                           char *av0, const char *args)
152 {
153     int x, numwords;
154     char **av;
155     char *w;
156     int idx = 0;
157
158     /* count the number of keywords */
159
160     for (x = 0, numwords = 1; args[x]; x++) {
161         if (args[x] == '+') {
162             ++numwords;
163         }
164     }
165
166     if (numwords > APACHE_ARG_MAX - 5) {
167         numwords = APACHE_ARG_MAX - 5;  /* Truncate args to prevent overrun */
168     }
169     av = (char **) ap_palloc(p, (numwords + 5) * sizeof(char *));
170
171     if (path) {
172         av[idx++] = path;
173     }
174     if (user) {
175         av[idx++] = user;
176     }
177     if (group) {
178         av[idx++] = group;
179      }
180
181     av[idx++] = av0;
182
183     for (x = 1; x <= numwords; x++) {
184         w = ap_getword_nulls(p, &args, '+');
185         ap_unescape_url(w);
186         av[idx++] = ap_escape_shell_cmd(p, w);
187     }
188     av[idx] = NULL;
189     return av;
190 }
191
192 static int call_exec(request_rec *r, char *argv0, char **env, int shellcmd)
193 {
194     int pid = 0;
195     int errfileno = STDERR_FILENO;
196     /* the fd on r->server->error_log is closed, but we need somewhere to            
197      * put the error messages from the log_* functions. So, we use stderr,
198      * since that is better than allowing errors to go unnoticed. 
199      */
200     ap_put_os_file(&r->server->error_log, &errfileno, r->pool);
201     /* TODO: reimplement suexec */
202 #if 0
203     if (ap_suexec_enabled
204         && ((r->server->server_uid != ap_user_id)
205             || (r->server->server_gid != ap_group_id)
206             || (!strncmp("/~", r->uri, 2)))) {
207
208         char *execuser, *grpname;
209         struct passwd *pw;
210         struct group *gr;
211
212         if (!strncmp("/~", r->uri, 2)) {
213             gid_t user_gid;
214             char *username = ap_pstrdup(r->pool, r->uri + 2);
215             char *pos = strchr(username, '/');
216
217             if (pos) {
218                 *pos = '\0';
219             }
220
221             if ((pw = getpwnam(username)) == NULL) {
222                 ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
223                              "getpwnam: invalid username %s", username);
224                 return (pid);
225             }
226             execuser = ap_pstrcat(r->pool, "~", pw->pw_name, NULL);
227             user_gid = pw->pw_gid;
228
229             if ((gr = getgrgid(user_gid)) == NULL) {
230                 if ((grpname = ap_palloc(r->pool, 16)) == NULL) {
231                     return (pid);
232                 }
233                 else {
234                     ap_snprintf(grpname, 16, "%ld", (long) user_gid);
235                 }
236             }
237             else {
238                 grpname = gr->gr_name;
239             }
240         }
241         else {
242             if ((pw = getpwuid(r->server->server_uid)) == NULL) {
243                 ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
244                              "getpwuid: invalid userid %ld",
245                              (long) r->server->server_uid);
246                 return (pid);
247             }
248             execuser = ap_pstrdup(r->pool, pw->pw_name);
249
250             if ((gr = getgrgid(r->server->server_gid)) == NULL) {
251                 ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
252                              "getgrgid: invalid groupid %ld",
253                              (long) r->server->server_gid);
254                 return (pid);
255             }
256             grpname = gr->gr_name;
257         }
258
259         if (shellcmd) {
260             execle(SUEXEC_BIN, SUEXEC_BIN, execuser, grpname, argv0,
261                    NULL, env);
262         }
263
264         else if ((!r->args) || (!r->args[0]) || strchr(r->args, '=')) {
265             execle(SUEXEC_BIN, SUEXEC_BIN, execuser, grpname, argv0,
266                    NULL, env);
267         }
268
269         else {
270             execve(SUEXEC_BIN,
271                    create_argv(r->pool, SUEXEC_BIN, execuser, grpname,
272                                argv0, r->args),
273                    env);
274         }
275     }
276     else {
277 #endif
278         if (shellcmd) {
279             execle(SHELL_PATH, SHELL_PATH, "-c", argv0, NULL, env);
280         }
281
282         else if ((!r->args) || (!r->args[0]) || strchr(r->args, '=')) {
283             execle(r->filename, argv0, NULL, env);
284         }
285
286         else {
287             execve(r->filename,
288                    create_argv(r->pool, NULL, NULL, NULL, argv0, r->args),
289                    env);
290         }
291 #if 0
292     }
293 #endif
294     return (pid);
295 }
296
297 static void cgid_maint(int reason, void *data, ap_wait_t status)
298 {
299 #ifdef APR_HAS_OTHER_CHILD
300     int *sd = data;
301     switch (reason) {
302         case APR_OC_REASON_DEATH:
303         case APR_OC_REASON_LOST:
304             /* stop gap to make sure everything else works.  In the end,
305              * we'll just restart the cgid server. */
306             ap_destroy_pool(pcgi);
307             kill(getppid(), SIGWINCH);
308             break;
309         case APR_OC_REASON_RESTART:
310         case APR_OC_REASON_UNREGISTER:
311             ap_destroy_pool(pcgi);
312             kill(*sd, SIGHUP);
313             break;
314     }
315 #endif
316 }
317
318 static void get_req(int fd, request_rec *r, char **filename, char **argv0, char ***env) 
319
320     int i, len, j; 
321     unsigned char *data; 
322     char **environ; 
323     core_dir_config *temp_core; 
324     void **dconf; 
325
326     r->server = ap_pcalloc(r->pool, sizeof(server_rec)); 
327
328     read(fd, &j, sizeof(int)); 
329     read(fd, &len, sizeof(int)); 
330     data = ap_pcalloc(r->pool, len + 1); /* get a cleared byte for final '\0' */
331     i = read(fd, data, len); 
332
333     r->filename = ap_getword(r->pool, (const char **)&data, '\n'); 
334     *argv0 = ap_getword(r->pool, (const char **)&data, '\n'); 
335
336     r->uri = ap_getword(r->pool, (const char **)&data, '\n'); 
337     
338     environ = ap_pcalloc(r->pool, (j + 2) *sizeof(char *)); 
339     i = 0; 
340     for (i = 0; i < j; i++) { 
341         environ[i] = ap_getword(r->pool, (const char **)&data, '\n'); 
342     } 
343     *env = environ; 
344     r->args = ap_getword(r->pool, (const char **)&data, '\n'); 
345   
346     read(fd, &r->server->server_uid, sizeof(uid_t)); 
347     read(fd, &r->server->server_gid, sizeof(gid_t)); 
348
349     read(fd, &i, sizeof(int)); 
350      
351     /* add 1, so that if i == 0, we still malloc something. */ 
352     dconf = (void **)malloc(sizeof(void *) * i + 1); 
353
354     temp_core = (core_dir_config *)malloc(sizeof(core_module)); 
355 #if 0
356 #ifdef RLIMIT_CPU 
357     read(fd, &j, sizeof(int)); 
358     if (j) { 
359         temp_core->limit_cpu = (struct rlimit *)malloc (sizeof(struct rlimit)); 
360         read(fd, temp_core->limit_cpu, sizeof(struct rlimit)); 
361     } 
362     else { 
363         temp_core->limit_cpu = NULL; 
364     } 
365 #endif 
366
367 #if defined (RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS) 
368     read(fd, &j, sizeof(int)); 
369     if (j) { 
370         temp_core->limit_mem = (struct rlimit *)malloc (sizeof(struct rlimit)); 
371         read(fd, temp_core->limit_mem, sizeof(struct rlimit)); 
372     } 
373     else { 
374         temp_core->limit_mem = NULL; 
375     } 
376 #endif 
377
378 #ifdef RLIMIT_NPROC 
379     read(fd, &j, sizeof(int)); 
380     if (j) { 
381         temp_core->limit_nproc = (struct rlimit *)malloc (sizeof(struct rlimit)); 
382         read(fd, temp_core->limit_nproc, sizeof(struct rlimit)); 
383     } 
384     else { 
385         temp_core->limit_nproc = NULL; 
386     } 
387 #endif 
388 #endif
389     dconf[i] = (void *)temp_core; 
390     r->per_dir_config = dconf; 
391
392
393
394
395 static void send_req(int fd, request_rec *r, char *argv0, char **env) 
396
397     int len; 
398     int i = 0; 
399     char *data; 
400
401     data = ap_pstrcat(r->pool, r->filename, "\n", argv0, "\n", r->uri, "\n", 
402                      NULL); 
403
404     for (i =0; env[i]; i++) { 
405         continue; 
406     } 
407
408     if (write(fd, &i, sizeof(int)) < 0) {
409         ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r, 
410                      "write to cgi daemon process"); 
411         }     
412
413     for (i = 0; env[i]; i++) { 
414         data = ap_pstrcat(r->pool, data, env[i], "\n", NULL); 
415     } 
416     data = ap_pstrcat(r->pool, data, r->args, NULL); 
417     len = strlen(data); 
418     if (write(fd, &len, sizeof(int)) < 0) { 
419         ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r, 
420                      "write to cgi daemon process"); 
421         }     
422     if (write(fd, data, len) < 0) {
423         ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r, 
424                      "write to cgi daemon process"); 
425         }     
426     if (write(fd, &r->server->server_uid, sizeof(uid_t)) < 0) {
427         ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r, 
428                      "write to cgi daemon process"); 
429         }     
430     if (write(fd, &r->server->server_gid, sizeof(gid_t)) < 0) { 
431         ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r, 
432                      "write to cgi daemon process"); 
433         }     
434     if (write(fd, &core_module.module_index, sizeof(int)) < 0) { 
435         ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r, 
436                      "write to cgi daemon process"); 
437         }     
438 #if 0
439 #ifdef RLIMIT_CPU 
440     if (conf->limit_cpu) { 
441         len = 1; 
442         write(fd, &len, sizeof(int)); 
443         write(fd, conf->limit_cpu, sizeof(struct rlimit)); 
444     } 
445     else { 
446         len = 0; 
447         write(fd, &len, sizeof(int)); 
448     } 
449 #endif 
450
451 #if defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS) 
452     if (conf->limit_mem) { 
453         len = 1; 
454         write(fd, &len, sizeof(int)); 
455         write(fd, conf->limit_mem, sizeof(struct rlimit)); 
456     } 
457     else { 
458         len = 0; 
459         write(fd, &len, sizeof(int)); 
460     } 
461 #endif 
462   
463 #ifdef RLIMIT_NPROC 
464     if (conf->limit_nproc) { 
465         len = 1; 
466         write(fd, &len, sizeof(int)); 
467         write(fd, conf->limit_nproc, sizeof(struct rlimit)); 
468     } 
469     else { 
470         len = 0; 
471         write(fd, &len, sizeof(int)); 
472     } 
473 #endif
474 #endif 
475
476
477 static int cgid_server_child(int sd) 
478
479     char *argv0; 
480     char *filename; 
481     char **env; 
482     ap_pool_t *p; 
483     request_rec *r; 
484
485     ap_create_pool(&p, pcgi); 
486     r = ap_pcalloc(p, sizeof(request_rec)); 
487     r->pool = p; 
488     dup2(sd, STDIN_FILENO); 
489     dup2(sd, STDOUT_FILENO); 
490     get_req(sd, r, &filename, &argv0, &env); 
491     call_exec(r, argv0, env, 0); 
492     exit(-1);   /* We should NEVER get here */
493
494
495 static int cgid_server(void *data) 
496
497     struct sockaddr_un unix_addr;
498     int pid; 
499     int sd, sd2, len, rc;
500     int errfile;
501     mode_t omask;
502     server_rec *main_server = data;
503     cgid_server_conf *sconf = (cgid_server_conf *)ap_get_module_config( 
504                        main_server->module_config, &cgid_module); 
505
506     ap_signal(SIGCHLD, SIG_IGN); 
507     if (unlink(sconf->sockname) < 0 &&
508         errno != ENOENT) {
509         ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
510                      "Couldn't unlink unix domain socket %s",
511                      sconf->sockname);
512         /* just a warning; don't bail out */
513     }
514
515     if ((sd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
516         ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server, 
517                      "Couldn't create unix domain socket");
518         return errno;
519     } 
520
521     memset(&unix_addr, 0, sizeof(unix_addr));
522     unix_addr.sun_family = AF_UNIX;
523     strcpy(unix_addr.sun_path, sconf->sockname);
524
525     omask = umask(0077); /* so that only Apache can use socket */
526     rc = bind(sd, (struct sockaddr *)&unix_addr, sizeof(unix_addr));
527     umask(omask); /* can't fail, so can't clobber errno */
528     if (rc < 0) {
529         ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server, 
530                      "Couldn't bind unix domain socket %s",
531                      sconf->sockname); 
532         return errno;
533     } 
534     /* Most implementations silently enforce a value of 5 anyway.  
535      * This way, it'll work the same everywhere. */
536     if (listen(sd, 5) < 0) {
537         ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server, 
538                      "Couldn't listen on unix domain socket"); 
539         return errno;
540     } 
541
542     if (!geteuid()) {
543         if (chown(sconf->sockname, unixd_config.user_id, -1) < 0) {
544             ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server, 
545                          "Couldn't change owner of unix domain socket %s",
546                          sconf->sockname); 
547             return errno;
548         }
549     }
550     
551     unixd_setup_child(); /* if running as root, switch to configured user/group */
552
553     while (1) {
554         len = sizeof(unix_addr);
555         sd2 = accept(sd, (struct sockaddr *)&unix_addr, &len);
556         if (sd2 < 0) {
557             ap_log_error(APLOG_MARK, APLOG_ERR, errno, (server_rec *)data,
558                          "Error accepting on cgid socket.");
559             continue;
560         }
561        
562         if ((pid = fork()) > 0) {
563             close(sd2);
564         } 
565         else if (pid == 0) { 
566             /* setup the STDERR here, because I have all the info
567              * for it.  I'll do the STDIN and STDOUT later, but I can't
568              * do STDERR as easily.
569              */
570             if (sconf->logname) {
571                 dup2(open(sconf->logname, O_WRONLY), STDERR_FILENO);
572             }
573             else {
574                 ap_get_os_file(&errfile, main_server->error_log);
575                 dup2(errfile, STDERR_FILENO);
576             }
577             cgid_server_child(sd2); 
578         } 
579         else { 
580             ap_log_error(APLOG_MARK, APLOG_ERR, errno, (server_rec *)data, 
581                          "Couldn't fork cgi script"); 
582         } 
583     } 
584     return -1; 
585
586
587 static void cgid_init(ap_pool_t *p, ap_pool_t *plog, ap_pool_t *ptemp, server_rec *main_server) 
588
589     pid_t pid; 
590     ap_proc_t ap_pid;
591
592     if (once_through > 0) { 
593         ap_create_pool(&pcgi, p); 
594
595         if ((pid = fork()) < 0) {
596             ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server, 
597                          "Couldn't spawn cgid daemon process"); 
598         }
599         else if (pid == 0) {
600             cgid_server(main_server);
601             exit(-1);
602         } 
603 #ifdef APR_HAS_OTHER_CHILD
604         ap_pid.pid = pid;
605         ap_pid.err = ap_pid.in = ap_pid.out = NULL;
606         ap_register_other_child(&ap_pid, cgid_maint, NULL, NULL, p);
607 #endif
608     } 
609     else once_through++; 
610
611
612 static void *create_cgid_config(ap_pool_t *p, server_rec *s) 
613
614     cgid_server_conf *c = 
615     (cgid_server_conf *) ap_pcalloc(p, sizeof(cgid_server_conf)); 
616
617     c->logname = NULL; 
618     c->logbytes = DEFAULT_LOGBYTES; 
619     c->bufbytes = DEFAULT_BUFBYTES; 
620     c->sockname = ap_server_root_relative(p, DEFAULT_SOCKET); 
621     c->bin = c->bout = c->berror = NULL; 
622     return c; 
623
624
625 static void *merge_cgid_config(ap_pool_t *p, void *basev, void *overridesv) 
626
627     cgid_server_conf *base = (cgid_server_conf *) basev, *overrides = (cgid_server_conf *) overridesv; 
628
629     return overrides->logname ? overrides : base; 
630
631
632 static const char *set_scriptlog(cmd_parms *cmd, void *dummy, const char *arg) 
633
634     server_rec *s = cmd->server; 
635     cgid_server_conf *conf = 
636     (cgid_server_conf *) ap_get_module_config(s->module_config, &cgid_module); 
637
638     conf->logname = arg; 
639     return NULL; 
640
641
642 static const char *set_scriptlog_length(cmd_parms *cmd, void *dummy, const char *arg) 
643
644     server_rec *s = cmd->server; 
645     cgid_server_conf *conf = 
646     (cgid_server_conf *) ap_get_module_config(s->module_config, &cgid_module); 
647
648     conf->logbytes = atol(arg); 
649     return NULL; 
650
651
652 static const char *set_scriptlog_buffer(cmd_parms *cmd, void *dummy, const char *arg) 
653
654     server_rec *s = cmd->server; 
655     cgid_server_conf *conf = 
656     (cgid_server_conf *) ap_get_module_config(s->module_config, &cgid_module); 
657
658     conf->bufbytes = atoi(arg); 
659     return NULL; 
660
661
662 static const char *set_script_socket(cmd_parms *cmd, void *dummy, const char *arg) 
663
664     server_rec *s = cmd->server; 
665     cgid_server_conf *conf = 
666     (cgid_server_conf *) ap_get_module_config(s->module_config, &cgid_module); 
667
668     conf->sockname = ap_server_root_relative(cmd->pool, arg); 
669     return NULL; 
670
671
672 static const command_rec cgid_cmds[] = 
673
674     AP_INIT_TAKE1("ScriptLog", set_scriptlog, NULL, RSRC_CONF,
675                   "the name of a log for script debugging info"), 
676     AP_INIT_TAKE1("ScriptLogLength", set_scriptlog_length, NULL, RSRC_CONF,
677                   "the maximum length (in bytes) of the script debug log"), 
678     AP_INIT_TAKE1("ScriptLogBuffer", set_scriptlog_buffer, NULL, RSRC_CONF,
679                   "the maximum size (in bytes) to record of a POST request"), 
680     AP_INIT_TAKE1("Scriptsock", set_script_socket, NULL, RSRC_CONF,
681                   "the name of the socket to use for communication with "
682                   "the cgi daemon."), 
683     {NULL} 
684 }; 
685
686 static int log_scripterror(request_rec *r, cgid_server_conf * conf, int ret, 
687                            int show_errno, char *error) 
688
689     ap_file_t *f = NULL; 
690     struct stat finfo; 
691     char time_str[AP_CTIME_LEN];
692
693     ap_log_rerror(APLOG_MARK, show_errno|APLOG_ERR, errno, r, 
694                 "%s: %s", error, r->filename); 
695
696     if (!conf->logname || 
697         ((stat(ap_server_root_relative(r->pool, conf->logname), &finfo) == 0) 
698          && (finfo.st_size > conf->logbytes)) || 
699          (ap_open(&f, ap_server_root_relative(r->pool, conf->logname),
700                   APR_APPEND|APR_WRITE|APR_CREATE, APR_OS_DEFAULT, r->pool) != APR_SUCCESS)) { 
701         return ret; 
702     } 
703
704     /* "%% [Wed Jun 19 10:53:21 1996] GET /cgid-bin/printenv HTTP/1.0" */ 
705     ap_ctime(time_str, ap_now());
706     ap_fprintf(f, "%%%% [%s] %s %s%s%s %s\n", time_str, r->method, r->uri, 
707             r->args ? "?" : "", r->args ? r->args : "", r->protocol); 
708     /* "%% 500 /usr/local/apache/cgid-bin */ 
709     ap_fprintf(f, "%%%% %d %s\n", ret, r->filename); 
710
711     ap_fprintf(f, "%%error\n%s\n", error); 
712
713     ap_close(f); 
714     return ret; 
715
716
717 static int log_script(request_rec *r, cgid_server_conf * conf, int ret, 
718                   char *dbuf, const char *sbuf, BUFF *script_in, BUFF *script_err) 
719
720     ap_array_header_t *hdrs_arr = ap_table_elts(r->headers_in); 
721     ap_table_entry_t *hdrs = (ap_table_entry_t *) hdrs_arr->elts; 
722     char argsbuffer[HUGE_STRING_LEN]; 
723     ap_file_t *f = NULL; 
724     int i; 
725     struct stat finfo; 
726     char time_str[AP_CTIME_LEN];
727
728     if (!conf->logname || 
729         ((stat(ap_server_root_relative(r->pool, conf->logname), &finfo) == 0) 
730          && (finfo.st_size > conf->logbytes)) || 
731          (ap_open(&f, ap_server_root_relative(r->pool, conf->logname), 
732                   APR_APPEND|APR_WRITE|APR_CREATE, APR_OS_DEFAULT, r->pool) != APR_SUCCESS)) { 
733         /* Soak up script output */ 
734         while (ap_bgets(argsbuffer, HUGE_STRING_LEN, script_in) > 0) 
735             continue; 
736         if (script_err) {
737             while (ap_bgets(argsbuffer, HUGE_STRING_LEN, script_err) > 0) 
738                 continue; 
739         }
740         return ret; 
741     } 
742
743     /* "%% [Wed Jun 19 10:53:21 1996] GET /cgid-bin/printenv HTTP/1.0" */ 
744     ap_ctime(time_str, ap_now());
745     ap_fprintf(f, "%%%% [%s] %s %s%s%s %s\n", time_str, r->method, r->uri, 
746             r->args ? "?" : "", r->args ? r->args : "", r->protocol); 
747     /* "%% 500 /usr/local/apache/cgid-bin" */ 
748     ap_fprintf(f, "%%%% %d %s\n", ret, r->filename); 
749
750     ap_puts("%request\n", f); 
751     for (i = 0; i < hdrs_arr->nelts; ++i) { 
752         if (!hdrs[i].key) 
753             continue; 
754         ap_fprintf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val); 
755     } 
756     if ((r->method_number == M_POST || r->method_number == M_PUT) 
757         && *dbuf) { 
758         ap_fprintf(f, "\n%s\n", dbuf); 
759     } 
760
761     ap_puts("%response\n", f); 
762     hdrs_arr = ap_table_elts(r->err_headers_out); 
763     hdrs = (ap_table_entry_t *) hdrs_arr->elts; 
764
765     for (i = 0; i < hdrs_arr->nelts; ++i) { 
766         if (!hdrs[i].key) 
767             continue; 
768         ap_fprintf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val); 
769     } 
770
771     if (sbuf && *sbuf) 
772         ap_fprintf(f, "%s\n", sbuf); 
773
774     if (ap_bgets(argsbuffer, HUGE_STRING_LEN, script_in) > 0) { 
775         ap_puts("%stdout\n", f); 
776         ap_puts(argsbuffer, f); 
777         while (ap_bgets(argsbuffer, HUGE_STRING_LEN, script_in) > 0) 
778             ap_puts(argsbuffer, f); 
779         ap_puts("\n", f); 
780     } 
781
782     if (script_err) {
783         if (ap_bgets(argsbuffer, HUGE_STRING_LEN, script_err) > 0) { 
784             ap_puts("%stderr\n", f); 
785             ap_puts(argsbuffer, f); 
786             while (ap_bgets(argsbuffer, HUGE_STRING_LEN, script_err) > 0) 
787                 ap_puts(argsbuffer, f); 
788             ap_puts("\n", f); 
789         } 
790     }
791
792     ap_bclose(script_in); 
793     if (script_err) {
794         ap_bclose(script_err); 
795     }
796
797     ap_close(f); 
798     return ret; 
799
800
801
802
803 /**************************************************************** 
804  * 
805  * Actual cgid handling... 
806  */ 
807 static int cgid_handler(request_rec *r) 
808
809     int retval, nph, dbpos = 0; 
810     char *argv0, *dbuf = NULL; 
811     BUFF *script = NULL; 
812     char argsbuffer[HUGE_STRING_LEN]; 
813     void *sconf = r->server->module_config; 
814     cgid_server_conf *conf = (cgid_server_conf *) ap_get_module_config(sconf, &cgid_module); 
815     int is_included = !strcmp(r->protocol, "INCLUDED"); 
816     int sd;
817     char **env; 
818     struct sockaddr_un unix_addr;
819     ap_socket_t *tempsock = NULL;
820     int nbytes;
821     ap_iol *iol;
822     script = ap_bcreate(r->pool, B_RDWR); 
823
824     if (r->method_number == M_OPTIONS) { 
825         /* 99 out of 100 cgid scripts, this is all they support */ 
826         r->allowed |= (1 << M_GET); 
827         r->allowed |= (1 << M_POST); 
828         return DECLINED; 
829     } 
830
831     if ((argv0 = strrchr(r->filename, '/')) != NULL)
832         argv0++;
833     else
834         argv0 = r->filename;
835  
836     nph = !(strncmp(argv0, "nph-", 4)); 
837
838     if ((argv0 = strrchr(r->filename, '/')) != NULL) 
839         argv0++; 
840     else 
841         argv0 = r->filename; 
842
843     if (!(ap_allow_options(r) & OPT_EXECCGI) && !is_scriptaliased(r)) 
844         return log_scripterror(r, conf, HTTP_FORBIDDEN, APLOG_NOERRNO, 
845                                "Options ExecCGI is off in this directory"); 
846     if (nph && is_included) 
847         return log_scripterror(r, conf, HTTP_FORBIDDEN, APLOG_NOERRNO, 
848                                "attempt to include NPH CGI script"); 
849
850 #if defined(OS2) || defined(WIN32) 
851     /* Allow for cgid files without the .EXE extension on them under OS/2 */ 
852     if (r->finfo.st_mode == 0) { 
853         struct stat statbuf; 
854         char *newfile; 
855
856         newfile = ap_pstrcat(r->pool, r->filename, ".EXE", NULL); 
857
858         if ((stat(newfile, &statbuf) != 0) || (!S_ISREG(statbuf.st_mode))) { 
859             return log_scripterror(r, conf, HTTP_NOT_FOUND, 0, 
860                                    "script not found or unable to stat"); 
861         } else { 
862             r->filename = newfile; 
863         } 
864     } 
865 #else 
866     if (r->finfo.protection == 0) 
867         return log_scripterror(r, conf, HTTP_NOT_FOUND, APLOG_NOERRNO, 
868                                "script not found or unable to stat"); 
869 #endif 
870     if (r->finfo.filetype == APR_DIR) 
871         return log_scripterror(r, conf, HTTP_FORBIDDEN, APLOG_NOERRNO, 
872                                "attempt to invoke directory as script"); 
873 /*
874     if (!ap_suexec_enabled) { 
875         if (!ap_can_exec(&r->finfo)) 
876             return log_scripterror(r, conf, HTTP_FORBIDDEN, APLOG_NOERRNO, 
877                                    "file permissions deny server execution"); 
878     } 
879 */
880     ap_add_common_vars(r); 
881     ap_add_cgi_vars(r); 
882     env = ap_create_environment(r->pool, r->subprocess_env); 
883
884     if ((sd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
885             return log_scripterror(r, conf, HTTP_NOT_FOUND, 0, 
886                                    "unable to create socket to cgi daemon");
887     } 
888     memset(&unix_addr, 0, sizeof(unix_addr));
889     unix_addr.sun_family = AF_UNIX;
890     strcpy(unix_addr.sun_path, conf->sockname);
891
892     if (connect(sd, (struct sockaddr *)&unix_addr, sizeof(unix_addr)) < 0) {
893             return log_scripterror(r, conf, HTTP_NOT_FOUND, 0, 
894                                    "unable to connect to cgi daemon");
895     } 
896
897     send_req(sd, r, argv0, env); 
898
899     ap_put_os_sock(&tempsock, &sd, pcgi);
900
901     iol = ap_iol_attach_socket(pcgi, tempsock);
902
903     ap_bpush_iol(script, iol); 
904
905     if ((retval = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR))) 
906         return retval; 
907      
908     if ((argv0 = strrchr(r->filename, '/')) != NULL) 
909         argv0++; 
910     else 
911         argv0 = r->filename; 
912
913     /* Transfer any put/post args, CERN style... 
914      * Note that we already ignore SIGPIPE in the core server. 
915      */ 
916
917     if (ap_should_client_block(r)) { 
918         int dbsize, len_read; 
919
920         if (conf->logname) { 
921             dbuf = ap_pcalloc(r->pool, conf->bufbytes + 1); 
922             dbpos = 0; 
923         } 
924
925
926
927         while ((len_read = 
928                 ap_get_client_block(r, argsbuffer, HUGE_STRING_LEN)) > 0) { 
929             if (conf->logname) { 
930                 if ((dbpos + len_read) > conf->bufbytes) { 
931                     dbsize = conf->bufbytes - dbpos; 
932                 } 
933                 else { 
934                     dbsize = len_read; 
935                 } 
936                 memcpy(dbuf + dbpos, argsbuffer, dbsize); 
937                 dbpos += dbsize; 
938             } 
939             ap_bwrite(script, argsbuffer, len_read, &nbytes);
940             if (nbytes < len_read) { 
941                 /* silly script stopped reading, soak up remaining message */ 
942                 while (ap_get_client_block(r, argsbuffer, HUGE_STRING_LEN) > 0) { 
943                     /* dump it */ 
944                 } 
945                 break; 
946             } 
947         } 
948
949         ap_bflush(script); 
950
951     } 
952
953     /* Handle script return... */ 
954     if (script && !nph) { 
955         const char *location; 
956         char sbuf[MAX_STRING_LEN]; 
957         int ret; 
958
959         if ((ret = ap_scan_script_header_err_buff(r, script, sbuf))) { 
960             return log_script(r, conf, ret, dbuf, sbuf, script, NULL); 
961         } 
962
963         location = ap_table_get(r->headers_out, "Location"); 
964
965         if (location && location[0] == '/' && r->status == 200) { 
966
967             /* Soak up all the script output */ 
968             while (ap_bgets(argsbuffer, HUGE_STRING_LEN, script) > 0) { 
969                 continue; 
970             } 
971             /* This redirect needs to be a GET no matter what the original 
972              * method was. 
973              */ 
974             r->method = ap_pstrdup(r->pool, "GET"); 
975             r->method_number = M_GET; 
976
977             /* We already read the message body (if any), so don't allow 
978              * the redirected request to think it has one. We can ignore 
979              * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR. 
980              */ 
981             ap_table_unset(r->headers_in, "Content-Length"); 
982
983             ap_internal_redirect_handler(location, r); 
984             return OK; 
985         } 
986         else if (location && r->status == 200) { 
987             /* XX Note that if a script wants to produce its own Redirect 
988              * body, it now has to explicitly *say* "Status: 302" 
989              */ 
990             return HTTP_MOVED_TEMPORARILY; 
991         } 
992
993         ap_send_http_header(r); 
994         if (!r->header_only) { 
995             ap_send_fb(script, r); 
996         } 
997         ap_bclose(script); 
998     } 
999
1000     if (script && nph) { 
1001         ap_send_fb(script, r); 
1002     } 
1003
1004     return OK; /* NOT r->status, even if it has changed. */ 
1005
1006
1007 static const handler_rec cgid_handlers[] = 
1008
1009     {CGI_MAGIC_TYPE, cgid_handler}, 
1010     {"cgi-script", cgid_handler}, 
1011     {NULL} 
1012 };
1013
1014 static void register_hook(void)
1015 {
1016     ap_hook_post_config(cgid_init, NULL, NULL, AP_HOOK_MIDDLE);
1017 }
1018
1019 module MODULE_VAR_EXPORT cgid_module = { 
1020     STANDARD20_MODULE_STUFF, 
1021     NULL, /* dir config creater */ 
1022     NULL, /* dir merger --- default is to override */ 
1023     create_cgid_config, /* server config */ 
1024     merge_cgid_config, /* merge server config */ 
1025     cgid_cmds, /* command table */ 
1026     cgid_handlers, /* handlers */ 
1027     register_hook /* register_handlers */ 
1028 }; 
1029