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