1 /* ====================================================================
2 * The Apache Software License, Version 1.1
4 * Copyright (c) 2000 The Apache Software Foundation. All rights
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in
16 * the documentation and/or other materials provided with the
19 * 3. The end-user documentation included with the redistribution,
20 * if any, must include the following acknowledgment:
21 * "This product includes software developed by the
22 * Apache Software Foundation (http://www.apache.org/)."
23 * Alternately, this acknowledgment may appear in the software itself,
24 * if and wherever such third-party acknowledgments normally appear.
26 * 4. The names "Apache" and "Apache Software Foundation" must
27 * not be used to endorse or promote products derived from this
28 * software without prior written permission. For written
29 * permission, please contact apache@apache.org.
31 * 5. Products derived from this software may not be called "Apache",
32 * nor may "Apache" appear in their name, without prior written
33 * permission of the Apache Software Foundation.
35 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38 * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
39 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47 * ====================================================================
49 * This software consists of voluntary contributions made by many
50 * individuals on behalf of the Apache Software Foundation. For more
51 * information on the Apache Software Foundation, please see
52 * <http://www.apache.org/>.
54 * Portions of this software are based upon public domain software
55 * originally written at the National Center for Supercomputing Applications,
56 * University of Illinois, Urbana-Champaign.
60 * http_script: keeps all script-related ramblings together.
62 * Compliant to cgi/1.1 spec
64 * Adapted by rst from original NCSA code by Rob McCool
66 * Apache adds some new env vars; REDIRECT_URL and REDIRECT_QUERY_STRING for
67 * custom error responses, and DOCUMENT_ROOT because we found it useful.
68 * It also adds SERVER_ADMIN - useful for scripts to know who to mail when
77 #include "apr_strings.h"
78 #include "apr_general.h"
79 #include "apr_file_io.h"
80 #include "apr_portable.h"
81 #include "apr_buckets.h"
82 #include "util_filter.h"
84 #include "http_config.h"
85 #include "http_request.h"
86 #include "http_core.h"
87 #include "http_protocol.h"
88 #include "http_main.h"
90 #include "util_script.h"
93 #include "mod_suexec.h"
94 #include "apr_optional.h"
95 #include "../filters/mod_include.h"
97 #ifdef HAVE_SYS_SOCKET_H
98 #include <sys/socket.h>
103 #ifdef HAVE_STRINGS_H
106 #include <sys/un.h> /* for sockaddr_un */
107 #include <sys/types.h>
109 module AP_MODULE_DECLARE_DATA cgid_module;
111 static void cgid_init(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *main_server);
112 static int handle_exec(include_ctx_t *ctx, apr_bucket_brigade **bb, request_rec *r,
113 ap_filter_t *f, apr_bucket *head_ptr, apr_bucket **inserted_head);
115 static APR_OPTIONAL_FN_TYPE(ap_register_include_handler) *cgid_pfn_reg_with_ssi;
116 static APR_OPTIONAL_FN_TYPE(ap_ssi_get_tag_and_value) *cgid_pfn_gtv;
117 static APR_OPTIONAL_FN_TYPE(ap_ssi_parse_string) *cgid_pfn_ps;
119 static apr_pool_t *pcgi;
120 static int total_modules = 0;
122 /* KLUDGE --- for back-combatibility, we don't have to check Execcgid
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 "logs/cgisock"
140 #define SHELL_PATH "/bin/sh"
145 /* DEFAULT_CGID_LISTENBACKLOG controls the max depth on the unix socket's
146 * pending connection queue. If a bunch of cgi requests arrive at about
147 * the same time, connections from httpd threads/processes will back up
148 * in the queue while the cgid process slowly forks off a child to process
149 * each connection on the unix socket. If the queue is too short, the
150 * httpd process will get ECONNREFUSED when trying to connect.
152 #ifndef DEFAULT_CGID_LISTENBACKLOG
153 #define DEFAULT_CGID_LISTENBACKLOG 100
157 const char *sockname;
163 /* If a request includes query info in the URL (stuff after "?"), and
164 * the query info does not contain "=" (indicative of a FORM submission),
165 * then this routine is called to create the argument list to be passed
166 * to the CGI script. When suexec is enabled, the suexec path, user, and
167 * group are the first three arguments to be passed; if not, all three
168 * must be NULL. The query info is split into separate arguments, where
169 * "+" is the separator between keyword arguments.
171 * XXXX: note that the WIN32 code uses one of the suexec strings
172 * to pass an interpreter name. Remember this if changing the way they
173 * are handled in create_argv.
176 static char **create_argv(apr_pool_t *p, char *path, char *user, char *group,
177 char *av0, const char *args)
184 /* count the number of keywords */
186 for (x = 0, numwords = 1; args[x]; x++) {
187 if (args[x] == '+') {
192 if (numwords > APACHE_ARG_MAX - 5) {
193 numwords = APACHE_ARG_MAX - 5; /* Truncate args to prevent overrun */
195 av = (char **) apr_pcalloc(p, (numwords + 5) * sizeof(char *));
207 av[idx++] = apr_pstrdup(p, av0);
209 for (x = 1; x <= numwords; x++) {
210 w = ap_getword_nulls(p, &args, '+');
213 av[idx++] = ap_escape_shell_cmd(p, w);
220 static void cgid_maint(int reason, void *data, apr_wait_t status)
222 #if APR_HAS_OTHER_CHILD
225 case APR_OC_REASON_DEATH:
226 case APR_OC_REASON_LOST:
227 /* stop gap to make sure everything else works. In the end,
228 * we'll just restart the cgid server. */
229 apr_pool_destroy(pcgi);
230 kill(getppid(), SIGWINCH);
232 case APR_OC_REASON_RESTART:
233 case APR_OC_REASON_UNREGISTER:
234 apr_pool_destroy(pcgi);
241 static void get_req(int fd, request_rec *r, char **filename, char **argv0, char ***env, int *req_type)
246 core_dir_config *temp_core;
248 module *suexec_mod = ap_find_linked_module("mod_suexec.c");
250 r->server = apr_pcalloc(r->pool, sizeof(server_rec));
252 read(fd, req_type, sizeof(int));
253 read(fd, &j, sizeof(int));
254 read(fd, &len, sizeof(int));
255 data = apr_pcalloc(r->pool, len + 1); /* get a cleared byte for final '\0' */
256 i = read(fd, data, len);
258 r->filename = ap_getword(r->pool, (const char **)&data, '\n');
259 *argv0 = ap_getword(r->pool, (const char **)&data, '\n');
261 r->uri = ap_getword(r->pool, (const char **)&data, '\n');
263 environ = apr_pcalloc(r->pool, (j + 2) *sizeof(char *));
265 for (i = 0; i < j; i++) {
266 environ[i] = ap_getword(r->pool, (const char **)&data, '\n');
269 r->args = ap_getword(r->pool, (const char **)&data, '\n');
271 read(fd, &i, sizeof(int));
273 /* add 1, so that if i == 0, we still malloc something. */
275 dconf = (void **) apr_pcalloc(r->pool, sizeof(void *) * (total_modules + DYNAMIC_MODULE_LIMIT));
277 temp_core = (core_dir_config *)apr_palloc(r->pool, sizeof(core_module));
279 dconf[i] = (void *)temp_core;
282 suexec_config_t *suexec_cfg = apr_pcalloc(r->pool, sizeof(*suexec_cfg));
284 read(fd, &i, sizeof(int));
285 read(fd, &suexec_cfg->ugid.uid, sizeof(uid_t));
286 read(fd, &suexec_cfg->ugid.gid, sizeof(gid_t));
287 read(fd, &suexec_cfg->active, sizeof(int));
288 dconf[i] = (void *)suexec_cfg;
291 r->per_dir_config = dconf;
294 read(fd, &j, sizeof(int));
296 temp_core->limit_cpu = (struct rlimit *)apr_palloc (sizeof(struct rlimit));
297 read(fd, temp_core->limit_cpu, sizeof(struct rlimit));
300 temp_core->limit_cpu = NULL;
304 #if defined (RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
305 read(fd, &j, sizeof(int));
307 temp_core->limit_mem = (struct rlimit *)apr_palloc(r->pool, sizeof(struct rlimit));
308 read(fd, temp_core->limit_mem, sizeof(struct rlimit));
311 temp_core->limit_mem = NULL;
316 read(fd, &j, sizeof(int));
318 temp_core->limit_nproc = (struct rlimit *)apr_palloc(r->pool, sizeof(struct rlimit));
319 read(fd, temp_core->limit_nproc, sizeof(struct rlimit));
322 temp_core->limit_nproc = NULL;
326 /* For right now, just make the notes table. At some point we will need
327 * to actually fill this out, but for now we just don't want suexec to
330 r->notes = apr_table_make(r->pool, 1);
335 static void send_req(int fd, request_rec *r, char *argv0, char **env, int req_type)
337 int len, r_type = req_type;
340 module *suexec_mod = ap_find_linked_module("mod_suexec.c");
342 data = apr_pstrcat(r->pool, r->filename, "\n", argv0, "\n", r->uri, "\n",
345 for (i =0; env[i]; i++) {
349 /* Write the request type (SSI "exec cmd" or cgi). */
350 if (write(fd, &r_type, sizeof(int)) < 0) {
351 ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r,
352 "write to cgi daemon process");
355 /* Write the number of entries in the environment. */
356 if (write(fd, &i, sizeof(int)) < 0) {
357 ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r,
358 "write to cgi daemon process");
361 for (i = 0; env[i]; i++) {
362 data = apr_pstrcat(r->pool, data, env[i], "\n", NULL);
364 data = apr_pstrcat(r->pool, data, r->args, NULL);
366 /* Write the length of the concatenated env string. */
367 if (write(fd, &len, sizeof(int)) < 0) {
368 ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r,
369 "write to cgi daemon process");
371 /* Write the concatted env string. */
372 if (write(fd, data, len) < 0) {
373 ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r,
374 "write to cgi daemon process");
376 /* Write module_index id value. */
377 if (write(fd, &core_module.module_index, sizeof(int)) < 0) {
378 ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r,
379 "write to cgi daemon process");
382 suexec_config_t *suexec_cfg = ap_get_module_config(r->per_dir_config,
385 write(fd, &suexec_mod->module_index, sizeof(int));
386 write(fd, &suexec_cfg->ugid.uid, sizeof(uid_t));
387 write(fd, &suexec_cfg->ugid.gid, sizeof(gid_t));
388 write(fd, &suexec_cfg->active, sizeof(int));
393 if (conf->limit_cpu) {
395 write(fd, &len, sizeof(int));
396 write(fd, conf->limit_cpu, sizeof(struct rlimit));
400 write(fd, &len, sizeof(int));
404 #if defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
405 if (conf->limit_mem) {
407 write(fd, &len, sizeof(int));
408 write(fd, conf->limit_mem, sizeof(struct rlimit));
412 write(fd, &len, sizeof(int));
417 if (conf->limit_nproc) {
419 write(fd, &len, sizeof(int));
420 write(fd, conf->limit_nproc, sizeof(struct rlimit));
424 write(fd, &len, sizeof(int));
430 static int cgid_server(void *data)
432 struct sockaddr_un unix_addr;
433 int sd, sd2, rc, req_type;
436 server_rec *main_server = data;
437 cgid_server_conf *sconf = (cgid_server_conf *)ap_get_module_config(
438 main_server->module_config, &cgid_module);
440 apr_signal(SIGCHLD, SIG_IGN);
441 if (unlink(sconf->sockname) < 0 && errno != ENOENT) {
442 ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
443 "Couldn't unlink unix domain socket %s",
445 /* just a warning; don't bail out */
448 if ((sd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
449 ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
450 "Couldn't create unix domain socket");
454 memset(&unix_addr, 0, sizeof(unix_addr));
455 unix_addr.sun_family = AF_UNIX;
456 strcpy(unix_addr.sun_path, sconf->sockname);
458 omask = umask(0077); /* so that only Apache can use socket */
459 rc = bind(sd, (struct sockaddr *)&unix_addr, sizeof(unix_addr));
460 umask(omask); /* can't fail, so can't clobber errno */
462 ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
463 "Couldn't bind unix domain socket %s",
468 if (listen(sd, DEFAULT_CGID_LISTENBACKLOG) < 0) {
469 ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
470 "Couldn't listen on unix domain socket");
475 if (chown(sconf->sockname, unixd_config.user_id, -1) < 0) {
476 ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
477 "Couldn't change owner of unix domain socket %s",
483 unixd_setup_child(); /* if running as root, switch to configured user/group */
485 int errfileno = STDERR_FILENO;
489 const char * const *argv;
490 apr_int32_t in_pipe = APR_CHILD_BLOCK;
491 apr_int32_t out_pipe = APR_CHILD_BLOCK;
492 apr_int32_t err_pipe = APR_CHILD_BLOCK;
493 apr_cmdtype_e cmd_type = APR_PROGRAM;
496 apr_procattr_t *procattr = NULL;
497 apr_proc_t *procnew = NULL;
501 len = sizeof(unix_addr);
502 sd2 = accept(sd, (struct sockaddr *)&unix_addr, &len);
504 if (errno != EINTR) {
505 ap_log_error(APLOG_MARK, APLOG_ERR, errno,
507 "Error accepting on cgid socket.");
512 apr_pool_create(&p, pcgi);
514 r = apr_pcalloc(p, sizeof(request_rec));
515 procnew = apr_pcalloc(p, sizeof(*procnew));
517 get_req(sd2, r, &filename, &argv0, &env, &req_type);
518 apr_os_file_put(&r->server->error_log, &errfileno, r->pool);
519 apr_os_file_put(&inout, &sd2, r->pool);
521 if (req_type == SSI_REQ) {
522 in_pipe = APR_NO_PIPE;
523 out_pipe = APR_FULL_BLOCK;
524 err_pipe = APR_NO_PIPE;
525 cmd_type = APR_SHELLCMD;
528 if (((rc = apr_procattr_create(&procattr, p)) != APR_SUCCESS) ||
529 ((req_type == CGI_REQ) &&
530 (((rc = apr_procattr_io_set(procattr,
533 err_pipe)) != APR_SUCCESS) ||
534 ((rc = apr_procattr_child_err_set(procattr, r->server->error_log, NULL)) != APR_SUCCESS) ||
535 ((rc = apr_procattr_child_in_set(procattr, inout, NULL)) != APR_SUCCESS))) ||
536 ((rc = apr_procattr_child_out_set(procattr, inout, NULL)) != APR_SUCCESS) ||
537 ((rc = apr_procattr_dir_set(procattr,
538 ap_make_dirstr_parent(r->pool, r->filename))) != APR_SUCCESS) ||
539 ((rc = apr_procattr_cmdtype_set(procattr, cmd_type)) != APR_SUCCESS)) {
540 /* Something bad happened, tell the world. */
541 ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r,
542 "couldn't set child process attributes: %s", r->filename);
545 argv = (const char * const *)create_argv(r->pool, NULL, NULL, NULL, argv0, r->args);
546 rc = ap_os_create_privileged_process(r, procnew, argv0, argv,
547 (const char * const *)env,
551 if (rc != APR_SUCCESS) {
552 /* Bad things happened. Everyone should have cleaned up. */
553 ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r,
554 "couldn't create child process: %d: %s", rc, r->filename);
561 static void cgid_init(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp,
562 server_rec *main_server)
568 const char *userdata_key = "cgid_init";
571 apr_pool_userdata_get(&data, userdata_key, main_server->process->pool);
574 apr_pool_userdata_set((const void *)1, userdata_key,
575 apr_pool_cleanup_null, main_server->process->pool);
579 apr_pool_create(&pcgi, p);
582 for (m = ap_preloaded_modules; *m != NULL; m++)
586 if ((pid = fork()) < 0) {
587 ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
588 "Couldn't spawn cgid daemon process");
591 cgid_server(main_server);
594 procnew = apr_pcalloc(p, sizeof(*procnew));
596 procnew->err = procnew->in = procnew->out = NULL;
597 apr_pool_note_subprocess(p, procnew, kill_after_timeout);
598 #if APR_HAS_OTHER_CHILD
599 apr_proc_other_child_register(procnew, cgid_maint, &procnew->pid, NULL, p);
602 cgid_pfn_reg_with_ssi = APR_RETRIEVE_OPTIONAL_FN(ap_register_include_handler);
603 cgid_pfn_gtv = APR_RETRIEVE_OPTIONAL_FN(ap_ssi_get_tag_and_value);
604 cgid_pfn_ps = APR_RETRIEVE_OPTIONAL_FN(ap_ssi_parse_string);
606 if ((cgid_pfn_reg_with_ssi) && (cgid_pfn_gtv) && (cgid_pfn_ps)) {
607 /* Required by mod_include filter. This is how mod_cgid registers
608 * with mod_include to provide processing of the exec directive.
610 cgid_pfn_reg_with_ssi("exec", handle_exec);
615 static void *create_cgid_config(apr_pool_t *p, server_rec *s)
617 cgid_server_conf *c =
618 (cgid_server_conf *) apr_pcalloc(p, sizeof(cgid_server_conf));
621 c->logbytes = DEFAULT_LOGBYTES;
622 c->bufbytes = DEFAULT_BUFBYTES;
623 c->sockname = ap_server_root_relative(p, DEFAULT_SOCKET);
627 static void *merge_cgid_config(apr_pool_t *p, void *basev, void *overridesv)
629 cgid_server_conf *base = (cgid_server_conf *) basev, *overrides = (cgid_server_conf *) overridesv;
631 return overrides->logname ? overrides : base;
634 static const char *set_scriptlog(cmd_parms *cmd, void *dummy, const char *arg)
636 server_rec *s = cmd->server;
637 cgid_server_conf *conf =
638 (cgid_server_conf *) ap_get_module_config(s->module_config, &cgid_module);
644 static const char *set_scriptlog_length(cmd_parms *cmd, void *dummy, const char *arg)
646 server_rec *s = cmd->server;
647 cgid_server_conf *conf =
648 (cgid_server_conf *) ap_get_module_config(s->module_config, &cgid_module);
650 conf->logbytes = atol(arg);
654 static const char *set_scriptlog_buffer(cmd_parms *cmd, void *dummy, const char *arg)
656 server_rec *s = cmd->server;
657 cgid_server_conf *conf =
658 (cgid_server_conf *) ap_get_module_config(s->module_config, &cgid_module);
660 conf->bufbytes = atoi(arg);
664 static const char *set_script_socket(cmd_parms *cmd, void *dummy, const char *arg)
666 server_rec *s = cmd->server;
667 cgid_server_conf *conf =
668 (cgid_server_conf *) ap_get_module_config(s->module_config, &cgid_module);
670 conf->sockname = ap_server_root_relative(cmd->pool, arg);
674 static const command_rec cgid_cmds[] =
676 AP_INIT_TAKE1("ScriptLog", set_scriptlog, NULL, RSRC_CONF,
677 "the name of a log for script debugging info"),
678 AP_INIT_TAKE1("ScriptLogLength", set_scriptlog_length, NULL, RSRC_CONF,
679 "the maximum length (in bytes) of the script debug log"),
680 AP_INIT_TAKE1("ScriptLogBuffer", set_scriptlog_buffer, NULL, RSRC_CONF,
681 "the maximum size (in bytes) to record of a POST request"),
682 AP_INIT_TAKE1("Scriptsock", set_script_socket, NULL, RSRC_CONF,
683 "the name of the socket to use for communication with "
688 static int log_scripterror(request_rec *r, cgid_server_conf * conf, int ret,
689 apr_status_t rv, char *error)
691 apr_file_t *f = NULL;
693 char time_str[APR_CTIME_LEN];
694 int log_flags = rv ? APLOG_ERR : APLOG_NOERRNO | APLOG_ERR;
696 ap_log_rerror(APLOG_MARK, log_flags, rv, r,
697 "%s: %s", error, r->filename);
699 if (!conf->logname ||
700 ((stat(ap_server_root_relative(r->pool, conf->logname), &finfo) == 0)
701 && (finfo.st_size > conf->logbytes)) ||
702 (apr_file_open(&f, ap_server_root_relative(r->pool, conf->logname),
703 APR_APPEND|APR_WRITE|APR_CREATE, APR_OS_DEFAULT, r->pool) != APR_SUCCESS)) {
707 /* "%% [Wed Jun 19 10:53:21 1996] GET /cgid-bin/printenv HTTP/1.0" */
708 apr_ctime(time_str, apr_time_now());
709 apr_file_printf(f, "%%%% [%s] %s %s%s%s %s\n", time_str, r->method, r->uri,
710 r->args ? "?" : "", r->args ? r->args : "", r->protocol);
711 /* "%% 500 /usr/local/apache/cgid-bin */
712 apr_file_printf(f, "%%%% %d %s\n", ret, r->filename);
714 apr_file_printf(f, "%%error\n%s\n", error);
720 static int log_script(request_rec *r, cgid_server_conf * conf, int ret,
721 char *dbuf, const char *sbuf, apr_file_t *script_in, apr_file_t *script_err)
723 apr_array_header_t *hdrs_arr = apr_table_elts(r->headers_in);
724 apr_table_entry_t *hdrs = (apr_table_entry_t *) hdrs_arr->elts;
725 char argsbuffer[HUGE_STRING_LEN];
726 apr_file_t *f = NULL;
729 char time_str[APR_CTIME_LEN];
731 if (!conf->logname ||
732 ((stat(ap_server_root_relative(r->pool, conf->logname), &finfo) == 0)
733 && (finfo.st_size > conf->logbytes)) ||
734 (apr_file_open(&f, ap_server_root_relative(r->pool, conf->logname),
735 APR_APPEND|APR_WRITE|APR_CREATE, APR_OS_DEFAULT, r->pool) != APR_SUCCESS)) {
736 /* Soak up script output */
737 while (apr_file_gets(argsbuffer, HUGE_STRING_LEN, script_in) == 0)
740 while (apr_file_gets(argsbuffer, HUGE_STRING_LEN, script_err) == 0)
746 /* "%% [Wed Jun 19 10:53:21 1996] GET /cgid-bin/printenv HTTP/1.0" */
747 apr_ctime(time_str, apr_time_now());
748 apr_file_printf(f, "%%%% [%s] %s %s%s%s %s\n", time_str, r->method, r->uri,
749 r->args ? "?" : "", r->args ? r->args : "", r->protocol);
750 /* "%% 500 /usr/local/apache/cgid-bin" */
751 apr_file_printf(f, "%%%% %d %s\n", ret, r->filename);
753 apr_file_puts("%request\n", f);
754 for (i = 0; i < hdrs_arr->nelts; ++i) {
757 apr_file_printf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val);
759 if ((r->method_number == M_POST || r->method_number == M_PUT)
761 apr_file_printf(f, "\n%s\n", dbuf);
764 apr_file_puts("%response\n", f);
765 hdrs_arr = apr_table_elts(r->err_headers_out);
766 hdrs = (apr_table_entry_t *) hdrs_arr->elts;
768 for (i = 0; i < hdrs_arr->nelts; ++i) {
771 apr_file_printf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val);
775 apr_file_printf(f, "%s\n", sbuf);
777 if (apr_file_gets(argsbuffer, HUGE_STRING_LEN, script_in) == 0) {
778 apr_file_puts("%stdout\n", f);
779 apr_file_puts(argsbuffer, f);
780 while (apr_file_gets(argsbuffer, HUGE_STRING_LEN, script_in) == 0)
781 apr_file_puts(argsbuffer, f);
782 apr_file_puts("\n", f);
786 if (apr_file_gets(argsbuffer, HUGE_STRING_LEN, script_err) == 0) {
787 apr_file_puts("%stderr\n", f);
788 apr_file_puts(argsbuffer, f);
789 while (apr_file_gets(argsbuffer, HUGE_STRING_LEN, script_err) == 0)
790 apr_file_puts(argsbuffer, f);
791 apr_file_puts("\n", f);
795 apr_file_close(script_in);
797 apr_file_close(script_err);
806 /****************************************************************
808 * Actual cgid handling...
810 static int cgid_handler(request_rec *r)
812 int retval, nph, dbpos = 0;
813 char *argv0, *dbuf = NULL;
814 apr_bucket_brigade *bb;
816 char argsbuffer[HUGE_STRING_LEN];
818 cgid_server_conf *conf;
822 struct sockaddr_un unix_addr;
823 apr_file_t *tempsock;
826 if(strcmp(r->handler,CGI_MAGIC_TYPE) && strcmp(r->handler,"cgi-script"))
829 if (r->method_number == M_OPTIONS) {
830 /* 99 out of 100 cgid scripts, this is all they support */
831 r->allowed |= (1 << M_GET);
832 r->allowed |= (1 << M_POST);
836 sconf = r->server->module_config;
837 conf = (cgid_server_conf *) ap_get_module_config(sconf, &cgid_module);
838 is_included = !strcmp(r->protocol, "INCLUDED");
840 if ((argv0 = strrchr(r->filename, '/')) != NULL)
845 nph = !(strncmp(argv0, "nph-", 4));
847 if ((argv0 = strrchr(r->filename, '/')) != NULL)
852 if (!(ap_allow_options(r) & OPT_EXECCGI) && !is_scriptaliased(r))
853 return log_scripterror(r, conf, HTTP_FORBIDDEN, 0,
854 "Options ExecCGI is off in this directory");
855 if (nph && is_included)
856 return log_scripterror(r, conf, HTTP_FORBIDDEN, 0,
857 "attempt to include NPH CGI script");
859 #if defined(OS2) || defined(WIN32)
860 #error mod_cgid does not work on this platform. If you teach it to, look
861 #error at mod_cgi.c for required code in this path.
863 if (r->finfo.filetype == 0)
864 return log_scripterror(r, conf, HTTP_NOT_FOUND, 0,
865 "script not found or unable to stat");
867 if (r->finfo.filetype == APR_DIR)
868 return log_scripterror(r, conf, HTTP_FORBIDDEN, 0,
869 "attempt to invoke directory as script");
871 if (!ap_suexec_enabled) {
872 if (!ap_can_exec(&r->finfo))
873 return log_scripterror(r, conf, HTTP_FORBIDDEN, 0,
874 "file permissions deny server execution");
877 ap_add_common_vars(r);
879 env = ap_create_environment(r->pool, r->subprocess_env);
881 if ((sd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
882 return log_scripterror(r, conf, HTTP_INTERNAL_SERVER_ERROR, errno,
883 "unable to create socket to cgi daemon");
885 memset(&unix_addr, 0, sizeof(unix_addr));
886 unix_addr.sun_family = AF_UNIX;
887 strcpy(unix_addr.sun_path, conf->sockname);
889 if (connect(sd, (struct sockaddr *)&unix_addr, sizeof(unix_addr)) < 0) {
890 return log_scripterror(r, conf, HTTP_INTERNAL_SERVER_ERROR, errno,
891 "unable to connect to cgi daemon");
894 send_req(sd, r, argv0, env, CGI_REQ);
896 /* We are putting the tempsock variable into a file so that we can use
897 * a pipe bucket to send the data to the client.
899 apr_os_file_put(&tempsock, &sd, r->pool);
901 if ((retval = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR)))
904 if ((argv0 = strrchr(r->filename, '/')) != NULL)
909 /* Transfer any put/post args, CERN style...
910 * Note that we already ignore SIGPIPE in the core server.
913 if (ap_should_client_block(r)) {
914 int dbsize, len_read;
917 dbuf = apr_pcalloc(r->pool, conf->bufbytes + 1);
922 ap_get_client_block(r, argsbuffer, HUGE_STRING_LEN)) > 0) {
924 if ((dbpos + len_read) > conf->bufbytes) {
925 dbsize = conf->bufbytes - dbpos;
930 memcpy(dbuf + dbpos, argsbuffer, dbsize);
934 apr_file_write(tempsock, argsbuffer, &nbytes);
935 if (nbytes < len_read) {
936 /* silly script stopped reading, soak up remaining message */
937 while (ap_get_client_block(r, argsbuffer, HUGE_STRING_LEN) > 0) {
943 shutdown(sd, 1); /* done writing; force EOF on child's stdin */
946 /* Handle script return... */
948 const char *location;
949 char sbuf[MAX_STRING_LEN];
952 if ((ret = ap_scan_script_header_err(r, tempsock, sbuf))) {
953 return log_script(r, conf, ret, dbuf, sbuf, tempsock, NULL);
956 location = apr_table_get(r->headers_out, "Location");
958 if (location && location[0] == '/' && r->status == 200) {
960 /* Soak up all the script output */
961 while (apr_file_gets(argsbuffer, HUGE_STRING_LEN, tempsock) > 0) {
964 /* This redirect needs to be a GET no matter what the original
967 r->method = apr_pstrdup(r->pool, "GET");
968 r->method_number = M_GET;
970 /* We already read the message body (if any), so don't allow
971 * the redirected request to think it has one. We can ignore
972 * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR.
974 apr_table_unset(r->headers_in, "Content-Length");
976 ap_internal_redirect_handler(location, r);
979 else if (location && r->status == 200) {
980 /* XX Note that if a script wants to produce its own Redirect
981 * body, it now has to explicitly *say* "Status: 302"
983 return HTTP_MOVED_TEMPORARILY;
986 ap_send_http_header(r);
987 if (!r->header_only) {
988 bb = apr_brigade_create(r->pool);
989 b = apr_bucket_pipe_creat(tempsock);
990 APR_BRIGADE_INSERT_TAIL(bb, b);
991 b = apr_bucket_eos_create();
992 APR_BRIGADE_INSERT_TAIL(bb, b);
993 ap_pass_brigade(r->output_filters, bb);
998 bb = apr_brigade_create(r->pool);
999 b = apr_bucket_pipe_creat(tempsock);
1000 APR_BRIGADE_INSERT_TAIL(bb, b);
1001 b = apr_bucket_eos_create();
1002 APR_BRIGADE_INSERT_TAIL(bb, b);
1003 ap_pass_brigade(r->output_filters, bb);
1006 apr_file_close(tempsock);
1008 return OK; /* NOT r->status, even if it has changed. */
1014 /*============================================================================
1015 *============================================================================
1016 * This is the beginning of the cgi filter code moved from mod_include. This
1017 * is the code required to handle the "exec" SSI directive.
1018 *============================================================================
1019 *============================================================================*/
1020 static int include_cgi(char *s, request_rec *r, ap_filter_t *next,
1021 apr_bucket *head_ptr, apr_bucket **inserted_head)
1023 request_rec *rr = ap_sub_req_lookup_uri(s, r, next);
1025 apr_bucket *tmp_buck, *tmp2_buck;
1027 if (rr->status != HTTP_OK) {
1031 /* No hardwired path info or query allowed */
1033 if ((rr->path_info && rr->path_info[0]) || rr->args) {
1036 if (rr->finfo.protection == 0) {
1040 /* Script gets parameters of the *document*, for back compatibility */
1042 rr->path_info = r->path_info; /* hard to get right; see mod_cgi.c */
1045 /* Force sub_req to be treated as a CGI request, even if ordinary
1046 * typing rules would have called it something else.
1049 rr->content_type = CGI_MAGIC_TYPE;
1053 rr_status = ap_run_sub_req(rr);
1054 if (ap_is_HTTP_REDIRECT(rr_status)) {
1055 apr_size_t len_loc, h_wrt;
1056 const char *location = apr_table_get(rr->headers_out, "Location");
1058 location = ap_escape_html(rr->pool, location);
1059 len_loc = strlen(location);
1061 tmp_buck = apr_bucket_immortal_create("<A HREF=\"", sizeof("<A HREF=\""));
1062 APR_BUCKET_INSERT_BEFORE(head_ptr, tmp_buck);
1063 tmp2_buck = apr_bucket_heap_create(location, len_loc, 1, &h_wrt);
1064 APR_BUCKET_INSERT_BEFORE(head_ptr, tmp2_buck);
1065 tmp2_buck = apr_bucket_immortal_create("\">", sizeof("\">"));
1066 APR_BUCKET_INSERT_BEFORE(head_ptr, tmp2_buck);
1067 tmp2_buck = apr_bucket_heap_create(location, len_loc, 1, &h_wrt);
1068 APR_BUCKET_INSERT_BEFORE(head_ptr, tmp2_buck);
1069 tmp2_buck = apr_bucket_immortal_create("</A>", sizeof("</A>"));
1070 APR_BUCKET_INSERT_BEFORE(head_ptr, tmp2_buck);
1072 if (*inserted_head == NULL) {
1073 *inserted_head = tmp_buck;
1077 ap_destroy_sub_req(rr);
1083 /* This is the special environment used for running the "exec cmd="
1084 * variety of SSI directives.
1086 static void add_ssi_vars(request_rec *r, ap_filter_t *next)
1088 apr_table_t *e = r->subprocess_env;
1090 if (r->path_info && r->path_info[0] != '\0') {
1091 request_rec *pa_req;
1093 apr_table_setn(e, "PATH_INFO", ap_escape_shell_cmd(r->pool, r->path_info));
1095 pa_req = ap_sub_req_lookup_uri(ap_escape_uri(r->pool, r->path_info), r, next);
1096 if (pa_req->filename) {
1097 apr_table_setn(e, "PATH_TRANSLATED",
1098 apr_pstrcat(r->pool, pa_req->filename, pa_req->path_info, NULL));
1103 char *arg_copy = apr_pstrdup(r->pool, r->args);
1105 apr_table_setn(e, "QUERY_STRING", r->args);
1106 ap_unescape_url(arg_copy);
1107 apr_table_setn(e, "QUERY_STRING_UNESCAPED", ap_escape_shell_cmd(r->pool, arg_copy));
1111 static int include_cmd(include_ctx_t *ctx, apr_bucket_brigade **bb, char *command,
1112 request_rec *r, ap_filter_t *f)
1115 const char *location;
1118 apr_bucket_brigade *bcgi;
1120 struct sockaddr_un unix_addr;
1121 apr_file_t *tempsock = NULL;
1122 void *sconf = r->server->module_config;
1123 cgid_server_conf *conf = (cgid_server_conf *) ap_get_module_config(sconf, &cgid_module);
1125 add_ssi_vars(r, f->next);
1126 env = ap_create_environment(r->pool, r->subprocess_env);
1128 if ((sd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
1129 return log_scripterror(r, conf, HTTP_INTERNAL_SERVER_ERROR, 0,
1130 "unable to create socket to cgi daemon");
1133 memset(&unix_addr, 0, sizeof(unix_addr));
1134 unix_addr.sun_family = AF_UNIX;
1135 strcpy(unix_addr.sun_path, conf->sockname);
1137 if (connect(sd, (struct sockaddr *)&unix_addr, sizeof(unix_addr)) < 0) {
1138 return log_scripterror(r, conf, HTTP_INTERNAL_SERVER_ERROR, 0,
1139 "unable to connect to cgi daemon");
1142 SPLIT_AND_PASS_PRETAG_BUCKETS(*bb, ctx, f->next);
1144 send_req(sd, r, command, env, SSI_REQ);
1146 /* We are putting the tempsock variable into a file so that we can use
1147 * a pipe bucket to send the data to the client.
1149 apr_os_file_put(&tempsock, &sd, r->pool);
1151 if ((retval = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR)))
1154 location = apr_table_get(r->headers_out, "Location");
1156 if (location && location[0] == '/' && r->status == 200) {
1157 char argsbuffer[HUGE_STRING_LEN];
1159 /* Soak up all the script output */
1160 while (apr_file_gets(argsbuffer, HUGE_STRING_LEN, tempsock) > 0) {
1163 /* This redirect needs to be a GET no matter what the original
1166 r->method = apr_pstrdup(r->pool, "GET");
1167 r->method_number = M_GET;
1169 /* We already read the message body (if any), so don't allow
1170 * the redirected request to think it has one. We can ignore
1171 * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR.
1173 apr_table_unset(r->headers_in, "Content-Length");
1175 ap_internal_redirect_handler(location, r);
1178 else if (location && r->status == 200) {
1179 /* XX Note that if a script wants to produce its own Redirect
1180 * body, it now has to explicitly *say* "Status: 302"
1182 return HTTP_MOVED_TEMPORARILY;
1185 ap_send_http_header(r);
1186 if (!r->header_only) {
1187 bcgi = apr_brigade_create(r->pool);
1188 b = apr_bucket_pipe_creat(tempsock);
1189 APR_BRIGADE_INSERT_TAIL(bcgi, b);
1190 ap_pass_brigade(f->next, bcgi);
1196 static int handle_exec(include_ctx_t *ctx, apr_bucket_brigade **bb, request_rec *r,
1197 ap_filter_t *f, apr_bucket *head_ptr, apr_bucket **inserted_head)
1200 char *tag_val = NULL;
1201 char *file = r->filename;
1202 apr_bucket *tmp_buck;
1203 char parsed_string[MAX_STRING_LEN];
1205 *inserted_head = NULL;
1206 if (ctx->flags & FLAG_PRINTING) {
1207 if (ctx->flags & FLAG_NO_EXEC) {
1208 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1209 "exec used but not allowed in %s", r->filename);
1210 CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, *inserted_head);
1214 cgid_pfn_gtv(ctx, &tag, &tag_val, 1);
1215 if (tag_val == NULL) {
1223 if (!strcmp(tag, "cmd")) {
1224 cgid_pfn_ps(r, tag_val, parsed_string, sizeof(parsed_string), 1);
1225 if (include_cmd(ctx, bb, parsed_string, r, f) == -1) {
1226 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1227 "execution failure for parameter \"%s\" "
1228 "to tag exec in file %s", tag, r->filename);
1229 CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, *inserted_head);
1231 /* just in case some stooge changed directories */
1233 else if (!strcmp(tag, "cgi")) {
1234 cgid_pfn_ps(r, tag_val, parsed_string, sizeof(parsed_string), 0);
1235 SPLIT_AND_PASS_PRETAG_BUCKETS(*bb, ctx, f->next);
1236 if (include_cgi(parsed_string, r, f->next, head_ptr, inserted_head) == -1) {
1237 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1238 "invalid CGI ref \"%s\" in %s", tag_val, file);
1239 CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, *inserted_head);
1243 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1244 "unknown parameter \"%s\" to tag exec in %s", tag, file);
1245 CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, *inserted_head);
1252 /*============================================================================
1253 *============================================================================
1254 * This is the end of the cgi filter code moved from mod_include.
1255 *============================================================================
1256 *============================================================================*/
1259 static void register_hook(apr_pool_t *p)
1261 static const char * const aszPre[] = { "mod_include.c", NULL };
1263 ap_hook_post_config(cgid_init, aszPre, NULL, APR_HOOK_MIDDLE);
1264 ap_hook_handler(cgid_handler, NULL, NULL, APR_HOOK_MIDDLE);
1267 module AP_MODULE_DECLARE_DATA cgid_module = {
1268 STANDARD20_MODULE_STUFF,
1269 NULL, /* dir config creater */
1270 NULL, /* dir merger --- default is to override */
1271 create_cgid_config, /* server config */
1272 merge_cgid_config, /* merge server config */
1273 cgid_cmds, /* command table */
1274 register_hook /* register_handlers */