mod_cgid.c revision 1fbf6ba0f5207e6637b49f9a9dfcc779bbe952a9
/* ====================================================================
* The Apache Software License, Version 1.1
*
* Copyright (c) 2000-2003 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Apache" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
*
* Portions of this software are based upon public domain software
* originally written at the National Center for Supercomputing Applications,
* University of Illinois, Urbana-Champaign.
*/
/*
* http_script: keeps all script-related ramblings together.
*
* Compliant to cgi/1.1 spec
*
* Adapted by rst from original NCSA code by Rob McCool
*
* Apache adds some new env vars; REDIRECT_URL and REDIRECT_QUERY_STRING for
* custom error responses, and DOCUMENT_ROOT because we found it useful.
* It also adds SERVER_ADMIN - useful for scripts to know who to mail when
* they fail.
*/
#include "apr_lib.h"
#include "apr_strings.h"
#include "apr_general.h"
#include "apr_file_io.h"
#include "apr_portable.h"
#include "apr_buckets.h"
#include "apr_optional.h"
#include "apr_signal.h"
#define APR_WANT_STRFUNC
#include "apr_want.h"
#endif
#include <unistd.h>
#endif
#endif
#define CORE_PRIVATE
#include "util_filter.h"
#include "httpd.h"
#include "http_config.h"
#include "http_request.h"
#include "http_core.h"
#include "http_protocol.h"
#include "http_main.h"
#include "http_log.h"
#include "util_script.h"
#include "ap_mpm.h"
#include "unixd.h"
#include "mod_suexec.h"
#include "../filters/mod_include.h"
#include "mod_core.h"
/* ### should be tossed in favor of APR */
static int total_modules = 0;
static pid_t daemon_pid;
static int daemon_should_exit = 0;
/* Read and discard the data in the brigade produced by a CGI script */
/* KLUDGE --- for back-combatibility, we don't have to check ExecCGI
* in ScriptAliased directories, which means we need to know if this
* request came through ScriptAlias or not... so the Alias module
* leaves a note for us.
*/
static int is_scriptaliased(request_rec *r)
{
return t && (!strcasecmp(t, "cgi-script"));
}
/* Configuration stuff */
#define DEFAULT_LOGBYTES 10385760
#define DEFAULT_BUFBYTES 1024
#define CGI_REQ 1
#define SSI_REQ 2
#define ERRFN_USERDATA_KEY "CGIDCHILDERRFN"
/* DEFAULT_CGID_LISTENBACKLOG controls the max depth on the unix socket's
* pending connection queue. If a bunch of cgi requests arrive at about
* in the queue while the cgid process slowly forks off a child to process
* each connection on the unix socket. If the queue is too short, the
* httpd process will get ECONNREFUSED when trying to connect.
*/
#ifndef DEFAULT_CGID_LISTENBACKLOG
#define DEFAULT_CGID_LISTENBACKLOG 100
#endif
/* DEFAULT_CONNECT_ATTEMPTS controls how many times we'll try to connect
* Generally we want to retry when we get ECONNREFUSED since it is
* probably because the listen queue is full. We need to try harder so
* the client doesn't see it as a 503 error.
*
* Set this to 0 to continually retry until the connect works or Apache
* terminates.
*/
#ifndef DEFAULT_CONNECT_ATTEMPTS
#define DEFAULT_CONNECT_ATTEMPTS 15
#endif
typedef struct {
const char *sockname;
const char *logname;
long logbytes;
int bufbytes;
typedef struct {
int req_type; /* request type (CGI_REQ, SSI_REQ, etc.) */
unsigned long conn_id; /* connection id; daemon uses this as a hash value
* to find the script pid when it is time for that
* process to be cleaned up
*/
int core_module_index;
int have_suexec;
int suexec_module_index;
int env_count;
int loglevel; /* to stuff in server_rec */
} cgid_req_t;
/* This routine is called to create the argument list to be passed
* to the CGI script. When suexec is enabled, the suexec path, user, and
* group are the first three arguments to be passed; if not, all three
* must be NULL. The query info is split into separate arguments, where
* "+" is the separator between keyword arguments.
*
* Do not process the args if they containing an '=' assignment.
*/
{
int x, numwords;
char **av;
char *w;
int idx = 0;
numwords = 0;
}
else {
/* count the number of keywords */
if (args[x] == '+') {
++numwords;
}
}
}
}
if (path) {
}
if (user) {
}
if (group) {
}
for (x = 1; x <= numwords; x++) {
if (strcmp(w, "")) {
ap_unescape_url(w);
}
}
return av;
}
{
switch (reason) {
case APR_OC_REASON_DEATH:
/* If apache is not terminating or restarting,
* restart the cgid daemon
*/
if (!ap_graceful_stop_signalled()) {
"cgid daemon process died, restarting");
}
break;
case APR_OC_REASON_RESTART:
/* don't do anything; server is stopping or restarting */
break;
case APR_OC_REASON_LOST:
/* Restart the child cgid daemon process */
break;
case APR_OC_REASON_UNREGISTER:
/* we get here when pcgi is cleaned up; pcgi gets cleaned
* up when pconf gets cleaned up
*/
break;
}
}
#endif
/* deal with incomplete reads and signals
* assume you really have to read buf_size bytes
*/
{
int rc;
size_t bytes_read = 0;
do {
do {
switch(rc) {
case -1:
return errno;
case 0: /* unexpected */
return ECONNRESET;
default:
bytes_read += rc;
}
} while (bytes_read < buf_size);
return APR_SUCCESS;
}
/* deal with signals
*/
{
int rc;
do {
if (rc < 0) {
return errno;
}
return APR_SUCCESS;
}
{
int i;
char *user;
char **environ;
void **dconf;
/* read the request header */
if (stat != APR_SUCCESS) {
return stat;
}
/* no more data sent for this request */
return APR_SUCCESS;
}
/* handle module indexes and such */
if (req->have_suexec) {
}
/* Read the filename, argv0, uri, and args */
return stat;
}
return stat;
}
}
/* read the environment variables */
return stat;
}
return stat;
}
}
/* basic notes table to avoid segfaults */
/* mod_userdir requires the mod_userdir_user note */
if (req->mod_userdir_user_len) {
if (stat != APR_SUCCESS) {
return stat;
}
}
#if 0
#ifdef RLIMIT_CPU
if (j) {
}
else {
}
#endif
if (j) {
}
else {
}
#endif
#ifdef RLIMIT_NPROC
if (j) {
}
else {
}
#endif
#endif
return APR_SUCCESS;
}
int req_type)
{
int i;
const char *user;
cgid_req_t req = {0};
if (suexec_mod) {
}
continue;
}
}
/* Write the request header */
return stat;
}
/* Write filename, argv0, uri, and args */
return stat;
}
return stat;
}
}
/* write the environment variables */
return stat;
}
return stat;
}
}
/* send a minimal notes table */
if (user) {
return stat;
}
}
#if 0
#ifdef RLIMIT_CPU
len = 1;
}
else {
len = 0;
}
#endif
len = 1;
}
else {
len = 0;
}
#endif
#ifdef RLIMIT_NPROC
if (conf->limit_nproc) {
len = 1;
}
else {
len = 0;
}
#endif
#endif
return APR_SUCCESS;
}
static void daemon_signal_handler(int sig)
{
}
}
const char *description)
{
request_rec *r;
void *vr;
r = vr;
/* sure we got r, but don't call ap_log_rerror() because we don't
* have r->headers_in and possibly other storage referenced by
* ap_log_rerror()
*/
}
static int cgid_server(void *data)
{
struct sockaddr_un unix_addr;
&cgid_module);
"Couldn't unlink unix domain socket %s",
/* just a warning; don't bail out */
}
"Couldn't create unix domain socket");
return errno;
}
if (rc < 0) {
"Couldn't bind unix domain socket %s",
return errno;
}
"Couldn't listen on unix domain socket");
return errno;
}
if (!geteuid()) {
"Couldn't change owner of unix domain socket %s",
return errno;
}
}
unixd_setup_child(); /* if running as root, switch to configured user/group */
while (!daemon_should_exit) {
int errfileno = STDERR_FILENO;
char *argv0;
char **env;
const char * const *argv;
request_rec *r;
if (sd2 < 0) {
(server_rec *)data,
"Error accepting on cgid socket");
}
continue;
}
if (stat != APR_SUCCESS) {
"Error reading request on cgid socket");
continue;
}
}
continue;
}
}
else {
}
err_pipe)) != APR_SUCCESS) ||
/* XXX apr_procattr_child_*_set() is creating an unnecessary
* pipe between this process and the child being created...
* It is cleaned up with the temporary pool for this request.
*/
/* Something bad happened, tell the world.
* ap_log_rerror() won't work because the header table used by
* ap_log_rerror() hasn't been replicated in the phony r
*/
"couldn't set child process attributes: %s", r->filename);
}
else {
/* We want to close sd2 for the new CGI process too.
* If it is left open it'll make ap_pass_brigade() block
* waiting for EOF if CGI forked something running long.
* close(sd2) here should be okay, as CGI channel
* is already dup()ed by apr_procattr_child_{in,out}_set()
* above.
*/
(const char * const *)env,
if (rc != APR_SUCCESS) {
/* Bad things happened. Everyone should have cleaned up.
* ap_log_rerror() won't work because the header table used by
* ap_log_rerror() hasn't been replicated in the phony r
*/
"couldn't create child process: %d: %s", rc,
}
else {
}
}
}
return -1;
}
{
daemon_should_exit = 0; /* clear setting from previous generation */
if ((daemon_pid = fork()) < 0) {
"mod_cgid: Couldn't spawn cgid daemon process");
return DECLINED;
}
else if (daemon_pid == 0) {
apr_pool_create(&pcgi, p);
}
exit(-1);
}
#endif
return OK;
}
{
int first_time = 0;
const char *userdata_key = "cgid_init";
module **m;
root_pool = p;
if (!procnew) {
first_time = 1;
}
if (!first_time) {
total_modules = 0;
for (m = ap_preloaded_modules; *m != NULL; m++)
return ret;
}
/* Required by mod_include filter. This is how mod_cgid registers
* with mod_include to provide processing of the exec directive.
*/
}
}
return ret;
}
{
cgid_server_conf *c =
c->logbytes = DEFAULT_LOGBYTES;
c->bufbytes = DEFAULT_BUFBYTES;
return c;
}
{
}
{
&cgid_module);
}
return NULL;
}
{
&cgid_module);
return NULL;
}
{
&cgid_module);
return NULL;
}
{
&cgid_module);
}
return NULL;
}
static const command_rec cgid_cmds[] =
{
"the name of a log for script debugging info"),
"the maximum length (in bytes) of the script debug log"),
"the maximum size (in bytes) to record of a POST request"),
"the name of the socket to use for communication with "
"the cgi daemon."),
{NULL}
};
{
apr_file_t *f = NULL;
char time_str[APR_CTIME_LEN];
/* XXX Very expensive mainline case! Open, then getfileinfo! */
return ret;
}
apr_file_close(f);
return ret;
}
{
char argsbuffer[HUGE_STRING_LEN];
apr_file_t *f = NULL;
apr_bucket *e;
const char *buf;
int first;
int i;
char time_str[APR_CTIME_LEN];
/* XXX Very expensive mainline case! Open, then getfileinfo! */
/* Soak up script output */
if (script_err) {
script_err) == APR_SUCCESS)
continue;
}
return ret;
}
apr_file_puts("%request\n", f);
continue;
}
&& *dbuf) {
}
apr_file_puts("%response\n", f);
continue;
}
first = 1;
APR_BRIGADE_FOREACH(e, bb) {
if (APR_BUCKET_IS_EOS(e)) {
break;
}
break;
}
if (first) {
apr_file_puts("%stdout\n", f);
first = 0;
}
apr_file_puts("\n", f);
}
if (script_err) {
script_err) == APR_SUCCESS) {
apr_file_puts("%stderr\n", f);
apr_file_puts(argsbuffer, f);
script_err) == APR_SUCCESS)
apr_file_puts(argsbuffer, f);
apr_file_puts("\n", f);
}
}
if (script_err) {
}
apr_file_close(f);
return ret;
}
{
}
{
struct sockaddr_un unix_addr;
int sd;
int connect_tries;
connect_tries = 0;
while (1) {
"unable to create socket to cgi daemon");
}
"connect #%d to cgi daemon failed, sleeping before retry",
sliding_timer *= 2;
}
}
else {
"unable to connect to cgi daemon after multiple tries");
}
}
else {
break; /* we got connected! */
}
/* gotta try again, but make sure the cgid daemon is still around */
if (kill(daemon_pid, 0) != 0) {
"cgid daemon is gone; is Apache terminating?");
}
}
return OK;
}
{
apr_bucket *e;
const char *buf;
APR_BRIGADE_FOREACH(e, bb) {
if (APR_BUCKET_IS_EOS(e)) {
break;
}
if (!APR_STATUS_IS_SUCCESS(rv)) {
break;
}
}
}
/****************************************************************
*
* Actual cgid handling...
*/
struct cleanup_script_info {
request_rec *r;
unsigned long conn_id;
};
{
apr_interval_time_t total = 0;
do {
return APR_SUCCESS;
}
if (interval < 500000) {
interval *= 2;
}
return APR_EGENERAL;
}
{
return APR_SUCCESS;
}
pid);
return APR_SUCCESS;
}
pid);
return APR_EGENERAL;
}
{
int sd;
int rc;
cgid_req_t req = {0};
return APR_EGENERAL;
}
/* we got a socket, and there is already a cleanup registered for it */
if (stat != APR_SUCCESS) {
return stat;
}
/* wait for pid of script */
if (stat != APR_SUCCESS) {
return stat;
}
if (pid == 0) {
"daemon couldn't find CGI process for connection %lu",
return APR_EGENERAL;
}
}
static int cgid_handler(request_rec *r)
{
conn_rec *c = r->connection;
apr_bucket *b;
int is_included;
int sd;
char **env;
struct cleanup_script_info *info;
return DECLINED;
if (r->method_number == M_OPTIONS) {
/* 99 out of 100 cgid scripts, this is all they support */
return DECLINED;
}
argv0++;
else
argv0++;
else
"Options ExecCGI is off in this directory");
if (nph && is_included)
"attempt to include NPH CGI script");
#else
"script not found or unable to stat");
#endif
"attempt to invoke directory as script");
if ((r->used_path_info == AP_REQ_REJECT_PATH_INFO) &&
{
/* default to accept */
"AcceptPathInfo off disallows user's path");
}
/*
if (!ap_suexec_enabled) {
if (!ap_can_exec(&r->finfo))
return log_scripterror(r, conf, HTTP_FORBIDDEN, 0,
"file permissions deny server execution");
}
*/
ap_add_cgi_vars(r);
return retval;
}
if (rv != APR_SUCCESS) {
"write to cgi daemon process");
}
info->r = r;
/* We are putting the socket discriptor into an apr_file_t so that we can
* use a pipe bucket to send the data to the client.
* Note that this does not register a cleanup for the socket. We did
* that explicitly right after we created the socket.
*/
argv0++;
else
* Note that we already ignore SIGPIPE in the core server.
*/
seen_eos = 0;
dbpos = 0;
}
do {
if (rv != APR_SUCCESS) {
return rv;
}
const char *data;
if (APR_BUCKET_IS_EOS(bucket)) {
seen_eos = 1;
break;
}
/* We can't do much with this. */
if (APR_BUCKET_IS_FLUSH(bucket)) {
continue;
}
/* If the child stopped, we still must read to EOS. */
if (child_stopped_reading) {
continue;
}
/* read */
int cursize;
}
else {
}
}
/* Keep writing data to the child until done or too much time
* elapses with no progress or an error occurs.
*/
if (rv != APR_SUCCESS) {
/* silly script stopped reading, soak up remaining message */
}
}
}
while (!seen_eos);
}
/* we're done writing, or maybe we didn't write at all;
* force EOF on child's stdin so that the cgi detects end (or
* absence) of data
*/
/* Handle script return... */
if (!nph) {
const char *location;
char sbuf[MAX_STRING_LEN];
int ret;
b = apr_bucket_eos_create(c->bucket_alloc);
}
/* Soak up all the script output */
/* This redirect needs to be a GET no matter what the original
* method was.
*/
r->method_number = M_GET;
/* We already read the message body (if any), so don't allow
* the redirected request to think it has one. We can ignore
* Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR.
*/
return OK;
}
/* XX Note that if a script wants to produce its own Redirect
* body, it now has to explicitly *say* "Status: 302"
*/
return HTTP_MOVED_TEMPORARILY;
}
/* Passing our socket down the filter chain in a pipe bucket
* gives up the responsibility of closing the socket, so
* get rid of the cleanup.
*/
}
if (nph) {
struct ap_filter_t *cur;
/* Passing our socket down the filter chain in a pipe bucket
* gives up the responsibility of closing the socket, so
* get rid of the cleanup.
*/
/* get rid of all filters up through protocol... since we
* haven't parsed off the headers, there is no way they can
* work
*/
cur = r->proto_output_filters;
}
b = apr_bucket_eos_create(c->bucket_alloc);
}
return OK; /* NOT r->status, even if it has changed. */
}
/*============================================================================
*============================================================================
* This is the beginning of the cgi filter code moved from mod_include. This
* is the code required to handle the "exec" SSI directive.
*============================================================================
*============================================================================*/
apr_bucket_brigade *bb, char *s)
{
request_rec *r = f->r;
int rr_status;
return APR_EGENERAL;
}
/* No hardwired path info or query allowed */
return APR_EGENERAL;
}
return APR_EGENERAL;
}
/* Script gets parameters of the *document*, for back compatibility */
/* Force sub_req to be treated as a CGI request, even if ordinary
* typing rules would have called it something else.
*/
/* Run it. */
if (ap_is_HTTP_REDIRECT(rr_status)) {
if (location) {
char *buffer;
f->c->bucket_alloc));
}
}
return APR_SUCCESS;
}
/* This is the special environment used for running the "exec cmd="
* variety of SSI directives.
*/
static void add_ssi_vars(request_rec *r)
{
apr_table_t *e = r->subprocess_env;
apr_table_setn(e, "PATH_TRANSLATED",
}
}
if (r->args) {
}
}
{
char **env;
int sd;
int retval;
request_rec *r = f->r;
&cgid_module);
struct cleanup_script_info *info;
add_ssi_vars(r);
return retval;
}
info->r = r;
/* for this type of request, the script is invoked through an
* intermediate shell process... cleanup_script is only able
* to knock out the shell process, not the actual script
*/
/* We are putting the socket discriptor into an apr_file_t so that we can
* use a pipe bucket to send the data to the client.
* Note that this does not register a cleanup for the socket. We did
* that explicitly right after we created the socket.
*/
/* Passing our socket down the filter chain in a pipe bucket
* gives up the responsibility of closing the socket, so
* get rid of the cleanup.
*/
f->c->bucket_alloc));
return APR_SUCCESS;
}
{
request_rec *r = f->r;
char parsed_string[MAX_STRING_LEN];
? APLOG_ERR : APLOG_WARNING,
0, r, "missing argument for exec element in %s",
r->filename);
}
return APR_SUCCESS;
}
return APR_SUCCESS;
}
"in %s", r->filename);
return APR_SUCCESS;
}
while (1) {
break;
}
if (!APR_STATUS_IS_SUCCESS(rv)) {
"execution failure for parameter \"%s\" "
break;
}
}
if (!APR_STATUS_IS_SUCCESS(rv)) {
break;
}
}
else {
break;
}
}
return APR_SUCCESS;
}
/*============================================================================
*============================================================================
* This is the end of the cgi filter code moved from mod_include.
*============================================================================
*============================================================================*/
static void register_hook(apr_pool_t *p)
{
}
NULL, /* dir config creater */
NULL, /* dir merger --- default is to override */
create_cgid_config, /* server config */
merge_cgid_config, /* merge server config */
cgid_cmds, /* command table */
register_hook /* register_handlers */
};