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 ap_log_error(APLOG_MARK, APLOG_ERR, errno, (server_rec *)data,
575 "Error accepting on cgid socket.");
579 if ((pid = fork()) > 0) {
583 /* setup the STDERR here, because I have all the info
584 * for it. I'll do the STDIN and STDOUT later, but I can't
585 * do STDERR as easily.
587 if (sconf->logname) {
588 dup2(open(sconf->logname, O_WRONLY), STDERR_FILENO);
591 apr_get_os_file(&errfile, main_server->error_log);
592 dup2(errfile, STDERR_FILENO);
594 cgid_server_child(sd2);
597 ap_log_error(APLOG_MARK, APLOG_ERR, errno, (server_rec *)data,
598 "Couldn't fork cgi script");
604 static void cgid_init(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *main_server)
609 if (once_through > 0) {
610 apr_create_pool(&pcgi, p);
612 if ((pid = fork()) < 0) {
613 ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
614 "Couldn't spawn cgid daemon process");
617 cgid_server(main_server);
620 procnew = apr_pcalloc(p, sizeof(*procnew));
622 procnew->err = procnew->in = procnew->out = NULL;
623 apr_note_subprocess(p, procnew, kill_after_timeout);
624 #if APR_HAS_OTHER_CHILD
625 apr_register_other_child(procnew, cgid_maint, NULL, NULL, p);
631 static void *create_cgid_config(apr_pool_t *p, server_rec *s)
633 cgid_server_conf *c =
634 (cgid_server_conf *) apr_pcalloc(p, sizeof(cgid_server_conf));
637 c->logbytes = DEFAULT_LOGBYTES;
638 c->bufbytes = DEFAULT_BUFBYTES;
639 c->sockname = ap_server_root_relative(p, DEFAULT_SOCKET);
640 c->bin = c->bout = c->berror = NULL;
644 static void *merge_cgid_config(apr_pool_t *p, void *basev, void *overridesv)
646 cgid_server_conf *base = (cgid_server_conf *) basev, *overrides = (cgid_server_conf *) overridesv;
648 return overrides->logname ? overrides : base;
651 static const char *set_scriptlog(cmd_parms *cmd, void *dummy, const char *arg)
653 server_rec *s = cmd->server;
654 cgid_server_conf *conf =
655 (cgid_server_conf *) ap_get_module_config(s->module_config, &cgid_module);
661 static const char *set_scriptlog_length(cmd_parms *cmd, void *dummy, const char *arg)
663 server_rec *s = cmd->server;
664 cgid_server_conf *conf =
665 (cgid_server_conf *) ap_get_module_config(s->module_config, &cgid_module);
667 conf->logbytes = atol(arg);
671 static const char *set_scriptlog_buffer(cmd_parms *cmd, void *dummy, const char *arg)
673 server_rec *s = cmd->server;
674 cgid_server_conf *conf =
675 (cgid_server_conf *) ap_get_module_config(s->module_config, &cgid_module);
677 conf->bufbytes = atoi(arg);
681 static const char *set_script_socket(cmd_parms *cmd, void *dummy, const char *arg)
683 server_rec *s = cmd->server;
684 cgid_server_conf *conf =
685 (cgid_server_conf *) ap_get_module_config(s->module_config, &cgid_module);
687 conf->sockname = ap_server_root_relative(cmd->pool, arg);
691 static const command_rec cgid_cmds[] =
693 AP_INIT_TAKE1("ScriptLog", set_scriptlog, NULL, RSRC_CONF,
694 "the name of a log for script debugging info"),
695 AP_INIT_TAKE1("ScriptLogLength", set_scriptlog_length, NULL, RSRC_CONF,
696 "the maximum length (in bytes) of the script debug log"),
697 AP_INIT_TAKE1("ScriptLogBuffer", set_scriptlog_buffer, NULL, RSRC_CONF,
698 "the maximum size (in bytes) to record of a POST request"),
699 AP_INIT_TAKE1("Scriptsock", set_script_socket, NULL, RSRC_CONF,
700 "the name of the socket to use for communication with "
705 static int log_scripterror(request_rec *r, cgid_server_conf * conf, int ret,
706 int show_errno, char *error)
708 apr_file_t *f = NULL;
710 char time_str[AP_CTIME_LEN];
712 ap_log_rerror(APLOG_MARK, show_errno|APLOG_ERR, errno, r,
713 "%s: %s", error, r->filename);
715 if (!conf->logname ||
716 ((stat(ap_server_root_relative(r->pool, conf->logname), &finfo) == 0)
717 && (finfo.st_size > conf->logbytes)) ||
718 (apr_open(&f, ap_server_root_relative(r->pool, conf->logname),
719 APR_APPEND|APR_WRITE|APR_CREATE, APR_OS_DEFAULT, r->pool) != APR_SUCCESS)) {
723 /* "%% [Wed Jun 19 10:53:21 1996] GET /cgid-bin/printenv HTTP/1.0" */
724 apr_ctime(time_str, apr_now());
725 apr_fprintf(f, "%%%% [%s] %s %s%s%s %s\n", time_str, r->method, r->uri,
726 r->args ? "?" : "", r->args ? r->args : "", r->protocol);
727 /* "%% 500 /usr/local/apache/cgid-bin */
728 apr_fprintf(f, "%%%% %d %s\n", ret, r->filename);
730 apr_fprintf(f, "%%error\n%s\n", error);
736 static int log_script(request_rec *r, cgid_server_conf * conf, int ret,
737 char *dbuf, const char *sbuf, BUFF *script_in, BUFF *script_err)
739 apr_array_header_t *hdrs_arr = ap_table_elts(r->headers_in);
740 apr_table_entry_t *hdrs = (apr_table_entry_t *) hdrs_arr->elts;
741 char argsbuffer[HUGE_STRING_LEN];
742 apr_file_t *f = NULL;
745 char time_str[AP_CTIME_LEN];
747 if (!conf->logname ||
748 ((stat(ap_server_root_relative(r->pool, conf->logname), &finfo) == 0)
749 && (finfo.st_size > conf->logbytes)) ||
750 (apr_open(&f, ap_server_root_relative(r->pool, conf->logname),
751 APR_APPEND|APR_WRITE|APR_CREATE, APR_OS_DEFAULT, r->pool) != APR_SUCCESS)) {
752 /* Soak up script output */
753 while (ap_bgets(argsbuffer, HUGE_STRING_LEN, script_in) > 0)
756 while (ap_bgets(argsbuffer, HUGE_STRING_LEN, script_err) > 0)
762 /* "%% [Wed Jun 19 10:53:21 1996] GET /cgid-bin/printenv HTTP/1.0" */
763 apr_ctime(time_str, apr_now());
764 apr_fprintf(f, "%%%% [%s] %s %s%s%s %s\n", time_str, r->method, r->uri,
765 r->args ? "?" : "", r->args ? r->args : "", r->protocol);
766 /* "%% 500 /usr/local/apache/cgid-bin" */
767 apr_fprintf(f, "%%%% %d %s\n", ret, r->filename);
769 apr_puts("%request\n", f);
770 for (i = 0; i < hdrs_arr->nelts; ++i) {
773 apr_fprintf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val);
775 if ((r->method_number == M_POST || r->method_number == M_PUT)
777 apr_fprintf(f, "\n%s\n", dbuf);
780 apr_puts("%response\n", f);
781 hdrs_arr = ap_table_elts(r->err_headers_out);
782 hdrs = (apr_table_entry_t *) hdrs_arr->elts;
784 for (i = 0; i < hdrs_arr->nelts; ++i) {
787 apr_fprintf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val);
791 apr_fprintf(f, "%s\n", sbuf);
793 if (ap_bgets(argsbuffer, HUGE_STRING_LEN, script_in) > 0) {
794 apr_puts("%stdout\n", f);
795 apr_puts(argsbuffer, f);
796 while (ap_bgets(argsbuffer, HUGE_STRING_LEN, script_in) > 0)
797 apr_puts(argsbuffer, f);
802 if (ap_bgets(argsbuffer, HUGE_STRING_LEN, script_err) > 0) {
803 apr_puts("%stderr\n", f);
804 apr_puts(argsbuffer, f);
805 while (ap_bgets(argsbuffer, HUGE_STRING_LEN, script_err) > 0)
806 apr_puts(argsbuffer, f);
811 ap_bclose(script_in);
813 ap_bclose(script_err);
822 /****************************************************************
824 * Actual cgid handling...
826 static int cgid_handler(request_rec *r)
828 int retval, nph, dbpos = 0;
829 char *argv0, *dbuf = NULL;
831 char argsbuffer[HUGE_STRING_LEN];
832 void *sconf = r->server->module_config;
833 cgid_server_conf *conf = (cgid_server_conf *) ap_get_module_config(sconf, &cgid_module);
834 int is_included = !strcmp(r->protocol, "INCLUDED");
837 struct sockaddr_un unix_addr;
838 apr_socket_t *tempsock = NULL;
841 script = ap_bcreate(r->pool, B_RDWR);
843 if (r->method_number == M_OPTIONS) {
844 /* 99 out of 100 cgid scripts, this is all they support */
845 r->allowed |= (1 << M_GET);
846 r->allowed |= (1 << M_POST);
850 if ((argv0 = strrchr(r->filename, '/')) != NULL)
855 nph = !(strncmp(argv0, "nph-", 4));
857 if ((argv0 = strrchr(r->filename, '/')) != NULL)
862 if (!(ap_allow_options(r) & OPT_EXECCGI) && !is_scriptaliased(r))
863 return log_scripterror(r, conf, HTTP_FORBIDDEN, APLOG_NOERRNO,
864 "Options ExecCGI is off in this directory");
865 if (nph && is_included)
866 return log_scripterror(r, conf, HTTP_FORBIDDEN, APLOG_NOERRNO,
867 "attempt to include NPH CGI script");
869 #if defined(OS2) || defined(WIN32)
870 /* Allow for cgid files without the .EXE extension on them under OS/2 */
871 if (r->finfo.st_mode == 0) {
875 newfile = apr_pstrcat(r->pool, r->filename, ".EXE", NULL);
877 if ((stat(newfile, &statbuf) != 0) || (!S_ISREG(statbuf.st_mode))) {
878 return log_scripterror(r, conf, HTTP_NOT_FOUND, 0,
879 "script not found or unable to stat");
881 r->filename = newfile;
885 if (r->finfo.protection == 0)
886 return log_scripterror(r, conf, HTTP_NOT_FOUND, APLOG_NOERRNO,
887 "script not found or unable to stat");
889 if (r->finfo.filetype == APR_DIR)
890 return log_scripterror(r, conf, HTTP_FORBIDDEN, APLOG_NOERRNO,
891 "attempt to invoke directory as script");
893 if (!ap_suexec_enabled) {
894 if (!ap_can_exec(&r->finfo))
895 return log_scripterror(r, conf, HTTP_FORBIDDEN, APLOG_NOERRNO,
896 "file permissions deny server execution");
899 ap_add_common_vars(r);
901 env = ap_create_environment(r->pool, r->subprocess_env);
903 if ((sd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
904 return log_scripterror(r, conf, HTTP_NOT_FOUND, 0,
905 "unable to create socket to cgi daemon");
907 memset(&unix_addr, 0, sizeof(unix_addr));
908 unix_addr.sun_family = AF_UNIX;
909 strcpy(unix_addr.sun_path, conf->sockname);
911 if (connect(sd, (struct sockaddr *)&unix_addr, sizeof(unix_addr)) < 0) {
912 return log_scripterror(r, conf, HTTP_NOT_FOUND, 0,
913 "unable to connect to cgi daemon");
916 send_req(sd, r, argv0, env);
918 apr_put_os_sock(&tempsock, &sd, pcgi);
920 iol = ap_iol_attach_socket(pcgi, tempsock);
922 ap_bpush_iol(script, iol);
924 if ((retval = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR)))
927 if ((argv0 = strrchr(r->filename, '/')) != NULL)
932 /* Transfer any put/post args, CERN style...
933 * Note that we already ignore SIGPIPE in the core server.
936 if (ap_should_client_block(r)) {
937 int dbsize, len_read;
940 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);
958 ap_bwrite(script, argsbuffer, len_read, &nbytes);
959 if (nbytes < len_read) {
960 /* silly script stopped reading, soak up remaining message */
961 while (ap_get_client_block(r, argsbuffer, HUGE_STRING_LEN) > 0) {
972 /* Handle script return... */
973 if (script && !nph) {
974 const char *location;
975 char sbuf[MAX_STRING_LEN];
978 if ((ret = ap_scan_script_header_err_buff(r, script, sbuf))) {
979 return log_script(r, conf, ret, dbuf, sbuf, script, NULL);
982 location = apr_table_get(r->headers_out, "Location");
984 if (location && location[0] == '/' && r->status == 200) {
986 /* Soak up all the script output */
987 while (ap_bgets(argsbuffer, HUGE_STRING_LEN, script) > 0) {
990 /* This redirect needs to be a GET no matter what the original
993 r->method = apr_pstrdup(r->pool, "GET");
994 r->method_number = M_GET;
996 /* We already read the message body (if any), so don't allow
997 * the redirected request to think it has one. We can ignore
998 * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR.
1000 apr_table_unset(r->headers_in, "Content-Length");
1002 ap_internal_redirect_handler(location, r);
1005 else if (location && r->status == 200) {
1006 /* XX Note that if a script wants to produce its own Redirect
1007 * body, it now has to explicitly *say* "Status: 302"
1009 return HTTP_MOVED_TEMPORARILY;
1012 ap_send_http_header(r);
1013 if (!r->header_only) {
1014 ap_send_fb(script, r);
1019 if (script && nph) {
1020 ap_send_fb(script, r);
1023 return OK; /* NOT r->status, even if it has changed. */
1026 static const handler_rec cgid_handlers[] =
1028 {CGI_MAGIC_TYPE, cgid_handler},
1029 {"cgi-script", cgid_handler},
1033 static void register_hook(void)
1035 ap_hook_post_config(cgid_init, NULL, NULL, AP_HOOK_MIDDLE);
1038 module MODULE_VAR_EXPORT cgid_module = {
1039 STANDARD20_MODULE_STUFF,
1040 NULL, /* dir config creater */
1041 NULL, /* dir merger --- default is to override */
1042 create_cgid_config, /* server config */
1043 merge_cgid_config, /* merge server config */
1044 cgid_cmds, /* command table */
1045 cgid_handlers, /* handlers */
1046 register_hook /* register_handlers */