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