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"
96 #ifdef HAVE_SYS_SOCKET_H
97 #include <sys/socket.h>
102 #ifdef HAVE_STRINGS_H
105 #include <sys/un.h> /* for sockaddr_un */
106 #include <sys/types.h>
108 module MODULE_VAR_EXPORT cgid_module;
110 static void cgid_init(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *main_server);
111 static int once_through = 0;
113 static apr_pool_t *pcgi;
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.
121 static int is_scriptaliased(request_rec *r)
123 const char *t = apr_table_get(r->notes, "alias-forced-type");
124 return t && (!strcasecmp(t, "cgi-script"));
127 /* Configuration stuff */
129 #define DEFAULT_LOGBYTES 10385760
130 #define DEFAULT_BUFBYTES 1024
131 #define DEFAULT_SOCKET "logs/cgisock"
133 #define SHELL_PATH "/bin/sh"
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.
142 #ifndef DEFAULT_CGID_LISTENBACKLOG
143 #define DEFAULT_CGID_LISTENBACKLOG 100
147 const char *sockname;
156 /* If a request includes query info in the URL (stuff after "?"), and
157 * the query info does not contain "=" (indicative of a FORM submission),
158 * then this routine is called to create the argument list to be passed
159 * to the CGI script. When suexec is enabled, the suexec path, user, and
160 * group are the first three arguments to be passed; if not, all three
161 * must be NULL. The query info is split into separate arguments, where
162 * "+" is the separator between keyword arguments.
164 * XXXX: note that the WIN32 code uses one of the suexec strings
165 * to pass an interpreter name. Remember this if changing the way they
166 * are handled in create_argv.
169 static char **create_argv(apr_pool_t *p, char *path, char *user, char *group,
170 char *av0, const char *args)
177 /* count the number of keywords */
179 for (x = 0, numwords = 1; args[x]; x++) {
180 if (args[x] == '+') {
185 if (numwords > APACHE_ARG_MAX - 5) {
186 numwords = APACHE_ARG_MAX - 5; /* Truncate args to prevent overrun */
188 av = (char **) apr_palloc(p, (numwords + 5) * sizeof(char *));
202 for (x = 1; x <= numwords; x++) {
203 w = ap_getword_nulls(p, &args, '+');
205 av[idx++] = ap_escape_shell_cmd(p, w);
211 static int call_exec(request_rec *r, char *argv0, char **env, int shellcmd)
214 int errfileno = STDERR_FILENO;
215 /* the fd on r->server->error_log is closed, but we need somewhere to
216 * put the error messages from the log_* functions. So, we use stderr,
217 * since that is better than allowing errors to go unnoticed.
219 apr_put_os_file(&r->server->error_log, &errfileno, r->pool);
220 /* TODO: reimplement suexec */
222 if (ap_suexec_enabled
223 && ((r->server->server_uid != ap_user_id)
224 || (r->server->server_gid != ap_group_id)
225 || (!strncmp("/~", r->uri, 2)))) {
227 char *execuser, *grpname;
231 if (!strncmp("/~", r->uri, 2)) {
233 char *username = apr_pstrdup(r->pool, r->uri + 2);
234 char *pos = strchr(username, '/');
240 if ((pw = getpwnam(username)) == NULL) {
241 ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
242 "getpwnam: invalid username %s", username);
245 execuser = apr_pstrcat(r->pool, "~", pw->pw_name, NULL);
246 user_gid = pw->pw_gid;
248 if ((gr = getgrgid(user_gid)) == NULL) {
249 if ((grpname = apr_palloc(r->pool, 16)) == NULL) {
253 apr_snprintf(grpname, 16, "%ld", (long) user_gid);
257 grpname = gr->gr_name;
261 if ((pw = getpwuid(r->server->server_uid)) == NULL) {
262 ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
263 "getpwuid: invalid userid %ld",
264 (long) r->server->server_uid);
267 execuser = apr_pstrdup(r->pool, pw->pw_name);
269 if ((gr = getgrgid(r->server->server_gid)) == NULL) {
270 ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
271 "getgrgid: invalid groupid %ld",
272 (long) r->server->server_gid);
275 grpname = gr->gr_name;
279 execle(SUEXEC_BIN, SUEXEC_BIN, execuser, grpname, argv0,
283 else if ((!r->args) || (!r->args[0]) || strchr(r->args, '=')) {
284 execle(SUEXEC_BIN, SUEXEC_BIN, execuser, grpname, argv0,
290 create_argv(r->pool, SUEXEC_BIN, execuser, grpname,
298 execle(SHELL_PATH, SHELL_PATH, "-c", argv0, NULL, env);
301 else if ((!r->args) || (!r->args[0]) || strchr(r->args, '=')) {
302 execle(r->filename, argv0, NULL, env);
307 create_argv(r->pool, NULL, NULL, NULL, argv0, r->args),
316 static void cgid_maint(int reason, void *data, apr_wait_t status)
318 #if APR_HAS_OTHER_CHILD
321 case APR_OC_REASON_DEATH:
322 case APR_OC_REASON_LOST:
323 /* stop gap to make sure everything else works. In the end,
324 * we'll just restart the cgid server. */
325 apr_destroy_pool(pcgi);
326 kill(getppid(), SIGWINCH);
328 case APR_OC_REASON_RESTART:
329 case APR_OC_REASON_UNREGISTER:
330 apr_destroy_pool(pcgi);
337 static void get_req(int fd, request_rec *r, char **filename, char **argv0, char ***env)
342 core_dir_config *temp_core;
345 r->server = apr_pcalloc(r->pool, sizeof(server_rec));
347 read(fd, &j, sizeof(int));
348 read(fd, &len, sizeof(int));
349 data = apr_pcalloc(r->pool, len + 1); /* get a cleared byte for final '\0' */
350 i = read(fd, data, len);
352 r->filename = ap_getword(r->pool, (const char **)&data, '\n');
353 *argv0 = ap_getword(r->pool, (const char **)&data, '\n');
355 r->uri = ap_getword(r->pool, (const char **)&data, '\n');
357 environ = apr_pcalloc(r->pool, (j + 2) *sizeof(char *));
359 for (i = 0; i < j; i++) {
360 environ[i] = ap_getword(r->pool, (const char **)&data, '\n');
363 r->args = ap_getword(r->pool, (const char **)&data, '\n');
365 read(fd, &r->server->server_uid, sizeof(uid_t));
366 read(fd, &r->server->server_gid, sizeof(gid_t));
368 read(fd, &i, sizeof(int));
370 /* add 1, so that if i == 0, we still malloc something. */
371 dconf = (void **)malloc(sizeof(void *) * i + 1);
373 temp_core = (core_dir_config *)malloc(sizeof(core_module));
376 read(fd, &j, sizeof(int));
378 temp_core->limit_cpu = (struct rlimit *)malloc (sizeof(struct rlimit));
379 read(fd, temp_core->limit_cpu, sizeof(struct rlimit));
382 temp_core->limit_cpu = NULL;
386 #if defined (RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
387 read(fd, &j, sizeof(int));
389 temp_core->limit_mem = (struct rlimit *)malloc (sizeof(struct rlimit));
390 read(fd, temp_core->limit_mem, sizeof(struct rlimit));
393 temp_core->limit_mem = NULL;
398 read(fd, &j, sizeof(int));
400 temp_core->limit_nproc = (struct rlimit *)malloc (sizeof(struct rlimit));
401 read(fd, temp_core->limit_nproc, sizeof(struct rlimit));
404 temp_core->limit_nproc = NULL;
408 dconf[i] = (void *)temp_core;
409 r->per_dir_config = dconf;
414 static void send_req(int fd, request_rec *r, char *argv0, char **env)
420 data = apr_pstrcat(r->pool, r->filename, "\n", argv0, "\n", r->uri, "\n",
423 for (i =0; env[i]; i++) {
427 if (write(fd, &i, sizeof(int)) < 0) {
428 ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r,
429 "write to cgi daemon process");
432 for (i = 0; env[i]; i++) {
433 data = apr_pstrcat(r->pool, data, env[i], "\n", NULL);
435 data = apr_pstrcat(r->pool, data, r->args, NULL);
437 if (write(fd, &len, sizeof(int)) < 0) {
438 ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r,
439 "write to cgi daemon process");
441 if (write(fd, data, len) < 0) {
442 ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r,
443 "write to cgi daemon process");
445 if (write(fd, &r->server->server_uid, sizeof(uid_t)) < 0) {
446 ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r,
447 "write to cgi daemon process");
449 if (write(fd, &r->server->server_gid, sizeof(gid_t)) < 0) {
450 ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r,
451 "write to cgi daemon process");
453 if (write(fd, &core_module.module_index, sizeof(int)) < 0) {
454 ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r,
455 "write to cgi daemon process");
459 if (conf->limit_cpu) {
461 write(fd, &len, sizeof(int));
462 write(fd, conf->limit_cpu, sizeof(struct rlimit));
466 write(fd, &len, sizeof(int));
470 #if defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
471 if (conf->limit_mem) {
473 write(fd, &len, sizeof(int));
474 write(fd, conf->limit_mem, sizeof(struct rlimit));
478 write(fd, &len, sizeof(int));
483 if (conf->limit_nproc) {
485 write(fd, &len, sizeof(int));
486 write(fd, conf->limit_nproc, sizeof(struct rlimit));
490 write(fd, &len, sizeof(int));
496 static int cgid_server_child(int sd)
504 apr_create_pool(&p, pcgi);
505 r = apr_pcalloc(p, sizeof(request_rec));
507 dup2(sd, STDIN_FILENO);
508 dup2(sd, STDOUT_FILENO);
509 get_req(sd, r, &filename, &argv0, &env);
510 call_exec(r, argv0, env, 0);
511 exit(-1); /* We should NEVER get here */
514 static int cgid_server(void *data)
516 struct sockaddr_un unix_addr;
522 server_rec *main_server = data;
523 cgid_server_conf *sconf = (cgid_server_conf *)ap_get_module_config(
524 main_server->module_config, &cgid_module);
526 apr_signal(SIGCHLD, SIG_IGN);
527 if (unlink(sconf->sockname) < 0 && errno == ENOENT) {
528 ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
529 "Couldn't unlink unix domain socket %s",
531 /* just a warning; don't bail out */
534 if ((sd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
535 ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
536 "Couldn't create unix domain socket");
540 memset(&unix_addr, 0, sizeof(unix_addr));
541 unix_addr.sun_family = AF_UNIX;
542 strcpy(unix_addr.sun_path, sconf->sockname);
544 omask = umask(0077); /* so that only Apache can use socket */
545 rc = bind(sd, (struct sockaddr *)&unix_addr, sizeof(unix_addr));
546 umask(omask); /* can't fail, so can't clobber errno */
548 ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
549 "Couldn't bind unix domain socket %s",
554 if (listen(sd, DEFAULT_CGID_LISTENBACKLOG) < 0) {
555 ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
556 "Couldn't listen on unix domain socket");
561 if (chown(sconf->sockname, unixd_config.user_id, -1) < 0) {
562 ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
563 "Couldn't change owner of unix domain socket %s",
569 unixd_setup_child(); /* if running as root, switch to configured user/group */
572 len = sizeof(unix_addr);
573 sd2 = accept(sd, (struct sockaddr *)&unix_addr, &len);
575 if (errno != EINTR) {
576 ap_log_error(APLOG_MARK, APLOG_ERR, errno,
578 "Error accepting on cgid socket.");
583 if ((pid = fork()) > 0) {
587 /* setup the STDERR here, because I have all the info
588 * for it. I'll do the STDIN and STDOUT later, but I can't
589 * do STDERR as easily.
591 if (sconf->logname) {
592 dup2(open(sconf->logname, O_WRONLY), STDERR_FILENO);
595 apr_get_os_file(&errfile, main_server->error_log);
596 dup2(errfile, STDERR_FILENO);
598 cgid_server_child(sd2);
601 ap_log_error(APLOG_MARK, APLOG_ERR, errno, (server_rec *)data,
602 "Couldn't fork cgi script");
608 static void cgid_init(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *main_server)
613 if (once_through > 0) {
614 apr_create_pool(&pcgi, p);
616 if ((pid = fork()) < 0) {
617 ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
618 "Couldn't spawn cgid daemon process");
621 cgid_server(main_server);
624 procnew = apr_pcalloc(p, sizeof(*procnew));
626 procnew->err = procnew->in = procnew->out = NULL;
627 apr_note_subprocess(p, procnew, kill_after_timeout);
628 #if APR_HAS_OTHER_CHILD
629 apr_register_other_child(procnew, cgid_maint, NULL, NULL, p);
635 static void *create_cgid_config(apr_pool_t *p, server_rec *s)
637 cgid_server_conf *c =
638 (cgid_server_conf *) apr_pcalloc(p, sizeof(cgid_server_conf));
641 c->logbytes = DEFAULT_LOGBYTES;
642 c->bufbytes = DEFAULT_BUFBYTES;
643 c->sockname = ap_server_root_relative(p, DEFAULT_SOCKET);
644 c->bin = c->bout = c->berror = NULL;
648 static void *merge_cgid_config(apr_pool_t *p, void *basev, void *overridesv)
650 cgid_server_conf *base = (cgid_server_conf *) basev, *overrides = (cgid_server_conf *) overridesv;
652 return overrides->logname ? overrides : base;
655 static const char *set_scriptlog(cmd_parms *cmd, void *dummy, const char *arg)
657 server_rec *s = cmd->server;
658 cgid_server_conf *conf =
659 (cgid_server_conf *) ap_get_module_config(s->module_config, &cgid_module);
665 static const char *set_scriptlog_length(cmd_parms *cmd, void *dummy, const char *arg)
667 server_rec *s = cmd->server;
668 cgid_server_conf *conf =
669 (cgid_server_conf *) ap_get_module_config(s->module_config, &cgid_module);
671 conf->logbytes = atol(arg);
675 static const char *set_scriptlog_buffer(cmd_parms *cmd, void *dummy, const char *arg)
677 server_rec *s = cmd->server;
678 cgid_server_conf *conf =
679 (cgid_server_conf *) ap_get_module_config(s->module_config, &cgid_module);
681 conf->bufbytes = atoi(arg);
685 static const char *set_script_socket(cmd_parms *cmd, void *dummy, const char *arg)
687 server_rec *s = cmd->server;
688 cgid_server_conf *conf =
689 (cgid_server_conf *) ap_get_module_config(s->module_config, &cgid_module);
691 conf->sockname = ap_server_root_relative(cmd->pool, arg);
695 static const command_rec cgid_cmds[] =
697 AP_INIT_TAKE1("ScriptLog", set_scriptlog, NULL, RSRC_CONF,
698 "the name of a log for script debugging info"),
699 AP_INIT_TAKE1("ScriptLogLength", set_scriptlog_length, NULL, RSRC_CONF,
700 "the maximum length (in bytes) of the script debug log"),
701 AP_INIT_TAKE1("ScriptLogBuffer", set_scriptlog_buffer, NULL, RSRC_CONF,
702 "the maximum size (in bytes) to record of a POST request"),
703 AP_INIT_TAKE1("Scriptsock", set_script_socket, NULL, RSRC_CONF,
704 "the name of the socket to use for communication with "
709 static int log_scripterror(request_rec *r, cgid_server_conf * conf, int ret,
710 int show_errno, char *error)
712 apr_file_t *f = NULL;
714 char time_str[APR_CTIME_LEN];
716 ap_log_rerror(APLOG_MARK, show_errno|APLOG_ERR, errno, r,
717 "%s: %s", error, r->filename);
719 if (!conf->logname ||
720 ((stat(ap_server_root_relative(r->pool, conf->logname), &finfo) == 0)
721 && (finfo.st_size > conf->logbytes)) ||
722 (apr_open(&f, ap_server_root_relative(r->pool, conf->logname),
723 APR_APPEND|APR_WRITE|APR_CREATE, APR_OS_DEFAULT, r->pool) != APR_SUCCESS)) {
727 /* "%% [Wed Jun 19 10:53:21 1996] GET /cgid-bin/printenv HTTP/1.0" */
728 apr_ctime(time_str, apr_now());
729 apr_fprintf(f, "%%%% [%s] %s %s%s%s %s\n", time_str, r->method, r->uri,
730 r->args ? "?" : "", r->args ? r->args : "", r->protocol);
731 /* "%% 500 /usr/local/apache/cgid-bin */
732 apr_fprintf(f, "%%%% %d %s\n", ret, r->filename);
734 apr_fprintf(f, "%%error\n%s\n", error);
740 static int log_script(request_rec *r, cgid_server_conf * conf, int ret,
741 char *dbuf, const char *sbuf, apr_file_t *script_in, apr_file_t *script_err)
743 apr_array_header_t *hdrs_arr = apr_table_elts(r->headers_in);
744 apr_table_entry_t *hdrs = (apr_table_entry_t *) hdrs_arr->elts;
745 char argsbuffer[HUGE_STRING_LEN];
746 apr_file_t *f = NULL;
749 char time_str[APR_CTIME_LEN];
751 if (!conf->logname ||
752 ((stat(ap_server_root_relative(r->pool, conf->logname), &finfo) == 0)
753 && (finfo.st_size > conf->logbytes)) ||
754 (apr_open(&f, ap_server_root_relative(r->pool, conf->logname),
755 APR_APPEND|APR_WRITE|APR_CREATE, APR_OS_DEFAULT, r->pool) != APR_SUCCESS)) {
756 /* Soak up script output */
757 while (apr_fgets(argsbuffer, HUGE_STRING_LEN, script_in) == 0)
760 while (apr_fgets(argsbuffer, HUGE_STRING_LEN, script_err) == 0)
766 /* "%% [Wed Jun 19 10:53:21 1996] GET /cgid-bin/printenv HTTP/1.0" */
767 apr_ctime(time_str, apr_now());
768 apr_fprintf(f, "%%%% [%s] %s %s%s%s %s\n", time_str, r->method, r->uri,
769 r->args ? "?" : "", r->args ? r->args : "", r->protocol);
770 /* "%% 500 /usr/local/apache/cgid-bin" */
771 apr_fprintf(f, "%%%% %d %s\n", ret, r->filename);
773 apr_puts("%request\n", f);
774 for (i = 0; i < hdrs_arr->nelts; ++i) {
777 apr_fprintf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val);
779 if ((r->method_number == M_POST || r->method_number == M_PUT)
781 apr_fprintf(f, "\n%s\n", dbuf);
784 apr_puts("%response\n", f);
785 hdrs_arr = apr_table_elts(r->err_headers_out);
786 hdrs = (apr_table_entry_t *) hdrs_arr->elts;
788 for (i = 0; i < hdrs_arr->nelts; ++i) {
791 apr_fprintf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val);
795 apr_fprintf(f, "%s\n", sbuf);
797 if (apr_fgets(argsbuffer, HUGE_STRING_LEN, script_in) == 0) {
798 apr_puts("%stdout\n", f);
799 apr_puts(argsbuffer, f);
800 while (apr_fgets(argsbuffer, HUGE_STRING_LEN, script_in) == 0)
801 apr_puts(argsbuffer, f);
806 if (apr_fgets(argsbuffer, HUGE_STRING_LEN, script_err) == 0) {
807 apr_puts("%stderr\n", f);
808 apr_puts(argsbuffer, f);
809 while (apr_fgets(argsbuffer, HUGE_STRING_LEN, script_err) == 0)
810 apr_puts(argsbuffer, f);
815 apr_close(script_in);
817 apr_close(script_err);
826 /****************************************************************
828 * Actual cgid handling...
830 static int cgid_handler(request_rec *r)
832 int retval, nph, dbpos = 0;
833 char *argv0, *dbuf = NULL;
834 ap_bucket_brigade *bb;
836 char argsbuffer[HUGE_STRING_LEN];
837 void *sconf = r->server->module_config;
838 cgid_server_conf *conf = (cgid_server_conf *) ap_get_module_config(sconf, &cgid_module);
839 int is_included = !strcmp(r->protocol, "INCLUDED");
842 struct sockaddr_un unix_addr;
843 apr_file_t *tempsock = NULL;
846 if (r->method_number == M_OPTIONS) {
847 /* 99 out of 100 cgid scripts, this is all they support */
848 r->allowed |= (1 << M_GET);
849 r->allowed |= (1 << M_POST);
853 if ((argv0 = strrchr(r->filename, '/')) != NULL)
858 nph = !(strncmp(argv0, "nph-", 4));
860 if ((argv0 = strrchr(r->filename, '/')) != NULL)
865 if (!(ap_allow_options(r) & OPT_EXECCGI) && !is_scriptaliased(r))
866 return log_scripterror(r, conf, HTTP_FORBIDDEN, APLOG_NOERRNO,
867 "Options ExecCGI is off in this directory");
868 if (nph && is_included)
869 return log_scripterror(r, conf, HTTP_FORBIDDEN, APLOG_NOERRNO,
870 "attempt to include NPH CGI script");
872 #if defined(OS2) || defined(WIN32)
873 /* Allow for cgid files without the .EXE extension on them under OS/2 */
874 if (r->finfo.st_mode == 0) {
878 newfile = apr_pstrcat(r->pool, r->filename, ".EXE", NULL);
880 if ((stat(newfile, &statbuf) != 0) || (!S_ISREG(statbuf.st_mode))) {
881 return log_scripterror(r, conf, HTTP_NOT_FOUND, 0,
882 "script not found or unable to stat");
884 r->filename = newfile;
888 if (r->finfo.protection == 0)
889 return log_scripterror(r, conf, HTTP_NOT_FOUND, APLOG_NOERRNO,
890 "script not found or unable to stat");
892 if (r->finfo.filetype == APR_DIR)
893 return log_scripterror(r, conf, HTTP_FORBIDDEN, APLOG_NOERRNO,
894 "attempt to invoke directory as script");
896 if (!ap_suexec_enabled) {
897 if (!ap_can_exec(&r->finfo))
898 return log_scripterror(r, conf, HTTP_FORBIDDEN, APLOG_NOERRNO,
899 "file permissions deny server execution");
902 ap_add_common_vars(r);
904 env = ap_create_environment(r->pool, r->subprocess_env);
906 if ((sd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
907 return log_scripterror(r, conf, HTTP_NOT_FOUND, 0,
908 "unable to create socket to cgi daemon");
910 memset(&unix_addr, 0, sizeof(unix_addr));
911 unix_addr.sun_family = AF_UNIX;
912 strcpy(unix_addr.sun_path, conf->sockname);
914 if (connect(sd, (struct sockaddr *)&unix_addr, sizeof(unix_addr)) < 0) {
915 return log_scripterror(r, conf, HTTP_NOT_FOUND, 0,
916 "unable to connect to cgi daemon");
919 send_req(sd, r, argv0, env);
921 /* We are putting the tempsock variable into a file so that we can use
922 * a pipe bucket to send the data to the client.
924 apr_put_os_file(&tempsock, &sd, r->pool);
926 if ((retval = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR)))
929 if ((argv0 = strrchr(r->filename, '/')) != NULL)
934 /* Transfer any put/post args, CERN style...
935 * Note that we already ignore SIGPIPE in the core server.
938 if (ap_should_client_block(r)) {
939 int dbsize, len_read;
942 dbuf = apr_pcalloc(r->pool, conf->bufbytes + 1);
947 ap_get_client_block(r, argsbuffer, HUGE_STRING_LEN)) > 0) {
949 if ((dbpos + len_read) > conf->bufbytes) {
950 dbsize = conf->bufbytes - dbpos;
955 memcpy(dbuf + dbpos, argsbuffer, dbsize);
959 apr_write(tempsock, argsbuffer, &nbytes);
960 if (nbytes < len_read) {
961 /* silly script stopped reading, soak up remaining message */
962 while (ap_get_client_block(r, argsbuffer, HUGE_STRING_LEN) > 0) {
970 /* Handle script return... */
972 const char *location;
973 char sbuf[MAX_STRING_LEN];
976 if ((ret = ap_scan_script_header_err(r, tempsock, sbuf))) {
977 return log_script(r, conf, ret, dbuf, sbuf, tempsock, NULL);
980 location = apr_table_get(r->headers_out, "Location");
982 if (location && location[0] == '/' && r->status == 200) {
984 /* Soak up all the script output */
985 while (apr_fgets(argsbuffer, HUGE_STRING_LEN, tempsock) > 0) {
988 /* This redirect needs to be a GET no matter what the original
991 r->method = apr_pstrdup(r->pool, "GET");
992 r->method_number = M_GET;
994 /* We already read the message body (if any), so don't allow
995 * the redirected request to think it has one. We can ignore
996 * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR.
998 apr_table_unset(r->headers_in, "Content-Length");
1000 ap_internal_redirect_handler(location, r);
1003 else if (location && r->status == 200) {
1004 /* XX Note that if a script wants to produce its own Redirect
1005 * body, it now has to explicitly *say* "Status: 302"
1007 return HTTP_MOVED_TEMPORARILY;
1010 ap_send_http_header(r);
1011 if (!r->header_only) {
1012 bb = ap_brigade_create(r->pool);
1013 b = ap_bucket_create_pipe(tempsock);
1014 AP_BRIGADE_INSERT_TAIL(bb, b);
1015 b = ap_bucket_create_eos();
1016 AP_BRIGADE_INSERT_TAIL(bb, b);
1017 ap_pass_brigade(r->output_filters, bb);
1022 bb = ap_brigade_create(r->pool);
1023 b = ap_bucket_create_pipe(tempsock);
1024 AP_BRIGADE_INSERT_TAIL(bb, b);
1025 b = ap_bucket_create_eos();
1026 AP_BRIGADE_INSERT_TAIL(bb, b);
1027 ap_pass_brigade(r->output_filters, bb);
1030 apr_close(tempsock);
1032 return OK; /* NOT r->status, even if it has changed. */
1035 static const handler_rec cgid_handlers[] =
1037 {CGI_MAGIC_TYPE, cgid_handler},
1038 {"cgi-script", cgid_handler},
1042 static void register_hook(void)
1044 ap_hook_post_config(cgid_init, NULL, NULL, AP_HOOK_MIDDLE);
1047 module MODULE_VAR_EXPORT cgid_module = {
1048 STANDARD20_MODULE_STUFF,
1049 NULL, /* dir config creater */
1050 NULL, /* dir merger --- default is to override */
1051 create_cgid_config, /* server config */
1052 merge_cgid_config, /* merge server config */
1053 cgid_cmds, /* command table */
1054 cgid_handlers, /* handlers */
1055 register_hook /* register_handlers */