mod_cgid.c revision 43c3e6a4b559b76b750c245ee95e2782c15b4296
/* Copyright 1999-2005 The Apache Software Foundation or its licensors, as
* applicable.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* 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;
static const char *sockname;
static pid_t parent_pid;
/* Read and discard the data in the brigade produced by a CGI script */
/* This doer will only ever be called when we are sure that we have
* a valid ugid.
*/
{
return (ap_unix_identity_t *)
}
/* 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 *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
*/
* wrong cgid socket use
*/
int core_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;
}
{
int mpm_state;
int stopping;
switch (reason) {
case APR_OC_REASON_DEATH:
/* If apache is not terminating or restarting,
* restart the cgid daemon
*/
* assume we shouldn't restart daemon
*/
mpm_state != AP_MPMQ_STOPPING) {
stopping = 0;
}
if (!stopping) {
"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
*/
/* Remove the cgi socket, we must do it here in order to try and
* guarantee the same permissions as when the socket was created.
*/
"Couldn't unlink unix domain socket %s",
sockname);
}
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 **environ;
void **rconf;
/* 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 */
/* Read the filename, argv0, uri, and args */
return stat;
}
return stat;
}
}
/* read the environment variables */
return stat;
}
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;
cgid_req_t req = {0};
} else {
}
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;
}
}
#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;
/* Close our copy of the listening sockets */
/* cgid should use its own suexec doer */
"Couldn't create unix domain socket");
return errno;
}
if (rc < 0) {
"Couldn't bind unix domain socket %s",
sockname);
return errno;
}
"Couldn't listen on unix domain socket");
return errno;
}
if (!geteuid()) {
"Couldn't change owner of unix domain socket %s",
sockname);
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) {
#if defined(ENETDOWN)
/* The network has been shut down, no need to continue. Die gracefully */
}
#endif
(server_rec *)data,
"Error accepting on cgid socket");
}
continue;
}
if (stat != APR_SUCCESS) {
"Error reading request on cgid socket");
continue;
}
"CGI request received from wrong server instance; "
"see ScriptSock directive");
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.
*/
/* We have a valid identity, and can be sure that
* cgid_suexec_id_doer will return a valid ugid
*/
(const char * const *)env,
} else {
(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 {
/* We don't want to leak storage for the key, so only allocate
* a key if the key doesn't exist yet in the hash; there are
* only a limited number of possible keys (one for each
* possible thread in the server), so we can allocate a copy
* of the key the first time a thread has a cgid request.
* Note that apr_hash_set() only uses the storage passed in
* for the key if it is adding the key to the hash for the
* first time; new key storage isn't needed for replacing the
* existing value of a key.
*/
void *key;
}
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;
}
{
return OK;
}
{
int first_time = 0;
const char *userdata_key = "cgid_init";
module **m;
void *data;
root_pool = p;
if (!data) {
first_time = 1;
}
else {
}
if (!first_time) {
total_modules = 0;
for (m = ap_preloaded_modules; *m != NULL; m++)
parent_pid = getpid();
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;
}
{
return err;
}
/* Make sure the pid is appended to the sockname */
if (!sockname) {
}
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;
for (e = APR_BRIGADE_FIRST(bb);
e != APR_BRIGADE_SENTINEL(bb);
e = APR_BUCKET_NEXT(e))
{
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;
for (e = APR_BRIGADE_FIRST(bb);
e != APR_BRIGADE_SENTINEL(bb);
e = APR_BUCKET_NEXT(e))
{
if (APR_BUCKET_IS_EOS(e)) {
break;
}
if (rv != APR_SUCCESS) {
break;
}
}
}
/****************************************************************
*
* Actual cgid handling...
*/
struct cleanup_script_info {
request_rec *r;
unsigned long conn_id;
};
{
apr_interval_time_t total = 0;
do {
#ifdef _AIX
/* On AIX, for processes like mod_cgid's script children where
* SIGCHLD is ignored, kill(pid,0) returns success for up to
* one second after the script child exits, based on when a
* daemon runs to clean up unnecessary process table entries.
* getpgid() can report the proper info (-1/ESRCH) immediately.
*/
#else
#endif
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;
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. APR will create
* a cleanup for the apr_file_t which will close the socket, so we'll
* get rid of the cleanup we registered when 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;
}
}
if (nph) {
struct ap_filter_t *cur;
/* 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. APR will create
* a cleanup for the apr_file_t which will close the socket, so we'll
* get rid of the cleanup we registered when we created the socket.
*/
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 (rv != APR_SUCCESS) {
"execution failure for parameter \"%s\" "
break;
}
}
if (rv != APR_SUCCESS) {
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 */
};