]> granicus.if.org Git - apache/blob - modules/generators/mod_cgid.c
Fix a lot of the fallback from the apr_ssize_t to apr_size_t change
[apache] / modules / generators / mod_cgid.c
1 /* ====================================================================
2  * The Apache Software License, Version 1.1
3  *
4  * Copyright (c) 2000 The Apache Software Foundation.  All rights
5  * reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  *
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in
16  *    the documentation and/or other materials provided with the
17  *    distribution.
18  *
19  * 3. The end-user documentation included with the redistribution,
20  *    if any, must include the following acknowledgment:
21  *       "This product includes software developed by the
22  *        Apache Software Foundation (http://www.apache.org/)."
23  *    Alternately, this acknowledgment may appear in the software itself,
24  *    if and wherever such third-party acknowledgments normally appear.
25  *
26  * 4. The names "Apache" and "Apache Software Foundation" must
27  *    not be used to endorse or promote products derived from this
28  *    software without prior written permission. For written
29  *    permission, please contact apache@apache.org.
30  *
31  * 5. Products derived from this software may not be called "Apache",
32  *    nor may "Apache" appear in their name, without prior written
33  *    permission of the Apache Software Foundation.
34  *
35  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38  * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
39  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
46  * SUCH DAMAGE.
47  * ====================================================================
48  *
49  * This software consists of voluntary contributions made by many
50  * individuals on behalf of the Apache Software Foundation.  For more
51  * information on the Apache Software Foundation, please see
52  * <http://www.apache.org/>.
53  *
54  * Portions of this software are based upon public domain software
55  * originally written at the National Center for Supercomputing Applications,
56  * University of Illinois, Urbana-Champaign.
57  */
58
59 /* 
60  * http_script: keeps all script-related ramblings together. 
61  * 
62  * Compliant to cgi/1.1 spec 
63  * 
64  * Adapted by rst from original NCSA code by Rob McCool 
65  * 
66  * Apache adds some new env vars; REDIRECT_URL and REDIRECT_QUERY_STRING for 
67  * custom error responses, and DOCUMENT_ROOT because we found it useful. 
68  * It also adds SERVER_ADMIN - useful for scripts to know who to mail when 
69  * they fail. 
70  */ 
71
72
73
74 #define CORE_PRIVATE 
75
76 #include "apr_lib.h"
77 #include "apr_strings.h"
78 #include "apr_general.h"
79 #include "apr_file_io.h"
80 #include "apr_portable.h"
81 #include "ap_buckets.h"
82 #include "util_filter.h"
83 #include "httpd.h" 
84 #include "http_config.h" 
85 #include "http_request.h" 
86 #include "http_core.h" 
87 #include "http_protocol.h" 
88 #include "http_main.h" 
89 #include "http_log.h" 
90 #include "util_script.h" 
91 #include "http_conf_globals.h" 
92 #include "ap_mpm.h"
93 #include "unixd.h"
94 #include <sys/stat.h>
95 #ifdef HAVE_SYS_SOCKET_H
96 #include <sys/socket.h>
97 #endif
98 #ifdef HAVE_UNISTD_H
99 #include <unistd.h>
100 #endif
101 #ifdef HAVE_STRINGS_H
102 #include <strings.h>
103 #endif
104 #include <sys/un.h> /* for sockaddr_un */
105 #include <sys/types.h>
106
107 module AP_MODULE_DECLARE_DATA cgid_module; 
108
109 static void cgid_init(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *main_server); 
110 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 } cgid_server_conf; 
151
152 /* If a request includes query info in the URL (stuff after "?"), and
153  * the query info does not contain "=" (indicative of a FORM submission),
154  * then this routine is called to create the argument list to be passed
155  * to the CGI script.  When suexec is enabled, the suexec path, user, and
156  * group are the first three arguments to be passed; if not, all three
157  * must be NULL.  The query info is split into separate arguments, where
158  * "+" is the separator between keyword arguments.
159  *
160  * XXXX: note that the WIN32 code uses one of the suexec strings
161  * to pass an interpreter name.  Remember this if changing the way they
162  * are handled in create_argv.
163  *
164  */
165 static char **create_argv(apr_pool_t *p, char *path, char *user, char *group,
166                           char *av0, const char *args)
167 {
168     int x, numwords;
169     char **av;
170     char *w;
171     int idx = 0;
172
173     /* count the number of keywords */
174
175     for (x = 0, numwords = 1; args[x]; x++) {
176         if (args[x] == '+') {
177             ++numwords;
178         }
179     }
180
181     if (numwords > APACHE_ARG_MAX - 5) {
182         numwords = APACHE_ARG_MAX - 5;  /* Truncate args to prevent overrun */
183     }
184     av = (char **) apr_palloc(p, (numwords + 5) * sizeof(char *));
185
186     if (path) {
187         av[idx++] = path;
188     }
189     if (user) {
190         av[idx++] = user;
191     }
192     if (group) {
193         av[idx++] = group;
194      }
195
196     av[idx++] = av0;
197
198     for (x = 1; x <= numwords; x++) {
199         w = ap_getword_nulls(p, &args, '+');
200         ap_unescape_url(w);
201         av[idx++] = ap_escape_shell_cmd(p, w);
202     }
203     av[idx] = NULL;
204     return av;
205 }
206
207 static int call_exec(request_rec *r, char *argv0, char **env, int shellcmd)
208 {
209     int pid = 0;
210     int errfileno = STDERR_FILENO;
211     /* the fd on r->server->error_log is closed, but we need somewhere to            
212      * put the error messages from the log_* functions. So, we use stderr,
213      * since that is better than allowing errors to go unnoticed. 
214      */
215     apr_put_os_file(&r->server->error_log, &errfileno, r->pool);
216     if (shellcmd) {
217         execle(SHELL_PATH, SHELL_PATH, "-c", argv0, NULL, env);
218     }
219
220     else if ((!r->args) || (!r->args[0]) || strchr(r->args, '=')) {
221         execle(r->filename, argv0, NULL, env);
222     }
223
224     else {
225         execve(r->filename,
226                create_argv(r->pool, NULL, NULL, NULL, argv0, r->args),
227                env);
228     }
229     return (pid);
230 }
231
232 static void cgid_maint(int reason, void *data, apr_wait_t status)
233 {
234 #if APR_HAS_OTHER_CHILD
235     int *sd = data;
236     switch (reason) {
237         case APR_OC_REASON_DEATH:
238         case APR_OC_REASON_LOST:
239             /* stop gap to make sure everything else works.  In the end,
240              * we'll just restart the cgid server. */
241             apr_destroy_pool(pcgi);
242             kill(getppid(), SIGWINCH);
243             break;
244         case APR_OC_REASON_RESTART:
245         case APR_OC_REASON_UNREGISTER:
246             apr_destroy_pool(pcgi);
247             kill(*sd, SIGHUP);
248             break;
249     }
250 #endif
251 }
252
253 static void get_req(int fd, request_rec *r, char **filename, char **argv0, char ***env) 
254
255     int i, len, j; 
256     unsigned char *data; 
257     char **environ; 
258     core_dir_config *temp_core; 
259     void **dconf; 
260
261     r->server = apr_pcalloc(r->pool, sizeof(server_rec)); 
262
263     read(fd, &j, sizeof(int)); 
264     read(fd, &len, sizeof(int)); 
265     data = apr_pcalloc(r->pool, len + 1); /* get a cleared byte for final '\0' */
266     i = read(fd, data, len); 
267
268     r->filename = ap_getword(r->pool, (const char **)&data, '\n'); 
269     *argv0 = ap_getword(r->pool, (const char **)&data, '\n'); 
270
271     r->uri = ap_getword(r->pool, (const char **)&data, '\n'); 
272     
273     environ = apr_pcalloc(r->pool, (j + 2) *sizeof(char *)); 
274     i = 0; 
275     for (i = 0; i < j; i++) { 
276         environ[i] = ap_getword(r->pool, (const char **)&data, '\n'); 
277     } 
278     *env = environ; 
279     r->args = ap_getword(r->pool, (const char **)&data, '\n'); 
280   
281     read(fd, &i, sizeof(int)); 
282      
283     /* add 1, so that if i == 0, we still malloc something. */ 
284     dconf = (void **)malloc(sizeof(void *) * i + 1); 
285
286     temp_core = (core_dir_config *)malloc(sizeof(core_module)); 
287 #if 0
288 #ifdef RLIMIT_CPU 
289     read(fd, &j, sizeof(int)); 
290     if (j) { 
291         temp_core->limit_cpu = (struct rlimit *)malloc (sizeof(struct rlimit)); 
292         read(fd, temp_core->limit_cpu, sizeof(struct rlimit)); 
293     } 
294     else { 
295         temp_core->limit_cpu = NULL; 
296     } 
297 #endif 
298
299 #if defined (RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS) 
300     read(fd, &j, sizeof(int)); 
301     if (j) { 
302         temp_core->limit_mem = (struct rlimit *)malloc (sizeof(struct rlimit)); 
303         read(fd, temp_core->limit_mem, sizeof(struct rlimit)); 
304     } 
305     else { 
306         temp_core->limit_mem = NULL; 
307     } 
308 #endif 
309
310 #ifdef RLIMIT_NPROC 
311     read(fd, &j, sizeof(int)); 
312     if (j) { 
313         temp_core->limit_nproc = (struct rlimit *)malloc (sizeof(struct rlimit)); 
314         read(fd, temp_core->limit_nproc, sizeof(struct rlimit)); 
315     } 
316     else { 
317         temp_core->limit_nproc = NULL; 
318     } 
319 #endif 
320 #endif
321     dconf[i] = (void *)temp_core; 
322     r->per_dir_config = dconf; 
323
324
325
326
327 static void send_req(int fd, request_rec *r, char *argv0, char **env) 
328
329     int len; 
330     int i = 0; 
331     char *data; 
332
333     data = apr_pstrcat(r->pool, r->filename, "\n", argv0, "\n", r->uri, "\n", 
334                      NULL); 
335
336     for (i =0; env[i]; i++) { 
337         continue; 
338     } 
339
340     if (write(fd, &i, sizeof(int)) < 0) {
341         ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r, 
342                      "write to cgi daemon process"); 
343         }     
344
345     for (i = 0; env[i]; i++) { 
346         data = apr_pstrcat(r->pool, data, env[i], "\n", NULL); 
347     } 
348     data = apr_pstrcat(r->pool, data, r->args, NULL); 
349     len = strlen(data); 
350     if (write(fd, &len, sizeof(int)) < 0) { 
351         ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r, 
352                      "write to cgi daemon process"); 
353         }     
354     if (write(fd, data, len) < 0) {
355         ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r, 
356                      "write to cgi daemon process"); 
357         }     
358     if (write(fd, &core_module.module_index, sizeof(int)) < 0) { 
359         ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r, 
360                      "write to cgi daemon process"); 
361         }     
362 #if 0
363 #ifdef RLIMIT_CPU 
364     if (conf->limit_cpu) { 
365         len = 1; 
366         write(fd, &len, sizeof(int)); 
367         write(fd, conf->limit_cpu, sizeof(struct rlimit)); 
368     } 
369     else { 
370         len = 0; 
371         write(fd, &len, sizeof(int)); 
372     } 
373 #endif 
374
375 #if defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS) 
376     if (conf->limit_mem) { 
377         len = 1; 
378         write(fd, &len, sizeof(int)); 
379         write(fd, conf->limit_mem, sizeof(struct rlimit)); 
380     } 
381     else { 
382         len = 0; 
383         write(fd, &len, sizeof(int)); 
384     } 
385 #endif 
386   
387 #ifdef RLIMIT_NPROC 
388     if (conf->limit_nproc) { 
389         len = 1; 
390         write(fd, &len, sizeof(int)); 
391         write(fd, conf->limit_nproc, sizeof(struct rlimit)); 
392     } 
393     else { 
394         len = 0; 
395         write(fd, &len, sizeof(int)); 
396     } 
397 #endif
398 #endif 
399
400
401 static int cgid_server_child(int sd) 
402
403     char *argv0; 
404     char *filename; 
405     char **env; 
406     apr_pool_t *p; 
407     request_rec *r; 
408
409     apr_create_pool(&p, pcgi); 
410     r = apr_pcalloc(p, sizeof(request_rec)); 
411     r->pool = p; 
412     dup2(sd, STDIN_FILENO); 
413     dup2(sd, STDOUT_FILENO); 
414     get_req(sd, r, &filename, &argv0, &env); 
415     call_exec(r, argv0, env, 0); 
416     exit(-1);   /* We should NEVER get here */
417
418
419 static int cgid_server(void *data) 
420
421     struct sockaddr_un unix_addr;
422     int pid; 
423     int sd, sd2, rc;
424     int errfile;
425     mode_t omask;
426     apr_socklen_t len;
427     server_rec *main_server = data;
428     cgid_server_conf *sconf = (cgid_server_conf *)ap_get_module_config( 
429                        main_server->module_config, &cgid_module); 
430
431     apr_signal(SIGCHLD, SIG_IGN); 
432     if (unlink(sconf->sockname) < 0 && errno == ENOENT) {
433         ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
434                      "Couldn't unlink unix domain socket %s",
435                      sconf->sockname);
436         /* just a warning; don't bail out */
437     }
438
439     if ((sd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
440         ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server, 
441                      "Couldn't create unix domain socket");
442         return errno;
443     } 
444
445     memset(&unix_addr, 0, sizeof(unix_addr));
446     unix_addr.sun_family = AF_UNIX;
447     strcpy(unix_addr.sun_path, sconf->sockname);
448
449     omask = umask(0077); /* so that only Apache can use socket */
450     rc = bind(sd, (struct sockaddr *)&unix_addr, sizeof(unix_addr));
451     umask(omask); /* can't fail, so can't clobber errno */
452     if (rc < 0) {
453         ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server, 
454                      "Couldn't bind unix domain socket %s",
455                      sconf->sockname); 
456         return errno;
457     } 
458
459     if (listen(sd, DEFAULT_CGID_LISTENBACKLOG) < 0) {
460         ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server, 
461                      "Couldn't listen on unix domain socket"); 
462         return errno;
463     } 
464
465     if (!geteuid()) {
466         if (chown(sconf->sockname, unixd_config.user_id, -1) < 0) {
467             ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server, 
468                          "Couldn't change owner of unix domain socket %s",
469                          sconf->sockname); 
470             return errno;
471         }
472     }
473     
474     unixd_setup_child(); /* if running as root, switch to configured user/group */
475
476     while (1) {
477         len = sizeof(unix_addr);
478         sd2 = accept(sd, (struct sockaddr *)&unix_addr, &len);
479         if (sd2 < 0) {
480             if (errno != EINTR) {
481                 ap_log_error(APLOG_MARK, APLOG_ERR, errno, 
482                              (server_rec *)data,
483                              "Error accepting on cgid socket.");
484             }
485             continue;
486         }
487        
488         if ((pid = fork()) > 0) {
489             close(sd2);
490         } 
491         else if (pid == 0) { 
492             /* setup the STDERR here, because I have all the info
493              * for it.  I'll do the STDIN and STDOUT later, but I can't
494              * do STDERR as easily.
495              */
496             if (sconf->logname) {
497                 dup2(open(sconf->logname, O_WRONLY), STDERR_FILENO);
498             }
499             else {
500                 apr_get_os_file(&errfile, main_server->error_log);
501                 dup2(errfile, STDERR_FILENO);
502             }
503             cgid_server_child(sd2); 
504         } 
505         else { 
506             ap_log_error(APLOG_MARK, APLOG_ERR, errno, (server_rec *)data, 
507                          "Couldn't fork cgi script"); 
508         } 
509     } 
510     return -1; 
511
512
513 static void cgid_init(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *main_server) 
514
515     pid_t pid; 
516     apr_proc_t *procnew;
517
518     if (once_through > 0) { 
519         apr_create_pool(&pcgi, p); 
520
521         if ((pid = fork()) < 0) {
522             ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server, 
523                          "Couldn't spawn cgid daemon process"); 
524         }
525         else if (pid == 0) {
526             cgid_server(main_server);
527             exit(-1);
528         } 
529         procnew = apr_pcalloc(p, sizeof(*procnew));        
530         procnew->pid = pid;
531         procnew->err = procnew->in = procnew->out = NULL;
532         apr_note_subprocess(p, procnew, kill_after_timeout);
533 #if APR_HAS_OTHER_CHILD
534         apr_register_other_child(procnew, cgid_maint, NULL, NULL, p);
535 #endif
536     } 
537     else once_through++; 
538
539
540 static void *create_cgid_config(apr_pool_t *p, server_rec *s) 
541
542     cgid_server_conf *c = 
543     (cgid_server_conf *) apr_pcalloc(p, sizeof(cgid_server_conf)); 
544
545     c->logname = NULL; 
546     c->logbytes = DEFAULT_LOGBYTES; 
547     c->bufbytes = DEFAULT_BUFBYTES; 
548     c->sockname = ap_server_root_relative(p, DEFAULT_SOCKET); 
549     return c; 
550
551
552 static void *merge_cgid_config(apr_pool_t *p, void *basev, void *overridesv) 
553
554     cgid_server_conf *base = (cgid_server_conf *) basev, *overrides = (cgid_server_conf *) overridesv; 
555
556     return overrides->logname ? overrides : base; 
557
558
559 static const char *set_scriptlog(cmd_parms *cmd, void *dummy, const char *arg) 
560
561     server_rec *s = cmd->server; 
562     cgid_server_conf *conf = 
563     (cgid_server_conf *) ap_get_module_config(s->module_config, &cgid_module); 
564
565     conf->logname = arg; 
566     return NULL; 
567
568
569 static const char *set_scriptlog_length(cmd_parms *cmd, void *dummy, const char *arg) 
570
571     server_rec *s = cmd->server; 
572     cgid_server_conf *conf = 
573     (cgid_server_conf *) ap_get_module_config(s->module_config, &cgid_module); 
574
575     conf->logbytes = atol(arg); 
576     return NULL; 
577
578
579 static const char *set_scriptlog_buffer(cmd_parms *cmd, void *dummy, const char *arg) 
580
581     server_rec *s = cmd->server; 
582     cgid_server_conf *conf = 
583     (cgid_server_conf *) ap_get_module_config(s->module_config, &cgid_module); 
584
585     conf->bufbytes = atoi(arg); 
586     return NULL; 
587
588
589 static const char *set_script_socket(cmd_parms *cmd, void *dummy, const char *arg) 
590
591     server_rec *s = cmd->server; 
592     cgid_server_conf *conf = 
593     (cgid_server_conf *) ap_get_module_config(s->module_config, &cgid_module); 
594
595     conf->sockname = ap_server_root_relative(cmd->pool, arg); 
596     return NULL; 
597
598
599 static const command_rec cgid_cmds[] = 
600
601     AP_INIT_TAKE1("ScriptLog", set_scriptlog, NULL, RSRC_CONF,
602                   "the name of a log for script debugging info"), 
603     AP_INIT_TAKE1("ScriptLogLength", set_scriptlog_length, NULL, RSRC_CONF,
604                   "the maximum length (in bytes) of the script debug log"), 
605     AP_INIT_TAKE1("ScriptLogBuffer", set_scriptlog_buffer, NULL, RSRC_CONF,
606                   "the maximum size (in bytes) to record of a POST request"), 
607     AP_INIT_TAKE1("Scriptsock", set_script_socket, NULL, RSRC_CONF,
608                   "the name of the socket to use for communication with "
609                   "the cgi daemon."), 
610     {NULL} 
611 }; 
612
613 static int log_scripterror(request_rec *r, cgid_server_conf * conf, int ret, 
614                            int show_errno, char *error) 
615
616     apr_file_t *f = NULL; 
617     struct stat finfo; 
618     char time_str[APR_CTIME_LEN];
619
620     ap_log_rerror(APLOG_MARK, show_errno|APLOG_ERR, errno, r, 
621                 "%s: %s", error, r->filename); 
622
623     if (!conf->logname || 
624         ((stat(ap_server_root_relative(r->pool, conf->logname), &finfo) == 0) 
625          && (finfo.st_size > conf->logbytes)) || 
626          (apr_open(&f, ap_server_root_relative(r->pool, conf->logname),
627                   APR_APPEND|APR_WRITE|APR_CREATE, APR_OS_DEFAULT, r->pool) != APR_SUCCESS)) { 
628         return ret; 
629     } 
630
631     /* "%% [Wed Jun 19 10:53:21 1996] GET /cgid-bin/printenv HTTP/1.0" */ 
632     apr_ctime(time_str, apr_now());
633     apr_fprintf(f, "%%%% [%s] %s %s%s%s %s\n", time_str, r->method, r->uri, 
634             r->args ? "?" : "", r->args ? r->args : "", r->protocol); 
635     /* "%% 500 /usr/local/apache/cgid-bin */ 
636     apr_fprintf(f, "%%%% %d %s\n", ret, r->filename); 
637
638     apr_fprintf(f, "%%error\n%s\n", error); 
639
640     apr_close(f); 
641     return ret; 
642
643
644 static int log_script(request_rec *r, cgid_server_conf * conf, int ret, 
645                   char *dbuf, const char *sbuf, apr_file_t *script_in, apr_file_t *script_err) 
646
647     apr_array_header_t *hdrs_arr = apr_table_elts(r->headers_in); 
648     apr_table_entry_t *hdrs = (apr_table_entry_t *) hdrs_arr->elts; 
649     char argsbuffer[HUGE_STRING_LEN]; 
650     apr_file_t *f = NULL; 
651     int i; 
652     struct stat finfo; 
653     char time_str[APR_CTIME_LEN];
654
655     if (!conf->logname || 
656         ((stat(ap_server_root_relative(r->pool, conf->logname), &finfo) == 0) 
657          && (finfo.st_size > conf->logbytes)) || 
658          (apr_open(&f, ap_server_root_relative(r->pool, conf->logname), 
659                   APR_APPEND|APR_WRITE|APR_CREATE, APR_OS_DEFAULT, r->pool) != APR_SUCCESS)) { 
660         /* Soak up script output */ 
661         while (apr_fgets(argsbuffer, HUGE_STRING_LEN, script_in) == 0) 
662             continue; 
663         if (script_err) {
664             while (apr_fgets(argsbuffer, HUGE_STRING_LEN, script_err) == 0) 
665                 continue; 
666         }
667         return ret; 
668     } 
669
670     /* "%% [Wed Jun 19 10:53:21 1996] GET /cgid-bin/printenv HTTP/1.0" */ 
671     apr_ctime(time_str, apr_now());
672     apr_fprintf(f, "%%%% [%s] %s %s%s%s %s\n", time_str, r->method, r->uri, 
673             r->args ? "?" : "", r->args ? r->args : "", r->protocol); 
674     /* "%% 500 /usr/local/apache/cgid-bin" */ 
675     apr_fprintf(f, "%%%% %d %s\n", ret, r->filename); 
676
677     apr_puts("%request\n", f); 
678     for (i = 0; i < hdrs_arr->nelts; ++i) { 
679         if (!hdrs[i].key) 
680             continue; 
681         apr_fprintf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val); 
682     } 
683     if ((r->method_number == M_POST || r->method_number == M_PUT) 
684         && *dbuf) { 
685         apr_fprintf(f, "\n%s\n", dbuf); 
686     } 
687
688     apr_puts("%response\n", f); 
689     hdrs_arr = apr_table_elts(r->err_headers_out); 
690     hdrs = (apr_table_entry_t *) hdrs_arr->elts; 
691
692     for (i = 0; i < hdrs_arr->nelts; ++i) { 
693         if (!hdrs[i].key) 
694             continue; 
695         apr_fprintf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val); 
696     } 
697
698     if (sbuf && *sbuf) 
699         apr_fprintf(f, "%s\n", sbuf); 
700
701     if (apr_fgets(argsbuffer, HUGE_STRING_LEN, script_in) == 0) { 
702         apr_puts("%stdout\n", f); 
703         apr_puts(argsbuffer, f); 
704         while (apr_fgets(argsbuffer, HUGE_STRING_LEN, script_in) == 0) 
705             apr_puts(argsbuffer, f); 
706         apr_puts("\n", f); 
707     } 
708
709     if (script_err) {
710         if (apr_fgets(argsbuffer, HUGE_STRING_LEN, script_err) == 0) { 
711             apr_puts("%stderr\n", f); 
712             apr_puts(argsbuffer, f); 
713             while (apr_fgets(argsbuffer, HUGE_STRING_LEN, script_err) == 0) 
714                 apr_puts(argsbuffer, f); 
715             apr_puts("\n", f); 
716         } 
717     }
718
719     apr_close(script_in); 
720     if (script_err) {
721         apr_close(script_err); 
722     }
723
724     apr_close(f); 
725     return ret; 
726
727
728
729
730 /**************************************************************** 
731  * 
732  * Actual cgid handling... 
733  */ 
734 static int cgid_handler(request_rec *r) 
735
736     int retval, nph, dbpos = 0; 
737     char *argv0, *dbuf = NULL; 
738     ap_bucket_brigade *bb;
739     ap_bucket *b;
740     char argsbuffer[HUGE_STRING_LEN]; 
741     void *sconf = r->server->module_config; 
742     cgid_server_conf *conf = (cgid_server_conf *) ap_get_module_config(sconf, &cgid_module); 
743     int is_included = !strcmp(r->protocol, "INCLUDED"); 
744     int sd;
745     char **env; 
746     struct sockaddr_un unix_addr;
747     apr_file_t *tempsock = NULL;
748     apr_size_t nbytes;
749
750     if (r->method_number == M_OPTIONS) { 
751         /* 99 out of 100 cgid scripts, this is all they support */ 
752         r->allowed |= (1 << M_GET); 
753         r->allowed |= (1 << M_POST); 
754         return DECLINED; 
755     } 
756
757     if ((argv0 = strrchr(r->filename, '/')) != NULL)
758         argv0++;
759     else
760         argv0 = r->filename;
761  
762     nph = !(strncmp(argv0, "nph-", 4)); 
763
764     if ((argv0 = strrchr(r->filename, '/')) != NULL) 
765         argv0++; 
766     else 
767         argv0 = r->filename; 
768
769     if (!(ap_allow_options(r) & OPT_EXECCGI) && !is_scriptaliased(r)) 
770         return log_scripterror(r, conf, HTTP_FORBIDDEN, APLOG_NOERRNO, 
771                                "Options ExecCGI is off in this directory"); 
772     if (nph && is_included) 
773         return log_scripterror(r, conf, HTTP_FORBIDDEN, APLOG_NOERRNO, 
774                                "attempt to include NPH CGI script"); 
775
776 #if defined(OS2) || defined(WIN32) 
777     /* Allow for cgid files without the .EXE extension on them under OS/2 */ 
778     if (r->finfo.st_mode == 0) { 
779         struct stat statbuf; 
780         char *newfile; 
781
782         newfile = apr_pstrcat(r->pool, r->filename, ".EXE", NULL); 
783
784         if ((stat(newfile, &statbuf) != 0) || (!S_ISREG(statbuf.st_mode))) { 
785             return log_scripterror(r, conf, HTTP_NOT_FOUND, 0, 
786                                    "script not found or unable to stat"); 
787         } else { 
788             r->filename = newfile; 
789         } 
790     } 
791 #else 
792     if (r->finfo.protection == 0) 
793         return log_scripterror(r, conf, HTTP_NOT_FOUND, APLOG_NOERRNO, 
794                                "script not found or unable to stat"); 
795 #endif 
796     if (r->finfo.filetype == APR_DIR) 
797         return log_scripterror(r, conf, HTTP_FORBIDDEN, APLOG_NOERRNO, 
798                                "attempt to invoke directory as script"); 
799 /*
800     if (!ap_suexec_enabled) { 
801         if (!ap_can_exec(&r->finfo)) 
802             return log_scripterror(r, conf, HTTP_FORBIDDEN, APLOG_NOERRNO, 
803                                    "file permissions deny server execution"); 
804     } 
805 */
806     ap_add_common_vars(r); 
807     ap_add_cgi_vars(r); 
808     env = ap_create_environment(r->pool, r->subprocess_env); 
809
810     if ((sd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
811             return log_scripterror(r, conf, HTTP_NOT_FOUND, 0, 
812                                    "unable to create socket to cgi daemon");
813     } 
814     memset(&unix_addr, 0, sizeof(unix_addr));
815     unix_addr.sun_family = AF_UNIX;
816     strcpy(unix_addr.sun_path, conf->sockname);
817
818     if (connect(sd, (struct sockaddr *)&unix_addr, sizeof(unix_addr)) < 0) {
819             return log_scripterror(r, conf, HTTP_NOT_FOUND, 0, 
820                                    "unable to connect to cgi daemon");
821     } 
822
823     send_req(sd, r, argv0, env); 
824
825     /* We are putting the tempsock variable into a file so that we can use
826      * a pipe bucket to send the data to the client.
827      */
828     apr_put_os_file(&tempsock, &sd, r->pool);
829
830     if ((retval = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR))) 
831         return retval; 
832      
833     if ((argv0 = strrchr(r->filename, '/')) != NULL) 
834         argv0++; 
835     else 
836         argv0 = r->filename; 
837
838     /* Transfer any put/post args, CERN style... 
839      * Note that we already ignore SIGPIPE in the core server. 
840      */ 
841
842     if (ap_should_client_block(r)) { 
843         int dbsize, len_read; 
844
845         if (conf->logname) { 
846             dbuf = apr_pcalloc(r->pool, conf->bufbytes + 1); 
847             dbpos = 0; 
848         } 
849
850         while ((len_read = 
851                 ap_get_client_block(r, argsbuffer, HUGE_STRING_LEN)) > 0) { 
852             if (conf->logname) { 
853                 if ((dbpos + len_read) > conf->bufbytes) { 
854                     dbsize = conf->bufbytes - dbpos; 
855                 } 
856                 else { 
857                     dbsize = len_read; 
858                 } 
859                 memcpy(dbuf + dbpos, argsbuffer, dbsize); 
860                 dbpos += dbsize; 
861             } 
862             nbytes = len_read;
863             apr_write(tempsock, argsbuffer, &nbytes);
864             if (nbytes < len_read) { 
865                 /* silly script stopped reading, soak up remaining message */ 
866                 while (ap_get_client_block(r, argsbuffer, HUGE_STRING_LEN) > 0) { 
867                     /* dump it */ 
868                 } 
869                 break; 
870             } 
871         } 
872         shutdown(sd, 1); /* done writing; force EOF on child's stdin */
873     } 
874
875     /* Handle script return... */ 
876     if (!nph) { 
877         const char *location; 
878         char sbuf[MAX_STRING_LEN]; 
879         int ret; 
880
881         if ((ret = ap_scan_script_header_err(r, tempsock, sbuf))) { 
882             return log_script(r, conf, ret, dbuf, sbuf, tempsock, NULL); 
883         } 
884
885         location = apr_table_get(r->headers_out, "Location"); 
886
887         if (location && location[0] == '/' && r->status == 200) { 
888
889             /* Soak up all the script output */ 
890             while (apr_fgets(argsbuffer, HUGE_STRING_LEN, tempsock) > 0) { 
891                 continue; 
892             } 
893             /* This redirect needs to be a GET no matter what the original 
894              * method was. 
895              */ 
896             r->method = apr_pstrdup(r->pool, "GET"); 
897             r->method_number = M_GET; 
898
899             /* We already read the message body (if any), so don't allow 
900              * the redirected request to think it has one. We can ignore 
901              * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR. 
902              */ 
903             apr_table_unset(r->headers_in, "Content-Length"); 
904
905             ap_internal_redirect_handler(location, r); 
906             return OK; 
907         } 
908         else if (location && r->status == 200) { 
909             /* XX Note that if a script wants to produce its own Redirect 
910              * body, it now has to explicitly *say* "Status: 302" 
911              */ 
912             return HTTP_MOVED_TEMPORARILY; 
913         } 
914
915         ap_send_http_header(r); 
916         if (!r->header_only) { 
917             bb = ap_brigade_create(r->pool);
918             b = ap_bucket_create_pipe(tempsock);
919             AP_BRIGADE_INSERT_TAIL(bb, b);
920             b = ap_bucket_create_eos();
921             AP_BRIGADE_INSERT_TAIL(bb, b);
922             ap_pass_brigade(r->output_filters, bb);
923         } 
924     } 
925
926     if (nph) {
927         bb = ap_brigade_create(r->pool);
928         b = ap_bucket_create_pipe(tempsock);
929         AP_BRIGADE_INSERT_TAIL(bb, b);
930         b = ap_bucket_create_eos();
931         AP_BRIGADE_INSERT_TAIL(bb, b);
932         ap_pass_brigade(r->output_filters, bb);
933     } 
934
935     apr_close(tempsock);
936
937     return OK; /* NOT r->status, even if it has changed. */ 
938
939
940 static const handler_rec cgid_handlers[] = 
941
942     {CGI_MAGIC_TYPE, cgid_handler}, 
943     {"cgi-script", cgid_handler}, 
944     {NULL} 
945 };
946
947 static void register_hook(void)
948 {
949     ap_hook_post_config(cgid_init, NULL, NULL, AP_HOOK_MIDDLE);
950 }
951
952 module AP_MODULE_DECLARE_DATA cgid_module = { 
953     STANDARD20_MODULE_STUFF, 
954     NULL, /* dir config creater */ 
955     NULL, /* dir merger --- default is to override */ 
956     create_cgid_config, /* server config */ 
957     merge_cgid_config, /* merge server config */ 
958     cgid_cmds, /* command table */ 
959     cgid_handlers, /* handlers */ 
960     register_hook /* register_handlers */ 
961 }; 
962