mpm_winnt.c revision 9a0d076511763b559a755133f6a182e6c24ef643
/* ====================================================================
* The Apache Software License, Version 1.1
*
* Copyright (c) 2000-2001 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.
*/
#define CORE_PRIVATE
#include "httpd.h"
#include "http_main.h"
#include "http_log.h"
#include "http_config.h" /* for read_config */
#include "http_core.h" /* for get_remote_host */
#include "http_connection.h"
#include "apr_portable.h"
#include "apr_getopt.h"
#include "apr_strings.h"
#include "apr_lib.h"
#include "ap_mpm.h"
#include "ap_config.h"
#include "ap_listen.h"
#include "mpm_default.h"
#include "mpm_winnt.h"
#include "mpm_common.h"
#include "scoreboard.h"
/*
* Definitions of WINNT MPM specific config globals
*/
static int workers_may_exit = 0;
static int shutdown_in_progress = 0;
static unsigned int g_blocked_threads = 0;
static char *ap_pid_fname = NULL;
int ap_threads_per_child = 0;
static int max_requests_per_child = 0;
static int num_listenfds = 0;
static char ap_coredump_dir[MAX_STRING_LEN];
static server_rec *server_conf;
static int one_process = 0;
static char const* signal_arg;
int ap_max_requests_per_child=0;
int ap_daemons_to_start=0;
static HANDLE exit_event;
static HANDLE maintenance_event;
/* ap_get_max_daemons and ap_my_generation are used by the scoreboard
* code
*/
/* This is the helper code to resolve late bound entry points
* missing from one or more releases of the Win32 API...
* but it sure would be nice if we didn't duplicate this code
* from the APR ;-)
*/
static const char* const lateDllName[DLL_defined] = {
"kernel32", "advapi32", "mswsock", "ws2_32" };
{
if (!lateDllHandle[fnLib]) {
if (!lateDllHandle[fnLib])
return NULL;
}
if (ordinal)
else
}
{
}
return APR_SUCCESS;
}
/* A bunch or routines from os/win32/multithread.c that need to be merged into APR
* or thrown out entirely...
*/
{
}
{
int rv;
return;
}
{
}
{
}
/* To share the semaphores with other processes, we need a NULL ACL
* Code from MS KB Q106387
*/
static PSECURITY_ATTRIBUTES GetNullACL()
{
return NULL;
}
apr_set_os_error(0);
|| apr_get_os_error()) {
return NULL;
}
|| apr_get_os_error()) {
return NULL;
}
return sa;
}
static void CleanNullACL( void *sa ) {
if( sa ) {
}
}
/*
* The Win32 call WaitForMultipleObjects will only allow you to wait for
* a maximum of MAXIMUM_WAIT_OBJECTS (current 64). Since the threading
* model in the multithreaded version of apache wants to use this call,
* we are restricted to a maximum of 64 threads. This is a simplistic
* routine that will increase this size.
*/
{
do {
if (!bFirst)
Sleep(1000);
else
0, 0);
if (dwRet != WAIT_TIMEOUT) {
break;
}
}
return dwRet;
}
/*
* Signalling Apache on NT.
*
* Under Unix, Apache can be told to shutdown or restart by sending various
* signals (HUP, USR, TERM). On NT we don't have easy access to signals, so
* we use "events" instead. The parent apache process goes into a loop
* where it waits forever for a set of events. Two of those events are
* called
*
* apPID_shutdown
* apPID_restart
*
* (where PID is the PID of the apache parent process). When one of these
* is signalled, the Apache parent performs the appropriate action. The events
* can become signalled through internal Apache methods (e.g. if the child
* finds a fatal error and needs to kill its parent), via the service
* control manager (the control thread will signal the shutdown event when
* requested to stop the Apache service), from the -k Apache command line,
* or from any external program which finds the Apache PID from the
* httpd.pid file.
*
* The signal_parent() function, below, is used to signal one of these events.
* It can be called by any child or parent process, since it does not
* rely on global variables.
*
* On entry, type gives the event to signal. 0 means shutdown, 1 means
* graceful restart.
*/
void signal_parent(int type)
{
HANDLE e;
char *signal_name;
/* after updating the shutdown_pending or restart flags, we need
* to wake up the parent process so it can see the changes. The
* parent will normally be waiting for either a child process
* to die, or for a signal on the "spache-signal" event. So set the
* "apache-signal" event here.
*/
if (one_process) {
return;
}
switch(type) {
case 0: signal_name = signal_shutdown_name; break;
default: return;
}
if (!e) {
/* Um, problem, can't signal the parent, which means we can't
* signal ourselves to die. Ignore for now...
*/
"OpenEvent on %s event", signal_name);
return;
}
if (SetEvent(e) == 0) {
/* Same problem as above */
"SetEvent on %s event", signal_name);
CloseHandle(e);
return;
}
CloseHandle(e);
}
static int volatile is_graceful = 0;
AP_DECLARE(int) ap_graceful_stop_signalled(void)
{
return is_graceful;
}
AP_DECLARE(void) ap_start_shutdown(void)
{
signal_parent(0);
}
{
signal_parent(1);
}
/*
* Initialise the signal names, in the global variables signal_name_prefix,
* signal_restart_name and signal_shutdown_name.
*/
void setup_signal_names(char *prefix)
{
"%s_shutdown", signal_name_prefix);
"%s_restart", signal_name_prefix);
}
/*
* Routines that deal with sockets, some are WIN32 specific...
*/
static void sock_disable_nagle(int s)
{
/* The Nagle algorithm says that we should delay sending partial
* packets in hopes of getting more data. We don't want to do
* this; we are not telnet. There are bad interactions between
* persistent connections and Nagle's algorithm that have very severe
* performance penalties. (Failing to disable Nagle is not much of a
* problem with simple HTTP.)
*
* In spite of these problems, failure here is not a shooting offense.
*/
int just_say_no = 1;
sizeof(int)) < 0) {
"setsockopt: (TCP_NODELAY)");
}
}
/*
* Routines to deal with managing the list of listening sockets.
*/
static ap_listen_rec *head_listener;
{
if (head_listener == NULL)
return (lr);
}
}
return NULL;
}
static int setup_listeners(server_rec *s)
{
int num_listeners = 0;
/* Setup the listeners */
return 0;
}
listenmaxfd = nsd;
}
}
}
return num_listeners;
}
static int setup_inherited_listeners(server_rec *s)
{
int num_listeners = 0;
/* Setup the listeners */
/* Set up a default listener if necessary */
if (ap_listeners == NULL) {
if (!lr)
return 0;
ap_listeners = lr;
}
/* Open the pipe to the parent process to receive the inherited socket
* data. The sockets have been set to listening in the parent process.
*/
"setup_inherited_listeners: Unable to read socket data from parent");
signal_parent(0); /* tell parent to die */
exit(1);
}
"Child %d: setup_inherited_listener() read = %d bytes of WSAProtocolInfo.", my_pid);
&WSAProtocolInfo, 0, 0);
if (nsd == INVALID_SOCKET) {
"Child %d: setup_inherited_listeners(), WSASocket failed to open the inherited socket.", my_pid);
signal_parent(0); /* tell parent to die */
exit(1);
}
if (nsd >= 0) {
listenmaxfd = nsd;
}
}
}
/* Now, read the AcceptExCompPort from the parent */
}
return num_listeners;
}
static void bind_listeners_to_completion_port()
{
/* Associate the open listeners with the completion port.
* Bypass the operation for Windows 95/98
*/
int nsd;
}
}
}
/**********************************************************************
* Child Process Notes
*
* The child process in the mpm_winnt consists of one 'master' thread
* and one or more worker threads. The master thread is responsible for
* creating the worker threads, performing server maintenance, and for
* listening for the parent process to signal the child process to
* shutdown. The master thread runs and sleeps in child_main(). The worker
* threads run in worker_main().
*
* mpm_winnt implements two seperate models for binding connections to
* threads: one specific to Windows 95/98 and another specific to Windows
* NT/2000.
*
* On Windows 95/98 a single thread (the accept thread, created by the
* master thread in child_main()) "accepts" connections off the listining
* socket. When a connection is accepted, the accepted socket is placed
* onto a queue of "jobs" (add_job()). The worker threads consume from
* the top of this job queue with remove_job() and handle requests coming
* in on that connection until the connection is taken down.
*
* Windows NT/2000 uses an advanced Winsock2 APIs (AcceptEx() and
* completion ports) to handle dispatching connections to worker
* threads. add_job/remove_job are not used by the NT/2000 specific
* code path. Instead, each worker thread is responsible for calling
* AcceptEx().
**********************************************************************/
/*
* Definition of jobs, shared by main and worker threads.
*/
typedef struct joblist_s {
int sock;
} joblist;
/*
* Globals common to main and worker threads. This structure is not
* used by the parent process.
*/
typedef struct globals_s {
int jobcount;
} globals;
#define MAX_SELECT_ERRORS 100
/* Windows 9x specific code...
* model. A single thread accepts connections and queues the accepted socket
* to the accept queue for consumption by a pool of worker threads.
*
* win9x_get_connection()
* Calls remove_job() to pull a job from the accept queue. All the worker
* threads block on remove_job.
* accept_and_queue_connections()
* The accept threads runs this function, which accepts connections off
* the network and calls add_job() to queue jobs to the accept_queue.
* add_job()/remove_job()
* Add or remove an accepted socket from the list of sockets
* connected to clients. allowed_globals.jobmutex protects
* against multiple concurrent access to the linked list of jobs.
*/
{
"Ouch! Out of memory in add_job()!");
return;
}
if (!allowed_globals.jobhead)
}
static int remove_job(void)
{
int sock;
return (-1);
}
return (sock);
}
static void accept_and_queue_connections(void * dummy)
{
int requests_this_child = 0;
int wait_time = 1;
int csd;
int nsd = INVALID_SOCKET;
struct sockaddr_in sa_client;
int count_select_errors = 0;
int rc;
int clen;
while (!shutdown_in_progress) {
break;
}
count_select_errors = 0; /* reset count of errors */
continue;
}
else if (rc == SOCKET_ERROR) {
/* A "real" error occurred, log it and increment the count of
* select errors. This count is used to ensure we don't go into
* a busy loop of continuous errors.
*/
"select failed with error %d", apr_get_netos_error());
if (count_select_errors > MAX_SELECT_ERRORS) {
shutdown_in_progress = 1;
"Too many errors in select loop. Child process exiting.");
break;
}
} else {
/* fetch the native socket descriptor */
}
}
do {
if (csd == INVALID_SOCKET) {
csd = -1;
}
if (csd < 0) {
"accept: (client socket)");
}
}
else {
}
}
}
{
int len;
/* allocate the completion context and the transaction pool */
if (!context) {
"win9x_get_connection: apr_pcalloc() failed. Process will exit.");
return NULL;
}
}
while (1) {
return NULL;
}
"getsockname failed");
continue;
}
"getpeername failed");
}
/* do we NEED_DUPPED_CSD ?? */
return context;
}
}
/*
* Windows 2000/NT specific code...
* create_acceptex_context()
* reset_acceptex_context()
* drain_acceptex_complport()
* winnt_get_connection()
*
* TODO: Insert a discussion of 'completion contexts' and what these function do here...
*/
{
int rc;
while (1) {
&pol, 1000);
if (!rc) {
rc = apr_get_os_error();
"Child %d: Draining an ABORTED packet off "
"the AcceptEx completion port.", my_pid);
continue;
}
break;
}
"Child %d: Draining and discarding an active connection "
"off the AcceptEx completion port.", my_pid);
/* It is only valid to clean-up in the process that initiated the I/O */
}
}
}
{
int lasterror;
/* allocate the completion context */
if (!context) {
"create_acceptex_context: apr_pcalloc() failed. Process will exit.");
return -1;
}
/* initialize the completion context */
"create_acceptex_context: CreateEvent() failed. Process will exit.");
return -1;
}
/* create and initialize the accept socket */
"create_acceptex_context: socket() failed. Process will exit.");
return -1;
}
/* SO_UPDATE_ACCEPT_CONTEXT is required for shutdown() to work */
SO_UPDATE_ACCEPT_CONTEXT, (char *)&nsd,
sizeof(nsd))) {
"setsockopt(SO_UPDATE_ACCEPT_CONTEXT) failed.");
/* Not a failure condition. Keep running. */
}
/* recv_buf must be large enough to hold the remote and local
* addresses. Note that recv_buf_size is the amount of recv_buf
* available for AcceptEx to receive bytes into. Since we
* don't want AcceptEx to do a recv, set the size to 0.
*/
context->recv_buf_size = 0;
/* AcceptEx on the completion context. The completion context will be signaled
* when a connection is accepted. */
(LPOVERLAPPED) context)) {
"create_acceptex_context: AcceptEx failed. Process will exit.");
return -1;
}
}
return 0;
}
{
int rc, i;
/* reset the buffer pools */
/* recreate and initialize the accept socket if it is not being reused */
/* AcceptEx on the completion context. The completion context will be signaled
* when a connection is accepted. Hack Alert: TransmitFile, under certain
* circumstances, can 'recycle' accept sockets, saving the overhead of calling
* socket(). Occasionally this fails (usually when the client closes his end
* of the connection early). When this occurs, AcceptEx will fail with 10022,
* Invalid Parameter. When this occurs, just open a fresh accept socket and
* retry the call.
*/
for (i=0; i<2; i++) {
rc = apr_get_netos_error();
"reset_acceptex_context: socket() failed. Process will exit.");
return rc;
}
/* SO_UPDATE_ACCEPT_CONTEXT is required for shutdown() to work */
"setsockopt(SO_UPDATE_ACCEPT_CONTEXT) failed.");
}
}
(LPOVERLAPPED) context)) {
rc = apr_get_netos_error();
"reset_acceptex_context: AcceptEx failed for "
"listening socket: %d and accept socket: %d. Getting a new accept socket.",
continue;
}
}
break;
}
return APR_SUCCESS;
}
{
int requests_this_child = 0;
int rc;
if (shutdown_in_progress) {
/* Clean-up the AcceptEx completion context */
}
else {
/* Prepare the completion context for reuse */
"Child %d: winnt_get_connection: reset_acceptex_context failed.",
my_pid);
/* Probably should just die now... */
}
}
}
/* May need to atomize the workers_may_exit check with the
* g_blocked_threads++ */
if (workers_may_exit) {
return NULL;
}
while (1) {
if (!rc) {
rc = apr_get_os_error();
/* Is this a deadly condition?
* We sometimes get ERROR_NETNAME_DELETED when a client
* disconnects when attempting to reuse sockets. Not sure why
* we see this now and not during AcceptEx(). Reset the
* AcceptEx context and continue...
*/
"Child %d: - GetQueuedCompletionStatus() failed",
my_pid);
/* Reset the completion context */
if (pol) {
"Child %d: winnt_get_connection: reset_acceptex_context failed.",
my_pid);
/* Probably should just die now... */
}
}
}
else {
/* Sometimes we catch ERROR_OPERATION_ABORTED completion packets
* from the old child process (during a restart). Ignore them.
*/
"Child %d: - Draining ERROR_OPERATION_ABORTED packet off "
"the completion port.", my_pid);
}
continue;
}
if (CompKey != 0) {
/* CompKey == my_pid means this thread was unblocked by
* the shutdown code (not by io completion).
*/
return NULL;
}
/* Sometimes we catch shutdown io completion packets
* posted by the old child process (during a restart). Ignore them.
*/
continue;
}
break;
}
/* Check to see if we need to create more completion contexts,
* but only if we are not in the process of shutting down
*/
if (!shutdown_in_progress) {
}
}
/* Received a connection */
&context->sa_client_len);
return context;
}
/*
* worker_main() - this is the main loop for the worker threads
*
* Windows 95/98
* Each thread runs within this function. They wait within remove_job()
* for a job to become available, then handle all the requests on that
* connection until it is closed, then return to remove_job().
*
* The worker thread will exit when it removes a job which contains
* socket number -1. This provides a graceful thread exit, since
* it will never exit during a connection.
*
* This code in this function is basically equivalent to the child_main()
* from the multi-process (Unix) environment, except that we
*
* - do not call child_init_modules (child init API phase)
* - block in remove_job, and when unblocked we have an already
* accepted socket, instead of blocking on a mutex or select().
*/
static void worker_main(int thread_num)
{
while (1) {
conn_rec *c;
(request_rec *) NULL);
/* Grab a connection off the network */
}
else {
}
if (!context)
break;
if (c) {
if (!disconnected) {
}
}
else {
/* ap_new_connection closes the socket on failure */
}
}
"Child %d: Thread exiting.", my_pid);
#if 0
#endif
/* TODO: Add code to clean-up completion contexts here */
}
{
int i;
(*thread_cnt)--;
}
static void create_listeners()
{
#define NUM_LISTENERS 5
"Unable to create an AcceptEx completion context -- process will exit");
signal_parent(0); /* tell parent to die */
}
}
}
}
/*
* child_main() runs the main control thread for the child process.
*
* The control thread:
* - sets up the worker thread pool
* - starts the accept thread (Win 9x)
* - creates AcceptEx contexts (Win NT)
* - waits for exit_event, maintenance_event or maintenance timeout
* and does the right thing depending on which event is received.
*/
static void child_main()
{
char* exit_event_name;
int nthreads = ap_threads_per_child;
int tid;
int rv;
int i;
int cld;
/* Set up the scoreboard. The scoreboard in this MPM only applies to the
* child process and is not shared across processes
*/
/* This is the child process or we are running in single process
* mode.
*/
if (one_process) {
/* Single process mode */
}
else {
/* Child process mode */
}
/* Initialize the child_events */
child_events[0] = exit_event;
/*
* Wait until we have permission to start accepting connections.
* start_mutex is used to ensure that only one child ever
*/
if (status != APR_SUCCESS) {
"Child %d: Failed to acquire the start_mutex. Process will exit.", my_pid);
signal_parent(0); /* tell parent to die */
exit(0);
}
"Child %d: Acquired the start mutex.", my_pid);
/* Create the worker thread pool */
for (i = 0; i < nthreads; i++) {
(void *) i, 0, &tid);
}
/* Begin accepting connections */
/* Win95/98: Start the accept thread */
(void *) i, 0, &tid);
} else {
/* Windows NT/2000: Create AcceptEx completion contexts */
}
/* Wait for one of three events:
* exit_event:
* The exit_event is signaled by the parent process to notify
* the child that it is time to exit.
*
* maintenance_event:
* This event is signaled by the worker thread pool to direct
* this thread to create more completion contexts.
*
* TIMEOUT:
* To do periodic maintenance on the server (check for thread exits,
* number of completion contexts, etc.)
*/
while (1) {
if (rv == WAIT_FAILED) {
/* Something serious is wrong */
"Child %d: WAIT_FAILED -- shutting down server");
break;
}
else if (rv == WAIT_TIMEOUT) {
/* Hey, this cannot happen */
"Child %d: WAIT_TIMEOUT -- shutting down server", my_pid);
break;
}
else if (cld == 0) {
/* Exit event was signaled */
"Child %d: Exit event signaled. Child process is ending.", my_pid);
break;
}
else {
/* Child maintenance event signaled */
}
"Child %d: Child maintenance event signaled.", my_pid);
}
}
/* Setting is_graceful will close keep-alive connections */
is_graceful = 1;
/* Shutdown the worker threads */
/* workers_may_exit = 1; Not used on Win9x */
shutdown_in_progress = 1;
for (i = 0; i < nthreads; i++) {
add_job(-1);
}
}
else { /* Windows NT/2000 */
/*
* Setting shutdown_in_progress prevents new AcceptEx completion
* contexts from being queued to the port but allows threads to
* continue consuming from the port. This gives the server a
* chance to handle any accepted connections.
*/
shutdown_in_progress = 1;
Sleep(1000);
/* Setting workers_may_exit prevents threads from consumimg from the
* completion port (especially threads that unblock off of keep-alive
* connections later on).
*/
workers_may_exit = 1;
/* Unblock threads blocked on the completion port */
while (g_blocked_threads > 0) {
for (i=g_blocked_threads; i > 0; i--) {
}
Sleep(1000);
}
/* Cancel any remaining pending AcceptEx completion contexts */
}
/* Drain the canceled contexts off the port */
}
/* Release the start_mutex to let the new process (in the restart
* scenario) a chance to begin servicing requests
*/
"Child %d: Releasing the start mutex", my_pid);
/* Give busy worker threads a chance to service their connections.
* Kill them off if they take too long
*/
while (nthreads) {
if (rv != WAIT_TIMEOUT) {
continue;
}
break;
}
for (i = 0; i < nthreads; i++) {
CloseHandle(child_handles[i]);
}
"Child %d: All worker threads have ended.", my_pid);
}
/**********************************************************************
* master_main - this is the parent (main) process. We create a
* child process to do the work, then sit around waiting for either
* the child to exit, or a restart or exit signal. If the child dies,
* we just respawn a new one. If we have a shutdown or graceful restart,
* tell the child to die when it is ready. If it is a non-graceful
* restart, force the child to die immediately.
**********************************************************************/
{
int i;
int handle = 0;
}
(*processes)--;
}
{
int rv;
char buf[1024];
char *pCommand;
char *pEnvVar;
char *pEnvBlock;
int i;
int iEnvBlockLen;
SECURITY_ATTRIBUTES sa = {0};
/* Build the command line. Should look something like this:
* C:/apache/bin/apache.exe -f ap_server_confname
* First, get the path to the executable...
*/
"Parent: Path to Apache process too long");
return -1;
} else if (rv == 0) {
"Parent: GetModuleFileName() returned NULL for current process.");
return -1;
}
/* Build the command line */
}
/* Build the environment, since Win9x disrespects the active env */
/*
* Win32's CreateProcess call requires that the environment
* be passed in an environment block, a null terminated block of
* null terminated strings.
*/
i = 0;
iEnvBlockLen = 1;
while (_environ[i]) {
i++;
}
i = 0;
while (_environ[i]) {
i++;
}
pEnvVar = '\0';
/* Create a pipe to send socket info to the child */
"Parent: Unable to create pipe to child process.");
return -1;
}
/* Give the read end of the pipe (hPipeRead) to the child as stdin. The
* parent will write the socket data to the child on this pipe.
*/
TRUE, /* Inherit handles */
CREATE_SUSPENDED, /* Creation flags */
pEnvBlock, /* Environment block */
NULL,
"Parent: Not able to create the child process.");
/*
* We must close the handles to the new process and its main thread
* to prevent handle and memory leaks.
*/
return -1;
}
/* Create the exit_event, apCchild_pid */
if (!kill_event) {
"Parent: Could not create exit event for child process");
return -1;
}
/* Assume the child process lives. Update the process and event tables */
(*processes)++;
/* We never store the thread's handle, so close it now. */
/* Run the chain of open sockets. For each socket, duplicate it
* for the target process then send the WSAPROTOCOL_INFO
* (returned by dup socket) to the child */
int nsd;
lpWSAProtocolInfo) == SOCKET_ERROR) {
return -1;
}
(LPOVERLAPPED) NULL)) {
return -1;
}
}
/* Now, send the AcceptEx completion port to the child */
"Parent: Unable to duplicate AcceptEx completion port. Shutting down.");
return -1;
}
WriteFile(hPipeWrite, &hDupedCompPort, (DWORD) sizeof(hDupedCompPort), &BytesWritten, (LPOVERLAPPED) NULL);
}
return 0;
}
{
int i;
int child_num = 0;
int restart_pending = 0;
int shutdown_pending = 0;
int current_live_processes = 0; /* number of child process we know about */
setup_listeners(s);
/* Create child process
* Should only be one in this version of Apache for WIN32
*/
while (remaining_children_to_start--) {
¤t_live_processes) < 0) {
"master_main: create child process failed. Exiting.");
shutdown_pending = 1;
goto die_now;
}
}
restart_pending = shutdown_pending = 0;
/* Wait for shutdown or restart events or for child death */
if (rv == WAIT_FAILED) {
/* Something serious is wrong */
"master_main: WaitForMultipeObjects WAIT_FAILED -- doing server shutdown");
shutdown_pending = 1;
}
else if (rv == WAIT_TIMEOUT) {
/* Hey, this cannot happen */
"master_main: WaitForMultipeObjects with INFINITE wait exited with WAIT_TIMEOUT");
shutdown_pending = 1;
}
else if (cld == current_live_processes) {
/* shutdown_event signalled */
shutdown_pending = 1;
printf("shutdown event signaled\n");
"Parent: SHUTDOWN EVENT SIGNALED -- Shutting down the server.");
if (ResetEvent(shutdown_event) == 0) {
"ResetEvent(shutdown_event)");
}
}
/* restart_event signalled */
restart_pending = 1;
"Parent: RESTART EVENT SIGNALED -- Restarting the server.");
if (ResetEvent(restart_event) == 0) {
"master_main: ResetEvent(restart_event) failed.");
}
/* Signal each child process to die
* We are making a big assumption here that the child process, once signaled,
* will REALLY go away. Since this is a restart, we do not want to hold the
* new child process up waiting for the old child to die. Remove the old
* child out of the process_handles apr_table_t and hope for the best...
*/
for (i = 0; i < children_to_kill; i++) {
if (SetEvent(process_kill_events[i]) == 0)
"master_main: SetEvent for child process in slot #%d failed", i);
}
}
else {
/* A child process must have exited because of a fatal error condition (seg fault, etc.).
* Remove the dead process
* from the process_handles and process_kill_events apr_table_t and create a new
* child process.
* TODO: Consider restarting the child immediately without looping through http_main
* and without rereading the configuration. Will need this if we ever support multiple
* children. One option, create a parent thread which waits on child death and restarts it.
* Consider, however, that if the user makes httpd.conf invalid, we want to die before
* our child tries it... otherwise we have a nasty loop.
*/
restart_pending = 1;
"Parent: CHILD PROCESS FAILED -- Restarting the child process.");
/* APD2("main_process: child in slot %d died", rv); */
/* restart_child(process_hancles, process_kill_events, cld, ¤t_live_processes); */
/* Drain the AcceptEx completion port of any outstanding I/O pending for the dead
* process. */
}
if (shutdown_pending)
{
}
/* Signal each child processes to die */
for (i = 0; i < current_live_processes; i++) {
if (SetEvent(process_kill_events[i]) == 0)
"master_main: SetEvent for child process in slot #%d failed", i);
}
if (rv == WAIT_TIMEOUT)
continue;
}
for (i = 0; i < current_live_processes; i++) {
"Parent: Forcing termination of child #%d (handle %d)", i, process_handles[i]);
}
return 0; /* Tell the caller we do not want to restart */
}
return 1; /* Tell the caller we want a restart */
}
#define SERVICE_UNNAMED (-1)
/* service_nt_main_fn needs to append the StartService() args
* outside of our call stack and thread as the service starts...
*/
/* Remember service_to_start failures to log and fail in pre_config.
* Remember inst_argc and inst_argv for installing or starting the
* service after we preflight the config.
*/
{
switch(query_code){
case AP_MPMQ_MAX_DAEMONS:
return APR_SUCCESS;
case AP_MPMQ_IS_THREADED:
*result = 1;
return APR_SUCCESS;
case AP_MPMQ_IS_FORKED:
*result = 0;
return APR_SUCCESS;
}
return APR_ENOTIMPL;
}
static apr_status_t service_to_start_success;
static int inst_argc;
static const char * const *inst_argv;
{
/* Handle the following SCM aspects in this phase:
*
* -k runservice [transition for WinNT, nothing for Win9x]
* -k (!)install [error out if name is not installed]
*
* We can't leave this phase until we know our identity
* and modify the command arguments appropriately.
*/
char *def_server_root;
char optbuf[3];
const char *optarg;
int fixed_args;
char *pid;
int running_as_service = 1;
/* AP_PARENT_PID is only valid in the child */
if (pid)
{
/* This is the child */
/* The parent is responsible for providing the
* COMPLETE ARGUMENTS REQUIRED to the child.
*
* No further argument parsing is needed, but
* for good measure we will provide a simple
* signal string for later testing.
*/
signal_arg = "runchild";
return;
}
/* This is the parent, we have a long way to go :-) */
/* Rewrite process->argv[];
*
* strip out -k signal into signal_arg
* strip out -n servicename into service_name & display_name
* add default -d serverroot from the path of this executable
*
* The end result will look like:
*
* The invocation command (%0)
* The -d serverroot default from the running executable
* The requested service's (-n) registry ConfigArgs
* The WinNT SCM's StartService() args
*/
rv = apr_get_os_error();
"Failed to get the path of Apache.exe");
exit(1);
}
/* WARNING: There is an implict assumption here that the
* executable resides in ServerRoot or ServerRoot\bin
*/
if (def_server_root > fnbuf) {
}
/* Use process->pool so that the rewritten argv
* lasts for the lifetime of the server process,
* because pconf will be destroyed after the
* initial pre-flight of the config parser.
*/
sizeof(const char *));
optbuf[0] = '-';
switch (optbuf[1]) {
case 'n':
break;
case 'k':
signal_arg = optarg;
break;
case 'i':
"-i is deprecated. Use -k install.");
signal_arg = "install";
break;
case 'u':
"-u is deprecated. Use -k uninstall.");
signal_arg = "uninstall";
break;
default:
*(const char **)apr_array_push(mpm_new_argv) =
if (optarg) {
}
break;
}
}
/* Track the number of args actually entered by the user */
/* Provide a default 'run' -k arg to simplify signal_arg tests */
if (!signal_arg)
{
signal_arg = "run";
running_as_service = 0;
}
{
/* Start the NT Service _NOW_ because the WinNT SCM is
* expecting us to rapidly assume control of our own
* process, the SCM will tell us our service name, and
* may have extra StartService() command arguments to
* add for us.
*
* Any other process has a console, so we don't to begin
* a Win9x service until the configuration is parsed and
* any command line errors are reported.
*
* We hold the return value so that we can die in pre_config
* after logging begins, and the failure can land in the log.
*/
if (service_to_start_success == APR_SUCCESS)
}
}
}
{
if (service_named == APR_SUCCESS)
{
"%s: Service is already installed.", display_name);
exit(1);
}
}
else if (running_as_service)
{
if (service_named == APR_SUCCESS)
{
if (rv == APR_SUCCESS) {
"Using ConfigArgs of the installed service "
"\"%s\".", display_name);
}
else {
"No installed ConfigArgs for the service "
"\"%s\", using Apache defaults.", display_name);
}
}
else
{
"No installed service named \"%s\".", display_name);
exit(1);
}
}
/* Track the args actually entered by the user.
* These will be used for the -k install parameters, as well as
* for the -k start service override arguments.
*/
}
{
/* Handle the following SCM aspects in this phase:
*
* -k runservice [WinNT errors logged from rewrite_args]
* -k uninstall
* -k stop
*
* in these cases we -don't- care if httpd.conf has config errors!
*/
if (ap_exists_config_define("ONE_PROCESS"))
one_process = -1;
if (ap_exists_config_define("ONE_PROCESS"))
one_process = -1;
&& (service_to_start_success != APR_SUCCESS)) {
"%s: Unable to start the service manager.",
exit(1);
}
rv = mpm_service_uninstall();
}
mpm_signal_service(ptemp, 0);
exit(0);
}
}
static void winnt_post_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp, server_rec* server)
{
static int restart_num = 0;
apr_status_t rv = 0;
/* Handle the following SCM aspects in this phase:
*
* -k install
* -k start
* -k restart
* -k runservice [Win95, only once - after we parsed the config]
*
* because all of these signals are useful _only_ if there
* is a valid conf\httpd.conf environment to start.
*
* We reached this phase by avoiding errors that would cause
* these options to fail unexpectedly in another process.
*/
}
}
}
if (parent_pid == my_pid)
{
if (restart_num++ == 1)
{
/* This code should be run once in the parent and not run
* across a restart
*/
/* Create the AcceptEx IoCompletionPort once in the parent.
* The completion port persists across restarts.
*/
NULL,
0,
0); /* CONCURRENT ACTIVE THREADS */
if (AcceptExCompPort == NULL) {
"Parent: Unable to create the AcceptExCompletionPort -- process will exit");
exit(1);
}
}
/* Create shutdown event, apPID_shutdown, where PID is the parent
* Apache process ID. Shutdown is signaled by 'apache -k shutdown'.
*/
if (!shutdown_event) {
"Parent: Cannot create shutdown event %s", signal_shutdown_name);
CleanNullACL((void *)sa);
exit(1);
}
/* Create restart event, apPID_restart, where PID is the parent
* Apache process ID. Restart is signaled by 'apache -k restart'.
*/
if (!restart_event) {
"Parent: Cannot create restart event %s", signal_restart_name);
CleanNullACL((void *)sa);
exit(1);
}
CleanNullACL((void *)sa);
/* Now that we are flying at 15000 feet...
* wipe out the Win95 service console,
* signal the SCM the WinNT service started, or
* if not a service, setup console handlers instead.
*/
{
{
rv = mpm_service_to_start();
if (rv != APR_SUCCESS) {
"%s: Unable to start the service manager.",
exit(1);
}
}
}
else /* ! -k runservice */
{
}
/* Create the start mutex, apPID, where PID is the parent Apache process ID.
* Ths start mutex is used during a restart to prevent more than one
* child process from entering the accept loop at once.
*/
}
}
else /* parent_pid != my_pid */
{
}
}
{
static int restart = 0; /* Default is "not a restart" */
server_conf = s;
/* Running as Child process or in one_process (debug) mode */
"Child %d: Child process is running", my_pid);
child_main();
"Child %d: Child process is exiting", my_pid);
return 1;
} /* Child or single process */
else { /* Parent process */
if (!restart) {
/* Shutting down. Clean up... */
server_conf, "removed PID file %s (pid=%ld)",
}
return 1;
}
} /* Parent process */
return 0; /* Restart */
}
static void winnt_hooks(apr_pool_t *p)
{
}
/*
* Command processors
*/
{
return err;
}
return "PidFile directive not allowed in <VirtualHost>";
}
ap_pid_fname = arg;
return NULL;
}
{
return err;
}
if (ap_threads_per_child > HARD_THREAD_LIMIT) {
"WARNING: ThreadsPerChild of %d exceeds compile time"
" limit of %d threads,", ap_threads_per_child,
" lowering ThreadsPerChild to %d. To increase, please"
" see the HARD_THREAD_LIMIT define in %s.",
}
else if (ap_threads_per_child < 1) {
"WARNING: Require ThreadsPerChild > 0, setting to 1");
ap_threads_per_child = 1;
}
return NULL;
}
{
return err;
}
return NULL;
}
{
const char *fname;
return err;
}
" does not exist or is not a directory", NULL);
}
return NULL;
}
/* Stub functions until this MPM supports the connection status API */
const char *value)
{
/* NOP */
}
{
/* NOP */
}
{
/* NOP */
return NULL;
}
static const command_rec winnt_cmds[] = {
"A file for logging the server process ID"},
"Number of threads each child creates" },
"Maximum number of requests a particular child serves before dying." },
"The location of the directory Apache changes to before dumping core" },
{ NULL }
};
winnt_rewrite_args, /* hook to run before apache parses args */
NULL, /* create per-directory config structure */
NULL, /* merge per-directory config structures */
NULL, /* create per-server config structure */
NULL, /* merge per-server config structures */
winnt_cmds, /* command apr_table_t */
winnt_hooks /* register_hooks */
};