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 */
73 #if APR_HAVE_STRUCT_RLIMIT
74 #if defined (RLIMIT_CPU) || defined (RLIMIT_NPROC) || defined (RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
75 #define AP_CGID_USE_RLIMIT
79 module AP_MODULE_DECLARE_DATA cgid_module;
81 static int cgid_start(apr_pool_t *p, server_rec *main_server, apr_proc_t *procnew);
82 static int cgid_init(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *main_server);
83 static int handle_exec(include_ctx_t *ctx, ap_filter_t *f, apr_bucket_brigade *bb);
85 static APR_OPTIONAL_FN_TYPE(ap_register_include_handler) *cgid_pfn_reg_with_ssi;
86 static APR_OPTIONAL_FN_TYPE(ap_ssi_get_tag_and_value) *cgid_pfn_gtv;
87 static APR_OPTIONAL_FN_TYPE(ap_ssi_parse_string) *cgid_pfn_ps;
89 static apr_pool_t *pcgi = NULL;
90 static int total_modules = 0;
91 static pid_t daemon_pid;
92 static int daemon_should_exit = 0;
93 static server_rec *root_server = NULL;
94 static apr_pool_t *root_pool = NULL;
95 static const char *sockname;
96 static struct sockaddr_un *server_addr;
97 static apr_socklen_t server_addr_len;
98 static pid_t parent_pid;
99 static ap_unix_identity_t empty_ugid = { (uid_t)-1, (gid_t)-1, -1 };
101 /* The APR other-child API doesn't tell us how the daemon exited
102 * (SIGSEGV vs. exit(1)). The other-child maintenance function
103 * needs to decide whether to restart the daemon after a failure
104 * based on whether or not it exited due to a fatal startup error
105 * or something that happened at steady-state. This exit status
106 * is unlikely to collide with exit signals.
108 #define DAEMON_STARTUP_ERROR 254
110 /* Read and discard the data in the brigade produced by a CGI script */
111 static void discard_script_output(apr_bucket_brigade *bb);
113 /* This doer will only ever be called when we are sure that we have
116 static ap_unix_identity_t *cgid_suexec_id_doer(const request_rec *r)
118 return (ap_unix_identity_t *)
119 ap_get_module_config(r->request_config, &cgid_module);
122 /* KLUDGE --- for back-combatibility, we don't have to check ExecCGI
123 * in ScriptAliased directories, which means we need to know if this
124 * request came through ScriptAlias or not... so the Alias module
125 * leaves a note for us.
128 static int is_scriptaliased(request_rec *r)
130 const char *t = apr_table_get(r->notes, "alias-forced-type");
131 return t && (!strcasecmp(t, "cgi-script"));
134 /* Configuration stuff */
136 #define DEFAULT_LOGBYTES 10385760
137 #define DEFAULT_BUFBYTES 1024
138 #define DEFAULT_SOCKET DEFAULT_REL_RUNTIMEDIR "/cgisock"
142 #define GETPID_REQ 3 /* get the pid of script created for prior request */
144 #define ERRFN_USERDATA_KEY "CGIDCHILDERRFN"
146 /* DEFAULT_CGID_LISTENBACKLOG controls the max depth on the unix socket's
147 * pending connection queue. If a bunch of cgi requests arrive at about
148 * the same time, connections from httpd threads/processes will back up
149 * in the queue while the cgid process slowly forks off a child to process
150 * each connection on the unix socket. If the queue is too short, the
151 * httpd process will get ECONNREFUSED when trying to connect.
153 #ifndef DEFAULT_CGID_LISTENBACKLOG
154 #define DEFAULT_CGID_LISTENBACKLOG 100
157 /* DEFAULT_CONNECT_ATTEMPTS controls how many times we'll try to connect
158 * to the cgi daemon from the thread/process handling the cgi request.
159 * Generally we want to retry when we get ECONNREFUSED since it is
160 * probably because the listen queue is full. We need to try harder so
161 * the client doesn't see it as a 503 error.
163 * Set this to 0 to continually retry until the connect works or Apache
166 #ifndef DEFAULT_CONNECT_ATTEMPTS
167 #define DEFAULT_CONNECT_ATTEMPTS 15
176 #ifdef AP_CGID_USE_RLIMIT
180 struct rlimit limit_cpu;
182 #if defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined(RLIMIT_AS)
184 struct rlimit limit_mem;
188 struct rlimit limit_nproc;
195 int req_type; /* request type (CGI_REQ, SSI_REQ, etc.) */
196 unsigned long conn_id; /* connection id; daemon uses this as a hash value
197 * to find the script pid when it is time for that
198 * process to be cleaned up
200 pid_t ppid; /* sanity check for config problems leading to
201 * wrong cgid socket use
204 ap_unix_identity_t ugid;
205 apr_size_t filename_len;
206 apr_size_t argv0_len;
209 int loglevel; /* to stuff in server_rec */
211 #ifdef AP_CGID_USE_RLIMIT
212 cgid_rlimit_t limits;
216 /* This routine is called to create the argument list to be passed
217 * to the CGI script. When suexec is enabled, the suexec path, user, and
218 * group are the first three arguments to be passed; if not, all three
219 * must be NULL. The query info is split into separate arguments, where
220 * "+" is the separator between keyword arguments.
222 * Do not process the args if they containing an '=' assignment.
224 static char **create_argv(apr_pool_t *p, char *path, char *user, char *group,
225 char *av0, const char *args)
232 if (!(*args) || ap_strchr_c(args, '=')) {
236 /* count the number of keywords */
238 for (x = 0, numwords = 1; args[x]; x++) {
239 if (args[x] == '+') {
245 if (numwords > APACHE_ARG_MAX - 5) {
246 numwords = APACHE_ARG_MAX - 5; /* Truncate args to prevent overrun */
248 av = (char **) apr_pcalloc(p, (numwords + 5) * sizeof(char *));
260 av[idx++] = apr_pstrdup(p, av0);
262 for (x = 1; x <= numwords; x++) {
263 w = ap_getword_nulls(p, &args, '+');
265 av[idx++] = ap_escape_shell_cmd(p, w);
271 #if APR_HAS_OTHER_CHILD
272 static void cgid_maint(int reason, void *data, apr_wait_t status)
274 apr_proc_t *proc = data;
279 case APR_OC_REASON_DEATH:
280 apr_proc_other_child_unregister(data);
281 /* If apache is not terminating or restarting,
282 * restart the cgid daemon
284 stopping = 1; /* if MPM doesn't support query,
285 * assume we shouldn't restart daemon
287 if (ap_mpm_query(AP_MPMQ_MPM_STATE, &mpm_state) == APR_SUCCESS &&
288 mpm_state != AP_MPMQ_STOPPING) {
292 if (status == DAEMON_STARTUP_ERROR) {
293 ap_log_error(APLOG_MARK, APLOG_CRIT, 0, ap_server_conf, APLOGNO(01238)
294 "cgid daemon failed to initialize");
297 ap_log_error(APLOG_MARK, APLOG_ERR, 0, ap_server_conf, APLOGNO(01239)
298 "cgid daemon process died, restarting");
299 cgid_start(root_pool, root_server, proc);
303 case APR_OC_REASON_RESTART:
304 /* don't do anything; server is stopping or restarting */
305 apr_proc_other_child_unregister(data);
307 case APR_OC_REASON_LOST:
308 /* Restart the child cgid daemon process */
309 apr_proc_other_child_unregister(data);
310 cgid_start(root_pool, root_server, proc);
312 case APR_OC_REASON_UNREGISTER:
313 /* we get here when pcgi is cleaned up; pcgi gets cleaned
314 * up when pconf gets cleaned up
316 kill(proc->pid, SIGHUP); /* send signal to daemon telling it to die */
318 /* Remove the cgi socket, we must do it here in order to try and
319 * guarantee the same permissions as when the socket was created.
321 if (unlink(sockname) < 0 && errno != ENOENT) {
322 ap_log_error(APLOG_MARK, APLOG_ERR, errno, ap_server_conf, APLOGNO(01240)
323 "Couldn't unlink unix domain socket %s",
331 static apr_status_t close_unix_socket(void *thefd)
333 int fd = (int)((long)thefd);
338 /* deal with incomplete reads and signals
339 * assume you really have to read buf_size bytes
341 static apr_status_t sock_read(int fd, void *vbuf, size_t buf_size)
345 size_t bytes_read = 0;
349 rc = read(fd, buf + bytes_read, buf_size - bytes_read);
350 } while (rc < 0 && errno == EINTR);
354 case 0: /* unexpected */
359 } while (bytes_read < buf_size);
366 static apr_status_t sock_write(int fd, const void *buf, size_t buf_size)
371 rc = write(fd, buf, buf_size);
372 } while (rc < 0 && errno == EINTR);
380 static apr_status_t sock_writev(int fd, request_rec *r, int count, ...)
387 vec = (struct iovec *)apr_palloc(r->pool, count * sizeof(struct iovec));
389 for (i = 0; i < count; i++) {
390 vec[i].iov_base = va_arg(ap, caddr_t);
391 vec[i].iov_len = va_arg(ap, apr_size_t);
396 rc = writev(fd, vec, count);
397 } while (rc < 0 && errno == EINTR);
405 static apr_status_t get_req(int fd, request_rec *r, char **argv0, char ***env,
410 core_request_config *temp_core;
414 r->server = apr_pcalloc(r->pool, sizeof(server_rec));
416 /* read the request header */
417 stat = sock_read(fd, req, sizeof(*req));
418 if (stat != APR_SUCCESS) {
421 r->server->log.level = req->loglevel;
422 if (req->req_type == GETPID_REQ) {
423 /* no more data sent for this request */
427 /* handle module indexes and such */
428 rconf = (void **)ap_create_request_config(r->pool);
430 temp_core = (core_request_config *)apr_palloc(r->pool, sizeof(core_module));
431 rconf[AP_CORE_MODULE_INDEX] = (void *)temp_core;
432 r->request_config = (ap_conf_vector_t *)rconf;
433 ap_set_module_config(r->request_config, &cgid_module, (void *)&req->ugid);
435 /* Read the filename, argv0, uri, and args */
436 r->filename = apr_pcalloc(r->pool, req->filename_len + 1);
437 *argv0 = apr_pcalloc(r->pool, req->argv0_len + 1);
438 r->uri = apr_pcalloc(r->pool, req->uri_len + 1);
439 if ((stat = sock_read(fd, r->filename, req->filename_len)) != APR_SUCCESS ||
440 (stat = sock_read(fd, *argv0, req->argv0_len)) != APR_SUCCESS ||
441 (stat = sock_read(fd, r->uri, req->uri_len)) != APR_SUCCESS) {
445 r->args = apr_pcalloc(r->pool, req->args_len + 1); /* empty string if no args */
447 if ((stat = sock_read(fd, r->args, req->args_len)) != APR_SUCCESS) {
452 /* read the environment variables */
453 environ = apr_pcalloc(r->pool, (req->env_count + 2) *sizeof(char *));
454 for (i = 0; i < req->env_count; i++) {
457 if ((stat = sock_read(fd, &curlen, sizeof(curlen))) != APR_SUCCESS) {
460 environ[i] = apr_pcalloc(r->pool, curlen + 1);
461 if ((stat = sock_read(fd, environ[i], curlen)) != APR_SUCCESS) {
467 #ifdef AP_CGID_USE_RLIMIT
468 if ((stat = sock_read(fd, &(req->limits), sizeof(cgid_rlimit_t))) != APR_SUCCESS)
475 static apr_status_t send_req(int fd, request_rec *r, char *argv0, char **env,
479 cgid_req_t req = {0};
481 ap_unix_identity_t * ugid = ap_run_get_suexec_identity(r);
482 core_dir_config *core_conf = ap_get_core_module_config(r->per_dir_config);
486 req.ugid = empty_ugid;
488 memcpy(&req.ugid, ugid, sizeof(ap_unix_identity_t));
491 req.req_type = req_type;
492 req.ppid = parent_pid;
493 req.conn_id = r->connection->id;
494 for (req.env_count = 0; env[req.env_count]; req.env_count++) {
497 req.filename_len = strlen(r->filename);
498 req.argv0_len = strlen(argv0);
499 req.uri_len = strlen(r->uri);
500 req.args_len = r->args ? strlen(r->args) : 0;
501 req.loglevel = r->server->log.level;
503 /* Write the request header */
505 stat = sock_writev(fd, r, 5,
507 r->filename, req.filename_len,
508 argv0, req.argv0_len,
510 r->args, req.args_len);
512 stat = sock_writev(fd, r, 4,
514 r->filename, req.filename_len,
515 argv0, req.argv0_len,
516 r->uri, req.uri_len);
519 if (stat != APR_SUCCESS) {
523 /* write the environment variables */
524 for (i = 0; i < req.env_count; i++) {
525 apr_size_t curlen = strlen(env[i]);
527 if ((stat = sock_writev(fd, r, 2, &curlen, sizeof(curlen),
528 env[i], curlen)) != APR_SUCCESS) {
532 #if defined(RLIMIT_CPU) && defined(AP_CGID_USE_RLIMIT)
533 if (core_conf->limit_cpu) {
534 req.limits.limit_cpu = *(core_conf->limit_cpu);
535 req.limits.limit_cpu_set = 1;
538 req.limits.limit_cpu_set = 0;
542 #if defined(AP_CGID_USE_RLIMIT) && (defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS))
543 if (core_conf->limit_mem) {
544 req.limits.limit_mem = *(core_conf->limit_mem);
545 req.limits.limit_mem_set = 1;
548 req.limits.limit_mem_set = 0;
553 #if defined(RLIMIT_NPROC) && defined(AP_CGID_USE_RLIMIT)
554 if (core_conf->limit_nproc) {
555 req.limits.limit_nproc = *(core_conf->limit_nproc);
556 req.limits.limit_nproc_set = 1;
559 req.limits.limit_nproc_set = 0;
563 #ifdef AP_CGID_USE_RLIMIT
564 if ( (stat = sock_write(fd, &(req.limits), sizeof(cgid_rlimit_t))) != APR_SUCCESS)
571 static void daemon_signal_handler(int sig)
574 ++daemon_should_exit;
578 static void cgid_child_errfn(apr_pool_t *pool, apr_status_t err,
579 const char *description)
584 apr_pool_userdata_get(&vr, ERRFN_USERDATA_KEY, pool);
587 /* sure we got r, but don't call ap_log_rerror() because we don't
588 * have r->headers_in and possibly other storage referenced by
591 ap_log_error(APLOG_MARK, APLOG_ERR, err, r->server, APLOGNO(01241) "%s", description);
594 static int cgid_server(void *data)
599 server_rec *main_server = data;
600 apr_hash_t *script_hash = apr_hash_make(pcgi);
603 apr_pool_create(&ptrans, pcgi);
605 apr_signal(SIGCHLD, SIG_IGN);
606 apr_signal(SIGHUP, daemon_signal_handler);
608 /* Close our copy of the listening sockets */
609 ap_close_listeners();
611 /* cgid should use its own suexec doer */
612 ap_hook_get_suexec_identity(cgid_suexec_id_doer, NULL, NULL,
613 APR_HOOK_REALLY_FIRST);
616 if ((sd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
617 ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server, APLOGNO(01242)
618 "Couldn't create unix domain socket");
622 omask = umask(0077); /* so that only Apache can use socket */
623 rc = bind(sd, (struct sockaddr *)server_addr, server_addr_len);
624 umask(omask); /* can't fail, so can't clobber errno */
626 ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server, APLOGNO(01243)
627 "Couldn't bind unix domain socket %s",
632 /* Not all flavors of unix use the current umask for AF_UNIX perms */
633 rv = apr_file_perms_set(sockname, APR_FPROT_UREAD|APR_FPROT_UWRITE|APR_FPROT_UEXECUTE);
634 if (rv != APR_SUCCESS) {
635 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, main_server, APLOGNO(01244)
636 "Couldn't set permissions on unix domain socket %s",
641 if (listen(sd, DEFAULT_CGID_LISTENBACKLOG) < 0) {
642 ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server, APLOGNO(01245)
643 "Couldn't listen on unix domain socket");
648 if (chown(sockname, ap_unixd_config.user_id, -1) < 0) {
649 ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server, APLOGNO(01246)
650 "Couldn't change owner of unix domain socket %s",
656 apr_pool_cleanup_register(pcgi, (void *)((long)sd),
657 close_unix_socket, close_unix_socket);
659 /* if running as root, switch to configured user/group */
660 if ((rc = ap_run_drop_privileges(pcgi, ap_server_conf)) != 0) {
664 while (!daemon_should_exit) {
665 int errfileno = STDERR_FILENO;
668 const char * const *argv;
670 apr_int32_t out_pipe;
671 apr_int32_t err_pipe;
672 apr_cmdtype_e cmd_type;
674 apr_procattr_t *procattr = NULL;
675 apr_proc_t *procnew = NULL;
681 struct sockaddr_un unix_addr;
683 apr_pool_clear(ptrans);
685 len = sizeof(unix_addr);
686 sd2 = accept(sd, (struct sockaddr *)&unix_addr, &len);
688 #if defined(ENETDOWN)
689 if (errno == ENETDOWN) {
690 /* The network has been shut down, no need to continue. Die gracefully */
691 ++daemon_should_exit;
694 if (errno != EINTR) {
695 ap_log_error(APLOG_MARK, APLOG_ERR, errno,
696 (server_rec *)data, APLOGNO(01247)
697 "Error accepting on cgid socket");
702 r = apr_pcalloc(ptrans, sizeof(request_rec));
703 procnew = apr_pcalloc(ptrans, sizeof(*procnew));
705 stat = get_req(sd2, r, &argv0, &env, &cgid_req);
706 if (stat != APR_SUCCESS) {
707 ap_log_error(APLOG_MARK, APLOG_ERR, stat,
708 main_server, APLOGNO(01248)
709 "Error reading request on cgid socket");
714 if (cgid_req.ppid != parent_pid) {
715 ap_log_error(APLOG_MARK, APLOG_CRIT, 0, main_server, APLOGNO(01249)
716 "CGI request received from wrong server instance; "
717 "see ScriptSock directive");
722 if (cgid_req.req_type == GETPID_REQ) {
726 pid = (pid_t)((long)apr_hash_get(script_hash, &cgid_req.conn_id, sizeof(cgid_req.conn_id)));
727 rv = sock_write(sd2, &pid, sizeof(pid));
728 if (rv != APR_SUCCESS) {
729 ap_log_error(APLOG_MARK, APLOG_ERR, rv,
730 main_server, APLOGNO(01250)
731 "Error writing pid %" APR_PID_T_FMT " to handler", pid);
737 apr_os_file_put(&r->server->error_log, &errfileno, 0, r->pool);
738 apr_os_file_put(&inout, &sd2, 0, r->pool);
740 if (cgid_req.req_type == SSI_REQ) {
741 in_pipe = APR_NO_PIPE;
742 out_pipe = APR_FULL_BLOCK;
743 err_pipe = APR_NO_PIPE;
744 cmd_type = APR_SHELLCMD;
747 in_pipe = APR_CHILD_BLOCK;
748 out_pipe = APR_CHILD_BLOCK;
749 err_pipe = APR_CHILD_BLOCK;
750 cmd_type = APR_PROGRAM;
753 if (((rc = apr_procattr_create(&procattr, ptrans)) != APR_SUCCESS) ||
754 ((cgid_req.req_type == CGI_REQ) &&
755 (((rc = apr_procattr_io_set(procattr,
758 err_pipe)) != APR_SUCCESS) ||
759 /* XXX apr_procattr_child_*_set() is creating an unnecessary
760 * pipe between this process and the child being created...
761 * It is cleaned up with the temporary pool for this request.
763 ((rc = apr_procattr_child_err_set(procattr, r->server->error_log, NULL)) != APR_SUCCESS) ||
764 ((rc = apr_procattr_child_in_set(procattr, inout, NULL)) != APR_SUCCESS))) ||
765 ((rc = apr_procattr_child_out_set(procattr, inout, NULL)) != APR_SUCCESS) ||
766 ((rc = apr_procattr_dir_set(procattr,
767 ap_make_dirstr_parent(r->pool, r->filename))) != APR_SUCCESS) ||
768 ((rc = apr_procattr_cmdtype_set(procattr, cmd_type)) != APR_SUCCESS) ||
769 #ifdef AP_CGID_USE_RLIMIT
771 ( (cgid_req.limits.limit_cpu_set) && ((rc = apr_procattr_limit_set(procattr, APR_LIMIT_CPU,
772 &cgid_req.limits.limit_cpu)) != APR_SUCCESS)) ||
774 #if defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
775 ( (cgid_req.limits.limit_mem_set) && ((rc = apr_procattr_limit_set(procattr, APR_LIMIT_MEM,
776 &cgid_req.limits.limit_mem)) != APR_SUCCESS)) ||
779 ( (cgid_req.limits.limit_nproc_set) && ((rc = apr_procattr_limit_set(procattr, APR_LIMIT_NPROC,
780 &cgid_req.limits.limit_nproc)) != APR_SUCCESS)) ||
784 ((rc = apr_procattr_child_errfn_set(procattr, cgid_child_errfn)) != APR_SUCCESS)) {
785 /* Something bad happened, tell the world.
786 * ap_log_rerror() won't work because the header table used by
787 * ap_log_rerror() hasn't been replicated in the phony r
789 ap_log_error(APLOG_MARK, APLOG_ERR, rc, r->server, APLOGNO(01251)
790 "couldn't set child process attributes: %s", r->filename);
792 procnew->pid = 0; /* no process to clean up */
796 apr_pool_userdata_set(r, ERRFN_USERDATA_KEY, apr_pool_cleanup_null, ptrans);
798 argv = (const char * const *)create_argv(r->pool, NULL, NULL, NULL, argv0, r->args);
800 /* We want to close sd2 for the new CGI process too.
801 * If it is left open it'll make ap_pass_brigade() block
802 * waiting for EOF if CGI forked something running long.
803 * close(sd2) here should be okay, as CGI channel
804 * is already dup()ed by apr_procattr_child_{in,out}_set()
809 if (memcmp(&empty_ugid, &cgid_req.ugid, sizeof(empty_ugid))) {
810 /* We have a valid identity, and can be sure that
811 * cgid_suexec_id_doer will return a valid ugid
813 rc = ap_os_create_privileged_process(r, procnew, argv0, argv,
814 (const char * const *)env,
817 rc = apr_proc_create(procnew, argv0, argv,
818 (const char * const *)env,
822 if (rc != APR_SUCCESS) {
823 /* Bad things happened. Everyone should have cleaned up.
824 * ap_log_rerror() won't work because the header table used by
825 * ap_log_rerror() hasn't been replicated in the phony r
827 ap_log_error(APLOG_MARK, APLOG_ERR, rc, r->server, APLOGNO(01252)
828 "couldn't create child process: %d: %s", rc,
829 apr_filepath_name_get(r->filename));
831 procnew->pid = 0; /* no process to clean up */
835 /* If the script process was created, remember the pid for
836 * later cleanup. If the script process wasn't created, clear
837 * out any prior pid with the same key.
839 * We don't want to leak storage for the key, so only allocate
840 * a key if the key doesn't exist yet in the hash; there are
841 * only a limited number of possible keys (one for each
842 * possible thread in the server), so we can allocate a copy
843 * of the key the first time a thread has a cgid request.
844 * Note that apr_hash_set() only uses the storage passed in
845 * for the key if it is adding the key to the hash for the
846 * first time; new key storage isn't needed for replacing the
847 * existing value of a key.
850 if (apr_hash_get(script_hash, &cgid_req.conn_id, sizeof(cgid_req.conn_id))) {
851 key = &cgid_req.conn_id;
854 key = apr_pmemdup(pcgi, &cgid_req.conn_id, sizeof(cgid_req.conn_id));
856 apr_hash_set(script_hash, key, sizeof(cgid_req.conn_id),
857 (void *)((long)procnew->pid));
859 return -1; /* should be <= 0 to distinguish from startup errors */
862 static int cgid_start(apr_pool_t *p, server_rec *main_server,
866 daemon_should_exit = 0; /* clear setting from previous generation */
867 if ((daemon_pid = fork()) < 0) {
868 ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server, APLOGNO(01253)
869 "mod_cgid: Couldn't spawn cgid daemon process");
872 else if (daemon_pid == 0) {
874 apr_pool_create(&pcgi, p);
876 exit(cgid_server(main_server) > 0 ? DAEMON_STARTUP_ERROR : -1);
878 procnew->pid = daemon_pid;
879 procnew->err = procnew->in = procnew->out = NULL;
880 apr_pool_note_subprocess(p, procnew, APR_KILL_AFTER_TIMEOUT);
881 #if APR_HAS_OTHER_CHILD
882 apr_proc_other_child_register(procnew, cgid_maint, procnew, NULL, p);
887 static int cgid_pre_config(apr_pool_t *pconf, apr_pool_t *plog,
890 sockname = ap_append_pid(pconf, DEFAULT_SOCKET, ".");
894 static int cgid_init(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp,
895 server_rec *main_server)
897 apr_proc_t *procnew = NULL;
898 const char *userdata_key = "cgid_init";
903 root_server = main_server;
906 apr_pool_userdata_get(&data, userdata_key, main_server->process->pool);
908 procnew = apr_pcalloc(main_server->process->pool, sizeof(*procnew));
910 procnew->err = procnew->in = procnew->out = NULL;
911 apr_pool_userdata_set((const void *)procnew, userdata_key,
912 apr_pool_cleanup_null, main_server->process->pool);
918 if (ap_state_query(AP_SQ_MAIN_STATE) != AP_SQ_MS_CREATE_PRE_CONFIG) {
921 for (m = ap_preloaded_modules; *m != NULL; m++)
924 parent_pid = getpid();
925 tmp_sockname = ap_server_root_relative(p, sockname);
926 if (strlen(tmp_sockname) > sizeof(server_addr->sun_path) - 1) {
927 tmp_sockname[sizeof(server_addr->sun_path)] = '\0';
928 ap_log_error(APLOG_MARK, APLOG_ERR, 0, main_server, APLOGNO(01254)
929 "The length of the ScriptSock path exceeds maximum, "
930 "truncating to %s", tmp_sockname);
932 sockname = tmp_sockname;
934 server_addr_len = APR_OFFSETOF(struct sockaddr_un, sun_path) + strlen(sockname);
935 server_addr = (struct sockaddr_un *)apr_palloc(p, server_addr_len + 1);
936 server_addr->sun_family = AF_UNIX;
937 strcpy(server_addr->sun_path, sockname);
939 ret = cgid_start(p, main_server, procnew);
943 cgid_pfn_reg_with_ssi = APR_RETRIEVE_OPTIONAL_FN(ap_register_include_handler);
944 cgid_pfn_gtv = APR_RETRIEVE_OPTIONAL_FN(ap_ssi_get_tag_and_value);
945 cgid_pfn_ps = APR_RETRIEVE_OPTIONAL_FN(ap_ssi_parse_string);
947 if ((cgid_pfn_reg_with_ssi) && (cgid_pfn_gtv) && (cgid_pfn_ps)) {
948 /* Required by mod_include filter. This is how mod_cgid registers
949 * with mod_include to provide processing of the exec directive.
951 cgid_pfn_reg_with_ssi("exec", handle_exec);
957 static void *create_cgid_config(apr_pool_t *p, server_rec *s)
959 cgid_server_conf *c =
960 (cgid_server_conf *) apr_pcalloc(p, sizeof(cgid_server_conf));
963 c->logbytes = DEFAULT_LOGBYTES;
964 c->bufbytes = DEFAULT_BUFBYTES;
968 static void *merge_cgid_config(apr_pool_t *p, void *basev, void *overridesv)
970 cgid_server_conf *base = (cgid_server_conf *) basev, *overrides = (cgid_server_conf *) overridesv;
972 return overrides->logname ? overrides : base;
975 static const char *set_scriptlog(cmd_parms *cmd, void *dummy, const char *arg)
977 server_rec *s = cmd->server;
978 cgid_server_conf *conf = ap_get_module_config(s->module_config,
981 conf->logname = ap_server_root_relative(cmd->pool, arg);
983 if (!conf->logname) {
984 return apr_pstrcat(cmd->pool, "Invalid ScriptLog path ",
990 static const char *set_scriptlog_length(cmd_parms *cmd, void *dummy, const char *arg)
992 server_rec *s = cmd->server;
993 cgid_server_conf *conf = ap_get_module_config(s->module_config,
996 conf->logbytes = atol(arg);
1000 static const char *set_scriptlog_buffer(cmd_parms *cmd, void *dummy, const char *arg)
1002 server_rec *s = cmd->server;
1003 cgid_server_conf *conf = ap_get_module_config(s->module_config,
1006 conf->bufbytes = atoi(arg);
1010 static const char *set_script_socket(cmd_parms *cmd, void *dummy, const char *arg)
1012 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1017 /* Make sure the pid is appended to the sockname */
1018 sockname = ap_append_pid(cmd->pool, arg, ".");
1019 sockname = ap_server_root_relative(cmd->pool, sockname);
1022 return apr_pstrcat(cmd->pool, "Invalid ScriptSock path",
1029 static const command_rec cgid_cmds[] =
1031 AP_INIT_TAKE1("ScriptLog", set_scriptlog, NULL, RSRC_CONF,
1032 "the name of a log for script debugging info"),
1033 AP_INIT_TAKE1("ScriptLogLength", set_scriptlog_length, NULL, RSRC_CONF,
1034 "the maximum length (in bytes) of the script debug log"),
1035 AP_INIT_TAKE1("ScriptLogBuffer", set_scriptlog_buffer, NULL, RSRC_CONF,
1036 "the maximum size (in bytes) to record of a POST request"),
1037 AP_INIT_TAKE1("ScriptSock", set_script_socket, NULL, RSRC_CONF,
1038 "the name of the socket to use for communication with "
1043 static int log_scripterror(request_rec *r, cgid_server_conf * conf, int ret,
1044 apr_status_t rv, char *error)
1046 apr_file_t *f = NULL;
1048 char time_str[APR_CTIME_LEN];
1049 int log_flags = rv ? APLOG_ERR : APLOG_ERR;
1051 ap_log_rerror(APLOG_MARK, log_flags, rv, r,
1052 "%s: %s", error, r->filename);
1054 /* XXX Very expensive mainline case! Open, then getfileinfo! */
1055 if (!conf->logname ||
1056 ((stat(conf->logname, &finfo) == 0)
1057 && (finfo.st_size > conf->logbytes)) ||
1058 (apr_file_open(&f, conf->logname,
1059 APR_APPEND|APR_WRITE|APR_CREATE, APR_OS_DEFAULT, r->pool) != APR_SUCCESS)) {
1063 /* "%% [Wed Jun 19 10:53:21 1996] GET /cgid-bin/printenv HTTP/1.0" */
1064 apr_ctime(time_str, apr_time_now());
1065 apr_file_printf(f, "%%%% [%s] %s %s%s%s %s\n", time_str, r->method, r->uri,
1066 r->args ? "?" : "", r->args ? r->args : "", r->protocol);
1067 /* "%% 500 /usr/local/apache/cgid-bin */
1068 apr_file_printf(f, "%%%% %d %s\n", ret, r->filename);
1070 apr_file_printf(f, "%%error\n%s\n", error);
1076 static int log_script(request_rec *r, cgid_server_conf * conf, int ret,
1077 char *dbuf, const char *sbuf, apr_bucket_brigade *bb,
1078 apr_file_t *script_err)
1080 const apr_array_header_t *hdrs_arr = apr_table_elts(r->headers_in);
1081 const apr_table_entry_t *hdrs = (apr_table_entry_t *) hdrs_arr->elts;
1082 char argsbuffer[HUGE_STRING_LEN];
1083 apr_file_t *f = NULL;
1091 char time_str[APR_CTIME_LEN];
1093 /* XXX Very expensive mainline case! Open, then getfileinfo! */
1094 if (!conf->logname ||
1095 ((stat(conf->logname, &finfo) == 0)
1096 && (finfo.st_size > conf->logbytes)) ||
1097 (apr_file_open(&f, conf->logname,
1098 APR_APPEND|APR_WRITE|APR_CREATE, APR_OS_DEFAULT, r->pool) != APR_SUCCESS)) {
1099 /* Soak up script output */
1100 discard_script_output(bb);
1102 while (apr_file_gets(argsbuffer, HUGE_STRING_LEN,
1103 script_err) == APR_SUCCESS)
1109 /* "%% [Wed Jun 19 10:53:21 1996] GET /cgid-bin/printenv HTTP/1.0" */
1110 apr_ctime(time_str, apr_time_now());
1111 apr_file_printf(f, "%%%% [%s] %s %s%s%s %s\n", time_str, r->method, r->uri,
1112 r->args ? "?" : "", r->args ? r->args : "", r->protocol);
1113 /* "%% 500 /usr/local/apache/cgid-bin" */
1114 apr_file_printf(f, "%%%% %d %s\n", ret, r->filename);
1116 apr_file_puts("%request\n", f);
1117 for (i = 0; i < hdrs_arr->nelts; ++i) {
1120 apr_file_printf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val);
1122 if ((r->method_number == M_POST || r->method_number == M_PUT)
1124 apr_file_printf(f, "\n%s\n", dbuf);
1127 apr_file_puts("%response\n", f);
1128 hdrs_arr = apr_table_elts(r->err_headers_out);
1129 hdrs = (const apr_table_entry_t *) hdrs_arr->elts;
1131 for (i = 0; i < hdrs_arr->nelts; ++i) {
1134 apr_file_printf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val);
1138 apr_file_printf(f, "%s\n", sbuf);
1142 for (e = APR_BRIGADE_FIRST(bb);
1143 e != APR_BRIGADE_SENTINEL(bb);
1144 e = APR_BUCKET_NEXT(e))
1146 if (APR_BUCKET_IS_EOS(e)) {
1149 rv = apr_bucket_read(e, &buf, &len, APR_BLOCK_READ);
1150 if (rv != APR_SUCCESS || (len == 0)) {
1154 apr_file_puts("%stdout\n", f);
1157 apr_file_write(f, buf, &len);
1158 apr_file_puts("\n", f);
1162 if (apr_file_gets(argsbuffer, HUGE_STRING_LEN,
1163 script_err) == APR_SUCCESS) {
1164 apr_file_puts("%stderr\n", f);
1165 apr_file_puts(argsbuffer, f);
1166 while (apr_file_gets(argsbuffer, HUGE_STRING_LEN,
1167 script_err) == APR_SUCCESS)
1168 apr_file_puts(argsbuffer, f);
1169 apr_file_puts("\n", f);
1174 apr_file_close(script_err);
1181 static int connect_to_daemon(int *sdptr, request_rec *r,
1182 cgid_server_conf *conf)
1186 apr_interval_time_t sliding_timer;
1189 sliding_timer = 100000; /* 100 milliseconds */
1192 if ((sd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
1193 return log_scripterror(r, conf, HTTP_INTERNAL_SERVER_ERROR, errno,
1194 APLOGNO(01255) "unable to create socket to cgi daemon");
1196 if (connect(sd, (struct sockaddr *)server_addr, server_addr_len) < 0) {
1197 if (errno == ECONNREFUSED && connect_tries < DEFAULT_CONNECT_ATTEMPTS) {
1198 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, errno, r, APLOGNO(01256)
1199 "connect #%d to cgi daemon failed, sleeping before retry",
1202 apr_sleep(sliding_timer);
1203 if (sliding_timer < apr_time_from_sec(2)) {
1209 return log_scripterror(r, conf, HTTP_SERVICE_UNAVAILABLE, errno, APLOGNO(01257)
1210 "unable to connect to cgi daemon after multiple tries");
1214 apr_pool_cleanup_register(r->pool, (void *)((long)sd),
1215 close_unix_socket, apr_pool_cleanup_null);
1216 break; /* we got connected! */
1218 /* gotta try again, but make sure the cgid daemon is still around */
1219 if (kill(daemon_pid, 0) != 0) {
1220 return log_scripterror(r, conf, HTTP_SERVICE_UNAVAILABLE, errno, APLOGNO(01258)
1221 "cgid daemon is gone; is Apache terminating?");
1228 static void discard_script_output(apr_bucket_brigade *bb)
1235 for (e = APR_BRIGADE_FIRST(bb);
1236 e != APR_BRIGADE_SENTINEL(bb);
1237 e = APR_BUCKET_NEXT(e))
1239 if (APR_BUCKET_IS_EOS(e)) {
1242 rv = apr_bucket_read(e, &buf, &len, APR_BLOCK_READ);
1243 if (rv != APR_SUCCESS) {
1249 /****************************************************************
1251 * Actual cgid handling...
1254 struct cleanup_script_info {
1256 unsigned long conn_id;
1257 cgid_server_conf *conf;
1260 static apr_status_t dead_yet(pid_t pid, apr_interval_time_t max_wait)
1262 apr_interval_time_t interval = 10000; /* 10 ms */
1263 apr_interval_time_t total = 0;
1267 /* On AIX, for processes like mod_cgid's script children where
1268 * SIGCHLD is ignored, kill(pid,0) returns success for up to
1269 * one second after the script child exits, based on when a
1270 * daemon runs to clean up unnecessary process table entries.
1271 * getpgid() can report the proper info (-1/ESRCH) immediately.
1273 if (getpgid(pid) < 0) {
1275 if (kill(pid, 0) < 0) {
1279 apr_sleep(interval);
1280 total = total + interval;
1281 if (interval < 500000) {
1284 } while (total < max_wait);
1285 return APR_EGENERAL;
1288 static apr_status_t cleanup_nonchild_process(request_rec *r, pid_t pid)
1290 kill(pid, SIGTERM); /* in case it isn't dead yet */
1291 if (dead_yet(pid, apr_time_from_sec(3)) == APR_SUCCESS) {
1294 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01259)
1295 "CGI process %" APR_PID_T_FMT " didn't exit, sending SIGKILL",
1298 if (dead_yet(pid, apr_time_from_sec(3)) == APR_SUCCESS) {
1301 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01260)
1302 "CGI process %" APR_PID_T_FMT " didn't exit, sending SIGKILL again",
1306 return APR_EGENERAL;
1309 static apr_status_t cleanup_script(void *vptr)
1311 struct cleanup_script_info *info = vptr;
1314 cgid_req_t req = {0};
1318 rc = connect_to_daemon(&sd, info->r, info->conf);
1320 return APR_EGENERAL;
1323 /* we got a socket, and there is already a cleanup registered for it */
1325 req.req_type = GETPID_REQ;
1326 req.ppid = parent_pid;
1327 req.conn_id = info->r->connection->id;
1329 stat = sock_write(sd, &req, sizeof(req));
1330 if (stat != APR_SUCCESS) {
1334 /* wait for pid of script */
1335 stat = sock_read(sd, &pid, sizeof(pid));
1336 if (stat != APR_SUCCESS) {
1341 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, info->r, APLOGNO(01261)
1342 "daemon couldn't find CGI process for connection %lu",
1344 return APR_EGENERAL;
1346 return cleanup_nonchild_process(info->r, pid);
1349 static int cgid_handler(request_rec *r)
1351 int retval, nph, dbpos;
1353 apr_bucket_brigade *bb;
1355 cgid_server_conf *conf;
1357 int seen_eos, child_stopped_reading;
1360 apr_file_t *tempsock;
1361 struct cleanup_script_info *info;
1364 if (strcmp(r->handler, CGI_MAGIC_TYPE) && strcmp(r->handler, "cgi-script")) {
1368 conf = ap_get_module_config(r->server->module_config, &cgid_module);
1369 is_included = !strcmp(r->protocol, "INCLUDED");
1371 if ((argv0 = strrchr(r->filename, '/')) != NULL) {
1375 argv0 = r->filename;
1378 nph = !(strncmp(argv0, "nph-", 4));
1380 argv0 = r->filename;
1382 if (!(ap_allow_options(r) & OPT_EXECCGI) && !is_scriptaliased(r)) {
1383 return log_scripterror(r, conf, HTTP_FORBIDDEN, 0, APLOGNO(01262)
1384 "Options ExecCGI is off in this directory");
1387 if (nph && is_included) {
1388 return log_scripterror(r, conf, HTTP_FORBIDDEN, 0, APLOGNO(01263)
1389 "attempt to include NPH CGI script");
1392 #if defined(OS2) || defined(WIN32)
1393 #error mod_cgid does not work on this platform. If you teach it to, look
1394 #error at mod_cgi.c for required code in this path.
1396 if (r->finfo.filetype == APR_NOFILE) {
1397 return log_scripterror(r, conf, HTTP_NOT_FOUND, 0, APLOGNO(01264)
1398 "script not found or unable to stat");
1401 if (r->finfo.filetype == APR_DIR) {
1402 return log_scripterror(r, conf, HTTP_FORBIDDEN, 0, APLOGNO(01265)
1403 "attempt to invoke directory as script");
1406 if ((r->used_path_info == AP_REQ_REJECT_PATH_INFO) &&
1407 r->path_info && *r->path_info)
1409 /* default to accept */
1410 return log_scripterror(r, conf, HTTP_NOT_FOUND, 0, APLOGNO(01266)
1411 "AcceptPathInfo off disallows user's path");
1414 if (!ap_suexec_enabled) {
1415 if (!ap_can_exec(&r->finfo))
1416 return log_scripterror(r, conf, HTTP_FORBIDDEN, 0, APLOGNO(01267)
1417 "file permissions deny server execution");
1420 ap_add_common_vars(r);
1422 env = ap_create_environment(r->pool, r->subprocess_env);
1424 if ((retval = connect_to_daemon(&sd, r, conf)) != OK) {
1428 rv = send_req(sd, r, argv0, env, CGI_REQ);
1429 if (rv != APR_SUCCESS) {
1430 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(01268)
1431 "write to cgi daemon process");
1434 info = apr_palloc(r->pool, sizeof(struct cleanup_script_info));
1436 info->conn_id = r->connection->id;
1438 apr_pool_cleanup_register(r->pool, info,
1440 apr_pool_cleanup_null);
1441 /* We are putting the socket discriptor into an apr_file_t so that we can
1442 * use a pipe bucket to send the data to the client. APR will create
1443 * a cleanup for the apr_file_t which will close the socket, so we'll
1444 * get rid of the cleanup we registered when we created the socket.
1447 apr_os_pipe_put_ex(&tempsock, &sd, 1, r->pool);
1448 apr_pool_cleanup_kill(r->pool, (void *)((long)sd), close_unix_socket);
1450 /* Transfer any put/post args, CERN style...
1451 * Note that we already ignore SIGPIPE in the core server.
1453 bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
1455 child_stopped_reading = 0;
1458 if (conf->logname) {
1459 dbuf = apr_palloc(r->pool, conf->bufbytes + 1);
1464 rv = ap_get_brigade(r->input_filters, bb, AP_MODE_READBYTES,
1465 APR_BLOCK_READ, HUGE_STRING_LEN);
1467 if (rv != APR_SUCCESS) {
1468 if (APR_STATUS_IS_TIMEUP(rv)) {
1469 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(01269)
1470 "Timeout during reading request entity data");
1471 return HTTP_REQUEST_TIME_OUT;
1473 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(01270)
1474 "Error reading request entity data");
1475 return HTTP_INTERNAL_SERVER_ERROR;
1478 for (bucket = APR_BRIGADE_FIRST(bb);
1479 bucket != APR_BRIGADE_SENTINEL(bb);
1480 bucket = APR_BUCKET_NEXT(bucket))
1485 if (APR_BUCKET_IS_EOS(bucket)) {
1490 /* We can't do much with this. */
1491 if (APR_BUCKET_IS_FLUSH(bucket)) {
1495 /* If the child stopped, we still must read to EOS. */
1496 if (child_stopped_reading) {
1501 apr_bucket_read(bucket, &data, &len, APR_BLOCK_READ);
1503 if (conf->logname && dbpos < conf->bufbytes) {
1506 if ((dbpos + len) > conf->bufbytes) {
1507 cursize = conf->bufbytes - dbpos;
1512 memcpy(dbuf + dbpos, data, cursize);
1516 /* Keep writing data to the child until done or too much time
1517 * elapses with no progress or an error occurs.
1519 rv = apr_file_write_full(tempsock, data, len, NULL);
1521 if (rv != APR_SUCCESS) {
1522 /* silly script stopped reading, soak up remaining message */
1523 child_stopped_reading = 1;
1526 apr_brigade_cleanup(bb);
1530 if (conf->logname) {
1534 /* we're done writing, or maybe we didn't write at all;
1535 * force EOF on child's stdin so that the cgi detects end (or
1540 /* Handle script return... */
1542 conn_rec *c = r->connection;
1543 const char *location;
1544 char sbuf[MAX_STRING_LEN];
1547 bb = apr_brigade_create(r->pool, c->bucket_alloc);
1548 b = apr_bucket_pipe_create(tempsock, c->bucket_alloc);
1549 APR_BRIGADE_INSERT_TAIL(bb, b);
1550 b = apr_bucket_eos_create(c->bucket_alloc);
1551 APR_BRIGADE_INSERT_TAIL(bb, b);
1553 if ((ret = ap_scan_script_header_err_brigade_ex(r, bb, sbuf,
1554 APLOG_MODULE_INDEX)))
1556 ret = log_script(r, conf, ret, dbuf, sbuf, bb, NULL);
1559 * ret could be HTTP_NOT_MODIFIED in the case that the CGI script
1560 * does not set an explicit status and ap_meets_conditions, which
1561 * is called by ap_scan_script_header_err_brigade, detects that
1562 * the conditions of the requests are met and the response is
1564 * In this case set r->status and return OK in order to prevent
1565 * running through the error processing stack as this would
1566 * break with mod_cache, if the conditions had been set by
1567 * mod_cache itself to validate a stale entity.
1568 * BTW: We circumvent the error processing stack anyway if the
1569 * CGI script set an explicit status code (whatever it is) and
1570 * the only possible values for ret here are:
1572 * HTTP_NOT_MODIFIED (set by ap_meets_conditions)
1573 * HTTP_PRECONDITION_FAILED (set by ap_meets_conditions)
1574 * HTTP_INTERNAL_SERVER_ERROR (if something went wrong during the
1575 * processing of the response of the CGI script, e.g broken headers
1576 * or a crashed CGI process).
1578 if (ret == HTTP_NOT_MODIFIED) {
1586 location = apr_table_get(r->headers_out, "Location");
1588 if (location && location[0] == '/' && r->status == 200) {
1590 /* Soak up all the script output */
1591 discard_script_output(bb);
1592 apr_brigade_destroy(bb);
1593 /* This redirect needs to be a GET no matter what the original
1596 r->method = apr_pstrdup(r->pool, "GET");
1597 r->method_number = M_GET;
1599 /* We already read the message body (if any), so don't allow
1600 * the redirected request to think it has one. We can ignore
1601 * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR.
1603 apr_table_unset(r->headers_in, "Content-Length");
1605 ap_internal_redirect_handler(location, r);
1608 else if (location && r->status == 200) {
1609 /* XXX: Note that if a script wants to produce its own Redirect
1610 * body, it now has to explicitly *say* "Status: 302"
1612 discard_script_output(bb);
1613 apr_brigade_destroy(bb);
1614 return HTTP_MOVED_TEMPORARILY;
1617 ap_pass_brigade(r->output_filters, bb);
1621 conn_rec *c = r->connection;
1622 struct ap_filter_t *cur;
1624 /* get rid of all filters up through protocol... since we
1625 * haven't parsed off the headers, there is no way they can
1629 cur = r->proto_output_filters;
1630 while (cur && cur->frec->ftype < AP_FTYPE_CONNECTION) {
1633 r->output_filters = r->proto_output_filters = cur;
1635 bb = apr_brigade_create(r->pool, c->bucket_alloc);
1636 b = apr_bucket_pipe_create(tempsock, c->bucket_alloc);
1637 APR_BRIGADE_INSERT_TAIL(bb, b);
1638 b = apr_bucket_eos_create(c->bucket_alloc);
1639 APR_BRIGADE_INSERT_TAIL(bb, b);
1640 ap_pass_brigade(r->output_filters, bb);
1643 return OK; /* NOT r->status, even if it has changed. */
1649 /*============================================================================
1650 *============================================================================
1651 * This is the beginning of the cgi filter code moved from mod_include. This
1652 * is the code required to handle the "exec" SSI directive.
1653 *============================================================================
1654 *============================================================================*/
1655 static apr_status_t include_cgi(include_ctx_t *ctx, ap_filter_t *f,
1656 apr_bucket_brigade *bb, char *s)
1658 request_rec *r = f->r;
1659 request_rec *rr = ap_sub_req_lookup_uri(s, r, f->next);
1662 if (rr->status != HTTP_OK) {
1663 ap_destroy_sub_req(rr);
1664 return APR_EGENERAL;
1667 /* No hardwired path info or query allowed */
1668 if ((rr->path_info && rr->path_info[0]) || rr->args) {
1669 ap_destroy_sub_req(rr);
1670 return APR_EGENERAL;
1672 if (rr->finfo.filetype != APR_REG) {
1673 ap_destroy_sub_req(rr);
1674 return APR_EGENERAL;
1677 /* Script gets parameters of the *document*, for back compatibility */
1678 rr->path_info = r->path_info; /* hard to get right; see mod_cgi.c */
1681 /* Force sub_req to be treated as a CGI request, even if ordinary
1682 * typing rules would have called it something else.
1684 ap_set_content_type(rr, CGI_MAGIC_TYPE);
1687 rr_status = ap_run_sub_req(rr);
1688 if (ap_is_HTTP_REDIRECT(rr_status)) {
1689 const char *location = apr_table_get(rr->headers_out, "Location");
1694 location = ap_escape_html(rr->pool, location);
1695 buffer = apr_pstrcat(ctx->pool, "<a href=\"", location, "\">",
1696 location, "</a>", NULL);
1698 APR_BRIGADE_INSERT_TAIL(bb, apr_bucket_pool_create(buffer,
1699 strlen(buffer), ctx->pool,
1700 f->c->bucket_alloc));
1704 ap_destroy_sub_req(rr);
1709 /* This is the special environment used for running the "exec cmd="
1710 * variety of SSI directives.
1712 static void add_ssi_vars(request_rec *r)
1714 apr_table_t *e = r->subprocess_env;
1716 if (r->path_info && r->path_info[0] != '\0') {
1717 request_rec *pa_req;
1719 apr_table_setn(e, "PATH_INFO", ap_escape_shell_cmd(r->pool, r->path_info));
1721 pa_req = ap_sub_req_lookup_uri(ap_escape_uri(r->pool, r->path_info), r, NULL);
1722 if (pa_req->filename) {
1723 apr_table_setn(e, "PATH_TRANSLATED",
1724 apr_pstrcat(r->pool, pa_req->filename, pa_req->path_info, NULL));
1726 ap_destroy_sub_req(pa_req);
1730 char *arg_copy = apr_pstrdup(r->pool, r->args);
1732 apr_table_setn(e, "QUERY_STRING", r->args);
1733 ap_unescape_url(arg_copy);
1734 apr_table_setn(e, "QUERY_STRING_UNESCAPED", ap_escape_shell_cmd(r->pool, arg_copy));
1738 static int include_cmd(include_ctx_t *ctx, ap_filter_t *f,
1739 apr_bucket_brigade *bb, char *command)
1744 apr_file_t *tempsock = NULL;
1745 request_rec *r = f->r;
1746 cgid_server_conf *conf = ap_get_module_config(r->server->module_config,
1748 struct cleanup_script_info *info;
1751 env = ap_create_environment(r->pool, r->subprocess_env);
1753 if ((retval = connect_to_daemon(&sd, r, conf)) != OK) {
1757 send_req(sd, r, command, env, SSI_REQ);
1759 info = apr_palloc(r->pool, sizeof(struct cleanup_script_info));
1761 info->conn_id = r->connection->id;
1763 /* for this type of request, the script is invoked through an
1764 * intermediate shell process... cleanup_script is only able
1765 * to knock out the shell process, not the actual script
1767 apr_pool_cleanup_register(r->pool, info,
1769 apr_pool_cleanup_null);
1771 /* We are putting the socket discriptor into an apr_file_t so that we can
1772 * use a pipe bucket to send the data to the client. APR will create
1773 * a cleanup for the apr_file_t which will close the socket, so we'll
1774 * get rid of the cleanup we registered when we created the socket.
1776 apr_os_pipe_put_ex(&tempsock, &sd, 1, r->pool);
1777 apr_pool_cleanup_kill(r->pool, (void *)((long)sd), close_unix_socket);
1779 APR_BRIGADE_INSERT_TAIL(bb, apr_bucket_pipe_create(tempsock,
1780 f->c->bucket_alloc));
1786 static apr_status_t handle_exec(include_ctx_t *ctx, ap_filter_t *f,
1787 apr_bucket_brigade *bb)
1790 char *tag_val = NULL;
1791 request_rec *r = f->r;
1792 char *file = r->filename;
1793 char parsed_string[MAX_STRING_LEN];
1796 ap_log_rerror(APLOG_MARK,
1797 (ctx->flags & SSI_FLAG_PRINTING)
1798 ? APLOG_ERR : APLOG_WARNING,
1799 0, r, "missing argument for exec element in %s",
1803 if (!(ctx->flags & SSI_FLAG_PRINTING)) {
1808 SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
1812 if (ctx->flags & SSI_FLAG_NO_EXEC) {
1813 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01271) "exec used but not allowed "
1814 "in %s", r->filename);
1815 SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
1820 cgid_pfn_gtv(ctx, &tag, &tag_val, SSI_VALUE_DECODED);
1821 if (!tag || !tag_val) {
1825 if (!strcmp(tag, "cmd")) {
1828 cgid_pfn_ps(ctx, tag_val, parsed_string, sizeof(parsed_string),
1829 SSI_EXPAND_LEAVE_NAME);
1831 rv = include_cmd(ctx, f, bb, parsed_string);
1832 if (rv != APR_SUCCESS) {
1833 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01272)
1834 "execution failure for parameter \"%s\" "
1835 "to tag exec in file %s", tag, r->filename);
1836 SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
1840 else if (!strcmp(tag, "cgi")) {
1843 cgid_pfn_ps(ctx, tag_val, parsed_string, sizeof(parsed_string),
1844 SSI_EXPAND_DROP_NAME);
1846 rv = include_cgi(ctx, f, bb, parsed_string);
1847 if (rv != APR_SUCCESS) {
1848 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01273) "invalid CGI ref "
1849 "\"%s\" in %s", tag_val, file);
1850 SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
1855 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01274) "unknown parameter "
1856 "\"%s\" to tag exec in %s", tag, file);
1857 SSI_CREATE_ERROR_BUCKET(ctx, f, bb);
1864 /*============================================================================
1865 *============================================================================
1866 * This is the end of the cgi filter code moved from mod_include.
1867 *============================================================================
1868 *============================================================================*/
1871 static void register_hook(apr_pool_t *p)
1873 static const char * const aszPre[] = { "mod_include.c", NULL };
1875 ap_hook_pre_config(cgid_pre_config, NULL, NULL, APR_HOOK_MIDDLE);
1876 ap_hook_post_config(cgid_init, aszPre, NULL, APR_HOOK_MIDDLE);
1877 ap_hook_handler(cgid_handler, NULL, NULL, APR_HOOK_MIDDLE);
1880 AP_DECLARE_MODULE(cgid) = {
1881 STANDARD20_MODULE_STUFF,
1882 NULL, /* dir config creater */
1883 NULL, /* dir merger --- default is to override */
1884 create_cgid_config, /* server config */
1885 merge_cgid_config, /* merge server config */
1886 cgid_cmds, /* command table */
1887 register_hook /* register_handlers */