1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 * http_script: keeps all script-related ramblings together.
20 * Compliant to cgi/1.1 spec
22 * Adapted by rst from original NCSA code by Rob McCool
24 * Apache adds some new env vars; REDIRECT_URL and REDIRECT_QUERY_STRING for
25 * custom error responses, and DOCUMENT_ROOT because we found it useful.
26 * It also adds SERVER_ADMIN - useful for scripts to know who to mail when
31 #include "apr_strings.h"
32 #include "apr_general.h"
33 #include "apr_file_io.h"
34 #include "apr_portable.h"
35 #include "apr_buckets.h"
36 #include "apr_optional.h"
37 #include "apr_signal.h"
39 #define APR_WANT_STRFUNC
42 #if APR_HAVE_SYS_SOCKET_H
43 #include <sys/socket.h>
48 #if APR_HAVE_SYS_TYPES_H
49 #include <sys/types.h>
52 #include "util_filter.h"
54 #include "http_config.h"
55 #include "http_request.h"
56 #include "http_core.h"
57 #include "http_protocol.h"
58 #include "http_main.h"
60 #include "util_script.h"
62 #include "mpm_common.h"
63 #include "mod_suexec.h"
64 #include "../filters/mod_include.h"
69 /* ### should be tossed in favor of APR */
71 #include <sys/un.h> /* for sockaddr_un */
74 module AP_MODULE_DECLARE_DATA cgid_module;
76 static int cgid_start(apr_pool_t *p, server_rec *main_server, apr_proc_t *procnew);
77 static int cgid_init(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *main_server);
78 static int handle_exec(include_ctx_t *ctx, ap_filter_t *f, apr_bucket_brigade *bb);
80 static APR_OPTIONAL_FN_TYPE(ap_register_include_handler) *cgid_pfn_reg_with_ssi;
81 static APR_OPTIONAL_FN_TYPE(ap_ssi_get_tag_and_value) *cgid_pfn_gtv;
82 static APR_OPTIONAL_FN_TYPE(ap_ssi_parse_string) *cgid_pfn_ps;
84 static apr_pool_t *pcgi = NULL;
85 static int total_modules = 0;
86 static pid_t daemon_pid;
87 static int daemon_should_exit = 0;
88 static server_rec *root_server = NULL;
89 static apr_pool_t *root_pool = NULL;
90 static const char *sockname;
91 static struct sockaddr_un *server_addr;
92 static apr_socklen_t server_addr_len;
93 static pid_t parent_pid;
94 static ap_unix_identity_t empty_ugid = { (uid_t)-1, (gid_t)-1, -1 };
96 /* The APR other-child API doesn't tell us how the daemon exited
97 * (SIGSEGV vs. exit(1)). The other-child maintenance function
98 * needs to decide whether to restart the daemon after a failure
99 * based on whether or not it exited due to a fatal startup error
100 * or something that happened at steady-state. This exit status
101 * is unlikely to collide with exit signals.
103 #define DAEMON_STARTUP_ERROR 254
105 /* Read and discard the data in the brigade produced by a CGI script */
106 static void discard_script_output(apr_bucket_brigade *bb);
108 /* This doer will only ever be called when we are sure that we have
111 static ap_unix_identity_t *cgid_suexec_id_doer(const request_rec *r)
113 return (ap_unix_identity_t *)
114 ap_get_module_config(r->request_config, &cgid_module);
117 /* KLUDGE --- for back-combatibility, we don't have to check ExecCGI
118 * in ScriptAliased directories, which means we need to know if this
119 * request came through ScriptAlias or not... so the Alias module
120 * leaves a note for us.
123 static int is_scriptaliased(request_rec *r)
125 const char *t = apr_table_get(r->notes, "alias-forced-type");
126 return t && (!strcasecmp(t, "cgi-script"));
129 /* Configuration stuff */
131 #define DEFAULT_LOGBYTES 10385760
132 #define DEFAULT_BUFBYTES 1024
133 #define DEFAULT_SOCKET DEFAULT_REL_RUNTIMEDIR "/cgisock"
137 #define GETPID_REQ 3 /* get the pid of script created for prior request */
139 #define ERRFN_USERDATA_KEY "CGIDCHILDERRFN"
141 /* DEFAULT_CGID_LISTENBACKLOG controls the max depth on the unix socket's
142 * pending connection queue. If a bunch of cgi requests arrive at about
143 * the same time, connections from httpd threads/processes will back up
144 * in the queue while the cgid process slowly forks off a child to process
145 * each connection on the unix socket. If the queue is too short, the
146 * httpd process will get ECONNREFUSED when trying to connect.
148 #ifndef DEFAULT_CGID_LISTENBACKLOG
149 #define DEFAULT_CGID_LISTENBACKLOG 100
152 /* DEFAULT_CONNECT_ATTEMPTS controls how many times we'll try to connect
153 * to the cgi daemon from the thread/process handling the cgi request.
154 * Generally we want to retry when we get ECONNREFUSED since it is
155 * probably because the listen queue is full. We need to try harder so
156 * the client doesn't see it as a 503 error.
158 * Set this to 0 to continually retry until the connect works or Apache
161 #ifndef DEFAULT_CONNECT_ATTEMPTS
162 #define DEFAULT_CONNECT_ATTEMPTS 15
171 #if defined (RLIMIT_CPU) || defined (RLIMIT_NPROC) || defined (RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
175 struct rlimit limit_cpu;
177 #if defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined(RLIMIT_AS)
179 struct rlimit limit_mem;
183 struct rlimit limit_nproc;
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 pid_t ppid; /* sanity check for config problems leading to
196 * wrong cgid socket use
198 int core_module_index;
200 ap_unix_identity_t ugid;
201 apr_size_t filename_len;
202 apr_size_t argv0_len;
205 int loglevel; /* to stuff in server_rec */
207 #if defined (RLIMIT_CPU) || defined (RLIMIT_NPROC) || defined (RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
208 cgid_rlimit_t limits;
212 /* This routine is called to create the argument list to be passed
213 * to the CGI script. When suexec is enabled, the suexec path, user, and
214 * group are the first three arguments to be passed; if not, all three
215 * must be NULL. The query info is split into separate arguments, where
216 * "+" is the separator between keyword arguments.
218 * Do not process the args if they containing an '=' assignment.
220 static char **create_argv(apr_pool_t *p, char *path, char *user, char *group,
221 char *av0, const char *args)
228 if (!(*args) || ap_strchr_c(args, '=')) {
232 /* count the number of keywords */
234 for (x = 0, numwords = 1; args[x]; x++) {
235 if (args[x] == '+') {
241 if (numwords > APACHE_ARG_MAX - 5) {
242 numwords = APACHE_ARG_MAX - 5; /* Truncate args to prevent overrun */
244 av = (char **) apr_pcalloc(p, (numwords + 5) * sizeof(char *));
256 av[idx++] = apr_pstrdup(p, av0);
258 for (x = 1; x <= numwords; x++) {
259 w = ap_getword_nulls(p, &args, '+');
261 av[idx++] = ap_escape_shell_cmd(p, w);
267 #if APR_HAS_OTHER_CHILD
268 static void cgid_maint(int reason, void *data, apr_wait_t status)
270 apr_proc_t *proc = data;
275 case APR_OC_REASON_DEATH:
276 apr_proc_other_child_unregister(data);
277 /* If apache is not terminating or restarting,
278 * restart the cgid daemon
280 stopping = 1; /* if MPM doesn't support query,
281 * assume we shouldn't restart daemon
283 if (ap_mpm_query(AP_MPMQ_MPM_STATE, &mpm_state) == APR_SUCCESS &&
284 mpm_state != AP_MPMQ_STOPPING) {
288 if (status == DAEMON_STARTUP_ERROR) {
289 ap_log_error(APLOG_MARK, APLOG_CRIT, 0, ap_server_conf,
290 "cgid daemon failed to initialize");
293 ap_log_error(APLOG_MARK, APLOG_ERR, 0, ap_server_conf,
294 "cgid daemon process died, restarting");
295 cgid_start(root_pool, root_server, proc);
299 case APR_OC_REASON_RESTART:
300 /* don't do anything; server is stopping or restarting */
301 apr_proc_other_child_unregister(data);
303 case APR_OC_REASON_LOST:
304 /* Restart the child cgid daemon process */
305 apr_proc_other_child_unregister(data);
306 cgid_start(root_pool, root_server, proc);
308 case APR_OC_REASON_UNREGISTER:
309 /* we get here when pcgi is cleaned up; pcgi gets cleaned
310 * up when pconf gets cleaned up
312 kill(proc->pid, SIGHUP); /* send signal to daemon telling it to die */
314 /* Remove the cgi socket, we must do it here in order to try and
315 * guarantee the same permissions as when the socket was created.
317 if (unlink(sockname) < 0 && errno != ENOENT) {
318 ap_log_error(APLOG_MARK, APLOG_ERR, errno, ap_server_conf,
319 "Couldn't unlink unix domain socket %s",
327 static apr_status_t close_unix_socket(void *thefd)
329 int fd = (int)((long)thefd);
334 /* deal with incomplete reads and signals
335 * assume you really have to read buf_size bytes
337 static apr_status_t sock_read(int fd, void *vbuf, size_t buf_size)
341 size_t bytes_read = 0;
345 rc = read(fd, buf + bytes_read, buf_size - bytes_read);
346 } while (rc < 0 && errno == EINTR);
350 case 0: /* unexpected */
355 } while (bytes_read < buf_size);
362 static apr_status_t sock_write(int fd, const void *buf, size_t buf_size)
367 rc = write(fd, buf, buf_size);
368 } while (rc < 0 && errno == EINTR);
376 static apr_status_t sock_writev(int fd, request_rec *r, int count, ...)
383 vec = (struct iovec *)apr_palloc(r->pool, count * sizeof(struct iovec));
385 for (i = 0; i < count; i++) {
386 vec[i].iov_base = va_arg(ap, caddr_t);
387 vec[i].iov_len = va_arg(ap, apr_size_t);
392 rc = writev(fd, vec, count);
393 } while (rc < 0 && errno == EINTR);
401 static apr_status_t get_req(int fd, request_rec *r, char **argv0, char ***env,
406 core_request_config *temp_core;
410 r->server = apr_pcalloc(r->pool, sizeof(server_rec));
412 /* read the request header */
413 stat = sock_read(fd, req, sizeof(*req));
414 if (stat != APR_SUCCESS) {
417 r->server->log.level = req->loglevel;
418 if (req->req_type == GETPID_REQ) {
419 /* no more data sent for this request */
423 /* handle module indexes and such */
424 rconf = (void **)ap_create_request_config(r->pool);
426 temp_core = (core_request_config *)apr_palloc(r->pool, sizeof(core_module));
427 rconf[req->core_module_index] = (void *)temp_core;
428 r->request_config = (ap_conf_vector_t *)rconf;
429 ap_set_module_config(r->request_config, &cgid_module, (void *)&req->ugid);
431 /* Read the filename, argv0, uri, and args */
432 r->filename = apr_pcalloc(r->pool, req->filename_len + 1);
433 *argv0 = apr_pcalloc(r->pool, req->argv0_len + 1);
434 r->uri = apr_pcalloc(r->pool, req->uri_len + 1);
435 if ((stat = sock_read(fd, r->filename, req->filename_len)) != APR_SUCCESS ||
436 (stat = sock_read(fd, *argv0, req->argv0_len)) != APR_SUCCESS ||
437 (stat = sock_read(fd, r->uri, req->uri_len)) != APR_SUCCESS) {
441 r->args = apr_pcalloc(r->pool, req->args_len + 1); /* empty string if no args */
443 if ((stat = sock_read(fd, r->args, req->args_len)) != APR_SUCCESS) {
448 /* read the environment variables */
449 environ = apr_pcalloc(r->pool, (req->env_count + 2) *sizeof(char *));
450 for (i = 0; i < req->env_count; i++) {
453 if ((stat = sock_read(fd, &curlen, sizeof(curlen))) != APR_SUCCESS) {
456 environ[i] = apr_pcalloc(r->pool, curlen + 1);
457 if ((stat = sock_read(fd, environ[i], curlen)) != APR_SUCCESS) {
463 #if defined (RLIMIT_CPU) || defined (RLIMIT_NPROC) || defined (RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
464 if ((stat = sock_read(fd, &(req->limits), sizeof(cgid_rlimit_t))) != APR_SUCCESS)
471 static apr_status_t send_req(int fd, request_rec *r, char *argv0, char **env,
475 cgid_req_t req = {0};
477 ap_unix_identity_t * ugid = ap_run_get_suexec_identity(r);
478 core_dir_config *core_conf = ap_get_module_config(r->per_dir_config,
483 req.ugid = empty_ugid;
485 memcpy(&req.ugid, ugid, sizeof(ap_unix_identity_t));
488 req.req_type = req_type;
489 req.ppid = parent_pid;
490 req.conn_id = r->connection->id;
491 req.core_module_index = core_module.module_index;
492 for (req.env_count = 0; env[req.env_count]; req.env_count++) {
495 req.filename_len = strlen(r->filename);
496 req.argv0_len = strlen(argv0);
497 req.uri_len = strlen(r->uri);
498 req.args_len = r->args ? strlen(r->args) : 0;
499 req.loglevel = r->server->log.level;
501 /* Write the request header */
503 stat = sock_writev(fd, r, 5,
505 r->filename, req.filename_len,
506 argv0, req.argv0_len,
508 r->args, req.args_len);
510 stat = sock_writev(fd, r, 4,
512 r->filename, req.filename_len,
513 argv0, req.argv0_len,
514 r->uri, req.uri_len);
517 if (stat != APR_SUCCESS) {
521 /* write the environment variables */
522 for (i = 0; i < req.env_count; i++) {
523 apr_size_t curlen = strlen(env[i]);
525 if ((stat = sock_writev(fd, r, 2, &curlen, sizeof(curlen),
526 env[i], curlen)) != APR_SUCCESS) {
531 if (core_conf->limit_cpu) {
532 req.limits.limit_cpu = *(core_conf->limit_cpu);
533 req.limits.limit_cpu_set = 1;
536 req.limits.limit_cpu_set = 0;
540 #if defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
541 if (core_conf->limit_mem) {
542 req.limits.limit_mem = *(core_conf->limit_mem);
543 req.limits.limit_mem_set = 1;
546 req.limits.limit_mem_set = 0;
552 if (core_conf->limit_nproc) {
553 req.limits.limit_nproc = *(core_conf->limit_nproc);
554 req.limits.limit_nproc_set = 1;
557 req.limits.limit_nproc_set = 0;
561 #if defined (RLIMIT_CPU) || defined (RLIMIT_NPROC) || defined (RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
562 if ( (stat = sock_write(fd, &(req.limits), sizeof(cgid_rlimit_t))) != APR_SUCCESS)
569 static void daemon_signal_handler(int sig)
572 ++daemon_should_exit;
576 static void cgid_child_errfn(apr_pool_t *pool, apr_status_t err,
577 const char *description)
582 apr_pool_userdata_get(&vr, ERRFN_USERDATA_KEY, pool);
585 /* sure we got r, but don't call ap_log_rerror() because we don't
586 * have r->headers_in and possibly other storage referenced by
589 ap_log_error(APLOG_MARK, APLOG_ERR, err, r->server, "%s", description);
592 static int cgid_server(void *data)
597 server_rec *main_server = data;
598 apr_hash_t *script_hash = apr_hash_make(pcgi);
601 apr_pool_create(&ptrans, pcgi);
603 apr_signal(SIGCHLD, SIG_IGN);
604 apr_signal(SIGHUP, daemon_signal_handler);
606 /* Close our copy of the listening sockets */
607 ap_close_listeners();
609 /* cgid should use its own suexec doer */
610 ap_hook_get_suexec_identity(cgid_suexec_id_doer, NULL, NULL,
611 APR_HOOK_REALLY_FIRST);
614 if ((sd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
615 ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
616 "Couldn't create unix domain socket");
620 omask = umask(0077); /* so that only Apache can use socket */
621 rc = bind(sd, (struct sockaddr *)server_addr, server_addr_len);
622 umask(omask); /* can't fail, so can't clobber errno */
624 ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
625 "Couldn't bind unix domain socket %s",
630 /* Not all flavors of unix use the current umask for AF_UNIX perms */
631 rv = apr_file_perms_set(sockname, APR_FPROT_UREAD|APR_FPROT_UWRITE|APR_FPROT_UEXECUTE);
632 if (rv != APR_SUCCESS) {
633 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, main_server,
634 "Couldn't set permissions on unix domain socket %s",
639 if (listen(sd, DEFAULT_CGID_LISTENBACKLOG) < 0) {
640 ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
641 "Couldn't listen on unix domain socket");
646 if (chown(sockname, ap_unixd_config.user_id, -1) < 0) {
647 ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
648 "Couldn't change owner of unix domain socket %s",
654 apr_pool_cleanup_register(pcgi, (void *)((long)sd),
655 close_unix_socket, close_unix_socket);
657 /* if running as root, switch to configured user/group */
658 if ((rc = ap_run_drop_privileges(pcgi, ap_server_conf)) != 0) {
662 while (!daemon_should_exit) {
663 int errfileno = STDERR_FILENO;
666 const char * const *argv;
668 apr_int32_t out_pipe;
669 apr_int32_t err_pipe;
670 apr_cmdtype_e cmd_type;
672 apr_procattr_t *procattr = NULL;
673 apr_proc_t *procnew = NULL;
679 struct sockaddr_un unix_addr;
681 apr_pool_clear(ptrans);
683 len = sizeof(unix_addr);
684 sd2 = accept(sd, (struct sockaddr *)&unix_addr, &len);
686 #if defined(ENETDOWN)
687 if (errno == ENETDOWN) {
688 /* The network has been shut down, no need to continue. Die gracefully */
689 ++daemon_should_exit;
692 if (errno != EINTR) {
693 ap_log_error(APLOG_MARK, APLOG_ERR, errno,
695 "Error accepting on cgid socket");
700 r = apr_pcalloc(ptrans, sizeof(request_rec));
701 procnew = apr_pcalloc(ptrans, sizeof(*procnew));
703 stat = get_req(sd2, r, &argv0, &env, &cgid_req);
704 if (stat != APR_SUCCESS) {
705 ap_log_error(APLOG_MARK, APLOG_ERR, stat,
707 "Error reading request on cgid socket");
712 if (cgid_req.ppid != parent_pid) {
713 ap_log_error(APLOG_MARK, APLOG_CRIT, 0, main_server,
714 "CGI request received from wrong server instance; "
715 "see ScriptSock directive");
720 if (cgid_req.req_type == GETPID_REQ) {
724 pid = (pid_t)((long)apr_hash_get(script_hash, &cgid_req.conn_id, sizeof(cgid_req.conn_id)));
725 rv = sock_write(sd2, &pid, sizeof(pid));
726 if (rv != APR_SUCCESS) {
727 ap_log_error(APLOG_MARK, APLOG_ERR, rv,
729 "Error writing pid %" APR_PID_T_FMT " to handler", pid);
735 apr_os_file_put(&r->server->error_log, &errfileno, 0, r->pool);
736 apr_os_file_put(&inout, &sd2, 0, r->pool);
738 if (cgid_req.req_type == SSI_REQ) {
739 in_pipe = APR_NO_PIPE;
740 out_pipe = APR_FULL_BLOCK;
741 err_pipe = APR_NO_PIPE;
742 cmd_type = APR_SHELLCMD;
745 in_pipe = APR_CHILD_BLOCK;
746 out_pipe = APR_CHILD_BLOCK;
747 err_pipe = APR_CHILD_BLOCK;
748 cmd_type = APR_PROGRAM;
751 if (((rc = apr_procattr_create(&procattr, ptrans)) != APR_SUCCESS) ||
752 ((cgid_req.req_type == CGI_REQ) &&
753 (((rc = apr_procattr_io_set(procattr,
756 err_pipe)) != APR_SUCCESS) ||
757 /* XXX apr_procattr_child_*_set() is creating an unnecessary
758 * pipe between this process and the child being created...
759 * It is cleaned up with the temporary pool for this request.
761 ((rc = apr_procattr_child_err_set(procattr, r->server->error_log, NULL)) != APR_SUCCESS) ||
762 ((rc = apr_procattr_child_in_set(procattr, inout, NULL)) != APR_SUCCESS))) ||
763 ((rc = apr_procattr_child_out_set(procattr, inout, NULL)) != APR_SUCCESS) ||
764 ((rc = apr_procattr_dir_set(procattr,
765 ap_make_dirstr_parent(r->pool, r->filename))) != APR_SUCCESS) ||
766 ((rc = apr_procattr_cmdtype_set(procattr, cmd_type)) != APR_SUCCESS) ||
768 ( (cgid_req.limits.limit_cpu_set) && ((rc = apr_procattr_limit_set(procattr, APR_LIMIT_CPU,
769 &cgid_req.limits.limit_cpu)) != APR_SUCCESS)) ||
771 #if defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
772 ( (cgid_req.limits.limit_mem_set) && ((rc = apr_procattr_limit_set(procattr, APR_LIMIT_MEM,
773 &cgid_req.limits.limit_mem)) != APR_SUCCESS)) ||
776 ( (cgid_req.limits.limit_nproc_set) && ((rc = apr_procattr_limit_set(procattr, APR_LIMIT_NPROC,
777 &cgid_req.limits.limit_nproc)) != APR_SUCCESS)) ||
780 ((rc = apr_procattr_child_errfn_set(procattr, cgid_child_errfn)) != APR_SUCCESS)) {
781 /* Something bad happened, tell the world.
782 * ap_log_rerror() won't work because the header table used by
783 * ap_log_rerror() hasn't been replicated in the phony r
785 ap_log_error(APLOG_MARK, APLOG_ERR, rc, r->server,
786 "couldn't set child process attributes: %s", r->filename);
788 procnew->pid = 0; /* no process to clean up */
792 apr_pool_userdata_set(r, ERRFN_USERDATA_KEY, apr_pool_cleanup_null, ptrans);
794 argv = (const char * const *)create_argv(r->pool, NULL, NULL, NULL, argv0, r->args);
796 /* We want to close sd2 for the new CGI process too.
797 * If it is left open it'll make ap_pass_brigade() block
798 * waiting for EOF if CGI forked something running long.
799 * close(sd2) here should be okay, as CGI channel
800 * is already dup()ed by apr_procattr_child_{in,out}_set()
805 if (memcmp(&empty_ugid, &cgid_req.ugid, sizeof(empty_ugid))) {
806 /* We have a valid identity, and can be sure that
807 * cgid_suexec_id_doer will return a valid ugid
809 rc = ap_os_create_privileged_process(r, procnew, argv0, argv,
810 (const char * const *)env,
813 rc = apr_proc_create(procnew, argv0, argv,
814 (const char * const *)env,
818 if (rc != APR_SUCCESS) {
819 /* Bad things happened. Everyone should have cleaned up.
820 * ap_log_rerror() won't work because the header table used by
821 * ap_log_rerror() hasn't been replicated in the phony r
823 ap_log_error(APLOG_MARK, APLOG_ERR, rc, r->server,
824 "couldn't create child process: %d: %s", rc,
825 apr_filepath_name_get(r->filename));
827 procnew->pid = 0; /* no process to clean up */
831 /* If the script process was created, remember the pid for
832 * later cleanup. If the script process wasn't created, clear
833 * out any prior pid with the same key.
835 * We don't want to leak storage for the key, so only allocate
836 * a key if the key doesn't exist yet in the hash; there are
837 * only a limited number of possible keys (one for each
838 * possible thread in the server), so we can allocate a copy
839 * of the key the first time a thread has a cgid request.
840 * Note that apr_hash_set() only uses the storage passed in
841 * for the key if it is adding the key to the hash for the
842 * first time; new key storage isn't needed for replacing the
843 * existing value of a key.
846 if (apr_hash_get(script_hash, &cgid_req.conn_id, sizeof(cgid_req.conn_id))) {
847 key = &cgid_req.conn_id;
850 key = apr_pmemdup(pcgi, &cgid_req.conn_id, sizeof(cgid_req.conn_id));
852 apr_hash_set(script_hash, key, sizeof(cgid_req.conn_id),
853 (void *)((long)procnew->pid));
855 return -1; /* should be <= 0 to distinguish from startup errors */
858 static int cgid_start(apr_pool_t *p, server_rec *main_server,
862 daemon_should_exit = 0; /* clear setting from previous generation */
863 if ((daemon_pid = fork()) < 0) {
864 ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
865 "mod_cgid: Couldn't spawn cgid daemon process");
868 else if (daemon_pid == 0) {
870 apr_pool_create(&pcgi, p);
872 exit(cgid_server(main_server) > 0 ? DAEMON_STARTUP_ERROR : -1);
874 procnew->pid = daemon_pid;
875 procnew->err = procnew->in = procnew->out = NULL;
876 apr_pool_note_subprocess(p, procnew, APR_KILL_AFTER_TIMEOUT);
877 #if APR_HAS_OTHER_CHILD
878 apr_proc_other_child_register(procnew, cgid_maint, procnew, NULL, p);
883 static int cgid_pre_config(apr_pool_t *pconf, apr_pool_t *plog,
886 sockname = ap_append_pid(pconf, DEFAULT_SOCKET, ".");
890 static int cgid_init(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp,
891 server_rec *main_server)
893 apr_proc_t *procnew = NULL;
894 const char *userdata_key = "cgid_init";
899 root_server = main_server;
902 apr_pool_userdata_get(&data, userdata_key, main_server->process->pool);
904 procnew = apr_pcalloc(main_server->process->pool, sizeof(*procnew));
906 procnew->err = procnew->in = procnew->out = NULL;
907 apr_pool_userdata_set((const void *)procnew, userdata_key,
908 apr_pool_cleanup_null, main_server->process->pool);
914 if (ap_state_query(AP_SQ_MAIN_STATE) != AP_SQ_MS_CREATE_PRE_CONFIG) {
917 for (m = ap_preloaded_modules; *m != NULL; m++)
920 parent_pid = getpid();
921 tmp_sockname = ap_server_root_relative(p, sockname);
922 if (strlen(tmp_sockname) > sizeof(server_addr->sun_path) - 1) {
923 tmp_sockname[sizeof(server_addr->sun_path)] = '\0';
924 ap_log_error(APLOG_MARK, APLOG_ERR, 0, main_server,
925 "The length of the ScriptSock path exceeds maximum, "
926 "truncating to %s", tmp_sockname);
928 sockname = tmp_sockname;
930 server_addr_len = APR_OFFSETOF(struct sockaddr_un, sun_path) + strlen(sockname);
931 server_addr = (struct sockaddr_un *)apr_palloc(p, server_addr_len + 1);
932 server_addr->sun_family = AF_UNIX;
933 strcpy(server_addr->sun_path, sockname);
935 ret = cgid_start(p, main_server, procnew);
939 cgid_pfn_reg_with_ssi = APR_RETRIEVE_OPTIONAL_FN(ap_register_include_handler);
940 cgid_pfn_gtv = APR_RETRIEVE_OPTIONAL_FN(ap_ssi_get_tag_and_value);
941 cgid_pfn_ps = APR_RETRIEVE_OPTIONAL_FN(ap_ssi_parse_string);
943 if ((cgid_pfn_reg_with_ssi) && (cgid_pfn_gtv) && (cgid_pfn_ps)) {
944 /* Required by mod_include filter. This is how mod_cgid registers
945 * with mod_include to provide processing of the exec directive.
947 cgid_pfn_reg_with_ssi("exec", handle_exec);
953 static void *create_cgid_config(apr_pool_t *p, server_rec *s)
955 cgid_server_conf *c =
956 (cgid_server_conf *) apr_pcalloc(p, sizeof(cgid_server_conf));
959 c->logbytes = DEFAULT_LOGBYTES;
960 c->bufbytes = DEFAULT_BUFBYTES;
964 static void *merge_cgid_config(apr_pool_t *p, void *basev, void *overridesv)
966 cgid_server_conf *base = (cgid_server_conf *) basev, *overrides = (cgid_server_conf *) overridesv;
968 return overrides->logname ? overrides : base;
971 static const char *set_scriptlog(cmd_parms *cmd, void *dummy, const char *arg)
973 server_rec *s = cmd->server;
974 cgid_server_conf *conf = ap_get_module_config(s->module_config,
977 conf->logname = ap_server_root_relative(cmd->pool, arg);
979 if (!conf->logname) {
980 return apr_pstrcat(cmd->pool, "Invalid ScriptLog path ",
986 static const char *set_scriptlog_length(cmd_parms *cmd, void *dummy, const char *arg)
988 server_rec *s = cmd->server;
989 cgid_server_conf *conf = ap_get_module_config(s->module_config,
992 conf->logbytes = atol(arg);
996 static const char *set_scriptlog_buffer(cmd_parms *cmd, void *dummy, const char *arg)
998 server_rec *s = cmd->server;
999 cgid_server_conf *conf = ap_get_module_config(s->module_config,
1002 conf->bufbytes = atoi(arg);
1006 static const char *set_script_socket(cmd_parms *cmd, void *dummy, const char *arg)
1008 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1013 /* Make sure the pid is appended to the sockname */
1014 sockname = ap_append_pid(cmd->pool, arg, ".");
1015 sockname = ap_server_root_relative(cmd->pool, sockname);
1018 return apr_pstrcat(cmd->pool, "Invalid ScriptSock path",
1025 static const command_rec cgid_cmds[] =
1027 AP_INIT_TAKE1("ScriptLog", set_scriptlog, NULL, RSRC_CONF,
1028 "the name of a log for script debugging info"),
1029 AP_INIT_TAKE1("ScriptLogLength", set_scriptlog_length, NULL, RSRC_CONF,
1030 "the maximum length (in bytes) of the script debug log"),
1031 AP_INIT_TAKE1("ScriptLogBuffer", set_scriptlog_buffer, NULL, RSRC_CONF,
1032 "the maximum size (in bytes) to record of a POST request"),
1033 AP_INIT_TAKE1("ScriptSock", set_script_socket, NULL, RSRC_CONF,
1034 "the name of the socket to use for communication with "
1039 static int log_scripterror(request_rec *r, cgid_server_conf * conf, int ret,
1040 apr_status_t rv, char *error)
1042 apr_file_t *f = NULL;
1044 char time_str[APR_CTIME_LEN];
1045 int log_flags = rv ? APLOG_ERR : APLOG_ERR;
1047 ap_log_rerror(APLOG_MARK, log_flags, rv, r,
1048 "%s: %s", error, r->filename);
1050 /* XXX Very expensive mainline case! Open, then getfileinfo! */
1051 if (!conf->logname ||
1052 ((stat(conf->logname, &finfo) == 0)
1053 && (finfo.st_size > conf->logbytes)) ||
1054 (apr_file_open(&f, conf->logname,
1055 APR_APPEND|APR_WRITE|APR_CREATE, APR_OS_DEFAULT, r->pool) != APR_SUCCESS)) {
1059 /* "%% [Wed Jun 19 10:53:21 1996] GET /cgid-bin/printenv HTTP/1.0" */
1060 apr_ctime(time_str, apr_time_now());
1061 apr_file_printf(f, "%%%% [%s] %s %s%s%s %s\n", time_str, r->method, r->uri,
1062 r->args ? "?" : "", r->args ? r->args : "", r->protocol);
1063 /* "%% 500 /usr/local/apache/cgid-bin */
1064 apr_file_printf(f, "%%%% %d %s\n", ret, r->filename);
1066 apr_file_printf(f, "%%error\n%s\n", error);
1072 static int log_script(request_rec *r, cgid_server_conf * conf, int ret,
1073 char *dbuf, const char *sbuf, apr_bucket_brigade *bb,
1074 apr_file_t *script_err)
1076 const apr_array_header_t *hdrs_arr = apr_table_elts(r->headers_in);
1077 const apr_table_entry_t *hdrs = (apr_table_entry_t *) hdrs_arr->elts;
1078 char argsbuffer[HUGE_STRING_LEN];
1079 apr_file_t *f = NULL;
1087 char time_str[APR_CTIME_LEN];
1089 /* XXX Very expensive mainline case! Open, then getfileinfo! */
1090 if (!conf->logname ||
1091 ((stat(conf->logname, &finfo) == 0)
1092 && (finfo.st_size > conf->logbytes)) ||
1093 (apr_file_open(&f, conf->logname,
1094 APR_APPEND|APR_WRITE|APR_CREATE, APR_OS_DEFAULT, r->pool) != APR_SUCCESS)) {
1095 /* Soak up script output */
1096 discard_script_output(bb);
1098 while (apr_file_gets(argsbuffer, HUGE_STRING_LEN,
1099 script_err) == APR_SUCCESS)
1105 /* "%% [Wed Jun 19 10:53:21 1996] GET /cgid-bin/printenv HTTP/1.0" */
1106 apr_ctime(time_str, apr_time_now());
1107 apr_file_printf(f, "%%%% [%s] %s %s%s%s %s\n", time_str, r->method, r->uri,
1108 r->args ? "?" : "", r->args ? r->args : "", r->protocol);
1109 /* "%% 500 /usr/local/apache/cgid-bin" */
1110 apr_file_printf(f, "%%%% %d %s\n", ret, r->filename);
1112 apr_file_puts("%request\n", f);
1113 for (i = 0; i < hdrs_arr->nelts; ++i) {
1116 apr_file_printf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val);
1118 if ((r->method_number == M_POST || r->method_number == M_PUT)
1120 apr_file_printf(f, "\n%s\n", dbuf);
1123 apr_file_puts("%response\n", f);
1124 hdrs_arr = apr_table_elts(r->err_headers_out);
1125 hdrs = (const apr_table_entry_t *) hdrs_arr->elts;
1127 for (i = 0; i < hdrs_arr->nelts; ++i) {
1130 apr_file_printf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val);
1134 apr_file_printf(f, "%s\n", sbuf);
1138 for (e = APR_BRIGADE_FIRST(bb);
1139 e != APR_BRIGADE_SENTINEL(bb);
1140 e = APR_BUCKET_NEXT(e))
1142 if (APR_BUCKET_IS_EOS(e)) {
1145 rv = apr_bucket_read(e, &buf, &len, APR_BLOCK_READ);
1146 if (rv != APR_SUCCESS || (len == 0)) {
1150 apr_file_puts("%stdout\n", f);
1153 apr_file_write(f, buf, &len);
1154 apr_file_puts("\n", f);
1158 if (apr_file_gets(argsbuffer, HUGE_STRING_LEN,
1159 script_err) == APR_SUCCESS) {
1160 apr_file_puts("%stderr\n", f);
1161 apr_file_puts(argsbuffer, f);
1162 while (apr_file_gets(argsbuffer, HUGE_STRING_LEN,
1163 script_err) == APR_SUCCESS)
1164 apr_file_puts(argsbuffer, f);
1165 apr_file_puts("\n", f);
1170 apr_file_close(script_err);
1177 static int connect_to_daemon(int *sdptr, request_rec *r,
1178 cgid_server_conf *conf)
1182 apr_interval_time_t sliding_timer;
1185 sliding_timer = 100000; /* 100 milliseconds */
1188 if ((sd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
1189 return log_scripterror(r, conf, HTTP_INTERNAL_SERVER_ERROR, errno,
1190 "unable to create socket to cgi daemon");
1192 if (connect(sd, (struct sockaddr *)server_addr, server_addr_len) < 0) {
1193 if (errno == ECONNREFUSED && connect_tries < DEFAULT_CONNECT_ATTEMPTS) {
1194 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, errno, r,
1195 "connect #%d to cgi daemon failed, sleeping before retry",
1198 apr_sleep(sliding_timer);
1199 if (sliding_timer < apr_time_from_sec(2)) {
1205 return log_scripterror(r, conf, HTTP_SERVICE_UNAVAILABLE, errno,
1206 "unable to connect to cgi daemon after multiple tries");
1210 apr_pool_cleanup_register(r->pool, (void *)((long)sd),
1211 close_unix_socket, apr_pool_cleanup_null);
1212 break; /* we got connected! */
1214 /* gotta try again, but make sure the cgid daemon is still around */
1215 if (kill(daemon_pid, 0) != 0) {
1216 return log_scripterror(r, conf, HTTP_SERVICE_UNAVAILABLE, errno,
1217 "cgid daemon is gone; is Apache terminating?");
1224 static void discard_script_output(apr_bucket_brigade *bb)
1231 for (e = APR_BRIGADE_FIRST(bb);
1232 e != APR_BRIGADE_SENTINEL(bb);
1233 e = APR_BUCKET_NEXT(e))
1235 if (APR_BUCKET_IS_EOS(e)) {
1238 rv = apr_bucket_read(e, &buf, &len, APR_BLOCK_READ);
1239 if (rv != APR_SUCCESS) {
1245 /****************************************************************
1247 * Actual cgid handling...
1250 struct cleanup_script_info {
1252 unsigned long conn_id;
1253 cgid_server_conf *conf;
1256 static apr_status_t dead_yet(pid_t pid, apr_interval_time_t max_wait)
1258 apr_interval_time_t interval = 10000; /* 10 ms */
1259 apr_interval_time_t total = 0;
1263 /* On AIX, for processes like mod_cgid's script children where
1264 * SIGCHLD is ignored, kill(pid,0) returns success for up to
1265 * one second after the script child exits, based on when a
1266 * daemon runs to clean up unnecessary process table entries.
1267 * getpgid() can report the proper info (-1/ESRCH) immediately.
1269 if (getpgid(pid) < 0) {
1271 if (kill(pid, 0) < 0) {
1275 apr_sleep(interval);
1276 total = total + interval;
1277 if (interval < 500000) {
1280 } while (total < max_wait);
1281 return APR_EGENERAL;
1284 static apr_status_t cleanup_nonchild_process(request_rec *r, pid_t pid)
1286 kill(pid, SIGTERM); /* in case it isn't dead yet */
1287 if (dead_yet(pid, apr_time_from_sec(3)) == APR_SUCCESS) {
1290 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1291 "CGI process %" APR_PID_T_FMT " didn't exit, sending SIGKILL",
1294 if (dead_yet(pid, apr_time_from_sec(3)) == APR_SUCCESS) {
1297 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1298 "CGI process %" APR_PID_T_FMT " didn't exit, sending SIGKILL again",
1302 return APR_EGENERAL;
1305 static apr_status_t cleanup_script(void *vptr)
1307 struct cleanup_script_info *info = vptr;
1310 cgid_req_t req = {0};
1314 rc = connect_to_daemon(&sd, info->r, info->conf);
1316 return APR_EGENERAL;
1319 /* we got a socket, and there is already a cleanup registered for it */
1321 req.req_type = GETPID_REQ;
1322 req.ppid = parent_pid;
1323 req.conn_id = info->r->connection->id;
1325 stat = sock_write(sd, &req, sizeof(req));
1326 if (stat != APR_SUCCESS) {
1330 /* wait for pid of script */
1331 stat = sock_read(sd, &pid, sizeof(pid));
1332 if (stat != APR_SUCCESS) {
1337 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, info->r,
1338 "daemon couldn't find CGI process for connection %lu",
1340 return APR_EGENERAL;
1342 return cleanup_nonchild_process(info->r, pid);
1345 static int cgid_handler(request_rec *r)
1347 int retval, nph, dbpos;
1349 apr_bucket_brigade *bb;
1351 cgid_server_conf *conf;
1353 int seen_eos, child_stopped_reading;
1356 apr_file_t *tempsock;
1357 struct cleanup_script_info *info;
1360 if (strcmp(r->handler, CGI_MAGIC_TYPE) && strcmp(r->handler, "cgi-script")) {
1364 conf = ap_get_module_config(r->server->module_config, &cgid_module);
1365 is_included = !strcmp(r->protocol, "INCLUDED");
1367 if ((argv0 = strrchr(r->filename, '/')) != NULL) {
1371 argv0 = r->filename;
1374 nph = !(strncmp(argv0, "nph-", 4));
1376 argv0 = r->filename;
1378 if (!(ap_allow_options(r) & OPT_EXECCGI) && !is_scriptaliased(r)) {
1379 return log_scripterror(r, conf, HTTP_FORBIDDEN, 0,
1380 "Options ExecCGI is off in this directory");
1383 if (nph && is_included) {
1384 return log_scripterror(r, conf, HTTP_FORBIDDEN, 0,
1385 "attempt to include NPH CGI script");
1388 #if defined(OS2) || defined(WIN32)
1389 #error mod_cgid does not work on this platform. If you teach it to, look
1390 #error at mod_cgi.c for required code in this path.
1392 if (r->finfo.filetype == APR_NOFILE) {
1393 return log_scripterror(r, conf, HTTP_NOT_FOUND, 0,
1394 "script not found or unable to stat");
1397 if (r->finfo.filetype == APR_DIR) {
1398 return log_scripterror(r, conf, HTTP_FORBIDDEN, 0,
1399 "attempt to invoke directory as script");
1402 if ((r->used_path_info == AP_REQ_REJECT_PATH_INFO) &&
1403 r->path_info && *r->path_info)
1405 /* default to accept */
1406 return log_scripterror(r, conf, HTTP_NOT_FOUND, 0,
1407 "AcceptPathInfo off disallows user's path");
1410 if (!ap_suexec_enabled) {
1411 if (!ap_can_exec(&r->finfo))
1412 return log_scripterror(r, conf, HTTP_FORBIDDEN, 0,
1413 "file permissions deny server execution");
1416 ap_add_common_vars(r);
1418 env = ap_create_environment(r->pool, r->subprocess_env);
1420 if ((retval = connect_to_daemon(&sd, r, conf)) != OK) {
1424 rv = send_req(sd, r, argv0, env, CGI_REQ);
1425 if (rv != APR_SUCCESS) {
1426 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1427 "write to cgi daemon process");
1430 info = apr_palloc(r->pool, sizeof(struct cleanup_script_info));
1432 info->conn_id = r->connection->id;
1434 apr_pool_cleanup_register(r->pool, info,
1436 apr_pool_cleanup_null);
1437 /* We are putting the socket discriptor into an apr_file_t so that we can
1438 * use a pipe bucket to send the data to the client. APR will create
1439 * a cleanup for the apr_file_t which will close the socket, so we'll
1440 * get rid of the cleanup we registered when we created the socket.
1443 apr_os_pipe_put_ex(&tempsock, &sd, 1, r->pool);
1444 apr_pool_cleanup_kill(r->pool, (void *)((long)sd), close_unix_socket);
1446 /* Transfer any put/post args, CERN style...
1447 * Note that we already ignore SIGPIPE in the core server.
1449 bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
1451 child_stopped_reading = 0;
1454 if (conf->logname) {
1455 dbuf = apr_palloc(r->pool, conf->bufbytes + 1);
1460 rv = ap_get_brigade(r->input_filters, bb, AP_MODE_READBYTES,
1461 APR_BLOCK_READ, HUGE_STRING_LEN);
1463 if (rv != APR_SUCCESS) {
1464 if (APR_STATUS_IS_TIMEUP(rv)) {
1465 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1466 "Timeout during reading request entity data");
1467 return HTTP_REQUEST_TIME_OUT;
1469 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1470 "Error reading request entity data");
1471 return HTTP_INTERNAL_SERVER_ERROR;
1474 for (bucket = APR_BRIGADE_FIRST(bb);
1475 bucket != APR_BRIGADE_SENTINEL(bb);
1476 bucket = APR_BUCKET_NEXT(bucket))
1481 if (APR_BUCKET_IS_EOS(bucket)) {
1486 /* We can't do much with this. */
1487 if (APR_BUCKET_IS_FLUSH(bucket)) {
1491 /* If the child stopped, we still must read to EOS. */
1492 if (child_stopped_reading) {
1497 apr_bucket_read(bucket, &data, &len, APR_BLOCK_READ);
1499 if (conf->logname && dbpos < conf->bufbytes) {
1502 if ((dbpos + len) > conf->bufbytes) {
1503 cursize = conf->bufbytes - dbpos;
1508 memcpy(dbuf + dbpos, data, cursize);
1512 /* Keep writing data to the child until done or too much time
1513 * elapses with no progress or an error occurs.
1515 rv = apr_file_write_full(tempsock, data, len, NULL);
1517 if (rv != APR_SUCCESS) {
1518 /* silly script stopped reading, soak up remaining message */
1519 child_stopped_reading = 1;
1522 apr_brigade_cleanup(bb);
1526 if (conf->logname) {
1530 /* we're done writing, or maybe we didn't write at all;
1531 * force EOF on child's stdin so that the cgi detects end (or
1536 /* Handle script return... */
1538 conn_rec *c = r->connection;
1539 const char *location;
1540 char sbuf[MAX_STRING_LEN];
1543 bb = apr_brigade_create(r->pool, c->bucket_alloc);
1544 b = apr_bucket_pipe_create(tempsock, c->bucket_alloc);
1545 APR_BRIGADE_INSERT_TAIL(bb, b);
1546 b = apr_bucket_eos_create(c->bucket_alloc);
1547 APR_BRIGADE_INSERT_TAIL(bb, b);
1549 if ((ret = ap_scan_script_header_err_brigade(r, bb, sbuf))) {
1550 ret = log_script(r, conf, ret, dbuf, sbuf, bb, NULL);
1553 * ret could be HTTP_NOT_MODIFIED in the case that the CGI script
1554 * does not set an explicit status and ap_meets_conditions, which
1555 * is called by ap_scan_script_header_err_brigade, detects that
1556 * the conditions of the requests are met and the response is
1558 * In this case set r->status and return OK in order to prevent
1559 * running through the error processing stack as this would
1560 * break with mod_cache, if the conditions had been set by
1561 * mod_cache itself to validate a stale entity.
1562 * BTW: We circumvent the error processing stack anyway if the
1563 * CGI script set an explicit status code (whatever it is) and
1564 * the only possible values for ret here are:
1566 * HTTP_NOT_MODIFIED (set by ap_meets_conditions)
1567 * HTTP_PRECONDITION_FAILED (set by ap_meets_conditions)
1568 * HTTP_INTERNAL_SERVER_ERROR (if something went wrong during the
1569 * processing of the response of the CGI script, e.g broken headers
1570 * or a crashed CGI process).
1572 if (ret == HTTP_NOT_MODIFIED) {
1580 location = apr_table_get(r->headers_out, "Location");
1582 if (location && location[0] == '/' && r->status == 200) {
1584 /* Soak up all the script output */
1585 discard_script_output(bb);
1586 apr_brigade_destroy(bb);
1587 /* This redirect needs to be a GET no matter what the original
1590 r->method = apr_pstrdup(r->pool, "GET");
1591 r->method_number = M_GET;
1593 /* We already read the message body (if any), so don't allow
1594 * the redirected request to think it has one. We can ignore
1595 * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR.
1597 apr_table_unset(r->headers_in, "Content-Length");
1599 ap_internal_redirect_handler(location, r);
1602 else if (location && r->status == 200) {
1603 /* XXX: Note that if a script wants to produce its own Redirect
1604 * body, it now has to explicitly *say* "Status: 302"
1606 discard_script_output(bb);
1607 apr_brigade_destroy(bb);
1608 return HTTP_MOVED_TEMPORARILY;
1611 ap_pass_brigade(r->output_filters, bb);
1615 conn_rec *c = r->connection;
1616 struct ap_filter_t *cur;
1618 /* get rid of all filters up through protocol... since we
1619 * haven't parsed off the headers, there is no way they can
1623 cur = r->proto_output_filters;
1624 while (cur && cur->frec->ftype < AP_FTYPE_CONNECTION) {
1627 r->output_filters = r->proto_output_filters = cur;
1629 bb = apr_brigade_create(r->pool, c->bucket_alloc);
1630 b = apr_bucket_pipe_create(tempsock, c->bucket_alloc);
1631 APR_BRIGADE_INSERT_TAIL(bb, b);
1632 b = apr_bucket_eos_create(c->bucket_alloc);
1633 APR_BRIGADE_INSERT_TAIL(bb, b);
1634 ap_pass_brigade(r->output_filters, bb);
1637 return OK; /* NOT r->status, even if it has changed. */
1643 /*============================================================================
1644 *============================================================================
1645 * This is the beginning of the cgi filter code moved from mod_include. This
1646 * is the code required to handle the "exec" SSI directive.
1647 *============================================================================
1648 *============================================================================*/
1649 static apr_status_t include_cgi(include_ctx_t *ctx, ap_filter_t *f,
1650 apr_bucket_brigade *bb, char *s)
1652 request_rec *r = f->r;
1653 request_rec *rr = ap_sub_req_lookup_uri(s, r, f->next);
1656 if (rr->status != HTTP_OK) {
1657 ap_destroy_sub_req(rr);
1658 return APR_EGENERAL;
1661 /* No hardwired path info or query allowed */
1662 if ((rr->path_info && rr->path_info[0]) || rr->args) {
1663 ap_destroy_sub_req(rr);
1664 return APR_EGENERAL;
1666 if (rr->finfo.filetype != APR_REG) {
1667 ap_destroy_sub_req(rr);
1668 return APR_EGENERAL;
1671 /* Script gets parameters of the *document*, for back compatibility */
1672 rr->path_info = r->path_info; /* hard to get right; see mod_cgi.c */
1675 /* Force sub_req to be treated as a CGI request, even if ordinary
1676 * typing rules would have called it something else.
1678 ap_set_content_type(rr, CGI_MAGIC_TYPE);
1681 rr_status = ap_run_sub_req(rr);
1682 if (ap_is_HTTP_REDIRECT(rr_status)) {
1683 const char *location = apr_table_get(rr->headers_out, "Location");
1688 location = ap_escape_html(rr->pool, location);
1689 buffer = apr_pstrcat(ctx->pool, "<a href=\"", location, "\">",
1690 location, "</a>", NULL);
1692 APR_BRIGADE_INSERT_TAIL(bb, apr_bucket_pool_create(buffer,
1693 strlen(buffer), ctx->pool,
1694 f->c->bucket_alloc));
1698 ap_destroy_sub_req(rr);
1703 /* This is the special environment used for running the "exec cmd="
1704 * variety of SSI directives.
1706 static void add_ssi_vars(request_rec *r)
1708 apr_table_t *e = r->subprocess_env;
1710 if (r->path_info && r->path_info[0] != '\0') {
1711 request_rec *pa_req;
1713 apr_table_setn(e, "PATH_INFO", ap_escape_shell_cmd(r->pool, r->path_info));
1715 pa_req = ap_sub_req_lookup_uri(ap_escape_uri(r->pool, r->path_info), r, NULL);
1716 if (pa_req->filename) {
1717 apr_table_setn(e, "PATH_TRANSLATED",
1718 apr_pstrcat(r->pool, pa_req->filename, pa_req->path_info, NULL));
1720 ap_destroy_sub_req(pa_req);
1724 char *arg_copy = apr_pstrdup(r->pool, r->args);
1726 apr_table_setn(e, "QUERY_STRING", r->args);
1727 ap_unescape_url(arg_copy);
1728 apr_table_setn(e, "QUERY_STRING_UNESCAPED", ap_escape_shell_cmd(r->pool, arg_copy));
1732 static int include_cmd(include_ctx_t *ctx, ap_filter_t *f,
1733 apr_bucket_brigade *bb, char *command)
1738 apr_file_t *tempsock = NULL;
1739 request_rec *r = f->r;
1740 cgid_server_conf *conf = ap_get_module_config(r->server->module_config,
1742 struct cleanup_script_info *info;
1745 env = ap_create_environment(r->pool, r->subprocess_env);
1747 if ((retval = connect_to_daemon(&sd, r, conf)) != OK) {
1751 send_req(sd, r, command, env, SSI_REQ);
1753 info = apr_palloc(r->pool, sizeof(struct cleanup_script_info));
1755 info->conn_id = r->connection->id;
1757 /* for this type of request, the script is invoked through an
1758 * intermediate shell process... cleanup_script is only able
1759 * to knock out the shell process, not the actual script
1761 apr_pool_cleanup_register(r->pool, info,
1763 apr_pool_cleanup_null);
1765 /* We are putting the socket discriptor into an apr_file_t so that we can
1766 * use a pipe bucket to send the data to the client. APR will create
1767 * a cleanup for the apr_file_t which will close the socket, so we'll
1768 * get rid of the cleanup we registered when we created the socket.
1770 apr_os_pipe_put_ex(&tempsock, &sd, 1, r->pool);
1771 apr_pool_cleanup_kill(r->pool, (void *)((long)sd), close_unix_socket);
1773 APR_BRIGADE_INSERT_TAIL(bb, apr_bucket_pipe_create(tempsock,
1774 f->c->bucket_alloc));
1780 static apr_status_t handle_exec(include_ctx_t *ctx, ap_filter_t *f,
1781 apr_bucket_brigade *bb)
1784 char *tag_val = NULL;
1785 request_rec *r = f->r;
1786 char *file = r->filename;
1787 char parsed_string[MAX_STRING_LEN];
1790 ap_log_rerror(APLOG_MARK,
1791 (ctx->flags & SSI_FLAG_PRINTING)
1792 ? APLOG_ERR : APLOG_WARNING,
1793 0, r, "missing argument for exec element in %s",
1797 if (!(ctx->flags & SSI_FLAG_PRINTING)) {
1802 SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
1806 if (ctx->flags & SSI_FLAG_NO_EXEC) {
1807 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "exec used but not allowed "
1808 "in %s", r->filename);
1809 SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
1814 cgid_pfn_gtv(ctx, &tag, &tag_val, SSI_VALUE_DECODED);
1815 if (!tag || !tag_val) {
1819 if (!strcmp(tag, "cmd")) {
1822 cgid_pfn_ps(ctx, tag_val, parsed_string, sizeof(parsed_string),
1823 SSI_EXPAND_LEAVE_NAME);
1825 rv = include_cmd(ctx, f, bb, parsed_string);
1826 if (rv != APR_SUCCESS) {
1827 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1828 "execution failure for parameter \"%s\" "
1829 "to tag exec in file %s", tag, r->filename);
1830 SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
1834 else if (!strcmp(tag, "cgi")) {
1837 cgid_pfn_ps(ctx, tag_val, parsed_string, sizeof(parsed_string),
1838 SSI_EXPAND_DROP_NAME);
1840 rv = include_cgi(ctx, f, bb, parsed_string);
1841 if (rv != APR_SUCCESS) {
1842 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "invalid CGI ref "
1843 "\"%s\" in %s", tag_val, file);
1844 SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
1849 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "unknown parameter "
1850 "\"%s\" to tag exec in %s", tag, file);
1851 SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
1858 /*============================================================================
1859 *============================================================================
1860 * This is the end of the cgi filter code moved from mod_include.
1861 *============================================================================
1862 *============================================================================*/
1865 static void register_hook(apr_pool_t *p)
1867 static const char * const aszPre[] = { "mod_include.c", NULL };
1869 ap_hook_pre_config(cgid_pre_config, NULL, NULL, APR_HOOK_MIDDLE);
1870 ap_hook_post_config(cgid_init, aszPre, NULL, APR_HOOK_MIDDLE);
1871 ap_hook_handler(cgid_handler, NULL, NULL, APR_HOOK_MIDDLE);
1874 AP_DECLARE_MODULE(cgid) = {
1875 STANDARD20_MODULE_STUFF,
1876 NULL, /* dir config creater */
1877 NULL, /* dir merger --- default is to override */
1878 create_cgid_config, /* server config */
1879 merge_cgid_config, /* merge server config */
1880 cgid_cmds, /* command table */
1881 register_hook /* register_handlers */