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"
82 #include "http_config.h"
83 #include "http_request.h"
84 #include "http_core.h"
85 #include "http_protocol.h"
86 #include "http_main.h"
88 #include "util_script.h"
89 #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 MODULE_VAR_EXPORT 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;
155 /* If a request includes query info in the URL (stuff after "?"), and
156 * the query info does not contain "=" (indicative of a FORM submission),
157 * then this routine is called to create the argument list to be passed
158 * to the CGI script. When suexec is enabled, the suexec path, user, and
159 * group are the first three arguments to be passed; if not, all three
160 * must be NULL. The query info is split into separate arguments, where
161 * "+" is the separator between keyword arguments.
163 * XXXX: note that the WIN32 code uses one of the suexec strings
164 * to pass an interpreter name. Remember this if changing the way they
165 * are handled in create_argv.
168 static char **create_argv(apr_pool_t *p, char *path, char *user, char *group,
169 char *av0, const char *args)
176 /* count the number of keywords */
178 for (x = 0, numwords = 1; args[x]; x++) {
179 if (args[x] == '+') {
184 if (numwords > APACHE_ARG_MAX - 5) {
185 numwords = APACHE_ARG_MAX - 5; /* Truncate args to prevent overrun */
187 av = (char **) apr_palloc(p, (numwords + 5) * sizeof(char *));
201 for (x = 1; x <= numwords; x++) {
202 w = ap_getword_nulls(p, &args, '+');
204 av[idx++] = ap_escape_shell_cmd(p, w);
210 static int call_exec(request_rec *r, char *argv0, char **env, int shellcmd)
213 int errfileno = STDERR_FILENO;
214 /* the fd on r->server->error_log is closed, but we need somewhere to
215 * put the error messages from the log_* functions. So, we use stderr,
216 * since that is better than allowing errors to go unnoticed.
218 apr_put_os_file(&r->server->error_log, &errfileno, r->pool);
219 /* TODO: reimplement suexec */
221 if (ap_suexec_enabled
222 && ((r->server->server_uid != ap_user_id)
223 || (r->server->server_gid != ap_group_id)
224 || (!strncmp("/~", r->uri, 2)))) {
226 char *execuser, *grpname;
230 if (!strncmp("/~", r->uri, 2)) {
232 char *username = apr_pstrdup(r->pool, r->uri + 2);
233 char *pos = strchr(username, '/');
239 if ((pw = getpwnam(username)) == NULL) {
240 ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
241 "getpwnam: invalid username %s", username);
244 execuser = apr_pstrcat(r->pool, "~", pw->pw_name, NULL);
245 user_gid = pw->pw_gid;
247 if ((gr = getgrgid(user_gid)) == NULL) {
248 if ((grpname = apr_palloc(r->pool, 16)) == NULL) {
252 apr_snprintf(grpname, 16, "%ld", (long) user_gid);
256 grpname = gr->gr_name;
260 if ((pw = getpwuid(r->server->server_uid)) == NULL) {
261 ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
262 "getpwuid: invalid userid %ld",
263 (long) r->server->server_uid);
266 execuser = apr_pstrdup(r->pool, pw->pw_name);
268 if ((gr = getgrgid(r->server->server_gid)) == NULL) {
269 ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
270 "getgrgid: invalid groupid %ld",
271 (long) r->server->server_gid);
274 grpname = gr->gr_name;
278 execle(SUEXEC_BIN, SUEXEC_BIN, execuser, grpname, argv0,
282 else if ((!r->args) || (!r->args[0]) || strchr(r->args, '=')) {
283 execle(SUEXEC_BIN, SUEXEC_BIN, execuser, grpname, argv0,
289 create_argv(r->pool, SUEXEC_BIN, execuser, grpname,
297 execle(SHELL_PATH, SHELL_PATH, "-c", argv0, NULL, env);
300 else if ((!r->args) || (!r->args[0]) || strchr(r->args, '=')) {
301 execle(r->filename, argv0, NULL, env);
306 create_argv(r->pool, NULL, NULL, NULL, argv0, r->args),
315 static void cgid_maint(int reason, void *data, ap_wait_t status)
317 #if APR_HAS_OTHER_CHILD
320 case APR_OC_REASON_DEATH:
321 case APR_OC_REASON_LOST:
322 /* stop gap to make sure everything else works. In the end,
323 * we'll just restart the cgid server. */
324 apr_destroy_pool(pcgi);
325 kill(getppid(), SIGWINCH);
327 case APR_OC_REASON_RESTART:
328 case APR_OC_REASON_UNREGISTER:
329 apr_destroy_pool(pcgi);
336 static void get_req(int fd, request_rec *r, char **filename, char **argv0, char ***env)
341 core_dir_config *temp_core;
344 r->server = apr_pcalloc(r->pool, sizeof(server_rec));
346 read(fd, &j, sizeof(int));
347 read(fd, &len, sizeof(int));
348 data = apr_pcalloc(r->pool, len + 1); /* get a cleared byte for final '\0' */
349 i = read(fd, data, len);
351 r->filename = ap_getword(r->pool, (const char **)&data, '\n');
352 *argv0 = ap_getword(r->pool, (const char **)&data, '\n');
354 r->uri = ap_getword(r->pool, (const char **)&data, '\n');
356 environ = apr_pcalloc(r->pool, (j + 2) *sizeof(char *));
358 for (i = 0; i < j; i++) {
359 environ[i] = ap_getword(r->pool, (const char **)&data, '\n');
362 r->args = ap_getword(r->pool, (const char **)&data, '\n');
364 read(fd, &r->server->server_uid, sizeof(uid_t));
365 read(fd, &r->server->server_gid, sizeof(gid_t));
367 read(fd, &i, sizeof(int));
369 /* add 1, so that if i == 0, we still malloc something. */
370 dconf = (void **)malloc(sizeof(void *) * i + 1);
372 temp_core = (core_dir_config *)malloc(sizeof(core_module));
375 read(fd, &j, sizeof(int));
377 temp_core->limit_cpu = (struct rlimit *)malloc (sizeof(struct rlimit));
378 read(fd, temp_core->limit_cpu, sizeof(struct rlimit));
381 temp_core->limit_cpu = NULL;
385 #if defined (RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
386 read(fd, &j, sizeof(int));
388 temp_core->limit_mem = (struct rlimit *)malloc (sizeof(struct rlimit));
389 read(fd, temp_core->limit_mem, sizeof(struct rlimit));
392 temp_core->limit_mem = NULL;
397 read(fd, &j, sizeof(int));
399 temp_core->limit_nproc = (struct rlimit *)malloc (sizeof(struct rlimit));
400 read(fd, temp_core->limit_nproc, sizeof(struct rlimit));
403 temp_core->limit_nproc = NULL;
407 dconf[i] = (void *)temp_core;
408 r->per_dir_config = dconf;
413 static void send_req(int fd, request_rec *r, char *argv0, char **env)
419 data = apr_pstrcat(r->pool, r->filename, "\n", argv0, "\n", r->uri, "\n",
422 for (i =0; env[i]; i++) {
426 if (write(fd, &i, sizeof(int)) < 0) {
427 ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r,
428 "write to cgi daemon process");
431 for (i = 0; env[i]; i++) {
432 data = apr_pstrcat(r->pool, data, env[i], "\n", NULL);
434 data = apr_pstrcat(r->pool, data, r->args, NULL);
436 if (write(fd, &len, sizeof(int)) < 0) {
437 ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r,
438 "write to cgi daemon process");
440 if (write(fd, data, len) < 0) {
441 ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r,
442 "write to cgi daemon process");
444 if (write(fd, &r->server->server_uid, sizeof(uid_t)) < 0) {
445 ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r,
446 "write to cgi daemon process");
448 if (write(fd, &r->server->server_gid, sizeof(gid_t)) < 0) {
449 ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r,
450 "write to cgi daemon process");
452 if (write(fd, &core_module.module_index, sizeof(int)) < 0) {
453 ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r,
454 "write to cgi daemon process");
458 if (conf->limit_cpu) {
460 write(fd, &len, sizeof(int));
461 write(fd, conf->limit_cpu, sizeof(struct rlimit));
465 write(fd, &len, sizeof(int));
469 #if defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
470 if (conf->limit_mem) {
472 write(fd, &len, sizeof(int));
473 write(fd, conf->limit_mem, sizeof(struct rlimit));
477 write(fd, &len, sizeof(int));
482 if (conf->limit_nproc) {
484 write(fd, &len, sizeof(int));
485 write(fd, conf->limit_nproc, sizeof(struct rlimit));
489 write(fd, &len, sizeof(int));
495 static int cgid_server_child(int sd)
503 apr_create_pool(&p, pcgi);
504 r = apr_pcalloc(p, sizeof(request_rec));
506 dup2(sd, STDIN_FILENO);
507 dup2(sd, STDOUT_FILENO);
508 get_req(sd, r, &filename, &argv0, &env);
509 call_exec(r, argv0, env, 0);
510 exit(-1); /* We should NEVER get here */
513 static int cgid_server(void *data)
515 struct sockaddr_un unix_addr;
517 int sd, sd2, len, rc;
520 server_rec *main_server = data;
521 cgid_server_conf *sconf = (cgid_server_conf *)ap_get_module_config(
522 main_server->module_config, &cgid_module);
524 apr_signal(SIGCHLD, SIG_IGN);
525 if (unlink(sconf->sockname) < 0 &&
527 ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
528 "Couldn't unlink unix domain socket %s",
530 /* just a warning; don't bail out */
533 if ((sd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
534 ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
535 "Couldn't create unix domain socket");
539 memset(&unix_addr, 0, sizeof(unix_addr));
540 unix_addr.sun_family = AF_UNIX;
541 strcpy(unix_addr.sun_path, sconf->sockname);
543 omask = umask(0077); /* so that only Apache can use socket */
544 rc = bind(sd, (struct sockaddr *)&unix_addr, sizeof(unix_addr));
545 umask(omask); /* can't fail, so can't clobber errno */
547 ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
548 "Couldn't bind unix domain socket %s",
553 if (listen(sd, DEFAULT_CGID_LISTENBACKLOG) < 0) {
554 ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
555 "Couldn't listen on unix domain socket");
560 if (chown(sconf->sockname, unixd_config.user_id, -1) < 0) {
561 ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
562 "Couldn't change owner of unix domain socket %s",
568 unixd_setup_child(); /* if running as root, switch to configured user/group */
571 len = sizeof(unix_addr);
572 sd2 = accept(sd, (struct sockaddr *)&unix_addr, &len);
574 if (errno != EINTR) {
575 ap_log_error(APLOG_MARK, APLOG_ERR, errno,
577 "Error accepting on cgid socket.");
582 if ((pid = fork()) > 0) {
586 /* setup the STDERR here, because I have all the info
587 * for it. I'll do the STDIN and STDOUT later, but I can't
588 * do STDERR as easily.
590 if (sconf->logname) {
591 dup2(open(sconf->logname, O_WRONLY), STDERR_FILENO);
594 apr_get_os_file(&errfile, main_server->error_log);
595 dup2(errfile, STDERR_FILENO);
597 cgid_server_child(sd2);
600 ap_log_error(APLOG_MARK, APLOG_ERR, errno, (server_rec *)data,
601 "Couldn't fork cgi script");
607 static void cgid_init(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *main_server)
612 if (once_through > 0) {
613 apr_create_pool(&pcgi, p);
615 if ((pid = fork()) < 0) {
616 ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
617 "Couldn't spawn cgid daemon process");
620 cgid_server(main_server);
623 procnew = apr_pcalloc(p, sizeof(*procnew));
625 procnew->err = procnew->in = procnew->out = NULL;
626 apr_note_subprocess(p, procnew, kill_after_timeout);
627 #if APR_HAS_OTHER_CHILD
628 apr_register_other_child(procnew, cgid_maint, NULL, NULL, p);
634 static void *create_cgid_config(apr_pool_t *p, server_rec *s)
636 cgid_server_conf *c =
637 (cgid_server_conf *) apr_pcalloc(p, sizeof(cgid_server_conf));
640 c->logbytes = DEFAULT_LOGBYTES;
641 c->bufbytes = DEFAULT_BUFBYTES;
642 c->sockname = ap_server_root_relative(p, DEFAULT_SOCKET);
643 c->bin = c->bout = c->berror = NULL;
647 static void *merge_cgid_config(apr_pool_t *p, void *basev, void *overridesv)
649 cgid_server_conf *base = (cgid_server_conf *) basev, *overrides = (cgid_server_conf *) overridesv;
651 return overrides->logname ? overrides : base;
654 static const char *set_scriptlog(cmd_parms *cmd, void *dummy, const char *arg)
656 server_rec *s = cmd->server;
657 cgid_server_conf *conf =
658 (cgid_server_conf *) ap_get_module_config(s->module_config, &cgid_module);
664 static const char *set_scriptlog_length(cmd_parms *cmd, void *dummy, const char *arg)
666 server_rec *s = cmd->server;
667 cgid_server_conf *conf =
668 (cgid_server_conf *) ap_get_module_config(s->module_config, &cgid_module);
670 conf->logbytes = atol(arg);
674 static const char *set_scriptlog_buffer(cmd_parms *cmd, void *dummy, const char *arg)
676 server_rec *s = cmd->server;
677 cgid_server_conf *conf =
678 (cgid_server_conf *) ap_get_module_config(s->module_config, &cgid_module);
680 conf->bufbytes = atoi(arg);
684 static const char *set_script_socket(cmd_parms *cmd, void *dummy, const char *arg)
686 server_rec *s = cmd->server;
687 cgid_server_conf *conf =
688 (cgid_server_conf *) ap_get_module_config(s->module_config, &cgid_module);
690 conf->sockname = ap_server_root_relative(cmd->pool, arg);
694 static const command_rec cgid_cmds[] =
696 AP_INIT_TAKE1("ScriptLog", set_scriptlog, NULL, RSRC_CONF,
697 "the name of a log for script debugging info"),
698 AP_INIT_TAKE1("ScriptLogLength", set_scriptlog_length, NULL, RSRC_CONF,
699 "the maximum length (in bytes) of the script debug log"),
700 AP_INIT_TAKE1("ScriptLogBuffer", set_scriptlog_buffer, NULL, RSRC_CONF,
701 "the maximum size (in bytes) to record of a POST request"),
702 AP_INIT_TAKE1("Scriptsock", set_script_socket, NULL, RSRC_CONF,
703 "the name of the socket to use for communication with "
708 static int log_scripterror(request_rec *r, cgid_server_conf * conf, int ret,
709 int show_errno, char *error)
711 apr_file_t *f = NULL;
713 char time_str[AP_CTIME_LEN];
715 ap_log_rerror(APLOG_MARK, show_errno|APLOG_ERR, errno, r,
716 "%s: %s", error, r->filename);
718 if (!conf->logname ||
719 ((stat(ap_server_root_relative(r->pool, conf->logname), &finfo) == 0)
720 && (finfo.st_size > conf->logbytes)) ||
721 (apr_open(&f, ap_server_root_relative(r->pool, conf->logname),
722 APR_APPEND|APR_WRITE|APR_CREATE, APR_OS_DEFAULT, r->pool) != APR_SUCCESS)) {
726 /* "%% [Wed Jun 19 10:53:21 1996] GET /cgid-bin/printenv HTTP/1.0" */
727 apr_ctime(time_str, apr_now());
728 apr_fprintf(f, "%%%% [%s] %s %s%s%s %s\n", time_str, r->method, r->uri,
729 r->args ? "?" : "", r->args ? r->args : "", r->protocol);
730 /* "%% 500 /usr/local/apache/cgid-bin */
731 apr_fprintf(f, "%%%% %d %s\n", ret, r->filename);
733 apr_fprintf(f, "%%error\n%s\n", error);
739 static int log_script(request_rec *r, cgid_server_conf * conf, int ret,
740 char *dbuf, const char *sbuf, BUFF *script_in, BUFF *script_err)
742 apr_array_header_t *hdrs_arr = ap_table_elts(r->headers_in);
743 apr_table_entry_t *hdrs = (apr_table_entry_t *) hdrs_arr->elts;
744 char argsbuffer[HUGE_STRING_LEN];
745 apr_file_t *f = NULL;
748 char time_str[AP_CTIME_LEN];
750 if (!conf->logname ||
751 ((stat(ap_server_root_relative(r->pool, conf->logname), &finfo) == 0)
752 && (finfo.st_size > conf->logbytes)) ||
753 (apr_open(&f, ap_server_root_relative(r->pool, conf->logname),
754 APR_APPEND|APR_WRITE|APR_CREATE, APR_OS_DEFAULT, r->pool) != APR_SUCCESS)) {
755 /* Soak up script output */
756 while (ap_bgets(argsbuffer, HUGE_STRING_LEN, script_in) > 0)
759 while (ap_bgets(argsbuffer, HUGE_STRING_LEN, script_err) > 0)
765 /* "%% [Wed Jun 19 10:53:21 1996] GET /cgid-bin/printenv HTTP/1.0" */
766 apr_ctime(time_str, apr_now());
767 apr_fprintf(f, "%%%% [%s] %s %s%s%s %s\n", time_str, r->method, r->uri,
768 r->args ? "?" : "", r->args ? r->args : "", r->protocol);
769 /* "%% 500 /usr/local/apache/cgid-bin" */
770 apr_fprintf(f, "%%%% %d %s\n", ret, r->filename);
772 apr_puts("%request\n", f);
773 for (i = 0; i < hdrs_arr->nelts; ++i) {
776 apr_fprintf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val);
778 if ((r->method_number == M_POST || r->method_number == M_PUT)
780 apr_fprintf(f, "\n%s\n", dbuf);
783 apr_puts("%response\n", f);
784 hdrs_arr = ap_table_elts(r->err_headers_out);
785 hdrs = (apr_table_entry_t *) hdrs_arr->elts;
787 for (i = 0; i < hdrs_arr->nelts; ++i) {
790 apr_fprintf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val);
794 apr_fprintf(f, "%s\n", sbuf);
796 if (ap_bgets(argsbuffer, HUGE_STRING_LEN, script_in) > 0) {
797 apr_puts("%stdout\n", f);
798 apr_puts(argsbuffer, f);
799 while (ap_bgets(argsbuffer, HUGE_STRING_LEN, script_in) > 0)
800 apr_puts(argsbuffer, f);
805 if (ap_bgets(argsbuffer, HUGE_STRING_LEN, script_err) > 0) {
806 apr_puts("%stderr\n", f);
807 apr_puts(argsbuffer, f);
808 while (ap_bgets(argsbuffer, HUGE_STRING_LEN, script_err) > 0)
809 apr_puts(argsbuffer, f);
814 ap_bclose(script_in);
816 ap_bclose(script_err);
825 /****************************************************************
827 * Actual cgid handling...
829 static int cgid_handler(request_rec *r)
831 int retval, nph, dbpos = 0;
832 char *argv0, *dbuf = NULL;
834 char argsbuffer[HUGE_STRING_LEN];
835 void *sconf = r->server->module_config;
836 cgid_server_conf *conf = (cgid_server_conf *) ap_get_module_config(sconf, &cgid_module);
837 int is_included = !strcmp(r->protocol, "INCLUDED");
840 struct sockaddr_un unix_addr;
841 apr_socket_t *tempsock = NULL;
844 script = ap_bcreate(r->pool, B_RDWR);
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 apr_put_os_sock(&tempsock, &sd, pcgi);
923 iol = ap_iol_attach_socket(pcgi, tempsock);
925 ap_bpush_iol(script, iol);
927 if ((retval = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR)))
930 if ((argv0 = strrchr(r->filename, '/')) != NULL)
935 /* Transfer any put/post args, CERN style...
936 * Note that we already ignore SIGPIPE in the core server.
939 if (ap_should_client_block(r)) {
940 int dbsize, len_read;
943 dbuf = apr_pcalloc(r->pool, conf->bufbytes + 1);
950 ap_get_client_block(r, argsbuffer, HUGE_STRING_LEN)) > 0) {
952 if ((dbpos + len_read) > conf->bufbytes) {
953 dbsize = conf->bufbytes - dbpos;
958 memcpy(dbuf + dbpos, argsbuffer, dbsize);
961 ap_bwrite(script, argsbuffer, len_read, &nbytes);
962 if (nbytes < len_read) {
963 /* silly script stopped reading, soak up remaining message */
964 while (ap_get_client_block(r, argsbuffer, HUGE_STRING_LEN) > 0) {
975 /* Handle script return... */
976 if (script && !nph) {
977 const char *location;
978 char sbuf[MAX_STRING_LEN];
981 if ((ret = ap_scan_script_header_err_buff(r, script, sbuf))) {
982 return log_script(r, conf, ret, dbuf, sbuf, script, NULL);
985 location = apr_table_get(r->headers_out, "Location");
987 if (location && location[0] == '/' && r->status == 200) {
989 /* Soak up all the script output */
990 while (ap_bgets(argsbuffer, HUGE_STRING_LEN, script) > 0) {
993 /* This redirect needs to be a GET no matter what the original
996 r->method = apr_pstrdup(r->pool, "GET");
997 r->method_number = M_GET;
999 /* We already read the message body (if any), so don't allow
1000 * the redirected request to think it has one. We can ignore
1001 * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR.
1003 apr_table_unset(r->headers_in, "Content-Length");
1005 ap_internal_redirect_handler(location, r);
1008 else if (location && r->status == 200) {
1009 /* XX Note that if a script wants to produce its own Redirect
1010 * body, it now has to explicitly *say* "Status: 302"
1012 return HTTP_MOVED_TEMPORARILY;
1015 ap_send_http_header(r);
1016 if (!r->header_only) {
1017 ap_send_fb(script, r);
1022 if (script && nph) {
1023 ap_send_fb(script, r);
1026 return OK; /* NOT r->status, even if it has changed. */
1029 static const handler_rec cgid_handlers[] =
1031 {CGI_MAGIC_TYPE, cgid_handler},
1032 {"cgi-script", cgid_handler},
1036 static void register_hook(void)
1038 ap_hook_post_config(cgid_init, NULL, NULL, AP_HOOK_MIDDLE);
1041 module MODULE_VAR_EXPORT cgid_module = {
1042 STANDARD20_MODULE_STUFF,
1043 NULL, /* dir config creater */
1044 NULL, /* dir merger --- default is to override */
1045 create_cgid_config, /* server config */
1046 merge_cgid_config, /* merge server config */
1047 cgid_cmds, /* command table */
1048 cgid_handlers, /* handlers */
1049 register_hook /* register_handlers */