]> granicus.if.org Git - apache/blob - modules/generators/mod_cgid.c
Eliminate all assumptions that finfo.protection reflects the existance
[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 "apr_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 "mod_suexec.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 AP_MODULE_DECLARE_DATA 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
112 static apr_pool_t *pcgi; 
113 static int total_modules = 0;
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 } cgid_server_conf; 
152
153 /* If a request includes query info in the URL (stuff after "?"), and
154  * the query info does not contain "=" (indicative of a FORM submission),
155  * then this routine is called to create the argument list to be passed
156  * to the CGI script.  When suexec is enabled, the suexec path, user, and
157  * group are the first three arguments to be passed; if not, all three
158  * must be NULL.  The query info is split into separate arguments, where
159  * "+" is the separator between keyword arguments.
160  *
161  * XXXX: note that the WIN32 code uses one of the suexec strings
162  * to pass an interpreter name.  Remember this if changing the way they
163  * are handled in create_argv.
164  *
165  */
166 static char **create_argv(apr_pool_t *p, char *path, char *user, char *group,
167                           char *av0, const char *args)
168 {
169     int x, numwords;
170     char **av;
171     char *w;
172     int idx = 0;
173
174     /* count the number of keywords */
175
176     for (x = 0, numwords = 1; args[x]; x++) {
177         if (args[x] == '+') {
178             ++numwords;
179         }
180     }
181
182     if (numwords > APACHE_ARG_MAX - 5) {
183         numwords = APACHE_ARG_MAX - 5;  /* Truncate args to prevent overrun */
184     }
185     av = (char **) apr_pcalloc(p, (numwords + 5) * sizeof(char *));
186
187     if (path) {
188         av[idx++] = path;
189     }
190     if (user) {
191         av[idx++] = user;
192     }
193     if (group) {
194         av[idx++] = group;
195     }
196
197     av[idx++] = apr_pstrdup(p, av0);
198
199     for (x = 1; x <= numwords; x++) {
200         w = ap_getword_nulls(p, &args, '+');
201         if (strcmp(w, "")) {
202             ap_unescape_url(w);
203             av[idx++] = ap_escape_shell_cmd(p, w);
204         }
205     }
206     av[idx] = NULL;
207     return av;
208 }
209
210 static void cgid_maint(int reason, void *data, apr_wait_t status)
211 {
212 #if APR_HAS_OTHER_CHILD
213     int *sd = data;
214     switch (reason) {
215         case APR_OC_REASON_DEATH:
216         case APR_OC_REASON_LOST:
217             /* stop gap to make sure everything else works.  In the end,
218              * we'll just restart the cgid server. */
219             apr_destroy_pool(pcgi);
220             kill(getppid(), SIGWINCH);
221             break;
222         case APR_OC_REASON_RESTART:
223         case APR_OC_REASON_UNREGISTER:
224             apr_destroy_pool(pcgi);
225             kill(*sd, SIGHUP);
226             break;
227     }
228 #endif
229 }
230
231 static void get_req(int fd, request_rec *r, char **filename, char **argv0, char ***env) 
232
233     int i, len, j; 
234     unsigned char *data; 
235     char **environ; 
236     core_dir_config *temp_core; 
237     void **dconf; 
238     module *suexec_mod = ap_find_linked_module("mod_suexec.c");
239
240     r->server = apr_pcalloc(r->pool, sizeof(server_rec)); 
241
242     read(fd, &j, sizeof(int)); 
243     read(fd, &len, sizeof(int)); 
244     data = apr_pcalloc(r->pool, len + 1); /* get a cleared byte for final '\0' */
245     i = read(fd, data, len); 
246
247     r->filename = ap_getword(r->pool, (const char **)&data, '\n'); 
248     *argv0 = ap_getword(r->pool, (const char **)&data, '\n'); 
249
250     r->uri = ap_getword(r->pool, (const char **)&data, '\n'); 
251     
252     environ = apr_pcalloc(r->pool, (j + 2) *sizeof(char *)); 
253     i = 0; 
254     for (i = 0; i < j; i++) { 
255         environ[i] = ap_getword(r->pool, (const char **)&data, '\n'); 
256     } 
257     *env = environ; 
258     r->args = ap_getword(r->pool, (const char **)&data, '\n'); 
259   
260     read(fd, &i, sizeof(int)); 
261      
262     /* add 1, so that if i == 0, we still malloc something. */ 
263
264     dconf = (void **) apr_pcalloc(r->pool, sizeof(void *) * (total_modules + DYNAMIC_MODULE_LIMIT));
265
266     temp_core = (core_dir_config *)apr_palloc(r->pool, sizeof(core_module)); 
267
268     dconf[i] = (void *)temp_core; 
269
270     if (suexec_mod) {
271         suexec_config_t *suexec_cfg = apr_pcalloc(r->pool, sizeof(*suexec_cfg));
272
273         read(fd, &i, sizeof(int));
274         read(fd, &suexec_cfg->ugid.uid, sizeof(uid_t));
275         read(fd, &suexec_cfg->ugid.gid, sizeof(gid_t));
276         read(fd, &suexec_cfg->active, sizeof(int));
277         dconf[i] = (void *)suexec_cfg;
278     }
279
280     r->per_dir_config = dconf; 
281 #if 0
282 #ifdef RLIMIT_CPU 
283     read(fd, &j, sizeof(int)); 
284     if (j) { 
285         temp_core->limit_cpu = (struct rlimit *)apr_palloc (sizeof(struct rlimit)); 
286         read(fd, temp_core->limit_cpu, sizeof(struct rlimit)); 
287     } 
288     else { 
289         temp_core->limit_cpu = NULL; 
290     } 
291 #endif 
292
293 #if defined (RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS) 
294     read(fd, &j, sizeof(int)); 
295     if (j) { 
296         temp_core->limit_mem = (struct rlimit *)apr_palloc(r->pool, sizeof(struct rlimit)); 
297         read(fd, temp_core->limit_mem, sizeof(struct rlimit)); 
298     } 
299     else { 
300         temp_core->limit_mem = NULL; 
301     } 
302 #endif 
303
304 #ifdef RLIMIT_NPROC 
305     read(fd, &j, sizeof(int)); 
306     if (j) { 
307         temp_core->limit_nproc = (struct rlimit *)apr_palloc(r->pool, sizeof(struct rlimit)); 
308         read(fd, temp_core->limit_nproc, sizeof(struct rlimit)); 
309     } 
310     else { 
311         temp_core->limit_nproc = NULL; 
312     } 
313 #endif 
314 #endif
315     /* For right now, just make the notes table.  At some point we will need
316      * to actually fill this out, but for now we just don't want suexec to
317      * seg fault.
318      */
319     r->notes = apr_make_table(r->pool, 1);
320
321
322
323
324 static void send_req(int fd, request_rec *r, char *argv0, char **env) 
325
326     int len; 
327     int i = 0; 
328     char *data; 
329     module *suexec_mod = ap_find_linked_module("mod_suexec.c");
330
331     data = apr_pstrcat(r->pool, r->filename, "\n", argv0, "\n", r->uri, "\n", 
332                      NULL); 
333
334     for (i =0; env[i]; i++) { 
335         continue; 
336     } 
337
338     if (write(fd, &i, sizeof(int)) < 0) {
339         ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r, 
340                      "write to cgi daemon process"); 
341         }     
342
343     for (i = 0; env[i]; i++) { 
344         data = apr_pstrcat(r->pool, data, env[i], "\n", NULL); 
345     } 
346     data = apr_pstrcat(r->pool, data, r->args, NULL); 
347     len = strlen(data); 
348     if (write(fd, &len, sizeof(int)) < 0) { 
349         ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r, 
350                      "write to cgi daemon process"); 
351         }     
352     if (write(fd, data, len) < 0) {
353         ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r, 
354                      "write to cgi daemon process"); 
355         }     
356     if (write(fd, &core_module.module_index, sizeof(int)) < 0) { 
357         ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r, 
358                      "write to cgi daemon process"); 
359         }     
360     if (suexec_mod) {
361         suexec_config_t *suexec_cfg = ap_get_module_config(r->per_dir_config,
362                                                            suexec_mod);
363
364         write(fd, &suexec_mod->module_index, sizeof(int));
365         write(fd, &suexec_cfg->ugid.uid, sizeof(uid_t));
366         write(fd, &suexec_cfg->ugid.gid, sizeof(gid_t));
367         write(fd, &suexec_cfg->active, sizeof(int));
368     }
369
370 #if 0
371 #ifdef RLIMIT_CPU 
372     if (conf->limit_cpu) { 
373         len = 1; 
374         write(fd, &len, sizeof(int)); 
375         write(fd, conf->limit_cpu, sizeof(struct rlimit)); 
376     } 
377     else { 
378         len = 0; 
379         write(fd, &len, sizeof(int)); 
380     } 
381 #endif 
382
383 #if defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS) 
384     if (conf->limit_mem) { 
385         len = 1; 
386         write(fd, &len, sizeof(int)); 
387         write(fd, conf->limit_mem, sizeof(struct rlimit)); 
388     } 
389     else { 
390         len = 0; 
391         write(fd, &len, sizeof(int)); 
392     } 
393 #endif 
394   
395 #ifdef RLIMIT_NPROC 
396     if (conf->limit_nproc) { 
397         len = 1; 
398         write(fd, &len, sizeof(int)); 
399         write(fd, conf->limit_nproc, sizeof(struct rlimit)); 
400     } 
401     else { 
402         len = 0; 
403         write(fd, &len, sizeof(int)); 
404     } 
405 #endif
406 #endif 
407
408
409 static int cgid_server(void *data) 
410
411     struct sockaddr_un unix_addr;
412     int sd, sd2, rc;
413     mode_t omask;
414     apr_socklen_t len;
415     server_rec *main_server = data;
416     cgid_server_conf *sconf = (cgid_server_conf *)ap_get_module_config( 
417                        main_server->module_config, &cgid_module); 
418
419     apr_signal(SIGCHLD, SIG_IGN); 
420     if (unlink(sconf->sockname) < 0 && errno != ENOENT) {
421         ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
422                      "Couldn't unlink unix domain socket %s",
423                      sconf->sockname);
424         /* just a warning; don't bail out */
425     }
426
427     if ((sd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
428         ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server, 
429                      "Couldn't create unix domain socket");
430         return errno;
431     } 
432
433     memset(&unix_addr, 0, sizeof(unix_addr));
434     unix_addr.sun_family = AF_UNIX;
435     strcpy(unix_addr.sun_path, sconf->sockname);
436
437     omask = umask(0077); /* so that only Apache can use socket */
438     rc = bind(sd, (struct sockaddr *)&unix_addr, sizeof(unix_addr));
439     umask(omask); /* can't fail, so can't clobber errno */
440     if (rc < 0) {
441         ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server, 
442                      "Couldn't bind unix domain socket %s",
443                      sconf->sockname); 
444         return errno;
445     } 
446
447     if (listen(sd, DEFAULT_CGID_LISTENBACKLOG) < 0) {
448         ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server, 
449                      "Couldn't listen on unix domain socket"); 
450         return errno;
451     } 
452
453     if (!geteuid()) {
454         if (chown(sconf->sockname, unixd_config.user_id, -1) < 0) {
455             ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server, 
456                          "Couldn't change owner of unix domain socket %s",
457                          sconf->sockname); 
458             return errno;
459         }
460     }
461     
462     unixd_setup_child(); /* if running as root, switch to configured user/group */
463     while (1) {
464         int errfileno = STDERR_FILENO;
465         char *argv0; 
466         char *filename; 
467         char **env; 
468         const char * const *argv; 
469         apr_pool_t *p; 
470         request_rec *r; 
471         apr_procattr_t *procattr = NULL;
472         apr_proc_t *procnew = NULL;
473         apr_file_t *inout;
474
475
476         len = sizeof(unix_addr);
477         sd2 = accept(sd, (struct sockaddr *)&unix_addr, &len);
478         if (sd2 < 0) {
479             if (errno != EINTR) {
480                 ap_log_error(APLOG_MARK, APLOG_ERR, errno, 
481                              (server_rec *)data,
482                              "Error accepting on cgid socket.");
483             }
484             continue;
485         }
486        
487         apr_create_pool(&p, pcgi); 
488
489         r = apr_pcalloc(p, sizeof(request_rec)); 
490         procnew = apr_pcalloc(p, sizeof(*procnew));
491         r->pool = p; 
492         get_req(sd2, r, &filename, &argv0, &env); 
493         apr_put_os_file(&r->server->error_log, &errfileno, r->pool);
494         apr_put_os_file(&inout, &sd2, r->pool);
495
496         if (((rc = apr_createprocattr_init(&procattr, p)) != APR_SUCCESS) ||
497             ((rc = apr_setprocattr_io(procattr,
498                                      APR_CHILD_BLOCK,
499                                      APR_CHILD_BLOCK,
500                                      APR_CHILD_BLOCK)) != APR_SUCCESS) ||
501             ((rc = apr_setprocattr_childin(procattr, inout, NULL)) != APR_SUCCESS) ||
502             ((rc = apr_setprocattr_childout(procattr, inout, NULL)) != APR_SUCCESS) ||
503             ((rc = apr_setprocattr_childerr(procattr, r->server->error_log, NULL)) != APR_SUCCESS) ||
504             ((rc = apr_setprocattr_dir(procattr,
505                                   ap_make_dirstr_parent(r->pool, r->filename))) != APR_SUCCESS) ||
506             ((rc = apr_setprocattr_cmdtype(procattr, APR_PROGRAM)) != APR_SUCCESS)) {
507             /* Something bad happened, tell the world. */
508             ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r,
509                       "couldn't set child process attributes: %s", r->filename);
510         }
511         else {
512             argv = (const char * const *)create_argv(r->pool, NULL, NULL, NULL, argv0, r->args);
513             rc = ap_os_create_privileged_process(r, procnew, argv0, argv, 
514                                                  (const char * const *)env, 
515                                                  procattr, p);
516
517             close(sd2);
518             if (rc != APR_SUCCESS) {
519                 /* Bad things happened. Everyone should have cleaned up. */
520                 ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r,
521                         "couldn't create child process: %d: %s", rc, r->filename);
522             }
523         }
524     } 
525     return -1; 
526
527
528 static void cgid_init(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, 
529                       server_rec *main_server) 
530
531     pid_t pid; 
532     apr_proc_t *procnew;
533     void *data;
534     int first_time = 0;
535     const char *userdata_key = "cgid_init";
536     module **m;
537
538     apr_get_userdata(&data, userdata_key, main_server->process->pool);
539     if (!data) {
540         first_time = 1;
541         apr_set_userdata((const void *)1, userdata_key,
542                          apr_null_cleanup, main_server->process->pool);
543     }
544
545     if (!first_time) {
546         apr_create_pool(&pcgi, p); 
547
548         total_modules = 0;
549         for (m = ap_preloaded_modules; *m != NULL; m++)
550             total_modules++;
551
552
553         if ((pid = fork()) < 0) {
554             ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server, 
555                          "Couldn't spawn cgid daemon process"); 
556         }
557         else if (pid == 0) {
558             cgid_server(main_server);
559             exit(-1);
560         } 
561         procnew = apr_pcalloc(p, sizeof(*procnew));        
562         procnew->pid = pid;
563         procnew->err = procnew->in = procnew->out = NULL;
564         apr_note_subprocess(p, procnew, kill_after_timeout);
565 #if APR_HAS_OTHER_CHILD
566         apr_register_other_child(procnew, cgid_maint, NULL, NULL, p);
567 #endif
568     }
569
570
571 static void *create_cgid_config(apr_pool_t *p, server_rec *s) 
572
573     cgid_server_conf *c = 
574     (cgid_server_conf *) apr_pcalloc(p, sizeof(cgid_server_conf)); 
575
576     c->logname = NULL; 
577     c->logbytes = DEFAULT_LOGBYTES; 
578     c->bufbytes = DEFAULT_BUFBYTES; 
579     c->sockname = ap_server_root_relative(p, DEFAULT_SOCKET); 
580     return c; 
581
582
583 static void *merge_cgid_config(apr_pool_t *p, void *basev, void *overridesv) 
584
585     cgid_server_conf *base = (cgid_server_conf *) basev, *overrides = (cgid_server_conf *) overridesv; 
586
587     return overrides->logname ? overrides : base; 
588
589
590 static const char *set_scriptlog(cmd_parms *cmd, void *dummy, const char *arg) 
591
592     server_rec *s = cmd->server; 
593     cgid_server_conf *conf = 
594     (cgid_server_conf *) ap_get_module_config(s->module_config, &cgid_module); 
595
596     conf->logname = arg; 
597     return NULL; 
598
599
600 static const char *set_scriptlog_length(cmd_parms *cmd, void *dummy, const char *arg) 
601
602     server_rec *s = cmd->server; 
603     cgid_server_conf *conf = 
604     (cgid_server_conf *) ap_get_module_config(s->module_config, &cgid_module); 
605
606     conf->logbytes = atol(arg); 
607     return NULL; 
608
609
610 static const char *set_scriptlog_buffer(cmd_parms *cmd, void *dummy, const char *arg) 
611
612     server_rec *s = cmd->server; 
613     cgid_server_conf *conf = 
614     (cgid_server_conf *) ap_get_module_config(s->module_config, &cgid_module); 
615
616     conf->bufbytes = atoi(arg); 
617     return NULL; 
618
619
620 static const char *set_script_socket(cmd_parms *cmd, void *dummy, const char *arg) 
621
622     server_rec *s = cmd->server; 
623     cgid_server_conf *conf = 
624     (cgid_server_conf *) ap_get_module_config(s->module_config, &cgid_module); 
625
626     conf->sockname = ap_server_root_relative(cmd->pool, arg); 
627     return NULL; 
628
629
630 static const command_rec cgid_cmds[] = 
631
632     AP_INIT_TAKE1("ScriptLog", set_scriptlog, NULL, RSRC_CONF,
633                   "the name of a log for script debugging info"), 
634     AP_INIT_TAKE1("ScriptLogLength", set_scriptlog_length, NULL, RSRC_CONF,
635                   "the maximum length (in bytes) of the script debug log"), 
636     AP_INIT_TAKE1("ScriptLogBuffer", set_scriptlog_buffer, NULL, RSRC_CONF,
637                   "the maximum size (in bytes) to record of a POST request"), 
638     AP_INIT_TAKE1("Scriptsock", set_script_socket, NULL, RSRC_CONF,
639                   "the name of the socket to use for communication with "
640                   "the cgi daemon."), 
641     {NULL} 
642 }; 
643
644 static int log_scripterror(request_rec *r, cgid_server_conf * conf, int ret, 
645                            apr_status_t rv, char *error) 
646
647     apr_file_t *f = NULL; 
648     struct stat finfo; 
649     char time_str[APR_CTIME_LEN];
650     int log_flags = rv ? APLOG_ERR : APLOG_NOERRNO | APLOG_ERR;
651
652     ap_log_rerror(APLOG_MARK, log_flags, rv, r, 
653                 "%s: %s", error, r->filename); 
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         return ret; 
661     } 
662
663     /* "%% [Wed Jun 19 10:53:21 1996] GET /cgid-bin/printenv HTTP/1.0" */ 
664     apr_ctime(time_str, apr_now());
665     apr_fprintf(f, "%%%% [%s] %s %s%s%s %s\n", time_str, r->method, r->uri, 
666             r->args ? "?" : "", r->args ? r->args : "", r->protocol); 
667     /* "%% 500 /usr/local/apache/cgid-bin */ 
668     apr_fprintf(f, "%%%% %d %s\n", ret, r->filename); 
669
670     apr_fprintf(f, "%%error\n%s\n", error); 
671
672     apr_close(f); 
673     return ret; 
674
675
676 static int log_script(request_rec *r, cgid_server_conf * conf, int ret, 
677                   char *dbuf, const char *sbuf, apr_file_t *script_in, apr_file_t *script_err) 
678
679     apr_array_header_t *hdrs_arr = apr_table_elts(r->headers_in); 
680     apr_table_entry_t *hdrs = (apr_table_entry_t *) hdrs_arr->elts; 
681     char argsbuffer[HUGE_STRING_LEN]; 
682     apr_file_t *f = NULL; 
683     int i; 
684     struct stat finfo; 
685     char time_str[APR_CTIME_LEN];
686
687     if (!conf->logname || 
688         ((stat(ap_server_root_relative(r->pool, conf->logname), &finfo) == 0) 
689          && (finfo.st_size > conf->logbytes)) || 
690          (apr_open(&f, ap_server_root_relative(r->pool, conf->logname), 
691                   APR_APPEND|APR_WRITE|APR_CREATE, APR_OS_DEFAULT, r->pool) != APR_SUCCESS)) { 
692         /* Soak up script output */ 
693         while (apr_fgets(argsbuffer, HUGE_STRING_LEN, script_in) == 0) 
694             continue; 
695         if (script_err) {
696             while (apr_fgets(argsbuffer, HUGE_STRING_LEN, script_err) == 0) 
697                 continue; 
698         }
699         return ret; 
700     } 
701
702     /* "%% [Wed Jun 19 10:53:21 1996] GET /cgid-bin/printenv HTTP/1.0" */ 
703     apr_ctime(time_str, apr_now());
704     apr_fprintf(f, "%%%% [%s] %s %s%s%s %s\n", time_str, r->method, r->uri, 
705             r->args ? "?" : "", r->args ? r->args : "", r->protocol); 
706     /* "%% 500 /usr/local/apache/cgid-bin" */ 
707     apr_fprintf(f, "%%%% %d %s\n", ret, r->filename); 
708
709     apr_puts("%request\n", f); 
710     for (i = 0; i < hdrs_arr->nelts; ++i) { 
711         if (!hdrs[i].key) 
712             continue; 
713         apr_fprintf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val); 
714     } 
715     if ((r->method_number == M_POST || r->method_number == M_PUT) 
716         && *dbuf) { 
717         apr_fprintf(f, "\n%s\n", dbuf); 
718     } 
719
720     apr_puts("%response\n", f); 
721     hdrs_arr = apr_table_elts(r->err_headers_out); 
722     hdrs = (apr_table_entry_t *) hdrs_arr->elts; 
723
724     for (i = 0; i < hdrs_arr->nelts; ++i) { 
725         if (!hdrs[i].key) 
726             continue; 
727         apr_fprintf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val); 
728     } 
729
730     if (sbuf && *sbuf) 
731         apr_fprintf(f, "%s\n", sbuf); 
732
733     if (apr_fgets(argsbuffer, HUGE_STRING_LEN, script_in) == 0) { 
734         apr_puts("%stdout\n", f); 
735         apr_puts(argsbuffer, f); 
736         while (apr_fgets(argsbuffer, HUGE_STRING_LEN, script_in) == 0) 
737             apr_puts(argsbuffer, f); 
738         apr_puts("\n", f); 
739     } 
740
741     if (script_err) {
742         if (apr_fgets(argsbuffer, HUGE_STRING_LEN, script_err) == 0) { 
743             apr_puts("%stderr\n", f); 
744             apr_puts(argsbuffer, f); 
745             while (apr_fgets(argsbuffer, HUGE_STRING_LEN, script_err) == 0) 
746                 apr_puts(argsbuffer, f); 
747             apr_puts("\n", f); 
748         } 
749     }
750
751     apr_close(script_in); 
752     if (script_err) {
753         apr_close(script_err); 
754     }
755
756     apr_close(f); 
757     return ret; 
758
759
760
761
762 /**************************************************************** 
763  * 
764  * Actual cgid handling... 
765  */ 
766 static int cgid_handler(request_rec *r) 
767
768     int retval, nph, dbpos = 0; 
769     char *argv0, *dbuf = NULL; 
770     apr_bucket_brigade *bb;
771     apr_bucket *b;
772     char argsbuffer[HUGE_STRING_LEN]; 
773     void *sconf;
774     cgid_server_conf *conf;
775     int is_included;
776     int sd;
777     char **env; 
778     struct sockaddr_un unix_addr;
779     apr_file_t *tempsock;
780     apr_size_t nbytes;
781
782     if(strcmp(r->handler,CGI_MAGIC_TYPE) && strcmp(r->handler,"cgi-script"))
783         return DECLINED;
784
785     if (r->method_number == M_OPTIONS) { 
786         /* 99 out of 100 cgid scripts, this is all they support */ 
787         r->allowed |= (1 << M_GET); 
788         r->allowed |= (1 << M_POST); 
789         return DECLINED; 
790     } 
791
792     sconf = r->server->module_config; 
793     conf = (cgid_server_conf *) ap_get_module_config(sconf, &cgid_module); 
794     is_included = !strcmp(r->protocol, "INCLUDED"); 
795
796     if ((argv0 = strrchr(r->filename, '/')) != NULL)
797         argv0++;
798     else
799         argv0 = r->filename;
800  
801     nph = !(strncmp(argv0, "nph-", 4)); 
802
803     if ((argv0 = strrchr(r->filename, '/')) != NULL) 
804         argv0++; 
805     else 
806         argv0 = r->filename; 
807
808     if (!(ap_allow_options(r) & OPT_EXECCGI) && !is_scriptaliased(r)) 
809         return log_scripterror(r, conf, HTTP_FORBIDDEN, 0, 
810                                "Options ExecCGI is off in this directory"); 
811     if (nph && is_included) 
812         return log_scripterror(r, conf, HTTP_FORBIDDEN, 0, 
813                                "attempt to include NPH CGI script"); 
814
815 #if defined(OS2) || defined(WIN32)
816 #error mod_cgid does not work on this platform.  If you teach it to, look 
817 #error at mod_cgi.c for required code in this path.
818 #else 
819     if (r->finfo.filetype == 0) 
820         return log_scripterror(r, conf, HTTP_NOT_FOUND, 0, 
821                                "script not found or unable to stat"); 
822 #endif 
823     if (r->finfo.filetype == APR_DIR) 
824         return log_scripterror(r, conf, HTTP_FORBIDDEN, 0, 
825                                "attempt to invoke directory as script"); 
826 /*
827     if (!ap_suexec_enabled) { 
828         if (!ap_can_exec(&r->finfo)) 
829             return log_scripterror(r, conf, HTTP_FORBIDDEN, 0, 
830                                    "file permissions deny server execution"); 
831     } 
832 */
833     ap_add_common_vars(r); 
834     ap_add_cgi_vars(r); 
835     env = ap_create_environment(r->pool, r->subprocess_env); 
836
837     if ((sd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
838             return log_scripterror(r, conf, HTTP_INTERNAL_SERVER_ERROR, errno, 
839                                    "unable to create socket to cgi daemon");
840     } 
841     memset(&unix_addr, 0, sizeof(unix_addr));
842     unix_addr.sun_family = AF_UNIX;
843     strcpy(unix_addr.sun_path, conf->sockname);
844
845     if (connect(sd, (struct sockaddr *)&unix_addr, sizeof(unix_addr)) < 0) {
846             return log_scripterror(r, conf, HTTP_INTERNAL_SERVER_ERROR, errno, 
847                                    "unable to connect to cgi daemon");
848     } 
849
850     send_req(sd, r, argv0, env); 
851
852     /* We are putting the tempsock variable into a file so that we can use
853      * a pipe bucket to send the data to the client.
854      */
855     apr_put_os_file(&tempsock, &sd, r->pool);
856
857     if ((retval = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR))) 
858         return retval; 
859      
860     if ((argv0 = strrchr(r->filename, '/')) != NULL) 
861         argv0++; 
862     else 
863         argv0 = r->filename; 
864
865     /* Transfer any put/post args, CERN style... 
866      * Note that we already ignore SIGPIPE in the core server. 
867      */ 
868
869     if (ap_should_client_block(r)) { 
870         int dbsize, len_read; 
871
872         if (conf->logname) { 
873             dbuf = apr_pcalloc(r->pool, conf->bufbytes + 1); 
874             dbpos = 0; 
875         } 
876
877         while ((len_read = 
878                 ap_get_client_block(r, argsbuffer, HUGE_STRING_LEN)) > 0) { 
879             if (conf->logname) { 
880                 if ((dbpos + len_read) > conf->bufbytes) { 
881                     dbsize = conf->bufbytes - dbpos; 
882                 } 
883                 else { 
884                     dbsize = len_read; 
885                 } 
886                 memcpy(dbuf + dbpos, argsbuffer, dbsize); 
887                 dbpos += dbsize; 
888             } 
889             nbytes = len_read;
890             apr_write(tempsock, argsbuffer, &nbytes);
891             if (nbytes < len_read) { 
892                 /* silly script stopped reading, soak up remaining message */ 
893                 while (ap_get_client_block(r, argsbuffer, HUGE_STRING_LEN) > 0) { 
894                     /* dump it */ 
895                 } 
896                 break; 
897             } 
898         } 
899         shutdown(sd, 1); /* done writing; force EOF on child's stdin */
900     } 
901
902     /* Handle script return... */ 
903     if (!nph) { 
904         const char *location; 
905         char sbuf[MAX_STRING_LEN]; 
906         int ret; 
907
908         if ((ret = ap_scan_script_header_err(r, tempsock, sbuf))) { 
909             return log_script(r, conf, ret, dbuf, sbuf, tempsock, NULL); 
910         } 
911
912         location = apr_table_get(r->headers_out, "Location"); 
913
914         if (location && location[0] == '/' && r->status == 200) { 
915
916             /* Soak up all the script output */ 
917             while (apr_fgets(argsbuffer, HUGE_STRING_LEN, tempsock) > 0) { 
918                 continue; 
919             } 
920             /* This redirect needs to be a GET no matter what the original 
921              * method was. 
922              */ 
923             r->method = apr_pstrdup(r->pool, "GET"); 
924             r->method_number = M_GET; 
925
926             /* We already read the message body (if any), so don't allow 
927              * the redirected request to think it has one. We can ignore 
928              * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR. 
929              */ 
930             apr_table_unset(r->headers_in, "Content-Length"); 
931
932             ap_internal_redirect_handler(location, r); 
933             return OK; 
934         } 
935         else if (location && r->status == 200) { 
936             /* XX Note that if a script wants to produce its own Redirect 
937              * body, it now has to explicitly *say* "Status: 302" 
938              */ 
939             return HTTP_MOVED_TEMPORARILY; 
940         } 
941
942         ap_send_http_header(r); 
943         if (!r->header_only) { 
944             bb = apr_brigade_create(r->pool);
945             b = apr_bucket_create_pipe(tempsock);
946             APR_BRIGADE_INSERT_TAIL(bb, b);
947             b = apr_bucket_create_eos();
948             APR_BRIGADE_INSERT_TAIL(bb, b);
949             ap_pass_brigade(r->output_filters, bb);
950         } 
951     } 
952
953     if (nph) {
954         bb = apr_brigade_create(r->pool);
955         b = apr_bucket_create_pipe(tempsock);
956         APR_BRIGADE_INSERT_TAIL(bb, b);
957         b = apr_bucket_create_eos();
958         APR_BRIGADE_INSERT_TAIL(bb, b);
959         ap_pass_brigade(r->output_filters, bb);
960     } 
961
962     apr_close(tempsock);
963
964     return OK; /* NOT r->status, even if it has changed. */ 
965
966
967 static void register_hook(apr_pool_t *p)
968 {
969     ap_hook_post_config(cgid_init, NULL, NULL, APR_HOOK_MIDDLE);
970     ap_hook_handler(cgid_handler, NULL, NULL, APR_HOOK_MIDDLE);
971 }
972
973 module AP_MODULE_DECLARE_DATA cgid_module = { 
974     STANDARD20_MODULE_STUFF, 
975     NULL, /* dir config creater */ 
976     NULL, /* dir merger --- default is to override */ 
977     create_cgid_config, /* server config */ 
978     merge_cgid_config, /* merge server config */ 
979     cgid_cmds, /* command table */ 
980     register_hook /* register_handlers */ 
981 }; 
982