1 /* ====================================================================
2 * The Apache Software License, Version 1.1
4 * Copyright (c) 2000 The Apache Software Foundation. All rights
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in
16 * the documentation and/or other materials provided with the
19 * 3. The end-user documentation included with the redistribution,
20 * if any, must include the following acknowledgment:
21 * "This product includes software developed by the
22 * Apache Software Foundation (http://www.apache.org/)."
23 * Alternately, this acknowledgment may appear in the software itself,
24 * if and wherever such third-party acknowledgments normally appear.
26 * 4. The names "Apache" and "Apache Software Foundation" must
27 * not be used to endorse or promote products derived from this
28 * software without prior written permission. For written
29 * permission, please contact apache@apache.org.
31 * 5. Products derived from this software may not be called "Apache",
32 * nor may "Apache" appear in their name, without prior written
33 * permission of the Apache Software Foundation.
35 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38 * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
39 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47 * ====================================================================
49 * This software consists of voluntary contributions made by many
50 * individuals on behalf of the Apache Software Foundation. For more
51 * information on the Apache Software Foundation, please see
52 * <http://www.apache.org/>.
54 * Portions of this software are based upon public domain software
55 * originally written at the National Center for Supercomputing Applications,
56 * University of Illinois, Urbana-Champaign.
60 * http_script: keeps all script-related ramblings together.
62 * Compliant to cgi/1.1 spec
64 * Adapted by rst from original NCSA code by Rob McCool
66 * Apache adds some new env vars; REDIRECT_URL and REDIRECT_QUERY_STRING for
67 * custom error responses, and DOCUMENT_ROOT because we found it useful.
68 * It also adds SERVER_ADMIN - useful for scripts to know who to mail when
77 #include "apr_strings.h"
78 #include "apr_general.h"
79 #include "apr_file_io.h"
80 #include "apr_portable.h"
81 #include "apr_buckets.h"
82 #include "util_filter.h"
84 #include "http_config.h"
85 #include "http_request.h"
86 #include "http_core.h"
87 #include "http_protocol.h"
88 #include "http_main.h"
90 #include "util_script.h"
91 #include "http_conf_globals.h"
94 #include "mod_suexec.h"
95 #include "apr_optional.h"
96 #include "../filters/mod_include.h"
98 #ifdef HAVE_SYS_SOCKET_H
99 #include <sys/socket.h>
104 #ifdef HAVE_STRINGS_H
107 #include <sys/un.h> /* for sockaddr_un */
108 #include <sys/types.h>
110 module AP_MODULE_DECLARE_DATA cgid_module;
112 static void cgid_init(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *main_server);
113 static int handle_exec(include_ctx_t *ctx, apr_bucket_brigade **bb, request_rec *r,
114 ap_filter_t *f, apr_bucket *head_ptr, apr_bucket **inserted_head);
116 static APR_OPTIONAL_FN_TYPE(ap_register_include_handler) *cgid_pfn_reg_with_ssi;
117 static APR_OPTIONAL_FN_TYPE(ap_ssi_get_tag_and_value) *cgid_pfn_gtv;
118 static APR_OPTIONAL_FN_TYPE(ap_ssi_parse_string) *cgid_pfn_ps;
120 static apr_pool_t *pcgi;
121 static int total_modules = 0;
123 /* KLUDGE --- for back-combatibility, we don't have to check Execcgid
124 * in ScriptAliased directories, which means we need to know if this
125 * request came through ScriptAlias or not... so the Alias module
126 * leaves a note for us.
129 static int is_scriptaliased(request_rec *r)
131 const char *t = apr_table_get(r->notes, "alias-forced-type");
132 return t && (!strcasecmp(t, "cgi-script"));
135 /* Configuration stuff */
137 #define DEFAULT_LOGBYTES 10385760
138 #define DEFAULT_BUFBYTES 1024
139 #define DEFAULT_SOCKET "logs/cgisock"
141 #define SHELL_PATH "/bin/sh"
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
158 const char *sockname;
164 /* If a request includes query info in the URL (stuff after "?"), and
165 * the query info does not contain "=" (indicative of a FORM submission),
166 * then this routine is called to create the argument list to be passed
167 * to the CGI script. When suexec is enabled, the suexec path, user, and
168 * group are the first three arguments to be passed; if not, all three
169 * must be NULL. The query info is split into separate arguments, where
170 * "+" is the separator between keyword arguments.
172 * XXXX: note that the WIN32 code uses one of the suexec strings
173 * to pass an interpreter name. Remember this if changing the way they
174 * are handled in create_argv.
177 static char **create_argv(apr_pool_t *p, char *path, char *user, char *group,
178 char *av0, const char *args)
185 /* count the number of keywords */
187 for (x = 0, numwords = 1; args[x]; x++) {
188 if (args[x] == '+') {
193 if (numwords > APACHE_ARG_MAX - 5) {
194 numwords = APACHE_ARG_MAX - 5; /* Truncate args to prevent overrun */
196 av = (char **) apr_pcalloc(p, (numwords + 5) * sizeof(char *));
208 av[idx++] = apr_pstrdup(p, av0);
210 for (x = 1; x <= numwords; x++) {
211 w = ap_getword_nulls(p, &args, '+');
214 av[idx++] = ap_escape_shell_cmd(p, w);
221 static void cgid_maint(int reason, void *data, apr_wait_t status)
223 #if APR_HAS_OTHER_CHILD
226 case APR_OC_REASON_DEATH:
227 case APR_OC_REASON_LOST:
228 /* stop gap to make sure everything else works. In the end,
229 * we'll just restart the cgid server. */
230 apr_destroy_pool(pcgi);
231 kill(getppid(), SIGWINCH);
233 case APR_OC_REASON_RESTART:
234 case APR_OC_REASON_UNREGISTER:
235 apr_destroy_pool(pcgi);
242 static void get_req(int fd, request_rec *r, char **filename, char **argv0, char ***env, int *req_type)
247 core_dir_config *temp_core;
249 module *suexec_mod = ap_find_linked_module("mod_suexec.c");
251 r->server = apr_pcalloc(r->pool, sizeof(server_rec));
253 read(fd, req_type, sizeof(int));
254 read(fd, &j, sizeof(int));
255 read(fd, &len, sizeof(int));
256 data = apr_pcalloc(r->pool, len + 1); /* get a cleared byte for final '\0' */
257 i = read(fd, data, len);
259 r->filename = ap_getword(r->pool, (const char **)&data, '\n');
260 *argv0 = ap_getword(r->pool, (const char **)&data, '\n');
262 r->uri = ap_getword(r->pool, (const char **)&data, '\n');
264 environ = apr_pcalloc(r->pool, (j + 2) *sizeof(char *));
266 for (i = 0; i < j; i++) {
267 environ[i] = ap_getword(r->pool, (const char **)&data, '\n');
270 r->args = ap_getword(r->pool, (const char **)&data, '\n');
272 read(fd, &i, sizeof(int));
274 /* add 1, so that if i == 0, we still malloc something. */
276 dconf = (void **) apr_pcalloc(r->pool, sizeof(void *) * (total_modules + DYNAMIC_MODULE_LIMIT));
278 temp_core = (core_dir_config *)apr_palloc(r->pool, sizeof(core_module));
280 dconf[i] = (void *)temp_core;
283 suexec_config_t *suexec_cfg = apr_pcalloc(r->pool, sizeof(*suexec_cfg));
285 read(fd, &i, sizeof(int));
286 read(fd, &suexec_cfg->ugid.uid, sizeof(uid_t));
287 read(fd, &suexec_cfg->ugid.gid, sizeof(gid_t));
288 read(fd, &suexec_cfg->active, sizeof(int));
289 dconf[i] = (void *)suexec_cfg;
292 r->per_dir_config = dconf;
295 read(fd, &j, sizeof(int));
297 temp_core->limit_cpu = (struct rlimit *)apr_palloc (sizeof(struct rlimit));
298 read(fd, temp_core->limit_cpu, sizeof(struct rlimit));
301 temp_core->limit_cpu = NULL;
305 #if defined (RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
306 read(fd, &j, sizeof(int));
308 temp_core->limit_mem = (struct rlimit *)apr_palloc(r->pool, sizeof(struct rlimit));
309 read(fd, temp_core->limit_mem, sizeof(struct rlimit));
312 temp_core->limit_mem = NULL;
317 read(fd, &j, sizeof(int));
319 temp_core->limit_nproc = (struct rlimit *)apr_palloc(r->pool, sizeof(struct rlimit));
320 read(fd, temp_core->limit_nproc, sizeof(struct rlimit));
323 temp_core->limit_nproc = NULL;
327 /* For right now, just make the notes table. At some point we will need
328 * to actually fill this out, but for now we just don't want suexec to
331 r->notes = apr_make_table(r->pool, 1);
336 static void send_req(int fd, request_rec *r, char *argv0, char **env, int req_type)
338 int len, r_type = req_type;
341 module *suexec_mod = ap_find_linked_module("mod_suexec.c");
343 data = apr_pstrcat(r->pool, r->filename, "\n", argv0, "\n", r->uri, "\n",
346 for (i =0; env[i]; i++) {
350 /* Write the request type (SSI "exec cmd" or cgi). */
351 if (write(fd, &r_type, sizeof(int)) < 0) {
352 ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r,
353 "write to cgi daemon process");
356 /* Write the number of entries in the environment. */
357 if (write(fd, &i, sizeof(int)) < 0) {
358 ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r,
359 "write to cgi daemon process");
362 for (i = 0; env[i]; i++) {
363 data = apr_pstrcat(r->pool, data, env[i], "\n", NULL);
365 data = apr_pstrcat(r->pool, data, r->args, NULL);
367 /* Write the length of the concatenated env string. */
368 if (write(fd, &len, sizeof(int)) < 0) {
369 ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r,
370 "write to cgi daemon process");
372 /* Write the concatted env string. */
373 if (write(fd, data, len) < 0) {
374 ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r,
375 "write to cgi daemon process");
377 /* Write module_index id value. */
378 if (write(fd, &core_module.module_index, sizeof(int)) < 0) {
379 ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r,
380 "write to cgi daemon process");
383 suexec_config_t *suexec_cfg = ap_get_module_config(r->per_dir_config,
386 write(fd, &suexec_mod->module_index, sizeof(int));
387 write(fd, &suexec_cfg->ugid.uid, sizeof(uid_t));
388 write(fd, &suexec_cfg->ugid.gid, sizeof(gid_t));
389 write(fd, &suexec_cfg->active, sizeof(int));
394 if (conf->limit_cpu) {
396 write(fd, &len, sizeof(int));
397 write(fd, conf->limit_cpu, sizeof(struct rlimit));
401 write(fd, &len, sizeof(int));
405 #if defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
406 if (conf->limit_mem) {
408 write(fd, &len, sizeof(int));
409 write(fd, conf->limit_mem, sizeof(struct rlimit));
413 write(fd, &len, sizeof(int));
418 if (conf->limit_nproc) {
420 write(fd, &len, sizeof(int));
421 write(fd, conf->limit_nproc, sizeof(struct rlimit));
425 write(fd, &len, sizeof(int));
431 static int cgid_server(void *data)
433 struct sockaddr_un unix_addr;
434 int sd, sd2, rc, req_type;
437 server_rec *main_server = data;
438 cgid_server_conf *sconf = (cgid_server_conf *)ap_get_module_config(
439 main_server->module_config, &cgid_module);
441 apr_signal(SIGCHLD, SIG_IGN);
442 if (unlink(sconf->sockname) < 0 && errno != ENOENT) {
443 ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
444 "Couldn't unlink unix domain socket %s",
446 /* just a warning; don't bail out */
449 if ((sd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
450 ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
451 "Couldn't create unix domain socket");
455 memset(&unix_addr, 0, sizeof(unix_addr));
456 unix_addr.sun_family = AF_UNIX;
457 strcpy(unix_addr.sun_path, sconf->sockname);
459 omask = umask(0077); /* so that only Apache can use socket */
460 rc = bind(sd, (struct sockaddr *)&unix_addr, sizeof(unix_addr));
461 umask(omask); /* can't fail, so can't clobber errno */
463 ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
464 "Couldn't bind unix domain socket %s",
469 if (listen(sd, DEFAULT_CGID_LISTENBACKLOG) < 0) {
470 ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
471 "Couldn't listen on unix domain socket");
476 if (chown(sconf->sockname, unixd_config.user_id, -1) < 0) {
477 ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
478 "Couldn't change owner of unix domain socket %s",
484 unixd_setup_child(); /* if running as root, switch to configured user/group */
486 int errfileno = STDERR_FILENO;
490 const char * const *argv;
491 apr_int32_t in_pipe = APR_CHILD_BLOCK;
492 apr_int32_t out_pipe = APR_CHILD_BLOCK;
493 apr_int32_t err_pipe = APR_CHILD_BLOCK;
494 apr_cmdtype_e cmd_type = APR_PROGRAM;
497 apr_procattr_t *procattr = NULL;
498 apr_proc_t *procnew = NULL;
502 len = sizeof(unix_addr);
503 sd2 = accept(sd, (struct sockaddr *)&unix_addr, &len);
505 if (errno != EINTR) {
506 ap_log_error(APLOG_MARK, APLOG_ERR, errno,
508 "Error accepting on cgid socket.");
513 apr_create_pool(&p, pcgi);
515 r = apr_pcalloc(p, sizeof(request_rec));
516 procnew = apr_pcalloc(p, sizeof(*procnew));
518 get_req(sd2, r, &filename, &argv0, &env, &req_type);
519 apr_put_os_file(&r->server->error_log, &errfileno, r->pool);
520 apr_put_os_file(&inout, &sd2, r->pool);
522 if (req_type == SSI_REQ) {
523 in_pipe = APR_NO_PIPE;
524 out_pipe = APR_FULL_BLOCK;
525 err_pipe = APR_NO_PIPE;
526 cmd_type = APR_SHELLCMD;
529 if (((rc = apr_createprocattr_init(&procattr, p)) != APR_SUCCESS) ||
530 ((req_type == CGI_REQ) &&
531 (((rc = apr_setprocattr_io(procattr,
534 err_pipe)) != APR_SUCCESS) ||
535 ((rc = apr_setprocattr_childerr(procattr, r->server->error_log, NULL)) != APR_SUCCESS) ||
536 ((rc = apr_setprocattr_childin(procattr, inout, NULL)) != APR_SUCCESS))) ||
537 ((rc = apr_setprocattr_childout(procattr, inout, NULL)) != APR_SUCCESS) ||
538 ((rc = apr_setprocattr_dir(procattr,
539 ap_make_dirstr_parent(r->pool, r->filename))) != APR_SUCCESS) ||
540 ((rc = apr_setprocattr_cmdtype(procattr, cmd_type)) != APR_SUCCESS)) {
541 /* Something bad happened, tell the world. */
542 ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r,
543 "couldn't set child process attributes: %s", r->filename);
546 argv = (const char * const *)create_argv(r->pool, NULL, NULL, NULL, argv0, r->args);
547 rc = ap_os_create_privileged_process(r, procnew, argv0, argv,
548 (const char * const *)env,
552 if (rc != APR_SUCCESS) {
553 /* Bad things happened. Everyone should have cleaned up. */
554 ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r,
555 "couldn't create child process: %d: %s", rc, r->filename);
562 static void cgid_init(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp,
563 server_rec *main_server)
569 const char *userdata_key = "cgid_init";
572 apr_get_userdata(&data, userdata_key, main_server->process->pool);
575 apr_set_userdata((const void *)1, userdata_key,
576 apr_null_cleanup, main_server->process->pool);
580 apr_create_pool(&pcgi, p);
583 for (m = ap_preloaded_modules; *m != NULL; m++)
587 if ((pid = fork()) < 0) {
588 ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
589 "Couldn't spawn cgid daemon process");
592 cgid_server(main_server);
595 procnew = apr_pcalloc(p, sizeof(*procnew));
597 procnew->err = procnew->in = procnew->out = NULL;
598 apr_note_subprocess(p, procnew, kill_after_timeout);
599 #if APR_HAS_OTHER_CHILD
600 apr_register_other_child(procnew, cgid_maint, &procnew->pid, NULL, p);
603 cgid_pfn_reg_with_ssi = APR_RETRIEVE_OPTIONAL_FN(ap_register_include_handler);
604 cgid_pfn_gtv = APR_RETRIEVE_OPTIONAL_FN(ap_ssi_get_tag_and_value);
605 cgid_pfn_ps = APR_RETRIEVE_OPTIONAL_FN(ap_ssi_parse_string);
607 if ((cgid_pfn_reg_with_ssi) && (cgid_pfn_gtv) && (cgid_pfn_ps)) {
608 /* Required by mod_include filter. This is how mod_cgid registers
609 * with mod_include to provide processing of the exec directive.
611 cgid_pfn_reg_with_ssi("exec", handle_exec);
616 static void *create_cgid_config(apr_pool_t *p, server_rec *s)
618 cgid_server_conf *c =
619 (cgid_server_conf *) apr_pcalloc(p, sizeof(cgid_server_conf));
622 c->logbytes = DEFAULT_LOGBYTES;
623 c->bufbytes = DEFAULT_BUFBYTES;
624 c->sockname = ap_server_root_relative(p, DEFAULT_SOCKET);
628 static void *merge_cgid_config(apr_pool_t *p, void *basev, void *overridesv)
630 cgid_server_conf *base = (cgid_server_conf *) basev, *overrides = (cgid_server_conf *) overridesv;
632 return overrides->logname ? overrides : base;
635 static const char *set_scriptlog(cmd_parms *cmd, void *dummy, const char *arg)
637 server_rec *s = cmd->server;
638 cgid_server_conf *conf =
639 (cgid_server_conf *) ap_get_module_config(s->module_config, &cgid_module);
645 static const char *set_scriptlog_length(cmd_parms *cmd, void *dummy, const char *arg)
647 server_rec *s = cmd->server;
648 cgid_server_conf *conf =
649 (cgid_server_conf *) ap_get_module_config(s->module_config, &cgid_module);
651 conf->logbytes = atol(arg);
655 static const char *set_scriptlog_buffer(cmd_parms *cmd, void *dummy, const char *arg)
657 server_rec *s = cmd->server;
658 cgid_server_conf *conf =
659 (cgid_server_conf *) ap_get_module_config(s->module_config, &cgid_module);
661 conf->bufbytes = atoi(arg);
665 static const char *set_script_socket(cmd_parms *cmd, void *dummy, const char *arg)
667 server_rec *s = cmd->server;
668 cgid_server_conf *conf =
669 (cgid_server_conf *) ap_get_module_config(s->module_config, &cgid_module);
671 conf->sockname = ap_server_root_relative(cmd->pool, arg);
675 static const command_rec cgid_cmds[] =
677 AP_INIT_TAKE1("ScriptLog", set_scriptlog, NULL, RSRC_CONF,
678 "the name of a log for script debugging info"),
679 AP_INIT_TAKE1("ScriptLogLength", set_scriptlog_length, NULL, RSRC_CONF,
680 "the maximum length (in bytes) of the script debug log"),
681 AP_INIT_TAKE1("ScriptLogBuffer", set_scriptlog_buffer, NULL, RSRC_CONF,
682 "the maximum size (in bytes) to record of a POST request"),
683 AP_INIT_TAKE1("Scriptsock", set_script_socket, NULL, RSRC_CONF,
684 "the name of the socket to use for communication with "
689 static int log_scripterror(request_rec *r, cgid_server_conf * conf, int ret,
690 apr_status_t rv, char *error)
692 apr_file_t *f = NULL;
694 char time_str[APR_CTIME_LEN];
695 int log_flags = rv ? APLOG_ERR : APLOG_NOERRNO | APLOG_ERR;
697 ap_log_rerror(APLOG_MARK, log_flags, rv, r,
698 "%s: %s", error, r->filename);
700 if (!conf->logname ||
701 ((stat(ap_server_root_relative(r->pool, conf->logname), &finfo) == 0)
702 && (finfo.st_size > conf->logbytes)) ||
703 (apr_open(&f, ap_server_root_relative(r->pool, conf->logname),
704 APR_APPEND|APR_WRITE|APR_CREATE, APR_OS_DEFAULT, r->pool) != APR_SUCCESS)) {
708 /* "%% [Wed Jun 19 10:53:21 1996] GET /cgid-bin/printenv HTTP/1.0" */
709 apr_ctime(time_str, apr_now());
710 apr_fprintf(f, "%%%% [%s] %s %s%s%s %s\n", time_str, r->method, r->uri,
711 r->args ? "?" : "", r->args ? r->args : "", r->protocol);
712 /* "%% 500 /usr/local/apache/cgid-bin */
713 apr_fprintf(f, "%%%% %d %s\n", ret, r->filename);
715 apr_fprintf(f, "%%error\n%s\n", error);
721 static int log_script(request_rec *r, cgid_server_conf * conf, int ret,
722 char *dbuf, const char *sbuf, apr_file_t *script_in, apr_file_t *script_err)
724 apr_array_header_t *hdrs_arr = apr_table_elts(r->headers_in);
725 apr_table_entry_t *hdrs = (apr_table_entry_t *) hdrs_arr->elts;
726 char argsbuffer[HUGE_STRING_LEN];
727 apr_file_t *f = NULL;
730 char time_str[APR_CTIME_LEN];
732 if (!conf->logname ||
733 ((stat(ap_server_root_relative(r->pool, conf->logname), &finfo) == 0)
734 && (finfo.st_size > conf->logbytes)) ||
735 (apr_open(&f, ap_server_root_relative(r->pool, conf->logname),
736 APR_APPEND|APR_WRITE|APR_CREATE, APR_OS_DEFAULT, r->pool) != APR_SUCCESS)) {
737 /* Soak up script output */
738 while (apr_fgets(argsbuffer, HUGE_STRING_LEN, script_in) == 0)
741 while (apr_fgets(argsbuffer, HUGE_STRING_LEN, script_err) == 0)
747 /* "%% [Wed Jun 19 10:53:21 1996] GET /cgid-bin/printenv HTTP/1.0" */
748 apr_ctime(time_str, apr_now());
749 apr_fprintf(f, "%%%% [%s] %s %s%s%s %s\n", time_str, r->method, r->uri,
750 r->args ? "?" : "", r->args ? r->args : "", r->protocol);
751 /* "%% 500 /usr/local/apache/cgid-bin" */
752 apr_fprintf(f, "%%%% %d %s\n", ret, r->filename);
754 apr_puts("%request\n", f);
755 for (i = 0; i < hdrs_arr->nelts; ++i) {
758 apr_fprintf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val);
760 if ((r->method_number == M_POST || r->method_number == M_PUT)
762 apr_fprintf(f, "\n%s\n", dbuf);
765 apr_puts("%response\n", f);
766 hdrs_arr = apr_table_elts(r->err_headers_out);
767 hdrs = (apr_table_entry_t *) hdrs_arr->elts;
769 for (i = 0; i < hdrs_arr->nelts; ++i) {
772 apr_fprintf(f, "%s: %s\n", hdrs[i].key, hdrs[i].val);
776 apr_fprintf(f, "%s\n", sbuf);
778 if (apr_fgets(argsbuffer, HUGE_STRING_LEN, script_in) == 0) {
779 apr_puts("%stdout\n", f);
780 apr_puts(argsbuffer, f);
781 while (apr_fgets(argsbuffer, HUGE_STRING_LEN, script_in) == 0)
782 apr_puts(argsbuffer, f);
787 if (apr_fgets(argsbuffer, HUGE_STRING_LEN, script_err) == 0) {
788 apr_puts("%stderr\n", f);
789 apr_puts(argsbuffer, f);
790 while (apr_fgets(argsbuffer, HUGE_STRING_LEN, script_err) == 0)
791 apr_puts(argsbuffer, f);
796 apr_close(script_in);
798 apr_close(script_err);
807 /****************************************************************
809 * Actual cgid handling...
811 static int cgid_handler(request_rec *r)
813 int retval, nph, dbpos = 0;
814 char *argv0, *dbuf = NULL;
815 apr_bucket_brigade *bb;
817 char argsbuffer[HUGE_STRING_LEN];
819 cgid_server_conf *conf;
823 struct sockaddr_un unix_addr;
824 apr_file_t *tempsock;
827 if(strcmp(r->handler,CGI_MAGIC_TYPE) && strcmp(r->handler,"cgi-script"))
830 if (r->method_number == M_OPTIONS) {
831 /* 99 out of 100 cgid scripts, this is all they support */
832 r->allowed |= (1 << M_GET);
833 r->allowed |= (1 << M_POST);
837 sconf = r->server->module_config;
838 conf = (cgid_server_conf *) ap_get_module_config(sconf, &cgid_module);
839 is_included = !strcmp(r->protocol, "INCLUDED");
841 if ((argv0 = strrchr(r->filename, '/')) != NULL)
846 nph = !(strncmp(argv0, "nph-", 4));
848 if ((argv0 = strrchr(r->filename, '/')) != NULL)
853 if (!(ap_allow_options(r) & OPT_EXECCGI) && !is_scriptaliased(r))
854 return log_scripterror(r, conf, HTTP_FORBIDDEN, 0,
855 "Options ExecCGI is off in this directory");
856 if (nph && is_included)
857 return log_scripterror(r, conf, HTTP_FORBIDDEN, 0,
858 "attempt to include NPH CGI script");
860 #if defined(OS2) || defined(WIN32)
861 #error mod_cgid does not work on this platform. If you teach it to, look
862 #error at mod_cgi.c for required code in this path.
864 if (r->finfo.filetype == 0)
865 return log_scripterror(r, conf, HTTP_NOT_FOUND, 0,
866 "script not found or unable to stat");
868 if (r->finfo.filetype == APR_DIR)
869 return log_scripterror(r, conf, HTTP_FORBIDDEN, 0,
870 "attempt to invoke directory as script");
872 if (!ap_suexec_enabled) {
873 if (!ap_can_exec(&r->finfo))
874 return log_scripterror(r, conf, HTTP_FORBIDDEN, 0,
875 "file permissions deny server execution");
878 ap_add_common_vars(r);
880 env = ap_create_environment(r->pool, r->subprocess_env);
882 if ((sd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
883 return log_scripterror(r, conf, HTTP_INTERNAL_SERVER_ERROR, errno,
884 "unable to create socket to cgi daemon");
886 memset(&unix_addr, 0, sizeof(unix_addr));
887 unix_addr.sun_family = AF_UNIX;
888 strcpy(unix_addr.sun_path, conf->sockname);
890 if (connect(sd, (struct sockaddr *)&unix_addr, sizeof(unix_addr)) < 0) {
891 return log_scripterror(r, conf, HTTP_INTERNAL_SERVER_ERROR, errno,
892 "unable to connect to cgi daemon");
895 send_req(sd, r, argv0, env, CGI_REQ);
897 /* We are putting the tempsock variable into a file so that we can use
898 * a pipe bucket to send the data to the client.
900 apr_put_os_file(&tempsock, &sd, r->pool);
902 if ((retval = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR)))
905 if ((argv0 = strrchr(r->filename, '/')) != NULL)
910 /* Transfer any put/post args, CERN style...
911 * Note that we already ignore SIGPIPE in the core server.
914 if (ap_should_client_block(r)) {
915 int dbsize, len_read;
918 dbuf = apr_pcalloc(r->pool, conf->bufbytes + 1);
923 ap_get_client_block(r, argsbuffer, HUGE_STRING_LEN)) > 0) {
925 if ((dbpos + len_read) > conf->bufbytes) {
926 dbsize = conf->bufbytes - dbpos;
931 memcpy(dbuf + dbpos, argsbuffer, dbsize);
935 apr_write(tempsock, argsbuffer, &nbytes);
936 if (nbytes < len_read) {
937 /* silly script stopped reading, soak up remaining message */
938 while (ap_get_client_block(r, argsbuffer, HUGE_STRING_LEN) > 0) {
944 shutdown(sd, 1); /* done writing; force EOF on child's stdin */
947 /* Handle script return... */
949 const char *location;
950 char sbuf[MAX_STRING_LEN];
953 if ((ret = ap_scan_script_header_err(r, tempsock, sbuf))) {
954 return log_script(r, conf, ret, dbuf, sbuf, tempsock, NULL);
957 location = apr_table_get(r->headers_out, "Location");
959 if (location && location[0] == '/' && r->status == 200) {
961 /* Soak up all the script output */
962 while (apr_fgets(argsbuffer, HUGE_STRING_LEN, tempsock) > 0) {
965 /* This redirect needs to be a GET no matter what the original
968 r->method = apr_pstrdup(r->pool, "GET");
969 r->method_number = M_GET;
971 /* We already read the message body (if any), so don't allow
972 * the redirected request to think it has one. We can ignore
973 * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR.
975 apr_table_unset(r->headers_in, "Content-Length");
977 ap_internal_redirect_handler(location, r);
980 else if (location && r->status == 200) {
981 /* XX Note that if a script wants to produce its own Redirect
982 * body, it now has to explicitly *say* "Status: 302"
984 return HTTP_MOVED_TEMPORARILY;
987 ap_send_http_header(r);
988 if (!r->header_only) {
989 bb = apr_brigade_create(r->pool);
990 b = apr_bucket_create_pipe(tempsock);
991 APR_BRIGADE_INSERT_TAIL(bb, b);
992 b = apr_bucket_create_eos();
993 APR_BRIGADE_INSERT_TAIL(bb, b);
994 ap_pass_brigade(r->output_filters, bb);
999 bb = apr_brigade_create(r->pool);
1000 b = apr_bucket_create_pipe(tempsock);
1001 APR_BRIGADE_INSERT_TAIL(bb, b);
1002 b = apr_bucket_create_eos();
1003 APR_BRIGADE_INSERT_TAIL(bb, b);
1004 ap_pass_brigade(r->output_filters, bb);
1007 apr_close(tempsock);
1009 return OK; /* NOT r->status, even if it has changed. */
1015 /*============================================================================
1016 *============================================================================
1017 * This is the beginning of the cgi filter code moved from mod_include. This
1018 * is the code required to handle the "exec" SSI directive.
1019 *============================================================================
1020 *============================================================================*/
1021 static int include_cgi(char *s, request_rec *r, ap_filter_t *next,
1022 apr_bucket *head_ptr, apr_bucket **inserted_head)
1024 request_rec *rr = ap_sub_req_lookup_uri(s, r, next);
1026 apr_bucket *tmp_buck, *tmp2_buck;
1028 if (rr->status != HTTP_OK) {
1032 /* No hardwired path info or query allowed */
1034 if ((rr->path_info && rr->path_info[0]) || rr->args) {
1037 if (rr->finfo.protection == 0) {
1041 /* Script gets parameters of the *document*, for back compatibility */
1043 rr->path_info = r->path_info; /* hard to get right; see mod_cgi.c */
1046 /* Force sub_req to be treated as a CGI request, even if ordinary
1047 * typing rules would have called it something else.
1050 rr->content_type = CGI_MAGIC_TYPE;
1054 rr_status = ap_run_sub_req(rr);
1055 if (ap_is_HTTP_REDIRECT(rr_status)) {
1056 apr_size_t len_loc, h_wrt;
1057 const char *location = apr_table_get(rr->headers_out, "Location");
1059 location = ap_escape_html(rr->pool, location);
1060 len_loc = strlen(location);
1062 tmp_buck = apr_bucket_create_immortal("<A HREF=\"", sizeof("<A HREF=\""));
1063 APR_BUCKET_INSERT_BEFORE(head_ptr, tmp_buck);
1064 tmp2_buck = apr_bucket_create_heap(location, len_loc, 1, &h_wrt);
1065 APR_BUCKET_INSERT_BEFORE(head_ptr, tmp2_buck);
1066 tmp2_buck = apr_bucket_create_immortal("\">", sizeof("\">"));
1067 APR_BUCKET_INSERT_BEFORE(head_ptr, tmp2_buck);
1068 tmp2_buck = apr_bucket_create_heap(location, len_loc, 1, &h_wrt);
1069 APR_BUCKET_INSERT_BEFORE(head_ptr, tmp2_buck);
1070 tmp2_buck = apr_bucket_create_immortal("</A>", sizeof("</A>"));
1071 APR_BUCKET_INSERT_BEFORE(head_ptr, tmp2_buck);
1073 if (*inserted_head == NULL) {
1074 *inserted_head = tmp_buck;
1078 ap_destroy_sub_req(rr);
1084 /* This is the special environment used for running the "exec cmd="
1085 * variety of SSI directives.
1087 static void add_ssi_vars(request_rec *r, ap_filter_t *next)
1089 apr_table_t *e = r->subprocess_env;
1091 if (r->path_info && r->path_info[0] != '\0') {
1092 request_rec *pa_req;
1094 apr_table_setn(e, "PATH_INFO", ap_escape_shell_cmd(r->pool, r->path_info));
1096 pa_req = ap_sub_req_lookup_uri(ap_escape_uri(r->pool, r->path_info), r, next);
1097 if (pa_req->filename) {
1098 apr_table_setn(e, "PATH_TRANSLATED",
1099 apr_pstrcat(r->pool, pa_req->filename, pa_req->path_info, NULL));
1104 char *arg_copy = apr_pstrdup(r->pool, r->args);
1106 apr_table_setn(e, "QUERY_STRING", r->args);
1107 ap_unescape_url(arg_copy);
1108 apr_table_setn(e, "QUERY_STRING_UNESCAPED", ap_escape_shell_cmd(r->pool, arg_copy));
1112 static int include_cmd(include_ctx_t *ctx, apr_bucket_brigade **bb, char *command,
1113 request_rec *r, ap_filter_t *f)
1116 const char *location;
1119 apr_bucket_brigade *bcgi;
1121 struct sockaddr_un unix_addr;
1122 apr_file_t *tempsock = NULL;
1123 void *sconf = r->server->module_config;
1124 cgid_server_conf *conf = (cgid_server_conf *) ap_get_module_config(sconf, &cgid_module);
1126 add_ssi_vars(r, f->next);
1127 env = ap_create_environment(r->pool, r->subprocess_env);
1129 if ((sd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
1130 return log_scripterror(r, conf, HTTP_INTERNAL_SERVER_ERROR, 0,
1131 "unable to create socket to cgi daemon");
1134 memset(&unix_addr, 0, sizeof(unix_addr));
1135 unix_addr.sun_family = AF_UNIX;
1136 strcpy(unix_addr.sun_path, conf->sockname);
1138 if (connect(sd, (struct sockaddr *)&unix_addr, sizeof(unix_addr)) < 0) {
1139 return log_scripterror(r, conf, HTTP_INTERNAL_SERVER_ERROR, 0,
1140 "unable to connect to cgi daemon");
1143 SPLIT_AND_PASS_PRETAG_BUCKETS(*bb, ctx, f->next);
1145 send_req(sd, r, command, env, SSI_REQ);
1147 /* We are putting the tempsock variable into a file so that we can use
1148 * a pipe bucket to send the data to the client.
1150 apr_put_os_file(&tempsock, &sd, r->pool);
1152 if ((retval = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR)))
1155 location = apr_table_get(r->headers_out, "Location");
1157 if (location && location[0] == '/' && r->status == 200) {
1158 char argsbuffer[HUGE_STRING_LEN];
1160 /* Soak up all the script output */
1161 while (apr_fgets(argsbuffer, HUGE_STRING_LEN, tempsock) > 0) {
1164 /* This redirect needs to be a GET no matter what the original
1167 r->method = apr_pstrdup(r->pool, "GET");
1168 r->method_number = M_GET;
1170 /* We already read the message body (if any), so don't allow
1171 * the redirected request to think it has one. We can ignore
1172 * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR.
1174 apr_table_unset(r->headers_in, "Content-Length");
1176 ap_internal_redirect_handler(location, r);
1179 else if (location && r->status == 200) {
1180 /* XX Note that if a script wants to produce its own Redirect
1181 * body, it now has to explicitly *say* "Status: 302"
1183 return HTTP_MOVED_TEMPORARILY;
1186 ap_send_http_header(r);
1187 if (!r->header_only) {
1188 bcgi = apr_brigade_create(r->pool);
1189 b = apr_bucket_create_pipe(tempsock);
1190 APR_BRIGADE_INSERT_TAIL(bcgi, b);
1191 ap_pass_brigade(f->next, bcgi);
1197 static int handle_exec(include_ctx_t *ctx, apr_bucket_brigade **bb, request_rec *r,
1198 ap_filter_t *f, apr_bucket *head_ptr, apr_bucket **inserted_head)
1201 char *tag_val = NULL;
1202 char *file = r->filename;
1203 apr_bucket *tmp_buck;
1204 char parsed_string[MAX_STRING_LEN];
1206 *inserted_head = NULL;
1207 if (ctx->flags & FLAG_PRINTING) {
1208 if (ctx->flags & FLAG_NO_EXEC) {
1209 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1210 "exec used but not allowed in %s", r->filename);
1211 CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, *inserted_head);
1215 cgid_pfn_gtv(ctx, &tag, &tag_val, 1);
1216 if (tag_val == NULL) {
1224 if (!strcmp(tag, "cmd")) {
1225 cgid_pfn_ps(r, tag_val, parsed_string, sizeof(parsed_string), 1);
1226 if (include_cmd(ctx, bb, parsed_string, r, f) == -1) {
1227 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1228 "execution failure for parameter \"%s\" "
1229 "to tag exec in file %s", tag, r->filename);
1230 CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, *inserted_head);
1232 /* just in case some stooge changed directories */
1234 else if (!strcmp(tag, "cgi")) {
1235 cgid_pfn_ps(r, tag_val, parsed_string, sizeof(parsed_string), 0);
1236 SPLIT_AND_PASS_PRETAG_BUCKETS(*bb, ctx, f->next);
1237 if (include_cgi(parsed_string, r, f->next, head_ptr, inserted_head) == -1) {
1238 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1239 "invalid CGI ref \"%s\" in %s", tag_val, file);
1240 CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, *inserted_head);
1244 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1245 "unknown parameter \"%s\" to tag exec in %s", tag, file);
1246 CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, *inserted_head);
1253 /*============================================================================
1254 *============================================================================
1255 * This is the end of the cgi filter code moved from mod_include.
1256 *============================================================================
1257 *============================================================================*/
1260 static void register_hook(apr_pool_t *p)
1262 ap_hook_post_config(cgid_init, NULL, NULL, APR_HOOK_MIDDLE);
1263 ap_hook_handler(cgid_handler, NULL, NULL, APR_HOOK_MIDDLE);
1266 module AP_MODULE_DECLARE_DATA cgid_module = {
1267 STANDARD20_MODULE_STUFF,
1268 NULL, /* dir config creater */
1269 NULL, /* dir merger --- default is to override */
1270 create_cgid_config, /* server config */
1271 merge_cgid_config, /* merge server config */
1272 cgid_cmds, /* command table */
1273 register_hook /* register_handlers */