service.c revision 179a355e3801a2c2e0a895964cf39488bac3c9cc
/* Copyright 1999-2005 The Apache Software Foundation or its licensors, as
* applicable.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* 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"
#include "ap_regkey.h"
#ifdef NOUSER
#endif
#include <winuser.h>
static char *mpm_service_name = NULL;
static char *mpm_display_name = NULL;
static struct
{
} globdat;
/*
* Get the server root from the registry into 'dir' which is
* size bytes long. Returns 0 if the server root was found
* or if the serverroot key does not exist (in which case
* dir will contain an empty string), or -1 if there was
* an error getting the key.
*/
{
APR_READ, p)) == APR_SUCCESS) {
if (rv == APR_SUCCESS)
return rv;
}
APR_READ, p)) == APR_SUCCESS) {
if (rv == APR_SUCCESS)
return rv;
}
return rv;
}
/* The service configuration's is stored under the following trees:
*
* HKLM\System\CurrentControlSet\Services\[service name]
*
* \DisplayName
* \ImagePath
* \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 ap_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.
*/
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 (!ap_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)
{
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:
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.
*/
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!
*/
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_STOPPED) {
!= SERVICE_STOP_PENDING) {
/* An unexpected exit? Better to error! */
exitCode = 1;
}
if (exitCode) {
}
}
else {
if(waitHint)
}
}
return(rv);
}
/* Set the service description regardless of platform.
* We revert to set_service_description on NT/9x, the
* very long way so any Apache management program can grab the
* description. This would be bad on Win2000, since it wouldn't
* notify the service control manager of the name change.
*/
/* borrowed from mpm_winnt.c */
extern apr_pool_t *pconf;
/* Windows 2000 alone supports ChangeServiceConfig2 in order to
* register our server_version string... so we need some fixups
* to avoid binding to that function if we are on WinNT/9x.
*/
static void set_service_description(void)
{
const char *full_description;
/* Nothing to do if we are a console
*/
if (!mpm_service_name)
return;
/* Time to fix up the description, upon each successful restart
*/
&& (ChangeServiceConfig2)
{
if (schService) {
/* Cast is necessary, ChangeServiceConfig2 handles multiple
* object types, some volatile, some not.
*/
/* ###: utf-ize */
1 /* SERVICE_CONFIG_DESCRIPTION */,
(LPVOID) &full_description)) {
}
}
}
if (full_description)
{
/* Find the Service key that Monitor Applications iterate */
"SYSTEM\\CurrentControlSet\\Services\\%s",
if (rv != APR_SUCCESS) {
return;
}
/* Attempt to set the Description value for our service */
}
}
/* handle the SCM's ControlService() callbacks to our service */
{
if (dwCtrlCode == SERVICE_CONTROL_STOP)
{
return;
}
if (dwCtrlCode == SERVICE_APACHE_RESTART)
{
return;
}
}
/* 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;
/* ###: utf-ize */
{
const char *ignored;
/* args and service names live in the same pool */
/* ###: utf-ize */
{
NULL, "Failure registering service handler");
return;
}
/* Report status, no errors, and buy 3 more seconds */
/* 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 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
*/
}
{
{
{ "", service_nt_main_fn },
};
/* ###: utf-ize */
{
/* This is a genuine failure of the SCM. */
rv = apr_get_os_error();
"Error starting service control dispatcher");
}
return (rv);
}
const char *set_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) {
}
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 != 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)
{
{
/* Stop logging to the event log */
/* Cause the service_nt_main_fn to complete */
NO_ERROR, // exit code
0); // wait hint
}
else /* osver.dwPlatformId != VER_PLATFORM_WIN32_NT */
{
RegisterServiceProcess(0, 0);
}
}
}
{
/* Prevent holding open the (hidden) console */
ap_real_exit_code = 0;
/* GetCurrentThread returns a psuedo-handle, we need
* a real handle for another thread to wait upon.
*/
0, FALSE, DUPLICATE_SAME_ACCESS)) {
return APR_ENOTHREAD;
}
{
return APR_EGENERAL;
}
}
else /* osver.dwPlatformId != VER_PLATFORM_WIN32_NT */
{
if (!RegisterServiceProcess(0, 1))
return GetLastError();
if (!globdat.service_init) {
return APR_EGENERAL;
}
(LPVOID) mpm_service_name, 0,
}
if (!globdat.service_thread) {
return APR_ENOTHREAD;
}
/* Wait for controlling thread init or termination */
return APR_ENOTHREAD;
}
return APR_SUCCESS;
}
{
{
NO_ERROR, // exit code
0); // wait hint
}
return APR_SUCCESS;
}
void mpm_service_stopping(void)
{
NO_ERROR, // exit code
30000); // wait hint
}
{
char *launch_cmd;
: "Installing the %s service\n", mpm_display_name);
/* ###: utf-ize */
{
"GetModuleFileName failed");
return rv;
}
{
if (!schSCManager) {
rv = apr_get_os_error();
"Failed to open the WinNT service manager");
return (rv);
}
if (reconfig) {
/* ###: utf-ize */
if (!schService) {
apr_get_os_error(), NULL,
"OpenService failed");
}
/* ###: utf-ize */
else if (!ChangeServiceConfig(schService,
mpm_display_name)) {
apr_get_os_error(), NULL,
"ChangeServiceConfig failed");
/* !schService aborts configuration below */
schService = NULL;
}
}
else {
/* 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.
*/
/* ###: utf-ize */
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) {
launch_cmd, 0, pconf);
}
if (rv != APR_SUCCESS) {
"%s: Failed to add the RunServices registry entry.",
return (rv);
}
if (rv != APR_SUCCESS) {
"%s: Failed to create the registry service key.",
return (rv);
}
if (rv != APR_SUCCESS) {
"%s: Failed to store ImagePath in the registry.",
return (rv);
}
mpm_display_name, 0, pconf);
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) {
}
if (rv != APR_SUCCESS) {
"%s: Failed to store the ConfigArgs in the registry.",
return (rv);
}
return APR_SUCCESS;
}
{
{
if (!schSCManager) {
rv = apr_get_os_error();
"Failed to open the WinNT service manager.");
return (rv);
}
/* ###: utf-ize */
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 */
if (rv == APR_SUCCESS) {
}
if (rv != APR_SUCCESS) {
"%s: Failed to remove the RunServices registry "
"entry.", mpm_display_name);
}
/* we blast Services/us, not just the Services/us/Parameters branch */
if (rv2 != APR_SUCCESS) {
"%s: Failed to remove the service config from the "
"registry.", mpm_display_name);
}
if (rv != APR_SUCCESS)
return rv;
}
return APR_SUCCESS;
}
/* signal_service_transition is a simple thunk to signal the service
* and monitor its 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;
if (!schSCManager) {
rv = apr_get_os_error();
"Failed to open the WinNT service manager");
return (rv);
}
/* ###: utf-ize */
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;
}
/* ###: utf-ize */
rv = APR_SUCCESS;
if (rv != APR_SUCCESS)
rv = apr_get_os_error();
}
else /* osver.dwPlatformId != VER_PLATFORM_WIN32_NT */
{
char *next_arg;
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;
}
"\"%s\" -n %s -k runservice",
for (i = 0; i < argc; ++i) {
" \"%s\"", argv[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;
}
/* ###: utf-ize */
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 {
}
}
}
if (success)
else
}