1 /* ====================================================================
2 * The Apache Software License, Version 1.1
4 * Copyright (c) 2000 The Apache Software Foundation. All rights
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
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
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.
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.
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.
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
47 * ====================================================================
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/>.
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.
60 * http_script: keeps all script-related ramblings together.
62 * Compliant to cgi/1.1 spec
64 * Adapted by rst from original NCSA code by Rob McCool
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
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"
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"
90 #include "util_script.h"
91 #include "http_conf_globals.h"
95 #ifdef HAVE_SYS_SOCKET_H
96 #include <sys/socket.h>
101 #ifdef HAVE_STRINGS_H
104 #include <sys/un.h> /* for sockaddr_un */
105 #include <sys/types.h>
107 module AP_MODULE_DECLARE_DATA cgid_module;
109 static void cgid_init(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *main_server);
110 static int once_through = 0;
112 static apr_pool_t *pcgi;
114 /* KLUDGE --- for back-combatibility, we don't have to check Execcgid
115 * in ScriptAliased directories, which means we need to know if this
116 * request came through ScriptAlias or not... so the Alias module
117 * leaves a note for us.
120 static int is_scriptaliased(request_rec *r)
122 const char *t = apr_table_get(r->notes, "alias-forced-type");
123 return t && (!strcasecmp(t, "cgi-script"));
126 /* Configuration stuff */
128 #define DEFAULT_LOGBYTES 10385760
129 #define DEFAULT_BUFBYTES 1024
130 #define DEFAULT_SOCKET "logs/cgisock"
132 #define SHELL_PATH "/bin/sh"
134 /* DEFAULT_CGID_LISTENBACKLOG controls the max depth on the unix socket's
135 * pending connection queue. If a bunch of cgi requests arrive at about
136 * the same time, connections from httpd threads/processes will back up
137 * in the queue while the cgid process slowly forks off a child to process
138 * each connection on the unix socket. If the queue is too short, the
139 * httpd process will get ECONNREFUSED when trying to connect.
141 #ifndef DEFAULT_CGID_LISTENBACKLOG
142 #define DEFAULT_CGID_LISTENBACKLOG 100
146 const char *sockname;
152 /* If a request includes query info in the URL (stuff after "?"), and
153 * the query info does not contain "=" (indicative of a FORM submission),
154 * then this routine is called to create the argument list to be passed
155 * to the CGI script. When suexec is enabled, the suexec path, user, and
156 * group are the first three arguments to be passed; if not, all three
157 * must be NULL. The query info is split into separate arguments, where
158 * "+" is the separator between keyword arguments.
160 * XXXX: note that the WIN32 code uses one of the suexec strings
161 * to pass an interpreter name. Remember this if changing the way they
162 * are handled in create_argv.
165 static char **create_argv(apr_pool_t *p, char *path, char *user, char *group,
166 char *av0, const char *args)
173 /* count the number of keywords */
175 for (x = 0, numwords = 1; args[x]; x++) {
176 if (args[x] == '+') {
181 if (numwords > APACHE_ARG_MAX - 5) {
182 numwords = APACHE_ARG_MAX - 5; /* Truncate args to prevent overrun */
184 av = (char **) apr_palloc(p, (numwords + 5) * sizeof(char *));
198 for (x = 1; x <= numwords; x++) {
199 w = ap_getword_nulls(p, &args, '+');
201 av[idx++] = ap_escape_shell_cmd(p, w);
207 static int call_exec(request_rec *r, char *argv0, char **env, int shellcmd)
210 int errfileno = STDERR_FILENO;
211 /* the fd on r->server->error_log is closed, but we need somewhere to
212 * put the error messages from the log_* functions. So, we use stderr,
213 * since that is better than allowing errors to go unnoticed.
215 apr_put_os_file(&r->server->error_log, &errfileno, r->pool);
217 execle(SHELL_PATH, SHELL_PATH, "-c", argv0, NULL, env);
220 else if ((!r->args) || (!r->args[0]) || strchr(r->args, '=')) {
221 execle(r->filename, argv0, NULL, env);
226 create_argv(r->pool, NULL, NULL, NULL, argv0, r->args),
232 static void cgid_maint(int reason, void *data, apr_wait_t status)
234 #if APR_HAS_OTHER_CHILD
237 case APR_OC_REASON_DEATH:
238 case APR_OC_REASON_LOST:
239 /* stop gap to make sure everything else works. In the end,
240 * we'll just restart the cgid server. */
241 apr_destroy_pool(pcgi);
242 kill(getppid(), SIGWINCH);
244 case APR_OC_REASON_RESTART:
245 case APR_OC_REASON_UNREGISTER:
246 apr_destroy_pool(pcgi);
253 static void get_req(int fd, request_rec *r, char **filename, char **argv0, char ***env)
258 core_dir_config *temp_core;
261 r->server = apr_pcalloc(r->pool, sizeof(server_rec));
263 read(fd, &j, sizeof(int));
264 read(fd, &len, sizeof(int));
265 data = apr_pcalloc(r->pool, len + 1); /* get a cleared byte for final '\0' */
266 i = read(fd, data, len);
268 r->filename = ap_getword(r->pool, (const char **)&data, '\n');
269 *argv0 = ap_getword(r->pool, (const char **)&data, '\n');
271 r->uri = ap_getword(r->pool, (const char **)&data, '\n');
273 environ = apr_pcalloc(r->pool, (j + 2) *sizeof(char *));
275 for (i = 0; i < j; i++) {
276 environ[i] = ap_getword(r->pool, (const char **)&data, '\n');
279 r->args = ap_getword(r->pool, (const char **)&data, '\n');
281 read(fd, &i, sizeof(int));
283 /* add 1, so that if i == 0, we still malloc something. */
284 dconf = (void **)malloc(sizeof(void *) * i + 1);
286 temp_core = (core_dir_config *)malloc(sizeof(core_module));
289 read(fd, &j, sizeof(int));
291 temp_core->limit_cpu = (struct rlimit *)malloc (sizeof(struct rlimit));
292 read(fd, temp_core->limit_cpu, sizeof(struct rlimit));
295 temp_core->limit_cpu = NULL;
299 #if defined (RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
300 read(fd, &j, sizeof(int));
302 temp_core->limit_mem = (struct rlimit *)malloc (sizeof(struct rlimit));
303 read(fd, temp_core->limit_mem, sizeof(struct rlimit));
306 temp_core->limit_mem = NULL;
311 read(fd, &j, sizeof(int));
313 temp_core->limit_nproc = (struct rlimit *)malloc (sizeof(struct rlimit));
314 read(fd, temp_core->limit_nproc, sizeof(struct rlimit));
317 temp_core->limit_nproc = NULL;
321 dconf[i] = (void *)temp_core;
322 r->per_dir_config = dconf;
327 static void send_req(int fd, request_rec *r, char *argv0, char **env)
333 data = apr_pstrcat(r->pool, r->filename, "\n", argv0, "\n", r->uri, "\n",
336 for (i =0; env[i]; i++) {
340 if (write(fd, &i, sizeof(int)) < 0) {
341 ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r,
342 "write to cgi daemon process");
345 for (i = 0; env[i]; i++) {
346 data = apr_pstrcat(r->pool, data, env[i], "\n", NULL);
348 data = apr_pstrcat(r->pool, data, r->args, NULL);
350 if (write(fd, &len, sizeof(int)) < 0) {
351 ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r,
352 "write to cgi daemon process");
354 if (write(fd, data, len) < 0) {
355 ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r,
356 "write to cgi daemon process");
358 if (write(fd, &core_module.module_index, sizeof(int)) < 0) {
359 ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r,
360 "write to cgi daemon process");
364 if (conf->limit_cpu) {
366 write(fd, &len, sizeof(int));
367 write(fd, conf->limit_cpu, sizeof(struct rlimit));
371 write(fd, &len, sizeof(int));
375 #if defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
376 if (conf->limit_mem) {
378 write(fd, &len, sizeof(int));
379 write(fd, conf->limit_mem, sizeof(struct rlimit));
383 write(fd, &len, sizeof(int));
388 if (conf->limit_nproc) {
390 write(fd, &len, sizeof(int));
391 write(fd, conf->limit_nproc, sizeof(struct rlimit));
395 write(fd, &len, sizeof(int));
401 static int cgid_server_child(int sd)
409 apr_create_pool(&p, pcgi);
410 r = apr_pcalloc(p, sizeof(request_rec));
412 dup2(sd, STDIN_FILENO);
413 dup2(sd, STDOUT_FILENO);
414 get_req(sd, r, &filename, &argv0, &env);
415 call_exec(r, argv0, env, 0);
416 exit(-1); /* We should NEVER get here */
419 static int cgid_server(void *data)
421 struct sockaddr_un unix_addr;
427 server_rec *main_server = data;
428 cgid_server_conf *sconf = (cgid_server_conf *)ap_get_module_config(
429 main_server->module_config, &cgid_module);
431 apr_signal(SIGCHLD, SIG_IGN);
432 if (unlink(sconf->sockname) < 0 && errno == ENOENT) {
433 ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
434 "Couldn't unlink unix domain socket %s",
436 /* just a warning; don't bail out */
439 if ((sd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
440 ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
441 "Couldn't create unix domain socket");
445 memset(&unix_addr, 0, sizeof(unix_addr));
446 unix_addr.sun_family = AF_UNIX;
447 strcpy(unix_addr.sun_path, sconf->sockname);
449 omask = umask(0077); /* so that only Apache can use socket */
450 rc = bind(sd, (struct sockaddr *)&unix_addr, sizeof(unix_addr));
451 umask(omask); /* can't fail, so can't clobber errno */
453 ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
454 "Couldn't bind unix domain socket %s",
459 if (listen(sd, DEFAULT_CGID_LISTENBACKLOG) < 0) {
460 ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
461 "Couldn't listen on unix domain socket");
466 if (chown(sconf->sockname, unixd_config.user_id, -1) < 0) {
467 ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
468 "Couldn't change owner of unix domain socket %s",
474 unixd_setup_child(); /* if running as root, switch to configured user/group */
477 len = sizeof(unix_addr);
478 sd2 = accept(sd, (struct sockaddr *)&unix_addr, &len);
480 if (errno != EINTR) {
481 ap_log_error(APLOG_MARK, APLOG_ERR, errno,
483 "Error accepting on cgid socket.");
488 if ((pid = fork()) > 0) {
492 /* setup the STDERR here, because I have all the info
493 * for it. I'll do the STDIN and STDOUT later, but I can't
494 * do STDERR as easily.
496 if (sconf->logname) {
497 dup2(open(sconf->logname, O_WRONLY), STDERR_FILENO);
500 apr_get_os_file(&errfile, main_server->error_log);
501 dup2(errfile, STDERR_FILENO);
503 cgid_server_child(sd2);
506 ap_log_error(APLOG_MARK, APLOG_ERR, errno, (server_rec *)data,
507 "Couldn't fork cgi script");
513 static void cgid_init(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *main_server)
518 if (once_through > 0) {
519 apr_create_pool(&pcgi, p);
521 if ((pid = fork()) < 0) {
522 ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
523 "Couldn't spawn cgid daemon process");
526 cgid_server(main_server);
529 procnew = apr_pcalloc(p, sizeof(*procnew));
531 procnew->err = procnew->in = procnew->out = NULL;
532 apr_note_subprocess(p, procnew, kill_after_timeout);
533 #if APR_HAS_OTHER_CHILD
534 apr_register_other_child(procnew, cgid_maint, NULL, NULL, p);
540 static void *create_cgid_config(apr_pool_t *p, server_rec *s)
542 cgid_server_conf *c =
543 (cgid_server_conf *) apr_pcalloc(p, sizeof(cgid_server_conf));
546 c->logbytes = DEFAULT_LOGBYTES;
547 c->bufbytes = DEFAULT_BUFBYTES;
548 c->sockname = ap_server_root_relative(p, DEFAULT_SOCKET);
552 static void *merge_cgid_config(apr_pool_t *p, void *basev, void *overridesv)
554 cgid_server_conf *base = (cgid_server_conf *) basev, *overrides = (cgid_server_conf *) overridesv;
556 return overrides->logname ? overrides : base;
559 static const char *set_scriptlog(cmd_parms *cmd, void *dummy, const char *arg)
561 server_rec *s = cmd->server;
562 cgid_server_conf *conf =
563 (cgid_server_conf *) ap_get_module_config(s->module_config, &cgid_module);
569 static const char *set_scriptlog_length(cmd_parms *cmd, void *dummy, const char *arg)
571 server_rec *s = cmd->server;
572 cgid_server_conf *conf =
573 (cgid_server_conf *) ap_get_module_config(s->module_config, &cgid_module);
575 conf->logbytes = atol(arg);
579 static const char *set_scriptlog_buffer(cmd_parms *cmd, void *dummy, const char *arg)
581 server_rec *s = cmd->server;
582 cgid_server_conf *conf =
583 (cgid_server_conf *) ap_get_module_config(s->module_config, &cgid_module);
585 conf->bufbytes = atoi(arg);
589 static const char *set_script_socket(cmd_parms *cmd, void *dummy, const char *arg)
591 server_rec *s = cmd->server;
592 cgid_server_conf *conf =
593 (cgid_server_conf *) ap_get_module_config(s->module_config, &cgid_module);
595 conf->sockname = ap_server_root_relative(cmd->pool, arg);
599 static const command_rec cgid_cmds[] =
601 AP_INIT_TAKE1("ScriptLog", set_scriptlog, NULL, RSRC_CONF,
602 "the name of a log for script debugging info"),
603 AP_INIT_TAKE1("ScriptLogLength", set_scriptlog_length, NULL, RSRC_CONF,
604 "the maximum length (in bytes) of the script debug log"),
605 AP_INIT_TAKE1("ScriptLogBuffer", set_scriptlog_buffer, NULL, RSRC_CONF,
606 "the maximum size (in bytes) to record of a POST request"),
607 AP_INIT_TAKE1("Scriptsock", set_script_socket, NULL, RSRC_CONF,
608 "the name of the socket to use for communication with "
613 static int log_scripterror(request_rec *r, cgid_server_conf * conf, int ret,
614 int show_errno, char *error)
616 apr_file_t *f = NULL;
618 char time_str[APR_CTIME_LEN];
620 ap_log_rerror(APLOG_MARK, show_errno|APLOG_ERR, errno, r,
621 "%s: %s", error, r->filename);
623 if (!conf->logname ||
624 ((stat(ap_server_root_relative(r->pool, conf->logname), &finfo) == 0)
625 && (finfo.st_size > conf->logbytes)) ||
626 (apr_open(&f, ap_server_root_relative(r->pool, conf->logname),
627 APR_APPEND|APR_WRITE|APR_CREATE, APR_OS_DEFAULT, r->pool) != APR_SUCCESS)) {
631 /* "%% [Wed Jun 19 10:53:21 1996] GET /cgid-bin/printenv HTTP/1.0" */
632 apr_ctime(time_str, apr_now());
633 apr_fprintf(f, "%%%% [%s] %s %s%s%s %s\n", time_str, r->method, r->uri,
634 r->args ? "?" : "", r->args ? r->args : "", r->protocol);
635 /* "%% 500 /usr/local/apache/cgid-bin */
636 apr_fprintf(f, "%%%% %d %s\n", ret, r->filename);
638 apr_fprintf(f, "%%error\n%s\n", error);
644 static int log_script(request_rec *r, cgid_server_conf * conf, int ret,
645 char *dbuf, const char *sbuf, apr_file_t *script_in, apr_file_t *script_err)
647 apr_array_header_t *hdrs_arr = apr_table_elts(r->headers_in);
648 apr_table_entry_t *hdrs = (apr_table_entry_t *) hdrs_arr->elts;
649 char argsbuffer[HUGE_STRING_LEN];
650 apr_file_t *f = NULL;
653 char time_str[APR_CTIME_LEN];
655 if (!conf->logname ||
656 ((stat(ap_server_root_relative(r->pool, conf->logname), &finfo) == 0)
657 && (finfo.st_size > conf->logbytes)) ||
658 (apr_open(&f, ap_server_root_relative(r->pool, conf->logname),
659 APR_APPEND|APR_WRITE|APR_CREATE, APR_OS_DEFAULT, r->pool) != APR_SUCCESS)) {
660 /* Soak up script output */
661 while (apr_fgets(argsbuffer, HUGE_STRING_LEN, script_in) == 0)
664 while (apr_fgets(argsbuffer, HUGE_STRING_LEN, script_err) == 0)
670 /* "%% [Wed Jun 19 10:53:21 1996] GET /cgid-bin/printenv HTTP/1.0" */
671 apr_ctime(time_str, apr_now());
672 apr_fprintf(f, "%%%% [%s] %s %s%s%s %s\n", time_str, r->method, r->uri,
673 r->args ? "?" : "", r->args ? r->args : "", r->protocol);
674 /* "%% 500 /usr/local/apache/cgid-bin" */
675 apr_fprintf(f, "%%%% %d %s\n", ret, r->filename);
677 apr_puts("%request\n", f);
678 for (i = 0; i < hdrs_arr->nelts; ++i) {
681 apr_fprintf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val);
683 if ((r->method_number == M_POST || r->method_number == M_PUT)
685 apr_fprintf(f, "\n%s\n", dbuf);
688 apr_puts("%response\n", f);
689 hdrs_arr = apr_table_elts(r->err_headers_out);
690 hdrs = (apr_table_entry_t *) hdrs_arr->elts;
692 for (i = 0; i < hdrs_arr->nelts; ++i) {
695 apr_fprintf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val);
699 apr_fprintf(f, "%s\n", sbuf);
701 if (apr_fgets(argsbuffer, HUGE_STRING_LEN, script_in) == 0) {
702 apr_puts("%stdout\n", f);
703 apr_puts(argsbuffer, f);
704 while (apr_fgets(argsbuffer, HUGE_STRING_LEN, script_in) == 0)
705 apr_puts(argsbuffer, f);
710 if (apr_fgets(argsbuffer, HUGE_STRING_LEN, script_err) == 0) {
711 apr_puts("%stderr\n", f);
712 apr_puts(argsbuffer, f);
713 while (apr_fgets(argsbuffer, HUGE_STRING_LEN, script_err) == 0)
714 apr_puts(argsbuffer, f);
719 apr_close(script_in);
721 apr_close(script_err);
730 /****************************************************************
732 * Actual cgid handling...
734 static int cgid_handler(request_rec *r)
736 int retval, nph, dbpos = 0;
737 char *argv0, *dbuf = NULL;
738 ap_bucket_brigade *bb;
740 char argsbuffer[HUGE_STRING_LEN];
741 void *sconf = r->server->module_config;
742 cgid_server_conf *conf = (cgid_server_conf *) ap_get_module_config(sconf, &cgid_module);
743 int is_included = !strcmp(r->protocol, "INCLUDED");
746 struct sockaddr_un unix_addr;
747 apr_file_t *tempsock = NULL;
750 if (r->method_number == M_OPTIONS) {
751 /* 99 out of 100 cgid scripts, this is all they support */
752 r->allowed |= (1 << M_GET);
753 r->allowed |= (1 << M_POST);
757 if ((argv0 = strrchr(r->filename, '/')) != NULL)
762 nph = !(strncmp(argv0, "nph-", 4));
764 if ((argv0 = strrchr(r->filename, '/')) != NULL)
769 if (!(ap_allow_options(r) & OPT_EXECCGI) && !is_scriptaliased(r))
770 return log_scripterror(r, conf, HTTP_FORBIDDEN, APLOG_NOERRNO,
771 "Options ExecCGI is off in this directory");
772 if (nph && is_included)
773 return log_scripterror(r, conf, HTTP_FORBIDDEN, APLOG_NOERRNO,
774 "attempt to include NPH CGI script");
776 #if defined(OS2) || defined(WIN32)
777 /* Allow for cgid files without the .EXE extension on them under OS/2 */
778 if (r->finfo.st_mode == 0) {
782 newfile = apr_pstrcat(r->pool, r->filename, ".EXE", NULL);
784 if ((stat(newfile, &statbuf) != 0) || (!S_ISREG(statbuf.st_mode))) {
785 return log_scripterror(r, conf, HTTP_NOT_FOUND, 0,
786 "script not found or unable to stat");
788 r->filename = newfile;
792 if (r->finfo.protection == 0)
793 return log_scripterror(r, conf, HTTP_NOT_FOUND, APLOG_NOERRNO,
794 "script not found or unable to stat");
796 if (r->finfo.filetype == APR_DIR)
797 return log_scripterror(r, conf, HTTP_FORBIDDEN, APLOG_NOERRNO,
798 "attempt to invoke directory as script");
800 if (!ap_suexec_enabled) {
801 if (!ap_can_exec(&r->finfo))
802 return log_scripterror(r, conf, HTTP_FORBIDDEN, APLOG_NOERRNO,
803 "file permissions deny server execution");
806 ap_add_common_vars(r);
808 env = ap_create_environment(r->pool, r->subprocess_env);
810 if ((sd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
811 return log_scripterror(r, conf, HTTP_NOT_FOUND, 0,
812 "unable to create socket to cgi daemon");
814 memset(&unix_addr, 0, sizeof(unix_addr));
815 unix_addr.sun_family = AF_UNIX;
816 strcpy(unix_addr.sun_path, conf->sockname);
818 if (connect(sd, (struct sockaddr *)&unix_addr, sizeof(unix_addr)) < 0) {
819 return log_scripterror(r, conf, HTTP_NOT_FOUND, 0,
820 "unable to connect to cgi daemon");
823 send_req(sd, r, argv0, env);
825 /* We are putting the tempsock variable into a file so that we can use
826 * a pipe bucket to send the data to the client.
828 apr_put_os_file(&tempsock, &sd, r->pool);
830 if ((retval = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR)))
833 if ((argv0 = strrchr(r->filename, '/')) != NULL)
838 /* Transfer any put/post args, CERN style...
839 * Note that we already ignore SIGPIPE in the core server.
842 if (ap_should_client_block(r)) {
843 int dbsize, len_read;
846 dbuf = apr_pcalloc(r->pool, conf->bufbytes + 1);
851 ap_get_client_block(r, argsbuffer, HUGE_STRING_LEN)) > 0) {
853 if ((dbpos + len_read) > conf->bufbytes) {
854 dbsize = conf->bufbytes - dbpos;
859 memcpy(dbuf + dbpos, argsbuffer, dbsize);
863 apr_write(tempsock, argsbuffer, &nbytes);
864 if (nbytes < len_read) {
865 /* silly script stopped reading, soak up remaining message */
866 while (ap_get_client_block(r, argsbuffer, HUGE_STRING_LEN) > 0) {
872 shutdown(sd, 1); /* done writing; force EOF on child's stdin */
875 /* Handle script return... */
877 const char *location;
878 char sbuf[MAX_STRING_LEN];
881 if ((ret = ap_scan_script_header_err(r, tempsock, sbuf))) {
882 return log_script(r, conf, ret, dbuf, sbuf, tempsock, NULL);
885 location = apr_table_get(r->headers_out, "Location");
887 if (location && location[0] == '/' && r->status == 200) {
889 /* Soak up all the script output */
890 while (apr_fgets(argsbuffer, HUGE_STRING_LEN, tempsock) > 0) {
893 /* This redirect needs to be a GET no matter what the original
896 r->method = apr_pstrdup(r->pool, "GET");
897 r->method_number = M_GET;
899 /* We already read the message body (if any), so don't allow
900 * the redirected request to think it has one. We can ignore
901 * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR.
903 apr_table_unset(r->headers_in, "Content-Length");
905 ap_internal_redirect_handler(location, r);
908 else if (location && r->status == 200) {
909 /* XX Note that if a script wants to produce its own Redirect
910 * body, it now has to explicitly *say* "Status: 302"
912 return HTTP_MOVED_TEMPORARILY;
915 ap_send_http_header(r);
916 if (!r->header_only) {
917 bb = ap_brigade_create(r->pool);
918 b = ap_bucket_create_pipe(tempsock);
919 AP_BRIGADE_INSERT_TAIL(bb, b);
920 b = ap_bucket_create_eos();
921 AP_BRIGADE_INSERT_TAIL(bb, b);
922 ap_pass_brigade(r->output_filters, bb);
927 bb = ap_brigade_create(r->pool);
928 b = ap_bucket_create_pipe(tempsock);
929 AP_BRIGADE_INSERT_TAIL(bb, b);
930 b = ap_bucket_create_eos();
931 AP_BRIGADE_INSERT_TAIL(bb, b);
932 ap_pass_brigade(r->output_filters, bb);
937 return OK; /* NOT r->status, even if it has changed. */
940 static const handler_rec cgid_handlers[] =
942 {CGI_MAGIC_TYPE, cgid_handler},
943 {"cgi-script", cgid_handler},
947 static void register_hook(void)
949 ap_hook_post_config(cgid_init, NULL, NULL, AP_HOOK_MIDDLE);
952 module AP_MODULE_DECLARE_DATA cgid_module = {
953 STANDARD20_MODULE_STUFF,
954 NULL, /* dir config creater */
955 NULL, /* dir merger --- default is to override */
956 create_cgid_config, /* server config */
957 merge_cgid_config, /* merge server config */
958 cgid_cmds, /* command table */
959 cgid_handlers, /* handlers */
960 register_hook /* register_handlers */