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