mpm_winnt.c revision 417f504d4d11631c0d062be85347f82a26c88677
/* ====================================================================
* 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 <malloc.h>
/* Limit on the threads per process. Clients will be locked out if more than
* this * HARD_SERVER_LIMIT are needed.
*
* We keep this for one reason it keeps the size of the scoreboard file small
* enough that we can read the whole thing without worrying too much about
* the overhead.
*/
#ifndef HARD_THREAD_LIMIT
#define HARD_THREAD_LIMIT 1920
#endif
/* Limit on the total --- clients will be locked out if more servers than
* this are needed. It is intended solely to keep the server from crashing
* when things get out of hand.
*
* We keep a hard maximum number of servers, for two reasons --- first off,
* in case something goes seriously wrong, we want to stop the fork bomb
* short of actually crashing the machine we're running on by filling some
* kernel table. Secondly, it keeps the size of the scoreboard file small
* enough that we can read the whole thing without worrying too much about
* the overhead.
*/
#define HARD_SERVER_LIMIT 1
extern apr_shm_t *ap_scoreboard_shm;
/* Definitions of WINNT MPM specific config globals */
static apr_pool_t *pconf;
static int workers_may_exit = 0;
static int shutdown_in_progress = 0;
static unsigned int g_blocked_threads = 0;
static HANDLE max_requests_per_child_event;
static char ap_coredump_dir[MAX_STRING_LEN];
static int one_process = 0;
static char const* signal_arg = NULL;
static DWORD parent_pid;
int ap_threads_per_child = 0;
/* ap_my_generation are used by the scoreboard code */
ap_generation_t volatile ap_my_generation=0;
/* Queue for managing the passing of COMP_CONTEXTs between
* the accept and worker threads.
*/
static apr_lock_t *qlock;
static int num_completion_contexts = 0;
{
/* Recycle the completion context.
* - destroy the ptrans pool
* - put the context on the queue to be consumed by the accept thread
* Note:
* pCompContext->accept_socket may be in a disconnected but reusable
* state so -don't- close it.
*/
if (pCompContext) {
if (qtail)
else
}
}
{
/* Grab a context off the queue */
if (qhead) {
if (!qhead)
}
/* If we failed to grab a context off the queue, alloc one out of
* the child pool. There may be up to ap_threads_per_child contexts
* in the system at once.
*/
if (!pCompContext) {
if (num_completion_contexts >= ap_threads_per_child) {
static int reported = 0;
if (!reported) {
"Server ran out of threads to serve requests. Consider "
"raising the ThreadsPerChild setting");
reported = 1;
}
return NULL;
}
/* Hopefully this is a temporary condition ... */
"mpm_get_completion_context: CreateEvent failed.");
return NULL;
}
}
return pCompContext;
}
{
if (pCompContext)
else
pOverlapped = NULL;
return APR_SUCCESS;
}
/* 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
}
/* 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.
*/
/*
* 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);
}
static int volatile is_graceful = 0;
AP_DECLARE(int) ap_graceful_stop_signalled(void)
{
return is_graceful;
}
{
HANDLE e;
char *signal_name;
if (one_process) {
return;
}
switch(type) {
case SIGNAL_PARENT_SHUTDOWN:
{
break;
}
/* This MPM supports only graceful restarts right now */
case SIGNAL_PARENT_RESTART:
{
is_graceful = 1;
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);
}
/*
* find_ready_listener()
* Only used by Win9* and should go away when the win9*_accept() function is
* reimplemented using apr_poll().
*/
static ap_listen_rec *head_listener;
{
if (head_listener == NULL)
return (lr);
}
}
return NULL;
}
/*
* get_listeners_from_parent()
* The listen sockets are opened in the parent. This function, which runs
* exclusively in the child process, receives them from the parent and
* makes them availeble in the child.
*/
static int get_listeners_from_parent(server_rec *s)
{
int num_listeners = 0;
/* 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");
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);
exit(1);
}
}
return num_listeners;
}
/* 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_accept()
* 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.
* win9x_get_connection()
* Calls remove_job() to pull a job from the accept queue. All the worker
* threads block on remove_job.
*/
typedef struct joblist_s {
int sock;
} joblist;
typedef struct globals_s {
int jobcount;
} globals;
#define MAX_SELECT_ERRORS 100
{
"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 win9x_accept(void * dummy)
{
int wait_time = 1;
int csd;
struct sockaddr_in sa_client;
int count_select_errors = 0;
int rc;
int clen;
/* Setup the listeners
* ToDo: Use apr_poll()
*/
listenmaxfd = nsd;
}
}
}
while (!shutdown_in_progress) {
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 */
}
while (1) {
return NULL;
}
"getsockname failed");
continue;
}
"getpeername failed");
}
/* do we NEED_DUPPED_CSD ?? */
return context;
}
}
/* Windows NT/2000 specific code...
* model. An accept thread accepts connections off the network then issues
* PostQueuedCompletionStatus() to awake a thread blocked on the ThreadDispatch
* IOCompletionPort.
*
* winnt_accept()
* One or more accept threads run in this function, each of which accepts
* connections off the network and calls PostQueuedCompletionStatus() to
* queue an io completion packet to the ThreadDispatch IOCompletionPort.
* winnt_get_connection()
* Worker threads block on the ThreadDispatch IOCompletionPort awaiting
* connections to service.
*/
static void winnt_accept(void *listen_socket)
{
int lasterror;
while (!shutdown_in_progress) {
if (!pCompContext) {
/* Hopefully whatever is preventing us from getting a
* completion context is a temporary resource constraint.
*/
Sleep(750);
continue;
}
/* Create and initialize the accept socket */
/* Hopefully another temporary condition. Be graceful. */
"winnt_accept: Failed to allocate an accept socket. "
"Temporary resource constraint? Try again.");
Sleep(500);
goto again;
}
}
/* AcceptEx on the completion context. The completion context will be
* signaled when a connection is accepted.
*/
0,
&pCompContext->Overlapped)) {
/* Hack alert. Occasionally, TransmitFile will not recycle the
* accept socket (usually when the client disconnects early).
* Get a new socket and try the call again.
*/
"winnt_accept: AcceptEx failed due to early client "
"disconnect. Reallocate the accept socket and try again.");
if (shutdown_in_progress)
break;
else
goto again;
}
"winnt_accept: AcceptEx failed. Attempting to recover.");
Sleep(500);
goto again;
}
/* Wait for pending i/o */
}
/* Inherit the listen socket settings. Required for
* shutdown() to work
*/
SO_UPDATE_ACCEPT_CONTEXT, (char *)&nlsd,
sizeof(nlsd))) {
"setsockopt(SO_UPDATE_ACCEPT_CONTEXT) failed.");
/* Not a failure condition. Keep running. */
}
/* Get the local & remote address */
0,
/* When a connection is received, send an io completion notification to
* the ThreadDispatchIOCP. This function could be replaced by
* mpm_post_completion_context(), but why do an extra function call...
*/
}
if (!shutdown_in_progress) {
/* Yow, hit an irrecoverable error! Tell the child to die. */
}
}
{
int rc;
while (1) {
if (workers_may_exit) {
return NULL;
}
if (!rc) {
rc = apr_get_os_error();
continue;
}
switch (CompKey) {
case IOCP_CONNECTION_ACCEPTED:
break;
case IOCP_SHUTDOWN:
return NULL;
default:
return NULL;
}
break;
}
}
return pCompContext;
}
/*
* worker_main()
* Main entry point for the worker threads. Worker threads block in
* win*_get_connection() awaiting a connection to service.
*/
static void worker_main(int thread_num)
{
static int requests_this_child = 0;
while (1) {
conn_rec *c;
(request_rec *) NULL);
/* Grab a connection off the network */
}
else {
}
if (!context) {
/* Time for the thread to exit */
break;
}
/* Have we hit MaxRequestPerChild connections? */
if (ap_max_requests_per_child) {
}
}
/* ### is this correct? Shouldn't be inheritable (at this point) */
thread_num, sbh);
if (c) {
if (!disconnected) {
}
}
else {
/* ap_new_connection closes the socket on failure */
}
}
(request_rec *) NULL);
"Child %d: Thread exiting.", my_pid);
}
{
int i;
(*thread_cnt)--;
}
/*
* child_main()
* Entry point for the main control thread for the child process.
* This thread creates the accept thread, worker threads and
* monitors the child process for maintenance and shutdown
* events.
*/
static void child_main()
{
char* exit_event_name;
int nthreads = ap_threads_per_child;
int tid;
int rv;
int i;
int cld;
/* 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);
exit(0);
}
"Child %d: Acquired the start mutex.", my_pid);
/*
* Create the worker thread dispatch IOCompletionPort
* on Windows NT/2000
*/
/* Create the worker thread dispatch IOCP */
NULL,
0,
0); /* CONCURRENT ACTIVE THREADS */
}
/*
* Create the pool of worker threads
*/
for (i = 0; i < nthreads; i++) {
(request_rec *) NULL);
(void *) i, 0, &tid);
}
/*
* Start the accept thread
*/
(void *) i, 0, &tid);
} else {
/* Start an accept thread per listener */
}
}
}
/* 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.
*
* max_requests_per_child_event:
* This event is signaled by the worker threads to indicate that
* the process has handled MaxRequestsPerChild connections.
*
* 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) {
}
else if (cld == 0) {
/* Exit event was signaled */
"Child %d: Exit event signaled. Child process is ending.", my_pid);
break;
}
else {
/* MaxRequestsPerChild event set by the worker threads.
* Signal the parent to restart
*/
"Child %d: Process exiting because it reached "
"MaxRequestsPerChild. Signaling the parent to "
"restart a new child process.", my_pid);
break;
}
}
/* Setting is_graceful will cause keep-alive connections to be closed
* rather than block on the next network read.
*/
is_graceful = 1;
/* Setting shutdown_in_progress prevents new connections from
* being accepted but allows the worker threads to continue
* handling connections that have already been accepted.
*/
shutdown_in_progress = 1;
/* Close the listening sockets. */
}
Sleep(1000);
/* Release the start_mutex to let the new process (in the restart
* scenario) a chance to begin accepting and servicing requests
*/
"Child %d: Releasing the start mutex", my_pid);
/* Tell the worker threads they may exit when done handling
* a connection.
*/
workers_may_exit = 1;
/* Shutdown the worker threads */
for (i = 0; i < nthreads; i++) {
add_job(-1);
}
}
else { /* Windows NT/2000 */
/* Post worker threads blocked on the ThreadDispatch IOCompletion port */
while (g_blocked_threads > 0) {
for (i=g_blocked_threads; i > 0; i--) {
}
Sleep(1000);
}
/* Empty the accept queue of completion contexts */
while (qhead) {
}
}
/* Give busy worker threads a chance to service their connections */
while (nthreads) {
if (rv != WAIT_TIMEOUT) {
continue;
}
break;
}
/* Kill remaining threads off the hard way */
for (i = 0; i < nthreads; i++) {
CloseHandle(child_handles[i]);
}
"Child %d: All worker threads have ended.", my_pid);
}
{
int rv;
char buf[1024];
char *pCommand;
char *pEnvVar;
char *pEnvBlock;
int i;
int iEnvBlockLen;
/* 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
* 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;
}
/* Make our end of the handle non-inherited */
}
else {
"Parent: Unable to duplicate pipe to child.\n");
}
/* Open a null handle to soak info from the child */
if (hNullOutput == INVALID_HANDLE_VALUE) {
"Parent: Unable to create null output pipe for child process.\n");
}
/* Child's initial stderr -> our main server error log (or, failing that, stderr) */
if (ap_server_conf->error_log) {
0, TRUE, DUPLICATE_SAME_ACCESS)) {
}
else {
rv = apr_get_os_error();
}
}
if (rv != APR_SUCCESS) {
"Parent: Unable to share error log with child.\n");
}
else if (hShareError == INVALID_HANDLE_VALUE) {
"Parent: Failed to share error log with child.\n");
}
else {
}
}
/* 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 child_exit_event, apCchild_pid. */
if (!(*child_exit_event)) {
"Parent: Could not create exit event for child process");
return -1;
}
/* Important:
* Give the child process a chance to run before dup'ing the sockets.
* We have already set the listening sockets noninheritable, but if
* WSADuplicateSocket runs before the child process initializes
* the listeners will be inherited anyway.
*/
Sleep(1000);
"Parent: Unable to retrieve the scoreboard handle");
return -1;
}
0, FALSE, DUPLICATE_SAME_ACCESS)) {
"Parent: Unable to duplicate the scoreboard handle to the child");
return -1;
}
|| (BytesWritten != sizeof(dup_os_shm))) {
"Parent: Unable to send the scoreboard handle to the child");
return -1;
}
/* 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;
"Parent: Duplicating socket %d and sending it to child process %d",
lpWSAProtocolInfo) == SOCKET_ERROR) {
return -1;
}
(LPOVERLAPPED) NULL)) {
return -1;
}
}
return 0;
}
/***********************************************************************
* master_main()
* master_main() runs in the parent process. It creates the child
* process which handles HTTP requests then waits on one of three
* events:
*
* restart_event
* -------------
* The restart event causes master_main to start a new child process and
* tells the old child process to exit (by setting the child_exit_event).
* The restart event is set as a result of one of the following:
* 1. An apache -k restart command on the command line
* 2. A command received from Windows service manager which gets
* translated into an ap_signal_parent(SIGNAL_PARENT_RESTART)
* call by code in service.c.
* 3. The child process calling ap_signal_parent(SIGNAL_PARENT_RESTART)
* as a result of hitting MaxRequestsPerChild.
*
* shutdown_event
* --------------
* The shutdown event causes master_main to tell the child process to
* exit and that the server is shutting down. The shutdown event is
* set as a result of one of the following:
* 1. An apache -k shutdown command on the command line
* 2. A command received from Windows service manager which gets
* translated into an ap_signal_parent(SIGNAL_PARENT_SHUTDOWN)
* call by code in service.c.
*
* child process handle
* --------------------
* The child process handle will be signaled if the child process
* exits for any reason. In a normal running server, the signaling
* of this event means that the child process has exited prematurely
* due to a seg fault or other irrecoverable error. For server
* robustness, master_main will restart the child process under this
* condtion.
*
* master_main uses the child_exit_event to signal the child process
* to exit.
**********************************************************************/
#define NUM_WAIT_HANDLES 3
#define CHILD_HANDLE 0
#define SHUTDOWN_HANDLE 1
#define RESTART_HANDLE 2
{
int restart_pending = 0;
int shutdown_pending = 0;
/* Create a single child process */
if (rv < 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 == SHUTDOWN_HANDLE) {
/* shutdown_event signalled */
shutdown_pending = 1;
"Parent: SHUTDOWN EVENT SIGNALED -- Shutting down the server.");
if (ResetEvent(shutdown_event) == 0) {
"ResetEvent(shutdown_event)");
}
}
else if (cld == RESTART_HANDLE) {
/* Received a restart event. Prepare the restart_event to be reused
* then signal the child process to exit.
*/
restart_pending = 1;
"Parent: RESTART EVENT SIGNALED -- Restarting the server.");
if (ResetEvent(restart_event) == 0) {
"Parent: ResetEvent(restart_event) failed.");
}
if (SetEvent(child_exit_event) == 0) {
"Parent: SetEvent for child process %d failed.",
}
/* Don't wait to verify that the child process really exits,
* just move on with the restart.
*/
}
else {
/* The child process exited prematurely due to a fatal error. */
restart_pending = 1;
"Parent: CHILD PROCESS FAILED -- Restarting the child process.");
}
if (shutdown_pending)
{
/* This shutdown is only marginally graceful. We will give the
* child a bit of time to exit gracefully. If the time expires,
* the child will be wacked.
*/
}
/* Signal the child processes to exit */
if (SetEvent(child_exit_event) == 0) {
}
if (rv == WAIT_OBJECT_0) {
}
else {
}
return 0; /* Tell the caller we do not want to restart */
}
return 1; /* Tell the caller we want a restart */
}
/* set_listeners_noninheritable()
* Make the listening socket handles noninheritable by processes
* started out of this process.
*/
static int set_listeners_noninheritable(apr_pool_t *p)
{
FALSE, /* Inherit flag */
"set_listeners_noninheritable: DuplicateHandle failed.");
return 0;
}
}
return 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_DAEMON_USED:
return APR_SUCCESS;
case AP_MPMQ_IS_THREADED:
*result = AP_MPMQ_STATIC;
return APR_SUCCESS;
case AP_MPMQ_IS_FORKED:
return APR_SUCCESS;
return APR_SUCCESS;
return APR_SUCCESS;
case AP_MPMQ_MAX_THREADS:
return APR_SUCCESS;
*result = 0;
return APR_SUCCESS;
*result = 0;
return APR_SUCCESS;
*result = 0;
return APR_SUCCESS;
*result = 0;
return APR_SUCCESS;
return APR_SUCCESS;
case AP_MPMQ_MAX_DAEMONS:
*result = 0;
return APR_SUCCESS;
}
return APR_ENOTIMPL;
}
#define SERVICE_UNSET (-1)
static apr_status_t service_to_start_success;
static int inst_argc;
static const char * const *inst_argv;
static char *service_name = NULL;
{
/* 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 and set the names
* 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':
optarg);
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;
}
}
/* back up to capture the bad argument */
}
*(const char **)apr_array_push(mpm_new_argv) =
}
/* 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)
}
}
/* Get the default for any -k option, except run */
}
{
if (service_set == APR_SUCCESS)
{
"%s: Service is already installed.", service_name);
exit(1);
}
}
else if (running_as_service)
{
if (service_set == APR_SUCCESS)
{
if (rv == APR_SUCCESS) {
"Using ConfigArgs of the installed service "
"\"%s\".", service_name);
}
else {
"No installed ConfigArgs for the service "
"\"%s\", using Apache defaults.", service_name);
}
}
else
{
"No installed service named \"%s\".", service_name);
exit(1);
}
}
{
"No installed service named \"%s\".", service_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") ||
ap_exists_config_define("DEBUG"))
one_process = -1;
&& (service_to_start_success != APR_SUCCESS)) {
"%s: Unable to start the service manager.",
/* XXX: return HTTP_INTERNAL_SERVER_ERROR? */
exit(1);
}
rv = mpm_service_uninstall();
}
mpm_signal_service(ptemp, 0);
exit(0);
}
return OK;
}
static int 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 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);
return HTTP_INTERNAL_SERVER_ERROR;
}
/* 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);
return HTTP_INTERNAL_SERVER_ERROR;
}
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.
*/
{
{
if (rv != APR_SUCCESS) {
"%s: Unable to start the service manager.",
return HTTP_INTERNAL_SERVER_ERROR;
}
}
}
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 */
{
}
return OK;
}
{
static int restart = 0; /* Default is "not a restart" */
ap_server_conf = s;
/* Child process or in one_process (debug) mode */
"Child %d: Child process is running", my_pid);
if (one_process) {
/* Set up the scoreboard. */
return 1;
}
return 1;
}
}
else {
/* Set up the scoreboard. */
"child: Unable to access scoreboard handle from parent");
exit(1);
}
!= APR_SUCCESS) {
"child: Unable to access scoreboard handle from parent");
exit(1);
}
exit(1);
}
}
if (!set_listeners_noninheritable(pconf)) {
return 1;
}
child_main();
"Child %d: Child process is exiting", my_pid);
return 1;
}
else /* Child */ {
/* Set up the scoreboard. */
return 1;
}
/* Parent process */
"no listening sockets available, shutting down");
return 1;
}
if (!set_listeners_noninheritable(pconf)) {
return 1;
}
if (!restart) {
/* Shutting down. Clean up... */
ap_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;
}
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;
}
/* Stub functions until this MPM supports the connection status API */
const char *value)
{
/* NOP */
}
{
/* NOP */
}
{
/* NOP */
return NULL;
}
static const command_rec winnt_cmds[] = {
"Number of threads each child creates" },
{ 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 */
};