service.c revision 9cd0aec6974ae53e89e98d2d157e3f705df7c997
/* ====================================================================
* 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.
*/
/* This module ALONE requires the window message API from user.h
* and the default APR include of windows.h will omit it, so
* preload the API symbols now...
*/
#define CORE_PRIVATE
#define _WINUSER_
#include "httpd.h"
#include "http_log.h"
#include "mpm_winnt.h"
#include "apr_strings.h"
#include "apr_lib.h"
#ifdef NOUSER
#endif
#include <winuser.h>
static char *mpm_service_name = NULL;
static char *mpm_display_name = NULL;
static struct
{
} globdat;
/* The service configuration's is stored under the following trees:
*
* HKLM\System\CurrentControlSet\Services\[service name]
*
* \DisplayName
* \ImagePath (NT Only)
* \Parameters\ConfigArgs
*
* For Win9x, the launch service command is stored under:
*
* HKLM\Software\Microsoft\Windows\CurrentVersion\RunServices\[service name]
*/
/* exit() for Win32 is macro mapped (horrible, we agree) that allows us
* to catch the non-zero conditions and inform the console process that
* the application died, and hang on to the console a bit longer.
*
* The macro only maps for http_main.c and other sources that include
* the service.h header, so we best assume it's an error to exit from
* _any_ other module.
*
* If real_exit_code is reset to 0, it will not be set or trigger this
* behavior on exit. All service and child processes are expected to
* reset this flag to zero to avoid undesireable side effects.
*/
int real_exit_code = 1;
void hold_console_open_on_error(void)
{
char *msg = "Note the errors or messages above, "
"and press the <ESC> key to exit. ";
char count[16];
if (!real_exit_code)
return;
return;
return;
return;
return;
do
{
{
return;
return;
return;
}
return;
|| !result)
return;
}
}
{
/* This is the WndProc procedure for our invisible window.
* When the user shuts down the system, this window is sent
* a signal WM_ENDSESSION. We clean up by signaling Apache
* to shut down, and idle until Apache's primary thread quits.
*/
if ((msg == WM_ENDSESSION)
{
signal_parent(0);
if (wParam)
/* Don't leave this message until we are dead! */
return 0;
}
}
{
/* When running as a service under Windows 9x, there is no console
* window present, and no ConsoleCtrlHandler to call when the system
* is shutdown. If the WatchWindow thread is created with a NULL
* service_name argument, then the ...SystemMonitor window class is
* used to create the "Apache" window to watch for logoff and shutdown.
* If the service_name is provided, the ...ServiceMonitor window class
* is used to create the window named by the service_name argument,
* and the logoff message is ignored.
*/
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
if (service_name)
else
if (!RegisterClass(&wc))
{
NULL, "Could not register window class for WatchWindow");
globdat.service_thread_id = 0;
return 0;
}
/* Create an invisible window */
if (!hwndMain)
{
NULL, "Could not create WatchWindow");
globdat.service_thread_id = 0;
return 0;
}
/* If we succeed, eliminate the console window.
* Signal the parent we are all set up, and
* watch the message queue while the window lives.
*/
FreeConsole();
{
else {
}
}
globdat.service_thread_id = 0;
return 0;
}
{
switch (ctrl_type)
{
case CTRL_BREAK_EVENT:
signal_parent(1);
return TRUE;
case CTRL_C_EVENT:
/* for Interrupt signals, shut down the server.
* Tell the system we have dealt with the signal
* without waiting for Apache to terminate.
*/
signal_parent(0);
return TRUE;
case CTRL_CLOSE_EVENT:
case CTRL_LOGOFF_EVENT:
case CTRL_SHUTDOWN_EVENT:
/* for Terminate signals, shut down the server.
* Wait for Apache to terminate, but respond
* after a reasonable time to tell the system
* that we did attempt to shut ourself down.
* THESE EVENTS WILL NOT OCCUR UNDER WIN9x!
*/
signal_parent(0);
Sleep(30000);
return TRUE;
}
/* We should never get here, but this is (mostly) harmless */
return FALSE;
}
static void stop_console_handler(void)
{
}
void mpm_start_console_handler(void)
{
}
/* Special situation - children of services need to mind their
* P's & Q's and wait quietly, ignoring the mean OS signaling
* shutdown and other horrors, to kill them gracefully...
*/
{
switch (ctrl_type)
{
case CTRL_C_EVENT:
case CTRL_BREAK_EVENT:
/* for Interrupt signals, ignore them.
* The system will also signal the parent process,
* which will terminate Apache.
*/
return TRUE;
case CTRL_CLOSE_EVENT:
case CTRL_LOGOFF_EVENT:
case CTRL_SHUTDOWN_EVENT:
/* for Shutdown signals, ignore them, but... .
* The system will also signal the parent process,
* which will terminate Apache, so we need to wait.
*/
Sleep(30000);
return TRUE;
}
/* We should never get here, but this is (mostly) harmless */
return FALSE;
}
static void stop_child_console_handler(void)
{
}
void mpm_start_child_console_handler(void)
{
FreeConsole();
}
else
{
}
}
/**********************************
WinNT service control management
**********************************/
{
static int checkPoint = 1;
int rv = APR_SUCCESS;
if (globdat.hServiceStatus)
{
if (currentState == SERVICE_RUNNING)
else
if ( ( currentState == SERVICE_RUNNING ) ||
( currentState == SERVICE_STOPPED ) )
{
}
else
{
if(waitHint)
}
}
return(rv);
}
/* handle the SCM's ControlService() callbacks to our service */
{
if (dwCtrlCode == SERVICE_CONTROL_STOP)
{
return;
}
if (dwCtrlCode == SERVICE_APACHE_RESTART)
{
ap_start_restart(1);
return;
}
}
{
char errbuf[256];
const char *errarg[9];
errarg[0] = "The Apache service named";
/* What are we going to do in here, bail on the user? not. */
"\\EventLog\\Application\\Apache Service", &hk))
{
/* The stock message file */
char *netmsgkey = "%SystemRoot%\\System32\\netmsg.dll";
}
{
{
++errlen;
++errmsg;
{
--errlen;
/* Generic message: '%1 %2 %3 %4 %5 %6 %7 %8 %9'
* The event code in netmsg.dll is 3299
*/
errlen = 0;
}
}
}
return 0;
}
/* service_nt_main_fn is outside of the call stack and outside of the
* primary server thread... so now we _really_ need a placeholder!
* The winnt_rewrite_args has created and shared mpm_new_argv with us.
*/
extern apr_array_header_t *mpm_new_argv;
{
SECURITY_ATTRIBUTES sa = {0};
const char *ignored;
/* args and service names live in the same pool */
{
NULL, "Failure registering service handler");
return;
}
NO_ERROR, // exit code
3000); // wait hint, 3 seconds more
/* Create a pipe to send stderr messages to the system error log */
{
{
if (thread)
{
int fh;
}
else
{
hPipeWrite = NULL;
}
}
else
{
hPipeWrite = NULL;
}
}
/* We need to append all the command arguments passed via StartService()
* to our running service... which just got here via the SCM...
* but we hvae no interest in argv[0] for the mpm_new_argv list.
*/
if (argc > 1)
{
char **cmb_data;
mpm_new_argv->nalloc * sizeof(const char *));
/* mpm_new_argv remains first (of lower significance) */
/* Service args follow from StartService() invocation */
/* The replacement arg list is complete */
}
/* Let the main thread continue now... but hang on to the
* signal_monitor event so we can take further action
*/
/* The process is ready to terminate, or already has */
}
{
{
{ "", service_nt_main_fn },
};
{
/* This is a genuine failure of the SCM. */
rv = apr_get_os_error();
"Error starting service control dispatcher");
}
globdat.service_thread_id = 0;
return (rv);
}
const char *set_name)
{
char *key_name;
/* ### Needs improvement, on Win2K the user can _easily_
* change the display name to a string that doesn't reflect
* the internal service name + whitespace!
*/
if (rv != APR_SUCCESS) {
/* Take the given literal name if there is no service entry */
}
return rv;
}
int fixed_args)
{
char **cmb_data;
if (rv != APR_SUCCESS) {
if (rv == ERROR_FILE_NOT_FOUND) {
"No ConfigArgs registered for %s, perhaps "
"this service is not installed?",
return APR_SUCCESS;
}
else
return (rv);
}
return (APR_SUCCESS);
}
/* Now we have the mpm_service_name arg, and the mpm_runservice_nt()
* call appended the arguments passed by StartService(), so it's
* time to _prepend_ the default arguments for the server from
* the service's default arguments (all others override them)...
*/
/* First three args (argv[0], -f, path) remain first */
/* Service args follow from service registry array */
/* Remaining new args follow */
return APR_SUCCESS;
}
void service_stopped(void)
{
/* Still have a thread & window to clean up, so signal now */
if (globdat.service_thread_id)
{
{
NO_ERROR, // exit code
0); // wait hint
/* Cause the service_nt_main_fn to complete */
}
else /* osver.dwPlatformId != VER_PLATFORM_WIN32_NT */
{
RegisterServiceProcess(0, 0);
}
}
}
{
{
if (globdat.signal_monitor)
NULL, 0,
}
else /* osver.dwPlatformId != VER_PLATFORM_WIN32_NT */
{
if (!RegisterServiceProcess(0, 1))
return GetLastError();
if (globdat.signal_monitor)
(LPVOID) mpm_service_name, 0,
}
{
/* SetEvent(globdat.signal_monitor) to clean up the SCM thread */
return APR_ENOTHREAD;
}
}
if (globdat.service_thread_id)
else if (globdat.service_thread)
return APR_SUCCESS;
}
{
{
NO_ERROR, // exit code
0); // wait hint
}
return APR_SUCCESS;
}
void mpm_service_stopping(void)
{
NO_ERROR, // exit code
3000); // wait hint
}
const char * const * argv)
{
char *launch_cmd;
{
"GetModuleFileName failed");
return rv;
}
{
// TODO: Determine the minimum permissions required for security
if (!schSCManager) {
rv = apr_get_os_error();
"Failed to open the WinNT service manager");
return (rv);
}
/* RPCSS is the Remote Procedure Call (RPC) Locator required for DCOM
* communication pipes. I am far from convinced we should add this to
* the default service dependencies, but be warned that future apache
* modules or ISAPI dll's may depend on it.
*/
mpm_service_name, // name of service
mpm_display_name, // name to display
SERVICE_ALL_ACCESS, // access required
SERVICE_WIN32_OWN_PROCESS, // service type
SERVICE_AUTO_START, // start type
SERVICE_ERROR_NORMAL, // error control type
launch_cmd, // service's binary
NULL, // no load svc group
NULL, // no tag identifier
"Tcpip\0Afd\0", // dependencies
NULL, // use SYSTEM account
NULL); // no password
if (!schService)
{
rv = apr_get_os_error();
"Failed to create WinNT Service Profile");
return (rv);
}
}
else /* osver.dwPlatformId != VER_PLATFORM_WIN32_NT */
{
/* Store the launch command in the registry */
if (rv != APR_SUCCESS) {
"%s: Failed to add the RunServices registry entry.",
return (rv);
}
if (rv != APR_SUCCESS) {
"%s: Failed to store DisplayName in the registry.",
return (rv);
}
}
/* For both WinNT & Win9x store the service ConfigArgs in the registry...
*/
if (rv != APR_SUCCESS) {
"%s: Failed to store the ConfigArgs in the registry.",
return (rv);
}
}
{
{
// TODO: Determine the minimum permissions required for security
if (!schSCManager) {
rv = apr_get_os_error();
"Failed to open the WinNT service manager.");
return (rv);
}
if (!schService) {
rv = apr_get_os_error();
"%s: OpenService failed", mpm_display_name);
return (rv);
}
/* assure the service is stopped before continuing
*
* This may be out of order... we might not be able to be
* granted all access if the service is running anyway.
*
* And do we want to make it *this easy* for them
* to uninstall their service unintentionally?
*/
// ap_stop_service(schService);
if (DeleteService(schService) == 0) {
rv = apr_get_os_error();
"%s: Failed to delete the service.", mpm_display_name);
return (rv);
}
}
else /* osver.dwPlatformId != VER_PLATFORM_WIN32_NT */
{
/* TODO: assure the service is stopped before continuing */
rv = apr_get_os_error();
"%s: Failed to remove the RunServices registry "
"entry.", mpm_display_name);
return (rv);
}
/* we blast Services/us, not just the Services/us/Parameters branch */
{
rv = apr_get_os_error();
"%s: Failed to remove the service config from the "
"registry.", mpm_display_name);
return (rv);
}
}
return APR_SUCCESS;
}
/* signal_service_transition is a simple thunk to signal the service
* and monitor it's successful transition. If the signal passed is 0,
* then the caller is assumed to already have performed some service
* operation to be monitored (such as StartService), and no actual
* ControlService signal is sent.
*/
static int signal_service_transition(SC_HANDLE schService, DWORD signal, DWORD pending, DWORD complete)
{
return FALSE;
do {
Sleep(1000);
return FALSE;
}
const char * const * argv)
{
{
char **start_argv;
// TODO: Determine the minimum permissions required for security
if (!schSCManager) {
rv = apr_get_os_error();
"Failed to open the WinNT service manager");
return (rv);
}
if (!schService) {
rv = apr_get_os_error();
"%s: Failed to open the service.", mpm_display_name);
return (rv);
}
"Service %s is already started!", mpm_display_name);
return 0;
}
argc += 1;
start_argv[0] = mpm_service_name;
if (argc > 1)
rv = APR_SUCCESS;
if (rv != APR_SUCCESS)
rv = apr_get_os_error();
}
else /* osver.dwPlatformId != VER_PLATFORM_WIN32_NT */
{
char *pCommand;
int i;
/* Locate the active top level window named service_name
* provided the class is ApacheWin95ServiceMonitor
*/
"Service %s is already started!", mpm_display_name);
return 0;
}
/* This may not appear intuitive, but Win9x will not allow a process
* to detach from the console without releasing the entire console.
* Ergo, we must spawn a new process for the service to get back our
* console window.
* The config is pre-flighted, so there should be no danger of failure.
*/
{
"GetModuleFileName failed");
return rv;
}
for (i = 0; i < argc; ++i) {
}
DETACHED_PROCESS, /* Creation flags */
{
rv = APR_SUCCESS;
break;
}
Sleep (1000);
}
}
if (rv != APR_SUCCESS)
rv = apr_get_os_error();
}
if (rv == APR_SUCCESS)
else
"%s: Failed to start the service process.",
return rv;
}
/* signal is zero to stop, non-zero for restart */
{
{
if (!schSCManager) {
"Failed to open the NT Service Manager");
return;
}
if (schService == NULL) {
/* Could not open the service */
"Failed to open the %s Service", mpm_display_name);
return;
}
"Query of Service %s failed", mpm_display_name);
return;
}
return;
}
if (!signal)
return;
}
else
}
else /* !isWindowsNT() */
{
char prefix[20];
/* Locate the active top level window named service_name
* provided the class is ApacheWin95ServiceMonitor
*/
else
{
if (!signal) {
return;
}
}
if (!signal)
{
int ticks = 60;
while (--ticks)
{
break;
}
Sleep(1000);
}
}
else /* !stop */
{
/* TODO: Aught to add a little test to the restart logic, and
* store the restart counter in the window's user dword.
* Then we can hang on and report a successful restart. But
* that's a project for another day.
*/
return;
}
else {
ap_start_restart(1);
}
}
}
if (success)
else
printf("Failed to %s the %s service.\n",
}