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