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 "apr_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"
94 #include "mod_suexec.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 AP_MODULE_DECLARE_DATA cgid_module;
110 static void cgid_init(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *main_server);
112 static apr_pool_t *pcgi;
113 static int total_modules = 0;
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;
153 /* If a request includes query info in the URL (stuff after "?"), and
154 * the query info does not contain "=" (indicative of a FORM submission),
155 * then this routine is called to create the argument list to be passed
156 * to the CGI script. When suexec is enabled, the suexec path, user, and
157 * group are the first three arguments to be passed; if not, all three
158 * must be NULL. The query info is split into separate arguments, where
159 * "+" is the separator between keyword arguments.
161 * XXXX: note that the WIN32 code uses one of the suexec strings
162 * to pass an interpreter name. Remember this if changing the way they
163 * are handled in create_argv.
166 static char **create_argv(apr_pool_t *p, char *path, char *user, char *group,
167 char *av0, const char *args)
174 /* count the number of keywords */
176 for (x = 0, numwords = 1; args[x]; x++) {
177 if (args[x] == '+') {
182 if (numwords > APACHE_ARG_MAX - 5) {
183 numwords = APACHE_ARG_MAX - 5; /* Truncate args to prevent overrun */
185 av = (char **) apr_pcalloc(p, (numwords + 5) * sizeof(char *));
197 av[idx++] = apr_pstrdup(p, av0);
199 for (x = 1; x <= numwords; x++) {
200 w = ap_getword_nulls(p, &args, '+');
203 av[idx++] = ap_escape_shell_cmd(p, w);
210 static void cgid_maint(int reason, void *data, apr_wait_t status)
212 #if APR_HAS_OTHER_CHILD
215 case APR_OC_REASON_DEATH:
216 case APR_OC_REASON_LOST:
217 /* stop gap to make sure everything else works. In the end,
218 * we'll just restart the cgid server. */
219 apr_destroy_pool(pcgi);
220 kill(getppid(), SIGWINCH);
222 case APR_OC_REASON_RESTART:
223 case APR_OC_REASON_UNREGISTER:
224 apr_destroy_pool(pcgi);
231 static void get_req(int fd, request_rec *r, char **filename, char **argv0, char ***env)
236 core_dir_config *temp_core;
238 module *suexec_mod = ap_find_linked_module("mod_suexec.c");
240 r->server = apr_pcalloc(r->pool, sizeof(server_rec));
242 read(fd, &j, sizeof(int));
243 read(fd, &len, sizeof(int));
244 data = apr_pcalloc(r->pool, len + 1); /* get a cleared byte for final '\0' */
245 i = read(fd, data, len);
247 r->filename = ap_getword(r->pool, (const char **)&data, '\n');
248 *argv0 = ap_getword(r->pool, (const char **)&data, '\n');
250 r->uri = ap_getword(r->pool, (const char **)&data, '\n');
252 environ = apr_pcalloc(r->pool, (j + 2) *sizeof(char *));
254 for (i = 0; i < j; i++) {
255 environ[i] = ap_getword(r->pool, (const char **)&data, '\n');
258 r->args = ap_getword(r->pool, (const char **)&data, '\n');
260 read(fd, &i, sizeof(int));
262 /* add 1, so that if i == 0, we still malloc something. */
264 dconf = (void **) apr_pcalloc(r->pool, sizeof(void *) * (total_modules + DYNAMIC_MODULE_LIMIT));
266 temp_core = (core_dir_config *)apr_palloc(r->pool, sizeof(core_module));
268 dconf[i] = (void *)temp_core;
271 suexec_config_t *suexec_cfg = apr_pcalloc(r->pool, sizeof(*suexec_cfg));
273 read(fd, &i, sizeof(int));
274 read(fd, &suexec_cfg->ugid.uid, sizeof(uid_t));
275 read(fd, &suexec_cfg->ugid.gid, sizeof(gid_t));
276 read(fd, &suexec_cfg->active, sizeof(int));
277 dconf[i] = (void *)suexec_cfg;
280 r->per_dir_config = dconf;
283 read(fd, &j, sizeof(int));
285 temp_core->limit_cpu = (struct rlimit *)apr_palloc (sizeof(struct rlimit));
286 read(fd, temp_core->limit_cpu, sizeof(struct rlimit));
289 temp_core->limit_cpu = NULL;
293 #if defined (RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
294 read(fd, &j, sizeof(int));
296 temp_core->limit_mem = (struct rlimit *)apr_palloc(r->pool, sizeof(struct rlimit));
297 read(fd, temp_core->limit_mem, sizeof(struct rlimit));
300 temp_core->limit_mem = NULL;
305 read(fd, &j, sizeof(int));
307 temp_core->limit_nproc = (struct rlimit *)apr_palloc(r->pool, sizeof(struct rlimit));
308 read(fd, temp_core->limit_nproc, sizeof(struct rlimit));
311 temp_core->limit_nproc = NULL;
315 /* For right now, just make the notes table. At some point we will need
316 * to actually fill this out, but for now we just don't want suexec to
319 r->notes = apr_make_table(r->pool, 1);
324 static void send_req(int fd, request_rec *r, char *argv0, char **env)
329 module *suexec_mod = ap_find_linked_module("mod_suexec.c");
331 data = apr_pstrcat(r->pool, r->filename, "\n", argv0, "\n", r->uri, "\n",
334 for (i =0; env[i]; i++) {
338 if (write(fd, &i, sizeof(int)) < 0) {
339 ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r,
340 "write to cgi daemon process");
343 for (i = 0; env[i]; i++) {
344 data = apr_pstrcat(r->pool, data, env[i], "\n", NULL);
346 data = apr_pstrcat(r->pool, data, r->args, NULL);
348 if (write(fd, &len, sizeof(int)) < 0) {
349 ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r,
350 "write to cgi daemon process");
352 if (write(fd, data, len) < 0) {
353 ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r,
354 "write to cgi daemon process");
356 if (write(fd, &core_module.module_index, sizeof(int)) < 0) {
357 ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r,
358 "write to cgi daemon process");
361 suexec_config_t *suexec_cfg = ap_get_module_config(r->per_dir_config,
364 write(fd, &suexec_mod->module_index, sizeof(int));
365 write(fd, &suexec_cfg->ugid.uid, sizeof(uid_t));
366 write(fd, &suexec_cfg->ugid.gid, sizeof(gid_t));
367 write(fd, &suexec_cfg->active, sizeof(int));
372 if (conf->limit_cpu) {
374 write(fd, &len, sizeof(int));
375 write(fd, conf->limit_cpu, sizeof(struct rlimit));
379 write(fd, &len, sizeof(int));
383 #if defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
384 if (conf->limit_mem) {
386 write(fd, &len, sizeof(int));
387 write(fd, conf->limit_mem, sizeof(struct rlimit));
391 write(fd, &len, sizeof(int));
396 if (conf->limit_nproc) {
398 write(fd, &len, sizeof(int));
399 write(fd, conf->limit_nproc, sizeof(struct rlimit));
403 write(fd, &len, sizeof(int));
409 static int cgid_server(void *data)
411 struct sockaddr_un unix_addr;
415 server_rec *main_server = data;
416 cgid_server_conf *sconf = (cgid_server_conf *)ap_get_module_config(
417 main_server->module_config, &cgid_module);
419 apr_signal(SIGCHLD, SIG_IGN);
420 if (unlink(sconf->sockname) < 0 && errno != ENOENT) {
421 ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
422 "Couldn't unlink unix domain socket %s",
424 /* just a warning; don't bail out */
427 if ((sd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
428 ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
429 "Couldn't create unix domain socket");
433 memset(&unix_addr, 0, sizeof(unix_addr));
434 unix_addr.sun_family = AF_UNIX;
435 strcpy(unix_addr.sun_path, sconf->sockname);
437 omask = umask(0077); /* so that only Apache can use socket */
438 rc = bind(sd, (struct sockaddr *)&unix_addr, sizeof(unix_addr));
439 umask(omask); /* can't fail, so can't clobber errno */
441 ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
442 "Couldn't bind unix domain socket %s",
447 if (listen(sd, DEFAULT_CGID_LISTENBACKLOG) < 0) {
448 ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
449 "Couldn't listen on unix domain socket");
454 if (chown(sconf->sockname, unixd_config.user_id, -1) < 0) {
455 ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
456 "Couldn't change owner of unix domain socket %s",
462 unixd_setup_child(); /* if running as root, switch to configured user/group */
464 int errfileno = STDERR_FILENO;
468 const char * const *argv;
471 apr_procattr_t *procattr = NULL;
472 apr_proc_t *procnew = NULL;
476 len = sizeof(unix_addr);
477 sd2 = accept(sd, (struct sockaddr *)&unix_addr, &len);
479 if (errno != EINTR) {
480 ap_log_error(APLOG_MARK, APLOG_ERR, errno,
482 "Error accepting on cgid socket.");
487 apr_create_pool(&p, pcgi);
489 r = apr_pcalloc(p, sizeof(request_rec));
490 procnew = apr_pcalloc(p, sizeof(*procnew));
492 get_req(sd2, r, &filename, &argv0, &env);
493 apr_put_os_file(&r->server->error_log, &errfileno, r->pool);
494 apr_put_os_file(&inout, &sd2, r->pool);
496 if (((rc = apr_createprocattr_init(&procattr, p)) != APR_SUCCESS) ||
497 ((rc = apr_setprocattr_io(procattr,
500 APR_CHILD_BLOCK)) != APR_SUCCESS) ||
501 ((rc = apr_setprocattr_childin(procattr, inout, NULL)) != APR_SUCCESS) ||
502 ((rc = apr_setprocattr_childout(procattr, inout, NULL)) != APR_SUCCESS) ||
503 ((rc = apr_setprocattr_childerr(procattr, r->server->error_log, NULL)) != APR_SUCCESS) ||
504 ((rc = apr_setprocattr_dir(procattr,
505 ap_make_dirstr_parent(r->pool, r->filename))) != APR_SUCCESS) ||
506 ((rc = apr_setprocattr_cmdtype(procattr, APR_PROGRAM)) != APR_SUCCESS)) {
507 /* Something bad happened, tell the world. */
508 ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r,
509 "couldn't set child process attributes: %s", r->filename);
512 argv = (const char * const *)create_argv(r->pool, NULL, NULL, NULL, argv0, r->args);
513 rc = ap_os_create_privileged_process(r, procnew, argv0, argv,
514 (const char * const *)env,
518 if (rc != APR_SUCCESS) {
519 /* Bad things happened. Everyone should have cleaned up. */
520 ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r,
521 "couldn't create child process: %d: %s", rc, r->filename);
528 static void cgid_init(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp,
529 server_rec *main_server)
535 const char *userdata_key = "cgid_init";
538 apr_get_userdata(&data, userdata_key, main_server->process->pool);
541 apr_set_userdata((const void *)1, userdata_key,
542 apr_null_cleanup, main_server->process->pool);
546 apr_create_pool(&pcgi, p);
549 for (m = ap_preloaded_modules; *m != NULL; m++)
553 if ((pid = fork()) < 0) {
554 ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
555 "Couldn't spawn cgid daemon process");
558 cgid_server(main_server);
561 procnew = apr_pcalloc(p, sizeof(*procnew));
563 procnew->err = procnew->in = procnew->out = NULL;
564 apr_note_subprocess(p, procnew, kill_after_timeout);
565 #if APR_HAS_OTHER_CHILD
566 apr_register_other_child(procnew, cgid_maint, &procnew->pid, NULL, p);
571 static void *create_cgid_config(apr_pool_t *p, server_rec *s)
573 cgid_server_conf *c =
574 (cgid_server_conf *) apr_pcalloc(p, sizeof(cgid_server_conf));
577 c->logbytes = DEFAULT_LOGBYTES;
578 c->bufbytes = DEFAULT_BUFBYTES;
579 c->sockname = ap_server_root_relative(p, DEFAULT_SOCKET);
583 static void *merge_cgid_config(apr_pool_t *p, void *basev, void *overridesv)
585 cgid_server_conf *base = (cgid_server_conf *) basev, *overrides = (cgid_server_conf *) overridesv;
587 return overrides->logname ? overrides : base;
590 static const char *set_scriptlog(cmd_parms *cmd, void *dummy, const char *arg)
592 server_rec *s = cmd->server;
593 cgid_server_conf *conf =
594 (cgid_server_conf *) ap_get_module_config(s->module_config, &cgid_module);
600 static const char *set_scriptlog_length(cmd_parms *cmd, void *dummy, const char *arg)
602 server_rec *s = cmd->server;
603 cgid_server_conf *conf =
604 (cgid_server_conf *) ap_get_module_config(s->module_config, &cgid_module);
606 conf->logbytes = atol(arg);
610 static const char *set_scriptlog_buffer(cmd_parms *cmd, void *dummy, const char *arg)
612 server_rec *s = cmd->server;
613 cgid_server_conf *conf =
614 (cgid_server_conf *) ap_get_module_config(s->module_config, &cgid_module);
616 conf->bufbytes = atoi(arg);
620 static const char *set_script_socket(cmd_parms *cmd, void *dummy, const char *arg)
622 server_rec *s = cmd->server;
623 cgid_server_conf *conf =
624 (cgid_server_conf *) ap_get_module_config(s->module_config, &cgid_module);
626 conf->sockname = ap_server_root_relative(cmd->pool, arg);
630 static const command_rec cgid_cmds[] =
632 AP_INIT_TAKE1("ScriptLog", set_scriptlog, NULL, RSRC_CONF,
633 "the name of a log for script debugging info"),
634 AP_INIT_TAKE1("ScriptLogLength", set_scriptlog_length, NULL, RSRC_CONF,
635 "the maximum length (in bytes) of the script debug log"),
636 AP_INIT_TAKE1("ScriptLogBuffer", set_scriptlog_buffer, NULL, RSRC_CONF,
637 "the maximum size (in bytes) to record of a POST request"),
638 AP_INIT_TAKE1("Scriptsock", set_script_socket, NULL, RSRC_CONF,
639 "the name of the socket to use for communication with "
644 static int log_scripterror(request_rec *r, cgid_server_conf * conf, int ret,
645 apr_status_t rv, char *error)
647 apr_file_t *f = NULL;
649 char time_str[APR_CTIME_LEN];
650 int log_flags = rv ? APLOG_ERR : APLOG_NOERRNO | APLOG_ERR;
652 ap_log_rerror(APLOG_MARK, log_flags, rv, r,
653 "%s: %s", error, r->filename);
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)) {
663 /* "%% [Wed Jun 19 10:53:21 1996] GET /cgid-bin/printenv HTTP/1.0" */
664 apr_ctime(time_str, apr_now());
665 apr_fprintf(f, "%%%% [%s] %s %s%s%s %s\n", time_str, r->method, r->uri,
666 r->args ? "?" : "", r->args ? r->args : "", r->protocol);
667 /* "%% 500 /usr/local/apache/cgid-bin */
668 apr_fprintf(f, "%%%% %d %s\n", ret, r->filename);
670 apr_fprintf(f, "%%error\n%s\n", error);
676 static int log_script(request_rec *r, cgid_server_conf * conf, int ret,
677 char *dbuf, const char *sbuf, apr_file_t *script_in, apr_file_t *script_err)
679 apr_array_header_t *hdrs_arr = apr_table_elts(r->headers_in);
680 apr_table_entry_t *hdrs = (apr_table_entry_t *) hdrs_arr->elts;
681 char argsbuffer[HUGE_STRING_LEN];
682 apr_file_t *f = NULL;
685 char time_str[APR_CTIME_LEN];
687 if (!conf->logname ||
688 ((stat(ap_server_root_relative(r->pool, conf->logname), &finfo) == 0)
689 && (finfo.st_size > conf->logbytes)) ||
690 (apr_open(&f, ap_server_root_relative(r->pool, conf->logname),
691 APR_APPEND|APR_WRITE|APR_CREATE, APR_OS_DEFAULT, r->pool) != APR_SUCCESS)) {
692 /* Soak up script output */
693 while (apr_fgets(argsbuffer, HUGE_STRING_LEN, script_in) == 0)
696 while (apr_fgets(argsbuffer, HUGE_STRING_LEN, script_err) == 0)
702 /* "%% [Wed Jun 19 10:53:21 1996] GET /cgid-bin/printenv HTTP/1.0" */
703 apr_ctime(time_str, apr_now());
704 apr_fprintf(f, "%%%% [%s] %s %s%s%s %s\n", time_str, r->method, r->uri,
705 r->args ? "?" : "", r->args ? r->args : "", r->protocol);
706 /* "%% 500 /usr/local/apache/cgid-bin" */
707 apr_fprintf(f, "%%%% %d %s\n", ret, r->filename);
709 apr_puts("%request\n", f);
710 for (i = 0; i < hdrs_arr->nelts; ++i) {
713 apr_fprintf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val);
715 if ((r->method_number == M_POST || r->method_number == M_PUT)
717 apr_fprintf(f, "\n%s\n", dbuf);
720 apr_puts("%response\n", f);
721 hdrs_arr = apr_table_elts(r->err_headers_out);
722 hdrs = (apr_table_entry_t *) hdrs_arr->elts;
724 for (i = 0; i < hdrs_arr->nelts; ++i) {
727 apr_fprintf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val);
731 apr_fprintf(f, "%s\n", sbuf);
733 if (apr_fgets(argsbuffer, HUGE_STRING_LEN, script_in) == 0) {
734 apr_puts("%stdout\n", f);
735 apr_puts(argsbuffer, f);
736 while (apr_fgets(argsbuffer, HUGE_STRING_LEN, script_in) == 0)
737 apr_puts(argsbuffer, f);
742 if (apr_fgets(argsbuffer, HUGE_STRING_LEN, script_err) == 0) {
743 apr_puts("%stderr\n", f);
744 apr_puts(argsbuffer, f);
745 while (apr_fgets(argsbuffer, HUGE_STRING_LEN, script_err) == 0)
746 apr_puts(argsbuffer, f);
751 apr_close(script_in);
753 apr_close(script_err);
762 /****************************************************************
764 * Actual cgid handling...
766 static int cgid_handler(request_rec *r)
768 int retval, nph, dbpos = 0;
769 char *argv0, *dbuf = NULL;
770 apr_bucket_brigade *bb;
772 char argsbuffer[HUGE_STRING_LEN];
774 cgid_server_conf *conf;
778 struct sockaddr_un unix_addr;
779 apr_file_t *tempsock;
782 if(strcmp(r->handler,CGI_MAGIC_TYPE) && strcmp(r->handler,"cgi-script"))
785 if (r->method_number == M_OPTIONS) {
786 /* 99 out of 100 cgid scripts, this is all they support */
787 r->allowed |= (1 << M_GET);
788 r->allowed |= (1 << M_POST);
792 sconf = r->server->module_config;
793 conf = (cgid_server_conf *) ap_get_module_config(sconf, &cgid_module);
794 is_included = !strcmp(r->protocol, "INCLUDED");
796 if ((argv0 = strrchr(r->filename, '/')) != NULL)
801 nph = !(strncmp(argv0, "nph-", 4));
803 if ((argv0 = strrchr(r->filename, '/')) != NULL)
808 if (!(ap_allow_options(r) & OPT_EXECCGI) && !is_scriptaliased(r))
809 return log_scripterror(r, conf, HTTP_FORBIDDEN, 0,
810 "Options ExecCGI is off in this directory");
811 if (nph && is_included)
812 return log_scripterror(r, conf, HTTP_FORBIDDEN, 0,
813 "attempt to include NPH CGI script");
815 #if defined(OS2) || defined(WIN32)
816 #error mod_cgid does not work on this platform. If you teach it to, look
817 #error at mod_cgi.c for required code in this path.
819 if (r->finfo.filetype == 0)
820 return log_scripterror(r, conf, HTTP_NOT_FOUND, 0,
821 "script not found or unable to stat");
823 if (r->finfo.filetype == APR_DIR)
824 return log_scripterror(r, conf, HTTP_FORBIDDEN, 0,
825 "attempt to invoke directory as script");
827 if (!ap_suexec_enabled) {
828 if (!ap_can_exec(&r->finfo))
829 return log_scripterror(r, conf, HTTP_FORBIDDEN, 0,
830 "file permissions deny server execution");
833 ap_add_common_vars(r);
835 env = ap_create_environment(r->pool, r->subprocess_env);
837 if ((sd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
838 return log_scripterror(r, conf, HTTP_INTERNAL_SERVER_ERROR, errno,
839 "unable to create socket to cgi daemon");
841 memset(&unix_addr, 0, sizeof(unix_addr));
842 unix_addr.sun_family = AF_UNIX;
843 strcpy(unix_addr.sun_path, conf->sockname);
845 if (connect(sd, (struct sockaddr *)&unix_addr, sizeof(unix_addr)) < 0) {
846 return log_scripterror(r, conf, HTTP_INTERNAL_SERVER_ERROR, errno,
847 "unable to connect to cgi daemon");
850 send_req(sd, r, argv0, env);
852 /* We are putting the tempsock variable into a file so that we can use
853 * a pipe bucket to send the data to the client.
855 apr_put_os_file(&tempsock, &sd, r->pool);
857 if ((retval = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR)))
860 if ((argv0 = strrchr(r->filename, '/')) != NULL)
865 /* Transfer any put/post args, CERN style...
866 * Note that we already ignore SIGPIPE in the core server.
869 if (ap_should_client_block(r)) {
870 int dbsize, len_read;
873 dbuf = apr_pcalloc(r->pool, conf->bufbytes + 1);
878 ap_get_client_block(r, argsbuffer, HUGE_STRING_LEN)) > 0) {
880 if ((dbpos + len_read) > conf->bufbytes) {
881 dbsize = conf->bufbytes - dbpos;
886 memcpy(dbuf + dbpos, argsbuffer, dbsize);
890 apr_write(tempsock, argsbuffer, &nbytes);
891 if (nbytes < len_read) {
892 /* silly script stopped reading, soak up remaining message */
893 while (ap_get_client_block(r, argsbuffer, HUGE_STRING_LEN) > 0) {
899 shutdown(sd, 1); /* done writing; force EOF on child's stdin */
902 /* Handle script return... */
904 const char *location;
905 char sbuf[MAX_STRING_LEN];
908 if ((ret = ap_scan_script_header_err(r, tempsock, sbuf))) {
909 return log_script(r, conf, ret, dbuf, sbuf, tempsock, NULL);
912 location = apr_table_get(r->headers_out, "Location");
914 if (location && location[0] == '/' && r->status == 200) {
916 /* Soak up all the script output */
917 while (apr_fgets(argsbuffer, HUGE_STRING_LEN, tempsock) > 0) {
920 /* This redirect needs to be a GET no matter what the original
923 r->method = apr_pstrdup(r->pool, "GET");
924 r->method_number = M_GET;
926 /* We already read the message body (if any), so don't allow
927 * the redirected request to think it has one. We can ignore
928 * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR.
930 apr_table_unset(r->headers_in, "Content-Length");
932 ap_internal_redirect_handler(location, r);
935 else if (location && r->status == 200) {
936 /* XX Note that if a script wants to produce its own Redirect
937 * body, it now has to explicitly *say* "Status: 302"
939 return HTTP_MOVED_TEMPORARILY;
942 ap_send_http_header(r);
943 if (!r->header_only) {
944 bb = apr_brigade_create(r->pool);
945 b = apr_bucket_create_pipe(tempsock);
946 APR_BRIGADE_INSERT_TAIL(bb, b);
947 b = apr_bucket_create_eos();
948 APR_BRIGADE_INSERT_TAIL(bb, b);
949 ap_pass_brigade(r->output_filters, bb);
954 bb = apr_brigade_create(r->pool);
955 b = apr_bucket_create_pipe(tempsock);
956 APR_BRIGADE_INSERT_TAIL(bb, b);
957 b = apr_bucket_create_eos();
958 APR_BRIGADE_INSERT_TAIL(bb, b);
959 ap_pass_brigade(r->output_filters, bb);
964 return OK; /* NOT r->status, even if it has changed. */
967 static void register_hook(apr_pool_t *p)
969 ap_hook_post_config(cgid_init, NULL, NULL, APR_HOOK_MIDDLE);
970 ap_hook_handler(cgid_handler, NULL, NULL, APR_HOOK_MIDDLE);
973 module AP_MODULE_DECLARE_DATA cgid_module = {
974 STANDARD20_MODULE_STUFF,
975 NULL, /* dir config creater */
976 NULL, /* dir merger --- default is to override */
977 create_cgid_config, /* server config */
978 merge_cgid_config, /* merge server config */
979 cgid_cmds, /* command table */
980 register_hook /* register_handlers */