📄 mod_cgid.c
字号:
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 * * http://www.apache.org/licenses/LICENSE-2.0 * * 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"#if APR_HAVE_SYS_SOCKET_H#include <sys/socket.h>#endif#if APR_HAVE_UNISTD_H#include <unistd.h>#endif#if APR_HAVE_SYS_TYPES_H#include <sys/types.h>#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 */#include <sys/stat.h>#include <sys/un.h> /* for sockaddr_un */module AP_MODULE_DECLARE_DATA cgid_module;static int cgid_start(apr_pool_t *p, server_rec *main_server, apr_proc_t *procnew);static int cgid_init(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *main_server);static int handle_exec(include_ctx_t *ctx, ap_filter_t *f, apr_bucket_brigade *bb);static APR_OPTIONAL_FN_TYPE(ap_register_include_handler) *cgid_pfn_reg_with_ssi;static APR_OPTIONAL_FN_TYPE(ap_ssi_get_tag_and_value) *cgid_pfn_gtv;static APR_OPTIONAL_FN_TYPE(ap_ssi_parse_string) *cgid_pfn_ps;static apr_pool_t *pcgi = NULL;static int total_modules = 0;static pid_t daemon_pid;static int daemon_should_exit = 0;static server_rec *root_server = NULL;static apr_pool_t *root_pool = NULL;static const char *sockname;static pid_t parent_pid;static ap_unix_identity_t empty_ugid = { (uid_t)-1, (gid_t)-1, -1 };/* The APR other-child API doesn't tell us how the daemon exited * (SIGSEGV vs. exit(1)). The other-child maintenance function * needs to decide whether to restart the daemon after a failure * based on whether or not it exited due to a fatal startup error * or something that happened at steady-state. This exit status * is unlikely to collide with exit signals. */#define DAEMON_STARTUP_ERROR 254/* Read and discard the data in the brigade produced by a CGI script */static void discard_script_output(apr_bucket_brigade *bb);/* This doer will only ever be called when we are sure that we have * a valid ugid. */static ap_unix_identity_t *cgid_suexec_id_doer(const request_rec *r){ return (ap_unix_identity_t *) ap_get_module_config(r->request_config, &cgid_module);}/* 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){ const char *t = apr_table_get(r->notes, "alias-forced-type"); return t && (!strcasecmp(t, "cgi-script"));}/* Configuration stuff */#define DEFAULT_LOGBYTES 10385760#define DEFAULT_BUFBYTES 1024#define DEFAULT_SOCKET DEFAULT_REL_RUNTIMEDIR "/cgisock"#define CGI_REQ 1#define SSI_REQ 2#define GETPID_REQ 3 /* get the pid of script created for prior request */#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 * the same time, connections from httpd threads/processes will back up * 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 * to the cgi daemon from the thread/process handling the cgi request. * 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#endiftypedef struct { const char *logname; long logbytes; int bufbytes;} cgid_server_conf;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 */ pid_t ppid; /* sanity check for config problems leading to * wrong cgid socket use */ int core_module_index; int env_count; ap_unix_identity_t ugid; apr_size_t filename_len; apr_size_t argv0_len; apr_size_t uri_len; apr_size_t args_len; 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. */static char **create_argv(apr_pool_t *p, char *path, char *user, char *group, char *av0, const char *args){ int x, numwords; char **av; char *w; int idx = 0; if (ap_strchr_c(args, '=')) { numwords = 0; } else { /* count the number of keywords */ for (x = 0, numwords = 1; args[x]; x++) { if (args[x] == '+') { ++numwords; } } } if (numwords > APACHE_ARG_MAX - 5) { numwords = APACHE_ARG_MAX - 5; /* Truncate args to prevent overrun */ } av = (char **) apr_pcalloc(p, (numwords + 5) * sizeof(char *)); if (path) { av[idx++] = path; } if (user) { av[idx++] = user; } if (group) { av[idx++] = group; } av[idx++] = apr_pstrdup(p, av0); for (x = 1; x <= numwords; x++) { w = ap_getword_nulls(p, &args, '+'); ap_unescape_url(w); av[idx++] = ap_escape_shell_cmd(p, w); } av[idx] = NULL; return av;}#if APR_HAS_OTHER_CHILDstatic void cgid_maint(int reason, void *data, apr_wait_t status){ apr_proc_t *proc = data; int mpm_state; int stopping; switch (reason) { case APR_OC_REASON_DEATH: apr_proc_other_child_unregister(data); /* If apache is not terminating or restarting, * restart the cgid daemon */ stopping = 1; /* if MPM doesn't support query, * assume we shouldn't restart daemon */ if (ap_mpm_query(AP_MPMQ_MPM_STATE, &mpm_state) == APR_SUCCESS && mpm_state != AP_MPMQ_STOPPING) { stopping = 0; } if (!stopping) { if (status == DAEMON_STARTUP_ERROR) { ap_log_error(APLOG_MARK, APLOG_CRIT, 0, NULL, "cgid daemon failed to initialize"); } else { ap_log_error(APLOG_MARK, APLOG_ERR, 0, NULL, "cgid daemon process died, restarting"); cgid_start(root_pool, root_server, proc); } } break; case APR_OC_REASON_RESTART: /* don't do anything; server is stopping or restarting */ apr_proc_other_child_unregister(data); break; case APR_OC_REASON_LOST: /* Restart the child cgid daemon process */ apr_proc_other_child_unregister(data); cgid_start(root_pool, root_server, proc); break; case APR_OC_REASON_UNREGISTER: /* we get here when pcgi is cleaned up; pcgi gets cleaned * up when pconf gets cleaned up */ kill(proc->pid, SIGHUP); /* send signal to daemon telling it to die */ /* Remove the cgi socket, we must do it here in order to try and * guarantee the same permissions as when the socket was created. */ if (unlink(sockname) < 0 && errno != ENOENT) { ap_log_error(APLOG_MARK, APLOG_ERR, errno, NULL, "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 */static apr_status_t sock_read(int fd, void *vbuf, size_t buf_size){ char *buf = vbuf; int rc; size_t bytes_read = 0; do { do { rc = read(fd, buf + bytes_read, buf_size - bytes_read); } while (rc < 0 && errno == EINTR); 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 */static apr_status_t sock_write(int fd, const void *buf, size_t buf_size){ int rc; do { rc = write(fd, buf, buf_size); } while (rc < 0 && errno == EINTR); if (rc < 0) { return errno; } return APR_SUCCESS;}static apr_status_t get_req(int fd, request_rec *r, char **argv0, char ***env, cgid_req_t *req){ int i; char **environ; core_request_config *temp_core; void **rconf; apr_status_t stat; r->server = apr_pcalloc(r->pool, sizeof(server_rec)); /* read the request header */ stat = sock_read(fd, req, sizeof(*req)); if (stat != APR_SUCCESS) { return stat; } r->server->loglevel = req->loglevel; if (req->req_type == GETPID_REQ) { /* no more data sent for this request */ return APR_SUCCESS; } /* handle module indexes and such */ rconf = (void **) apr_pcalloc(r->pool, sizeof(void *) * (total_modules + DYNAMIC_MODULE_LIMIT)); temp_core = (core_request_config *)apr_palloc(r->pool, sizeof(core_module)); rconf[req->core_module_index] = (void *)temp_core; r->request_config = (ap_conf_vector_t *)rconf; ap_set_module_config(r->request_config, &cgid_module, (void *)&req->ugid); /* Read the filename, argv0, uri, and args */ r->filename = apr_pcalloc(r->pool, req->filename_len + 1); *argv0 = apr_pcalloc(r->pool, req->argv0_len + 1); r->uri = apr_pcalloc(r->pool, req->uri_len + 1); if ((stat = sock_read(fd, r->filename, req->filename_len)) != APR_SUCCESS || (stat = sock_read(fd, *argv0, req->argv0_len)) != APR_SUCCESS || (stat = sock_read(fd, r->uri, req->uri_len)) != APR_SUCCESS) { return stat; } r->args = apr_pcalloc(r->pool, req->args_len + 1); /* empty string if no args */ if (req->args_len) { if ((stat = sock_read(fd, r->args, req->args_len)) != APR_SUCCESS) { return stat; } } /* read the environment variables */ environ = apr_pcalloc(r->pool, (req->env_count + 2) *sizeof(char *)); for (i = 0; i < req->env_count; i++) { apr_size_t curlen; if ((stat = sock_read(fd, &curlen, sizeof(curlen))) != APR_SUCCESS) { return stat; } environ[i] = apr_pcalloc(r->pool, curlen + 1); if ((stat = sock_read(fd, environ[i], curlen)) != APR_SUCCESS) { return stat; } } *env = environ;#if 0#ifdef RLIMIT_CPU sock_read(fd, &j, sizeof(int)); if (j) { temp_core->limit_cpu = (struct rlimit *)apr_palloc (sizeof(struct rlimit)); sock_read(fd, temp_core->limit_cpu, sizeof(struct rlimit)); } else { temp_core->limit_cpu = NULL; }#endif#if defined (RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS) sock_read(fd, &j, sizeof(int)); if (j) { temp_core->limit_mem = (struct rlimit *)apr_palloc(r->pool, sizeof(struct rlimit)); sock_read(fd, temp_core->limit_mem, sizeof(struct rlimit)); } else { temp_core->limit_mem = NULL; }#endif#ifdef RLIMIT_NPROC sock_read(fd, &j, sizeof(int)); if (j) { temp_core->limit_nproc = (struct rlimit *)apr_palloc(r->pool, sizeof(struct rlimit)); sock_read(fd, temp_core->limit_nproc, sizeof(struct rlimit)); } else { temp_core->limit_nproc = NULL; }#endif#endif return APR_SUCCESS;}static apr_status_t send_req(int fd, request_rec *r, char *argv0, char **env, int req_type){ int i; cgid_req_t req = {0}; apr_status_t stat; ap_unix_identity_t * ugid = ap_run_get_suexec_identity(r); if (ugid == NULL) { req.ugid = empty_ugid; } else {
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -