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