1 /* ====================================================================
2 * The Apache Software License, Version 1.1
4 * Copyright (c) 2000-2002 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
73 #include "apr_strings.h"
74 #include "apr_general.h"
75 #include "apr_file_io.h"
76 #include "apr_portable.h"
77 #include "apr_buckets.h"
78 #include "apr_optional.h"
79 #include "apr_signal.h"
81 #define APR_WANT_STRFUNC
84 #if APR_HAVE_SYS_SOCKET_H
85 #include <sys/socket.h>
90 #if APR_HAVE_SYS_TYPES_H
91 #include <sys/types.h>
96 #include "util_filter.h"
98 #include "http_config.h"
99 #include "http_request.h"
100 #include "http_core.h"
101 #include "http_protocol.h"
102 #include "http_main.h"
103 #include "http_log.h"
104 #include "util_script.h"
107 #include "mod_suexec.h"
108 #include "../filters/mod_include.h"
110 #include "mod_core.h"
113 /* ### should be tossed in favor of APR */
114 #include <sys/stat.h>
115 #include <sys/un.h> /* for sockaddr_un */
118 module AP_MODULE_DECLARE_DATA cgid_module;
120 static int cgid_init(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *main_server);
121 static int handle_exec(include_ctx_t *ctx, apr_bucket_brigade **bb, request_rec *r,
122 ap_filter_t *f, apr_bucket *head_ptr, apr_bucket **inserted_head);
124 static APR_OPTIONAL_FN_TYPE(ap_register_include_handler) *cgid_pfn_reg_with_ssi;
125 static APR_OPTIONAL_FN_TYPE(ap_ssi_get_tag_and_value) *cgid_pfn_gtv;
126 static APR_OPTIONAL_FN_TYPE(ap_ssi_parse_string) *cgid_pfn_ps;
128 static apr_pool_t *pcgi;
129 static int total_modules = 0;
130 static pid_t daemon_pid;
131 static int daemon_should_exit = 0;
133 /* Read and discard the data in the brigade produced by a CGI script */
134 static void discard_script_output(apr_bucket_brigade *bb);
136 /* KLUDGE --- for back-combatibility, we don't have to check ExecCGI
137 * in ScriptAliased directories, which means we need to know if this
138 * request came through ScriptAlias or not... so the Alias module
139 * leaves a note for us.
142 static int is_scriptaliased(request_rec *r)
144 const char *t = apr_table_get(r->notes, "alias-forced-type");
145 return t && (!strcasecmp(t, "cgi-script"));
148 /* Configuration stuff */
150 #define DEFAULT_LOGBYTES 10385760
151 #define DEFAULT_BUFBYTES 1024
152 #define DEFAULT_SOCKET DEFAULT_REL_RUNTIMEDIR "/cgisock"
156 #define GETPID_REQ 3 /* get the pid of script created for prior request */
158 /* DEFAULT_CGID_LISTENBACKLOG controls the max depth on the unix socket's
159 * pending connection queue. If a bunch of cgi requests arrive at about
160 * the same time, connections from httpd threads/processes will back up
161 * in the queue while the cgid process slowly forks off a child to process
162 * each connection on the unix socket. If the queue is too short, the
163 * httpd process will get ECONNREFUSED when trying to connect.
165 #ifndef DEFAULT_CGID_LISTENBACKLOG
166 #define DEFAULT_CGID_LISTENBACKLOG 100
169 /* DEFAULT_CONNECT_ATTEMPTS controls how many times we'll try to connect
170 * to the cgi daemon from the thread/process handling the cgi request.
171 * Generally we want to retry when we get ECONNREFUSED since it is
172 * probably because the listen queue is full. We need to try harder so
173 * the client doesn't see it as a 503 error.
175 * Set this to 0 to continually retry until the connect works or Apache
178 #ifndef DEFAULT_CONNECT_ATTEMPTS
179 #define DEFAULT_CONNECT_ATTEMPTS 15
183 const char *sockname;
190 int req_type; /* request type (CGI_REQ, SSI_REQ, etc.) */
191 unsigned long conn_id; /* connection id; daemon uses this as a hash value
192 * to find the script pid when it is time for that
193 * process to be cleaned up
195 int core_module_index;
197 int suexec_module_index;
198 suexec_config_t suexec_cfg;
200 apr_size_t filename_len;
201 apr_size_t argv0_len;
204 apr_size_t mod_userdir_user_len;
207 /* If a request includes query info in the URL (stuff after "?"), and
208 * the query info does not contain "=" (indicative of a FORM submission),
209 * then this routine is called to create the argument list to be passed
210 * to the CGI script. When suexec is enabled, the suexec path, user, and
211 * group are the first three arguments to be passed; if not, all three
212 * must be NULL. The query info is split into separate arguments, where
213 * "+" is the separator between keyword arguments.
215 static char **create_argv(apr_pool_t *p, char *path, char *user, char *group,
216 char *av0, const char *args)
223 /* count the number of keywords */
225 for (x = 0, numwords = 1; args[x]; x++) {
226 if (args[x] == '+') {
231 if (numwords > APACHE_ARG_MAX - 5) {
232 numwords = APACHE_ARG_MAX - 5; /* Truncate args to prevent overrun */
234 av = (char **) apr_pcalloc(p, (numwords + 5) * sizeof(char *));
246 av[idx++] = apr_pstrdup(p, av0);
248 for (x = 1; x <= numwords; x++) {
249 w = ap_getword_nulls(p, &args, '+');
252 av[idx++] = ap_escape_shell_cmd(p, w);
259 #if APR_HAS_OTHER_CHILD
260 static void cgid_maint(int reason, void *data, apr_wait_t status)
265 case APR_OC_REASON_DEATH:
266 case APR_OC_REASON_RESTART:
267 /* don't do anything; server is stopping or restarting */
268 apr_proc_other_child_unregister(data);
270 case APR_OC_REASON_LOST:
271 /* it would be better to restart just the cgid child
272 * process but for now we'll gracefully restart the entire
273 * server by sending AP_SIG_GRACEFUL to ourself, the httpd
276 kill(getpid(), AP_SIG_GRACEFUL);
278 case APR_OC_REASON_UNREGISTER:
279 /* we get here when pcgi is cleaned up; pcgi gets cleaned
280 * up when pconf gets cleaned up
282 kill(*sd, SIGHUP); /* send signal to daemon telling it to die */
288 /* deal with incomplete reads and signals
289 * assume you really have to read buf_size bytes
291 static apr_status_t sock_read(int fd, void *vbuf, size_t buf_size)
295 size_t bytes_read = 0;
299 rc = read(fd, buf + bytes_read, buf_size - bytes_read);
300 } while (rc < 0 && errno == EINTR);
304 case 0: /* unexpected */
309 } while (bytes_read < buf_size);
316 static apr_status_t sock_write(int fd, const void *buf, size_t buf_size)
321 rc = write(fd, buf, buf_size);
322 } while (rc < 0 && errno == EINTR);
330 static apr_status_t get_req(int fd, request_rec *r, char **argv0, char ***env,
336 core_dir_config *temp_core;
340 r->server = apr_pcalloc(r->pool, sizeof(server_rec));
342 /* read the request header */
343 stat = sock_read(fd, req, sizeof(*req));
344 if (stat != APR_SUCCESS) {
347 if (req->req_type == GETPID_REQ) {
348 /* no more data sent for this request */
352 /* handle module indexes and such */
353 dconf = (void **) apr_pcalloc(r->pool, sizeof(void *) * (total_modules + DYNAMIC_MODULE_LIMIT));
355 temp_core = (core_dir_config *)apr_palloc(r->pool, sizeof(core_module));
356 dconf[req->core_module_index] = (void *)temp_core;
358 if (req->have_suexec) {
359 dconf[req->suexec_module_index] = &req->suexec_cfg;
362 r->per_dir_config = (ap_conf_vector_t *)dconf;
364 /* Read the filename, argv0, uri, and args */
365 r->filename = apr_pcalloc(r->pool, req->filename_len + 1);
366 *argv0 = apr_pcalloc(r->pool, req->argv0_len + 1);
367 r->uri = apr_pcalloc(r->pool, req->uri_len + 1);
368 if ((stat = sock_read(fd, r->filename, req->filename_len)) != APR_SUCCESS ||
369 (stat = sock_read(fd, *argv0, req->argv0_len)) != APR_SUCCESS ||
370 (stat = sock_read(fd, r->uri, req->uri_len)) != APR_SUCCESS) {
374 r->args = apr_pcalloc(r->pool, req->args_len + 1); /* empty string if no args */
376 if ((stat = sock_read(fd, r->args, req->args_len)) != APR_SUCCESS) {
381 /* read the environment variables */
382 environ = apr_pcalloc(r->pool, (req->env_count + 2) *sizeof(char *));
383 for (i = 0; i < req->env_count; i++) {
386 if ((stat = sock_read(fd, &curlen, sizeof(curlen))) != APR_SUCCESS) {
389 environ[i] = apr_pcalloc(r->pool, curlen + 1);
390 if ((stat = sock_read(fd, environ[i], curlen)) != APR_SUCCESS) {
396 /* basic notes table to avoid segfaults */
397 r->notes = apr_table_make(r->pool, 1);
399 /* mod_userdir requires the mod_userdir_user note */
400 if (req->mod_userdir_user_len) {
401 user = apr_pcalloc(r->pool, req->mod_userdir_user_len + 1); /* last byte is '\0' */
402 stat = sock_read(fd, user, req->mod_userdir_user_len);
403 if (stat != APR_SUCCESS) {
406 apr_table_set(r->notes, "mod_userdir_user", (const char *)user);
411 sock_read(fd, &j, sizeof(int));
413 temp_core->limit_cpu = (struct rlimit *)apr_palloc (sizeof(struct rlimit));
414 sock_read(fd, temp_core->limit_cpu, sizeof(struct rlimit));
417 temp_core->limit_cpu = NULL;
421 #if defined (RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
422 sock_read(fd, &j, sizeof(int));
424 temp_core->limit_mem = (struct rlimit *)apr_palloc(r->pool, sizeof(struct rlimit));
425 sock_read(fd, temp_core->limit_mem, sizeof(struct rlimit));
428 temp_core->limit_mem = NULL;
433 sock_read(fd, &j, sizeof(int));
435 temp_core->limit_nproc = (struct rlimit *)apr_palloc(r->pool, sizeof(struct rlimit));
436 sock_read(fd, temp_core->limit_nproc, sizeof(struct rlimit));
439 temp_core->limit_nproc = NULL;
447 static apr_status_t send_req(int fd, request_rec *r, char *argv0, char **env,
452 module *suexec_mod = ap_find_linked_module("mod_suexec.c");
453 cgid_req_t req = {0};
454 suexec_config_t *suexec_cfg;
457 req.req_type = req_type;
458 req.conn_id = r->connection->id;
459 req.core_module_index = core_module.module_index;
462 req.suexec_module_index = suexec_mod->module_index;
463 suexec_cfg = ap_get_module_config(r->per_dir_config,
465 req.suexec_cfg = *suexec_cfg;
467 for (req.env_count = 0; env[req.env_count]; req.env_count++) {
470 req.filename_len = strlen(r->filename);
471 req.argv0_len = strlen(argv0);
472 req.uri_len = strlen(r->uri);
473 req.args_len = r->args ? strlen(r->args) : 0;
474 user = (const char *)apr_table_get(r->notes, "mod_userdir_user");
476 req.mod_userdir_user_len = strlen(user);
479 /* Write the request header */
480 if ((stat = sock_write(fd, &req, sizeof(req))) != APR_SUCCESS) {
484 /* Write filename, argv0, uri, and args */
485 if ((stat = sock_write(fd, r->filename, req.filename_len)) != APR_SUCCESS ||
486 (stat = sock_write(fd, argv0, req.argv0_len)) != APR_SUCCESS ||
487 (stat = sock_write(fd, r->uri, req.uri_len)) != APR_SUCCESS) {
491 if ((stat = sock_write(fd, r->args, req.args_len)) != APR_SUCCESS) {
496 /* write the environment variables */
497 for (i = 0; i < req.env_count; i++) {
498 apr_size_t curlen = strlen(env[i]);
500 if ((stat = sock_write(fd, &curlen, sizeof(curlen))) != APR_SUCCESS) {
504 if ((stat = sock_write(fd, env[i], curlen)) != APR_SUCCESS) {
509 /* send a minimal notes table */
511 if ((stat = sock_write(fd, user, req.mod_userdir_user_len)) != APR_SUCCESS) {
518 if (conf->limit_cpu) {
520 stat = sock_write(fd, &len, sizeof(int));
521 stat = sock_write(fd, conf->limit_cpu, sizeof(struct rlimit));
525 stat = sock_write(fd, &len, sizeof(int));
529 #if defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
530 if (conf->limit_mem) {
532 stat = sock_write(fd, &len, sizeof(int));
533 stat = sock_write(fd, conf->limit_mem, sizeof(struct rlimit));
537 stat = sock_write(fd, &len, sizeof(int));
542 if (conf->limit_nproc) {
544 stat = sock_write(fd, &len, sizeof(int));
545 stat = sock_write(fd, conf->limit_nproc, sizeof(struct rlimit));
549 stat = sock_write(fd, &len, sizeof(int));
556 static void daemon_signal_handler(int sig)
559 ++daemon_should_exit;
563 static int cgid_server(void *data)
565 struct sockaddr_un unix_addr;
570 server_rec *main_server = data;
571 cgid_server_conf *sconf = ap_get_module_config(main_server->module_config,
573 apr_hash_t *script_hash = apr_hash_make(pcgi);
575 apr_pool_create(&ptrans, pcgi);
577 apr_signal(SIGCHLD, SIG_IGN);
578 apr_signal(SIGHUP, daemon_signal_handler);
580 if (unlink(sconf->sockname) < 0 && errno != ENOENT) {
581 ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
582 "Couldn't unlink unix domain socket %s",
584 /* just a warning; don't bail out */
587 if ((sd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
588 ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
589 "Couldn't create unix domain socket");
593 memset(&unix_addr, 0, sizeof(unix_addr));
594 unix_addr.sun_family = AF_UNIX;
595 strcpy(unix_addr.sun_path, sconf->sockname);
597 omask = umask(0077); /* so that only Apache can use socket */
598 rc = bind(sd, (struct sockaddr *)&unix_addr, sizeof(unix_addr));
599 umask(omask); /* can't fail, so can't clobber errno */
601 ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
602 "Couldn't bind unix domain socket %s",
607 if (listen(sd, DEFAULT_CGID_LISTENBACKLOG) < 0) {
608 ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
609 "Couldn't listen on unix domain socket");
614 if (chown(sconf->sockname, unixd_config.user_id, -1) < 0) {
615 ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
616 "Couldn't change owner of unix domain socket %s",
622 unixd_setup_child(); /* if running as root, switch to configured user/group */
624 while (!daemon_should_exit) {
625 int errfileno = STDERR_FILENO;
628 const char * const *argv;
630 apr_int32_t out_pipe;
631 apr_int32_t err_pipe;
632 apr_cmdtype_e cmd_type;
634 apr_procattr_t *procattr = NULL;
635 apr_proc_t *procnew = NULL;
640 apr_pool_clear(ptrans);
642 len = sizeof(unix_addr);
643 sd2 = accept(sd, (struct sockaddr *)&unix_addr, &len);
645 if (errno != EINTR) {
646 ap_log_error(APLOG_MARK, APLOG_ERR, errno,
648 "Error accepting on cgid socket");
653 r = apr_pcalloc(ptrans, sizeof(request_rec));
654 procnew = apr_pcalloc(ptrans, sizeof(*procnew));
656 stat = get_req(sd2, r, &argv0, &env, &cgid_req);
657 if (stat != APR_SUCCESS) {
658 ap_log_error(APLOG_MARK, APLOG_ERR, stat,
660 "Error reading request on cgid socket");
665 if (cgid_req.req_type == GETPID_REQ) {
668 pid = (pid_t)apr_hash_get(script_hash, &cgid_req.conn_id, sizeof(cgid_req.conn_id));
669 if (write(sd2, &pid, sizeof(pid)) != sizeof(pid)) {
670 ap_log_error(APLOG_MARK, APLOG_ERR, 0,
672 "Error writing pid %" APR_PID_T_FMT " to handler", pid);
678 apr_os_file_put(&r->server->error_log, &errfileno, 0, r->pool);
679 apr_os_file_put(&inout, &sd2, 0, r->pool);
681 if (cgid_req.req_type == SSI_REQ) {
682 in_pipe = APR_NO_PIPE;
683 out_pipe = APR_FULL_BLOCK;
684 err_pipe = APR_NO_PIPE;
685 cmd_type = APR_SHELLCMD;
688 in_pipe = APR_CHILD_BLOCK;
689 out_pipe = APR_CHILD_BLOCK;
690 err_pipe = APR_CHILD_BLOCK;
691 cmd_type = APR_PROGRAM;
694 if (((rc = apr_procattr_create(&procattr, ptrans)) != APR_SUCCESS) ||
695 ((cgid_req.req_type == CGI_REQ) &&
696 (((rc = apr_procattr_io_set(procattr,
699 err_pipe)) != APR_SUCCESS) ||
700 /* XXX apr_procattr_child_*_set() is creating an unnecessary
701 * pipe between this process and the child being created...
702 * It is cleaned up with the temporary pool for this request.
704 ((rc = apr_procattr_child_err_set(procattr, r->server->error_log, NULL)) != APR_SUCCESS) ||
705 ((rc = apr_procattr_child_in_set(procattr, inout, NULL)) != APR_SUCCESS))) ||
706 ((rc = apr_procattr_child_out_set(procattr, inout, NULL)) != APR_SUCCESS) ||
707 ((rc = apr_procattr_dir_set(procattr,
708 ap_make_dirstr_parent(r->pool, r->filename))) != APR_SUCCESS) ||
709 ((rc = apr_procattr_cmdtype_set(procattr, cmd_type)) != APR_SUCCESS)) {
710 /* Something bad happened, tell the world. */
711 ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r,
712 "couldn't set child process attributes: %s", r->filename);
715 argv = (const char * const *)create_argv(r->pool, NULL, NULL, NULL, argv0, r->args);
717 /* We want to close sd2 for the new CGI process too.
718 * If it is left open it'll make ap_pass_brigade() block
719 * waiting for EOF if CGI forked something running long.
720 * close(sd2) here should be okay, as CGI channel
721 * is already dup()ed by apr_procattr_child_{in,out}_set()
726 rc = ap_os_create_privileged_process(r, procnew, argv0, argv,
727 (const char * const *)env,
730 if (rc != APR_SUCCESS) {
731 /* Bad things happened. Everyone should have cleaned up. */
732 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_TOCLIENT, rc, r,
733 "couldn't create child process: %d: %s", rc,
734 apr_filename_of_pathname(r->filename));
737 apr_hash_set(script_hash, &cgid_req.conn_id, sizeof(cgid_req.conn_id),
738 (void *)procnew->pid);
745 static int cgid_init(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp,
746 server_rec *main_server)
751 const char *userdata_key = "cgid_init";
754 apr_pool_userdata_get(&data, userdata_key, main_server->process->pool);
757 apr_pool_userdata_set((const void *)1, userdata_key,
758 apr_pool_cleanup_null, main_server->process->pool);
763 for (m = ap_preloaded_modules; *m != NULL; m++)
766 daemon_should_exit = 0; /* clear setting from previous generation */
767 if ((daemon_pid = fork()) < 0) {
768 ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
769 "mod_cgid: Couldn't spawn cgid daemon process");
772 else if (daemon_pid == 0) {
773 apr_pool_create(&pcgi, p);
774 cgid_server(main_server);
777 procnew = apr_pcalloc(p, sizeof(*procnew));
778 procnew->pid = daemon_pid;
779 procnew->err = procnew->in = procnew->out = NULL;
780 apr_pool_note_subprocess(p, procnew, APR_KILL_AFTER_TIMEOUT);
781 #if APR_HAS_OTHER_CHILD
782 apr_proc_other_child_register(procnew, cgid_maint, &procnew->pid, NULL, p);
785 cgid_pfn_reg_with_ssi = APR_RETRIEVE_OPTIONAL_FN(ap_register_include_handler);
786 cgid_pfn_gtv = APR_RETRIEVE_OPTIONAL_FN(ap_ssi_get_tag_and_value);
787 cgid_pfn_ps = APR_RETRIEVE_OPTIONAL_FN(ap_ssi_parse_string);
789 if ((cgid_pfn_reg_with_ssi) && (cgid_pfn_gtv) && (cgid_pfn_ps)) {
790 /* Required by mod_include filter. This is how mod_cgid registers
791 * with mod_include to provide processing of the exec directive.
793 cgid_pfn_reg_with_ssi("exec", handle_exec);
799 static void *create_cgid_config(apr_pool_t *p, server_rec *s)
801 cgid_server_conf *c =
802 (cgid_server_conf *) apr_pcalloc(p, sizeof(cgid_server_conf));
805 c->logbytes = DEFAULT_LOGBYTES;
806 c->bufbytes = DEFAULT_BUFBYTES;
807 c->sockname = ap_server_root_relative(p, DEFAULT_SOCKET);
811 static void *merge_cgid_config(apr_pool_t *p, void *basev, void *overridesv)
813 cgid_server_conf *base = (cgid_server_conf *) basev, *overrides = (cgid_server_conf *) overridesv;
815 return overrides->logname ? overrides : base;
818 static const char *set_scriptlog(cmd_parms *cmd, void *dummy, const char *arg)
820 server_rec *s = cmd->server;
821 cgid_server_conf *conf = ap_get_module_config(s->module_config,
824 conf->logname = ap_server_root_relative(cmd->pool, arg);
826 if (!conf->logname) {
827 return apr_pstrcat(cmd->pool, "Invalid ScriptLog path ",
833 static const char *set_scriptlog_length(cmd_parms *cmd, void *dummy, const char *arg)
835 server_rec *s = cmd->server;
836 cgid_server_conf *conf = ap_get_module_config(s->module_config,
839 conf->logbytes = atol(arg);
843 static const char *set_scriptlog_buffer(cmd_parms *cmd, void *dummy, const char *arg)
845 server_rec *s = cmd->server;
846 cgid_server_conf *conf = ap_get_module_config(s->module_config,
849 conf->bufbytes = atoi(arg);
853 static const char *set_script_socket(cmd_parms *cmd, void *dummy, const char *arg)
855 server_rec *s = cmd->server;
856 cgid_server_conf *conf = ap_get_module_config(s->module_config,
859 conf->sockname = ap_server_root_relative(cmd->pool, arg);
861 if (!conf->sockname) {
862 return apr_pstrcat(cmd->pool, "Invalid Scriptsock path ",
869 static const command_rec cgid_cmds[] =
871 AP_INIT_TAKE1("ScriptLog", set_scriptlog, NULL, RSRC_CONF,
872 "the name of a log for script debugging info"),
873 AP_INIT_TAKE1("ScriptLogLength", set_scriptlog_length, NULL, RSRC_CONF,
874 "the maximum length (in bytes) of the script debug log"),
875 AP_INIT_TAKE1("ScriptLogBuffer", set_scriptlog_buffer, NULL, RSRC_CONF,
876 "the maximum size (in bytes) to record of a POST request"),
877 AP_INIT_TAKE1("Scriptsock", set_script_socket, NULL, RSRC_CONF,
878 "the name of the socket to use for communication with "
883 static int log_scripterror(request_rec *r, cgid_server_conf * conf, int ret,
884 apr_status_t rv, char *error)
886 apr_file_t *f = NULL;
888 char time_str[APR_CTIME_LEN];
889 int log_flags = rv ? APLOG_ERR : APLOG_ERR;
891 ap_log_rerror(APLOG_MARK, log_flags, rv, r,
892 "%s: %s", error, r->filename);
894 /* XXX Very expensive mainline case! Open, then getfileinfo! */
895 if (!conf->logname ||
896 ((stat(conf->logname, &finfo) == 0)
897 && (finfo.st_size > conf->logbytes)) ||
898 (apr_file_open(&f, conf->logname,
899 APR_APPEND|APR_WRITE|APR_CREATE, APR_OS_DEFAULT, r->pool) != APR_SUCCESS)) {
903 /* "%% [Wed Jun 19 10:53:21 1996] GET /cgid-bin/printenv HTTP/1.0" */
904 apr_ctime(time_str, apr_time_now());
905 apr_file_printf(f, "%%%% [%s] %s %s%s%s %s\n", time_str, r->method, r->uri,
906 r->args ? "?" : "", r->args ? r->args : "", r->protocol);
907 /* "%% 500 /usr/local/apache/cgid-bin */
908 apr_file_printf(f, "%%%% %d %s\n", ret, r->filename);
910 apr_file_printf(f, "%%error\n%s\n", error);
916 static int log_script(request_rec *r, cgid_server_conf * conf, int ret,
917 char *dbuf, const char *sbuf, apr_bucket_brigade *bb,
918 apr_file_t *script_err)
920 const apr_array_header_t *hdrs_arr = apr_table_elts(r->headers_in);
921 const apr_table_entry_t *hdrs = (apr_table_entry_t *) hdrs_arr->elts;
922 char argsbuffer[HUGE_STRING_LEN];
923 apr_file_t *f = NULL;
931 char time_str[APR_CTIME_LEN];
933 /* XXX Very expensive mainline case! Open, then getfileinfo! */
934 if (!conf->logname ||
935 ((stat(conf->logname, &finfo) == 0)
936 && (finfo.st_size > conf->logbytes)) ||
937 (apr_file_open(&f, conf->logname,
938 APR_APPEND|APR_WRITE|APR_CREATE, APR_OS_DEFAULT, r->pool) != APR_SUCCESS)) {
939 /* Soak up script output */
940 discard_script_output(bb);
942 while (apr_file_gets(argsbuffer, HUGE_STRING_LEN,
943 script_err) == APR_SUCCESS)
949 /* "%% [Wed Jun 19 10:53:21 1996] GET /cgid-bin/printenv HTTP/1.0" */
950 apr_ctime(time_str, apr_time_now());
951 apr_file_printf(f, "%%%% [%s] %s %s%s%s %s\n", time_str, r->method, r->uri,
952 r->args ? "?" : "", r->args ? r->args : "", r->protocol);
953 /* "%% 500 /usr/local/apache/cgid-bin" */
954 apr_file_printf(f, "%%%% %d %s\n", ret, r->filename);
956 apr_file_puts("%request\n", f);
957 for (i = 0; i < hdrs_arr->nelts; ++i) {
960 apr_file_printf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val);
962 if ((r->method_number == M_POST || r->method_number == M_PUT)
964 apr_file_printf(f, "\n%s\n", dbuf);
967 apr_file_puts("%response\n", f);
968 hdrs_arr = apr_table_elts(r->err_headers_out);
969 hdrs = (const apr_table_entry_t *) hdrs_arr->elts;
971 for (i = 0; i < hdrs_arr->nelts; ++i) {
974 apr_file_printf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val);
978 apr_file_printf(f, "%s\n", sbuf);
981 APR_BRIGADE_FOREACH(e, bb) {
982 if (APR_BUCKET_IS_EOS(e)) {
985 rv = apr_bucket_read(e, &buf, &len, APR_BLOCK_READ);
986 if (!APR_STATUS_IS_SUCCESS(rv) || (len == 0)) {
990 apr_file_puts("%stdout\n", f);
993 apr_file_write(f, buf, &len);
994 apr_file_puts("\n", f);
998 if (apr_file_gets(argsbuffer, HUGE_STRING_LEN,
999 script_err) == APR_SUCCESS) {
1000 apr_file_puts("%stderr\n", f);
1001 apr_file_puts(argsbuffer, f);
1002 while (apr_file_gets(argsbuffer, HUGE_STRING_LEN,
1003 script_err) == APR_SUCCESS)
1004 apr_file_puts(argsbuffer, f);
1005 apr_file_puts("\n", f);
1010 apr_file_close(script_err);
1017 static apr_status_t close_unix_socket(void *thefd)
1019 int fd = (int)thefd;
1024 static int connect_to_daemon(int *sdptr, request_rec *r,
1025 cgid_server_conf *conf)
1027 struct sockaddr_un unix_addr;
1030 apr_interval_time_t sliding_timer;
1032 memset(&unix_addr, 0, sizeof(unix_addr));
1033 unix_addr.sun_family = AF_UNIX;
1034 strcpy(unix_addr.sun_path, conf->sockname);
1037 sliding_timer = 100000; /* 100 milliseconds */
1040 if ((sd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
1041 return log_scripterror(r, conf, HTTP_INTERNAL_SERVER_ERROR, errno,
1042 "unable to create socket to cgi daemon");
1044 if (connect(sd, (struct sockaddr *)&unix_addr, sizeof(unix_addr)) < 0) {
1045 if (errno == ECONNREFUSED && connect_tries < DEFAULT_CONNECT_ATTEMPTS) {
1046 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, errno, r,
1047 "connect #%d to cgi daemon failed, sleeping before retry",
1050 apr_sleep(sliding_timer);
1051 if (sliding_timer < apr_time_from_sec(2)) {
1057 return log_scripterror(r, conf, HTTP_SERVICE_UNAVAILABLE, errno,
1058 "unable to connect to cgi daemon after multiple tries");
1062 apr_pool_cleanup_register(r->pool, (void *)sd, close_unix_socket,
1063 apr_pool_cleanup_null);
1064 break; /* we got connected! */
1066 /* gotta try again, but make sure the cgid daemon is still around */
1067 if (kill(daemon_pid, 0) != 0) {
1068 return log_scripterror(r, conf, HTTP_SERVICE_UNAVAILABLE, errno,
1069 "cgid daemon is gone; is Apache terminating?");
1076 static void discard_script_output(apr_bucket_brigade *bb)
1082 APR_BRIGADE_FOREACH(e, bb) {
1083 if (APR_BUCKET_IS_EOS(e)) {
1086 rv = apr_bucket_read(e, &buf, &len, APR_BLOCK_READ);
1087 if (!APR_STATUS_IS_SUCCESS(rv)) {
1093 /****************************************************************
1095 * Actual cgid handling...
1098 struct cleanup_script_info {
1100 unsigned long conn_id;
1101 cgid_server_conf *conf;
1104 static apr_status_t dead_yet(pid_t pid, apr_interval_time_t max_wait)
1106 apr_interval_time_t interval = 10000; /* 10 ms */
1107 apr_interval_time_t total = 0;
1110 if (kill(pid, 0) < 0) {
1113 apr_sleep(interval);
1114 total = total + interval;
1115 if (interval < 500000) {
1118 } while (total < max_wait);
1119 return APR_EGENERAL;
1122 static apr_status_t cleanup_nonchild_process(request_rec *r, pid_t pid)
1124 kill(pid, SIGTERM); /* in case it isn't dead yet */
1125 if (dead_yet(pid, apr_time_from_sec(3)) == APR_SUCCESS) {
1128 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1129 "CGI process %" APR_PID_T_FMT " didn't exit, sending SIGKILL",
1132 if (dead_yet(pid, apr_time_from_sec(3)) == APR_SUCCESS) {
1135 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1136 "CGI process %" APR_PID_T_FMT " didn't exit, sending SIGKILL again",
1140 return APR_EGENERAL;
1143 static apr_status_t cleanup_script(void *vptr)
1145 struct cleanup_script_info *info = vptr;
1148 cgid_req_t req = {0};
1152 rc = connect_to_daemon(&sd, info->r, info->conf);
1154 return APR_EGENERAL;
1157 req.req_type = GETPID_REQ;
1158 req.conn_id = info->r->connection->id;
1160 stat = sock_write(sd, &req, sizeof(req));
1161 if (stat != APR_SUCCESS) {
1166 /* wait for pid of script */
1167 stat = sock_read(sd, &pid, sizeof(pid));
1168 if (stat != APR_SUCCESS) {
1175 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, info->r,
1176 "daemon couldn't find CGI process for connection %lu",
1178 return APR_EGENERAL;
1180 return cleanup_nonchild_process(info->r, pid);
1183 static int cgid_handler(request_rec *r)
1185 conn_rec *c = r->connection;
1186 int retval, nph, dbpos = 0;
1187 char *argv0, *dbuf = NULL;
1188 apr_bucket_brigade *bb;
1190 cgid_server_conf *conf;
1192 int seen_eos, child_stopped_reading;
1195 apr_file_t *tempsock;
1196 struct cleanup_script_info *info;
1199 if (strcmp(r->handler,CGI_MAGIC_TYPE) && strcmp(r->handler,"cgi-script"))
1202 if (r->method_number == M_OPTIONS) {
1203 /* 99 out of 100 cgid scripts, this is all they support */
1204 r->allowed |= (AP_METHOD_BIT << M_GET);
1205 r->allowed |= (AP_METHOD_BIT << M_POST);
1209 conf = ap_get_module_config(r->server->module_config, &cgid_module);
1210 is_included = !strcmp(r->protocol, "INCLUDED");
1212 if ((argv0 = strrchr(r->filename, '/')) != NULL)
1215 argv0 = r->filename;
1217 nph = !(strncmp(argv0, "nph-", 4));
1219 if ((argv0 = strrchr(r->filename, '/')) != NULL)
1222 argv0 = r->filename;
1224 if (!(ap_allow_options(r) & OPT_EXECCGI) && !is_scriptaliased(r))
1225 return log_scripterror(r, conf, HTTP_FORBIDDEN, 0,
1226 "Options ExecCGI is off in this directory");
1227 if (nph && is_included)
1228 return log_scripterror(r, conf, HTTP_FORBIDDEN, 0,
1229 "attempt to include NPH CGI script");
1231 #if defined(OS2) || defined(WIN32)
1232 #error mod_cgid does not work on this platform. If you teach it to, look
1233 #error at mod_cgi.c for required code in this path.
1235 if (r->finfo.filetype == 0)
1236 return log_scripterror(r, conf, HTTP_NOT_FOUND, 0,
1237 "script not found or unable to stat");
1239 if (r->finfo.filetype == APR_DIR)
1240 return log_scripterror(r, conf, HTTP_FORBIDDEN, 0,
1241 "attempt to invoke directory as script");
1243 if ((r->used_path_info == AP_REQ_REJECT_PATH_INFO) &&
1244 r->path_info && *r->path_info)
1246 /* default to accept */
1247 return log_scripterror(r, conf, HTTP_NOT_FOUND, 0,
1248 "AcceptPathInfo off disallows user's path");
1251 if (!ap_suexec_enabled) {
1252 if (!ap_can_exec(&r->finfo))
1253 return log_scripterror(r, conf, HTTP_FORBIDDEN, 0,
1254 "file permissions deny server execution");
1257 ap_add_common_vars(r);
1259 env = ap_create_environment(r->pool, r->subprocess_env);
1261 if ((retval = connect_to_daemon(&sd, r, conf)) != OK) {
1265 rv = send_req(sd, r, argv0, env, CGI_REQ);
1266 if (rv != APR_SUCCESS) {
1267 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1268 "write to cgi daemon process");
1271 info = apr_palloc(r->pool, sizeof(struct cleanup_script_info));
1273 info->conn_id = r->connection->id;
1275 apr_pool_cleanup_register(r->pool, info,
1277 apr_pool_cleanup_null);
1278 /* We are putting the socket discriptor into an apr_file_t so that we can
1279 * use a pipe bucket to send the data to the client.
1280 * Note that this does not register a cleanup for the socket. We did
1281 * that explicitly right after we created the socket.
1283 apr_os_pipe_put(&tempsock, &sd, r->pool);
1285 if ((argv0 = strrchr(r->filename, '/')) != NULL)
1288 argv0 = r->filename;
1290 /* Transfer any put/post args, CERN style...
1291 * Note that we already ignore SIGPIPE in the core server.
1293 bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
1295 child_stopped_reading = 0;
1296 if (conf->logname) {
1297 dbuf = apr_palloc(r->pool, conf->bufbytes + 1);
1303 rv = ap_get_brigade(r->input_filters, bb, AP_MODE_READBYTES,
1304 APR_BLOCK_READ, HUGE_STRING_LEN);
1306 if (rv != APR_SUCCESS) {
1310 APR_BRIGADE_FOREACH(bucket, bb) {
1314 if (APR_BUCKET_IS_EOS(bucket)) {
1319 /* We can't do much with this. */
1320 if (APR_BUCKET_IS_FLUSH(bucket)) {
1324 /* If the child stopped, we still must read to EOS. */
1325 if (child_stopped_reading) {
1330 apr_bucket_read(bucket, &data, &len, APR_BLOCK_READ);
1332 if (conf->logname && dbpos < conf->bufbytes) {
1335 if ((dbpos + len) > conf->bufbytes) {
1336 cursize = conf->bufbytes - dbpos;
1341 memcpy(dbuf + dbpos, data, cursize);
1345 /* Keep writing data to the child until done or too much time
1346 * elapses with no progress or an error occurs.
1348 rv = apr_file_write_full(tempsock, data, len, NULL);
1350 if (rv != APR_SUCCESS) {
1351 /* silly script stopped reading, soak up remaining message */
1352 child_stopped_reading = 1;
1355 apr_brigade_cleanup(bb);
1359 if (conf->logname) {
1363 /* we're done writing, or maybe we didn't write at all;
1364 * force EOF on child's stdin so that the cgi detects end (or
1369 /* Handle script return... */
1371 const char *location;
1372 char sbuf[MAX_STRING_LEN];
1375 bb = apr_brigade_create(r->pool, c->bucket_alloc);
1376 b = apr_bucket_pipe_create(tempsock, c->bucket_alloc);
1377 APR_BRIGADE_INSERT_TAIL(bb, b);
1378 b = apr_bucket_eos_create(c->bucket_alloc);
1379 APR_BRIGADE_INSERT_TAIL(bb, b);
1381 if ((ret = ap_scan_script_header_err_brigade(r, bb, sbuf))) {
1382 return log_script(r, conf, ret, dbuf, sbuf, bb, NULL);
1385 location = apr_table_get(r->headers_out, "Location");
1387 if (location && location[0] == '/' && r->status == 200) {
1389 /* Soak up all the script output */
1390 discard_script_output(bb);
1391 apr_brigade_destroy(bb);
1392 /* This redirect needs to be a GET no matter what the original
1395 r->method = apr_pstrdup(r->pool, "GET");
1396 r->method_number = M_GET;
1398 /* We already read the message body (if any), so don't allow
1399 * the redirected request to think it has one. We can ignore
1400 * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR.
1402 apr_table_unset(r->headers_in, "Content-Length");
1404 ap_internal_redirect_handler(location, r);
1407 else if (location && r->status == 200) {
1408 /* XX Note that if a script wants to produce its own Redirect
1409 * body, it now has to explicitly *say* "Status: 302"
1411 discard_script_output(bb);
1412 apr_brigade_destroy(bb);
1413 return HTTP_MOVED_TEMPORARILY;
1416 /* Passing our socket down the filter chain in a pipe bucket
1417 * gives up the responsibility of closing the socket, so
1418 * get rid of the cleanup.
1420 apr_pool_cleanup_kill(r->pool, (void *)sd, close_unix_socket);
1422 ap_pass_brigade(r->output_filters, bb);
1426 struct ap_filter_t *cur;
1428 /* Passing our socket down the filter chain in a pipe bucket
1429 * gives up the responsibility of closing the socket, so
1430 * get rid of the cleanup.
1432 apr_pool_cleanup_kill(r->pool, (void *)sd, close_unix_socket);
1434 /* get rid of all filters up through protocol... since we
1435 * haven't parsed off the headers, there is no way they can
1439 cur = r->proto_output_filters;
1440 while (cur && cur->frec->ftype < AP_FTYPE_CONNECTION) {
1443 r->output_filters = r->proto_output_filters = cur;
1445 bb = apr_brigade_create(r->pool, c->bucket_alloc);
1446 b = apr_bucket_pipe_create(tempsock, c->bucket_alloc);
1447 APR_BRIGADE_INSERT_TAIL(bb, b);
1448 b = apr_bucket_eos_create(c->bucket_alloc);
1449 APR_BRIGADE_INSERT_TAIL(bb, b);
1450 ap_pass_brigade(r->output_filters, bb);
1453 return OK; /* NOT r->status, even if it has changed. */
1459 /*============================================================================
1460 *============================================================================
1461 * This is the beginning of the cgi filter code moved from mod_include. This
1462 * is the code required to handle the "exec" SSI directive.
1463 *============================================================================
1464 *============================================================================*/
1465 static int include_cgi(char *s, request_rec *r, ap_filter_t *next,
1466 apr_bucket *head_ptr, apr_bucket **inserted_head)
1468 request_rec *rr = ap_sub_req_lookup_uri(s, r, next);
1470 apr_bucket *tmp_buck, *tmp2_buck;
1472 if (rr->status != HTTP_OK) {
1473 ap_destroy_sub_req(rr);
1477 /* No hardwired path info or query allowed */
1479 if ((rr->path_info && rr->path_info[0]) || rr->args) {
1480 ap_destroy_sub_req(rr);
1483 if (rr->finfo.filetype != APR_REG) {
1484 ap_destroy_sub_req(rr);
1488 /* Script gets parameters of the *document*, for back compatibility */
1490 rr->path_info = r->path_info; /* hard to get right; see mod_cgi.c */
1493 /* Force sub_req to be treated as a CGI request, even if ordinary
1494 * typing rules would have called it something else.
1496 ap_set_content_type(rr, CGI_MAGIC_TYPE);
1500 rr_status = ap_run_sub_req(rr);
1501 if (ap_is_HTTP_REDIRECT(rr_status)) {
1503 const char *location = apr_table_get(rr->headers_out, "Location");
1504 conn_rec *c = r->connection;
1506 location = ap_escape_html(rr->pool, location);
1507 len_loc = strlen(location);
1509 /* XXX: if most of this stuff is going to get copied anyway,
1510 * it'd be more efficient to pstrcat it into a single pool buffer
1511 * and a single pool bucket */
1513 tmp_buck = apr_bucket_immortal_create("<A HREF=\"",
1514 sizeof("<A HREF=\"") - 1,
1516 APR_BUCKET_INSERT_BEFORE(head_ptr, tmp_buck);
1517 tmp2_buck = apr_bucket_heap_create(location, len_loc, NULL,
1519 APR_BUCKET_INSERT_BEFORE(head_ptr, tmp2_buck);
1520 tmp2_buck = apr_bucket_immortal_create("\">", sizeof("\">") - 1,
1522 APR_BUCKET_INSERT_BEFORE(head_ptr, tmp2_buck);
1523 tmp2_buck = apr_bucket_heap_create(location, len_loc, NULL,
1525 APR_BUCKET_INSERT_BEFORE(head_ptr, tmp2_buck);
1526 tmp2_buck = apr_bucket_immortal_create("</A>", sizeof("</A>") - 1,
1528 APR_BUCKET_INSERT_BEFORE(head_ptr, tmp2_buck);
1530 if (*inserted_head == NULL) {
1531 *inserted_head = tmp_buck;
1535 ap_destroy_sub_req(rr);
1541 /* This is the special environment used for running the "exec cmd="
1542 * variety of SSI directives.
1544 static void add_ssi_vars(request_rec *r, ap_filter_t *next)
1546 apr_table_t *e = r->subprocess_env;
1548 if (r->path_info && r->path_info[0] != '\0') {
1549 request_rec *pa_req;
1551 apr_table_setn(e, "PATH_INFO", ap_escape_shell_cmd(r->pool, r->path_info));
1553 pa_req = ap_sub_req_lookup_uri(ap_escape_uri(r->pool, r->path_info), r, NULL);
1554 if (pa_req->filename) {
1555 apr_table_setn(e, "PATH_TRANSLATED",
1556 apr_pstrcat(r->pool, pa_req->filename, pa_req->path_info, NULL));
1558 ap_destroy_sub_req(pa_req);
1562 char *arg_copy = apr_pstrdup(r->pool, r->args);
1564 apr_table_setn(e, "QUERY_STRING", r->args);
1565 ap_unescape_url(arg_copy);
1566 apr_table_setn(e, "QUERY_STRING_UNESCAPED", ap_escape_shell_cmd(r->pool, arg_copy));
1570 static int include_cmd(include_ctx_t *ctx, apr_bucket_brigade **bb, char *command,
1571 request_rec *r, ap_filter_t *f)
1574 const char *location;
1576 apr_status_t rc = APR_SUCCESS;
1578 apr_bucket_brigade *bcgi;
1580 apr_file_t *tempsock = NULL;
1581 cgid_server_conf *conf = ap_get_module_config(r->server->module_config,
1583 struct cleanup_script_info *info;
1585 add_ssi_vars(r, f->next);
1586 env = ap_create_environment(r->pool, r->subprocess_env);
1588 if ((retval = connect_to_daemon(&sd, r, conf)) != OK) {
1592 SPLIT_AND_PASS_PRETAG_BUCKETS(*bb, ctx, f->next, rc);
1593 if (rc != APR_SUCCESS) {
1597 send_req(sd, r, command, env, SSI_REQ);
1599 info = apr_palloc(r->pool, sizeof(struct cleanup_script_info));
1601 info->conn_id = r->connection->id;
1603 /* for this type of request, the script is invoked through an
1604 * intermediate shell process... cleanup_script is only able
1605 * to knock out the shell process, not the actual script
1607 apr_pool_cleanup_register(r->pool, info,
1609 apr_pool_cleanup_null);
1610 /* We are putting the socket discriptor into an apr_file_t so that we can
1611 * use a pipe bucket to send the data to the client.
1612 * Note that this does not register a cleanup for the socket. We did
1613 * that explicitly right after we created the socket.
1615 apr_os_pipe_put(&tempsock, &sd, r->pool);
1617 if ((retval = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR)))
1620 location = apr_table_get(r->headers_out, "Location");
1622 if (location && location[0] == '/' && r->status == 200) {
1623 char argsbuffer[HUGE_STRING_LEN];
1625 /* Soak up all the script output */
1626 while (apr_file_gets(argsbuffer, HUGE_STRING_LEN,
1627 tempsock) == APR_SUCCESS) {
1630 /* This redirect needs to be a GET no matter what the original
1633 r->method = apr_pstrdup(r->pool, "GET");
1634 r->method_number = M_GET;
1636 /* We already read the message body (if any), so don't allow
1637 * the redirected request to think it has one. We can ignore
1638 * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR.
1640 apr_table_unset(r->headers_in, "Content-Length");
1642 ap_internal_redirect_handler(location, r);
1645 else if (location && r->status == 200) {
1646 /* XX Note that if a script wants to produce its own Redirect
1647 * body, it now has to explicitly *say* "Status: 302"
1649 return HTTP_MOVED_TEMPORARILY;
1652 if (!r->header_only) {
1653 /* Passing our socket down the filter chain in a pipe bucket
1654 * gives up the responsibility of closing the socket, so
1655 * get rid of the cleanup.
1657 apr_pool_cleanup_kill(r->pool, (void *)sd, close_unix_socket);
1659 bcgi = apr_brigade_create(r->pool, r->connection->bucket_alloc);
1660 b = apr_bucket_pipe_create(tempsock, r->connection->bucket_alloc);
1661 APR_BRIGADE_INSERT_TAIL(bcgi, b);
1662 ap_pass_brigade(f->next, bcgi);
1668 static int handle_exec(include_ctx_t *ctx, apr_bucket_brigade **bb, request_rec *r,
1669 ap_filter_t *f, apr_bucket *head_ptr, apr_bucket **inserted_head)
1672 char *tag_val = NULL;
1673 char *file = r->filename;
1674 apr_bucket *tmp_buck;
1675 char parsed_string[MAX_STRING_LEN];
1677 *inserted_head = NULL;
1678 if (ctx->flags & FLAG_PRINTING) {
1679 if (ctx->flags & FLAG_NO_EXEC) {
1680 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1681 "exec used but not allowed in %s", r->filename);
1682 CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, *inserted_head);
1686 cgid_pfn_gtv(ctx, &tag, &tag_val, 1);
1687 if (tag_val == NULL) {
1695 if (!strcmp(tag, "cmd")) {
1696 cgid_pfn_ps(r, ctx, tag_val, parsed_string, sizeof(parsed_string), 1);
1697 if (include_cmd(ctx, bb, parsed_string, r, f) == -1) {
1698 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1699 "execution failure for parameter \"%s\" "
1700 "to tag exec in file %s", tag, r->filename);
1701 CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, *inserted_head);
1703 /* just in case some stooge changed directories */
1705 else if (!strcmp(tag, "cgi")) {
1706 apr_status_t retval = APR_SUCCESS;
1708 cgid_pfn_ps(r, ctx, tag_val, parsed_string, sizeof(parsed_string), 0);
1709 SPLIT_AND_PASS_PRETAG_BUCKETS(*bb, ctx, f->next, retval);
1710 if (retval != APR_SUCCESS) {
1714 if (include_cgi(parsed_string, r, f->next, head_ptr, inserted_head) == -1) {
1715 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1716 "invalid CGI ref \"%s\" in %s", tag_val, file);
1717 CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, *inserted_head);
1721 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1722 "unknown parameter \"%s\" to tag exec in %s", tag, file);
1723 CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, *inserted_head);
1730 /*============================================================================
1731 *============================================================================
1732 * This is the end of the cgi filter code moved from mod_include.
1733 *============================================================================
1734 *============================================================================*/
1737 static void register_hook(apr_pool_t *p)
1739 static const char * const aszPre[] = { "mod_include.c", NULL };
1741 ap_hook_post_config(cgid_init, aszPre, NULL, APR_HOOK_MIDDLE);
1742 ap_hook_handler(cgid_handler, NULL, NULL, APR_HOOK_MIDDLE);
1745 module AP_MODULE_DECLARE_DATA cgid_module = {
1746 STANDARD20_MODULE_STUFF,
1747 NULL, /* dir config creater */
1748 NULL, /* dir merger --- default is to override */
1749 create_cgid_config, /* server config */
1750 merge_cgid_config, /* merge server config */
1751 cgid_cmds, /* command table */
1752 register_hook /* register_handlers */