1 /* ====================================================================
2 * The Apache Software License, Version 1.1
4 * Copyright (c) 2000-2004 The Apache Software Foundation. All rights
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in
16 * the documentation and/or other materials provided with the
19 * 3. The end-user documentation included with the redistribution,
20 * if any, must include the following acknowledgment:
21 * "This product includes software developed by the
22 * Apache Software Foundation (http://www.apache.org/)."
23 * Alternately, this acknowledgment may appear in the software itself,
24 * if and wherever such third-party acknowledgments normally appear.
26 * 4. The names "Apache" and "Apache Software Foundation" must
27 * not be used to endorse or promote products derived from this
28 * software without prior written permission. For written
29 * permission, please contact apache@apache.org.
31 * 5. Products derived from this software may not be called "Apache",
32 * nor may "Apache" appear in their name, without prior written
33 * permission of the Apache Software Foundation.
35 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38 * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
39 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47 * ====================================================================
49 * This software consists of voluntary contributions made by many
50 * individuals on behalf of the Apache Software Foundation. For more
51 * information on the Apache Software Foundation, please see
52 * <http://www.apache.org/>.
54 * Portions of this software are based upon public domain software
55 * originally written at the National Center for Supercomputing Applications,
56 * University of Illinois, Urbana-Champaign.
59 /* This module ALONE requires the window message API from user.h
60 * and the default APR include of windows.h will omit it, so
61 * preload the API symbols now...
69 #include "mpm_winnt.h"
70 #include "apr_strings.h"
72 #include "ap_regkey.h"
80 static char *mpm_service_name = NULL;
81 static char *mpm_display_name = NULL;
85 HANDLE mpm_thread; /* primary thread handle of the apache server */
86 HANDLE service_thread; /* thread service/monitor handle */
87 DWORD service_thread_id;/* thread service/monitor ID */
88 HANDLE service_init; /* controller thread init mutex */
89 HANDLE service_term; /* NT service thread kill signal */
90 SERVICE_STATUS ssStatus;
91 SERVICE_STATUS_HANDLE hServiceStatus;
94 static int ReportStatusToSCMgr(int currentState, int exitCode, int waitHint);
97 #define PRODREGKEY "SOFTWARE\\" AP_SERVER_BASEVENDOR "\\" \
98 AP_SERVER_BASEPRODUCT "\\" AP_SERVER_BASEREVISION
101 * Get the server root from the registry into 'dir' which is
102 * size bytes long. Returns 0 if the server root was found
103 * or if the serverroot key does not exist (in which case
104 * dir will contain an empty string), or -1 if there was
105 * an error getting the key.
107 apr_status_t ap_registry_get_server_root(apr_pool_t *p, char **buf)
112 if ((rv = ap_regkey_open(&key, AP_REGKEY_LOCAL_MACHINE, PRODREGKEY,
113 APR_READ, p)) == APR_SUCCESS) {
114 rv = ap_regkey_value_get(buf, key, "ServerRoot", p);
115 ap_regkey_close(key);
116 if (rv == APR_SUCCESS)
120 if ((rv = ap_regkey_open(&key, AP_REGKEY_CURRENT_USER, PRODREGKEY,
121 APR_READ, p)) == APR_SUCCESS) {
122 rv = ap_regkey_value_get(buf, key, "ServerRoot", p);
123 ap_regkey_close(key);
124 if (rv == APR_SUCCESS)
133 /* The service configuration's is stored under the following trees:
135 * HKLM\System\CurrentControlSet\Services\[service name]
139 * \Parameters\ConfigArgs
141 * For Win9x, the launch service command is stored under:
143 * HKLM\Software\Microsoft\Windows\CurrentVersion\RunServices\[service name]
147 /* exit() for Win32 is macro mapped (horrible, we agree) that allows us
148 * to catch the non-zero conditions and inform the console process that
149 * the application died, and hang on to the console a bit longer.
151 * The macro only maps for http_main.c and other sources that include
152 * the service.h header, so we best assume it's an error to exit from
153 * _any_ other module.
155 * If real_exit_code is reset to 0, it will not be set or trigger this
156 * behavior on exit. All service and child processes are expected to
157 * reset this flag to zero to avoid undesireable side effects.
159 AP_DECLARE_DATA int real_exit_code = 1;
161 void hold_console_open_on_error(void)
168 char *msg = "Note the errors or messages above, "
169 "and press the <ESC> key to exit. ";
170 CONSOLE_SCREEN_BUFFER_INFO coninfo;
176 hConIn = GetStdHandle(STD_INPUT_HANDLE);
177 hConErr = GetStdHandle(STD_ERROR_HANDLE);
178 if ((hConIn == INVALID_HANDLE_VALUE) || (hConErr == INVALID_HANDLE_VALUE))
180 if (!WriteConsole(hConErr, msg, strlen(msg), &result, NULL) || !result)
182 if (!GetConsoleScreenBufferInfo(hConErr, &coninfo))
184 if (!SetConsoleMode(hConIn, ENABLE_MOUSE_INPUT | 0x80))
190 while (PeekConsoleInput(hConIn, &in, 1, &result) && result)
192 if (!ReadConsoleInput(hConIn, &in, 1, &result) || !result)
194 if ((in.EventType == KEY_EVENT) && in.Event.KeyEvent.bKeyDown
195 && (in.Event.KeyEvent.uChar.AsciiChar == 27))
197 if (in.EventType == MOUSE_EVENT
198 && (in.Event.MouseEvent.dwEventFlags == DOUBLE_CLICK))
201 remains = ((start + 30) - time(NULL));
202 sprintf (count, "%d...", remains);
203 if (!SetConsoleCursorPosition(hConErr, coninfo.dwCursorPosition))
205 if (!WriteConsole(hConErr, count, strlen(count), &result, NULL)
209 while ((remains > 0) && WaitForSingleObject(hConIn, 1000) != WAIT_FAILED);
212 static BOOL die_on_logoff = FALSE;
214 static LRESULT CALLBACK monitor_service_9x_proc(HWND hWnd, UINT msg,
215 WPARAM wParam, LPARAM lParam)
217 /* This is the WndProc procedure for our invisible window.
218 * When the user shuts down the system, this window is sent
219 * a signal WM_ENDSESSION. We clean up by signaling Apache
220 * to shut down, and idle until Apache's primary thread quits.
222 if ((msg == WM_ENDSESSION)
223 && (die_on_logoff || (lParam != ENDSESSION_LOGOFF)))
225 ap_signal_parent(SIGNAL_PARENT_SHUTDOWN);
227 /* Don't leave this message until we are dead! */
228 WaitForSingleObject(globdat.mpm_thread, 30000);
231 return (DefWindowProc(hWnd, msg, wParam, lParam));
234 static DWORD WINAPI monitor_service_9x_thread(void *service_name)
236 /* When running as a service under Windows 9x, there is no console
237 * window present, and no ConsoleCtrlHandler to call when the system
238 * is shutdown. If the WatchWindow thread is created with a NULL
239 * service_name argument, then the ...SystemMonitor window class is
240 * used to create the "Apache" window to watch for logoff and shutdown.
241 * If the service_name is provided, the ...ServiceMonitor window class
242 * is used to create the window named by the service_name argument,
243 * and the logoff message is ignored.
249 wc.style = CS_GLOBALCLASS;
250 wc.lpfnWndProc = monitor_service_9x_proc;
256 wc.hbrBackground = NULL;
257 wc.lpszMenuName = NULL;
259 wc.lpszClassName = "ApacheWin95ServiceMonitor";
261 wc.lpszClassName = "ApacheWin95SystemMonitor";
263 die_on_logoff = service_name ? FALSE : TRUE;
265 if (!RegisterClass(&wc))
267 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, apr_get_os_error(),
268 NULL, "Could not register window class for WatchWindow");
269 globdat.service_thread_id = 0;
273 /* Create an invisible window */
274 hwndMain = CreateWindow(wc.lpszClassName,
275 service_name ? (char *) service_name : "Apache",
276 WS_OVERLAPPEDWINDOW & ~WS_VISIBLE,
277 CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
278 CW_USEDEFAULT, NULL, NULL, NULL, NULL);
282 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, apr_get_os_error(),
283 NULL, "Could not create WatchWindow");
284 globdat.service_thread_id = 0;
288 /* If we succeed, eliminate the console window.
289 * Signal the parent we are all set up, and
290 * watch the message queue while the window lives.
293 SetEvent(globdat.service_init);
295 while (GetMessage(&msg, NULL, 0, 0))
297 if (msg.message == WM_CLOSE)
298 DestroyWindow(hwndMain);
300 TranslateMessage(&msg);
301 DispatchMessage(&msg);
304 globdat.service_thread_id = 0;
309 static BOOL CALLBACK console_control_handler(DWORD ctrl_type)
313 case CTRL_BREAK_EVENT:
314 fprintf(stderr, "Apache server restarting...\n");
315 ap_signal_parent(SIGNAL_PARENT_RESTART);
318 fprintf(stderr, "Apache server interrupted...\n");
319 /* for Interrupt signals, shut down the server.
320 * Tell the system we have dealt with the signal
321 * without waiting for Apache to terminate.
323 ap_signal_parent(SIGNAL_PARENT_SHUTDOWN);
326 case CTRL_CLOSE_EVENT:
327 case CTRL_LOGOFF_EVENT:
328 case CTRL_SHUTDOWN_EVENT:
329 /* for Terminate signals, shut down the server.
330 * Wait for Apache to terminate, but respond
331 * after a reasonable time to tell the system
332 * that we did attempt to shut ourself down.
333 * THESE EVENTS WILL NOT OCCUR UNDER WIN9x!
335 fprintf(stderr, "Apache server shutdown initiated...\n");
336 ap_signal_parent(SIGNAL_PARENT_SHUTDOWN);
341 /* We should never get here, but this is (mostly) harmless */
346 static void stop_console_handler(void)
348 SetConsoleCtrlHandler(console_control_handler, FALSE);
352 void mpm_start_console_handler(void)
354 SetConsoleCtrlHandler(console_control_handler, TRUE);
355 atexit(stop_console_handler);
359 /* Special situation - children of services need to mind their
360 * P's & Q's and wait quietly, ignoring the mean OS signaling
361 * shutdown and other horrors, to kill them gracefully...
364 static BOOL CALLBACK child_control_handler(DWORD ctrl_type)
369 case CTRL_BREAK_EVENT:
370 /* for Interrupt signals, ignore them.
371 * The system will also signal the parent process,
372 * which will terminate Apache.
376 case CTRL_CLOSE_EVENT:
377 case CTRL_LOGOFF_EVENT:
378 case CTRL_SHUTDOWN_EVENT:
379 /* for Shutdown signals, ignore them, but... .
380 * The system will also signal the parent process,
381 * which will terminate Apache, so we need to wait.
387 /* We should never get here, but this is (mostly) harmless */
392 static void stop_child_console_handler(void)
394 SetConsoleCtrlHandler(child_control_handler, FALSE);
398 void mpm_start_child_console_handler(void)
400 if (osver.dwPlatformId == VER_PLATFORM_WIN32_NT) {
405 SetConsoleCtrlHandler(child_control_handler, TRUE);
406 atexit(stop_child_console_handler);
411 /**********************************
412 WinNT service control management
413 **********************************/
415 static int ReportStatusToSCMgr(int currentState, int exitCode, int waitHint)
417 static int checkPoint = 1;
418 int rv = APR_SUCCESS;
420 if (globdat.hServiceStatus)
422 if (currentState == SERVICE_RUNNING) {
423 globdat.ssStatus.dwWaitHint = 0;
424 globdat.ssStatus.dwCheckPoint = 0;
425 globdat.ssStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;
427 else if (currentState == SERVICE_STOPPED) {
428 globdat.ssStatus.dwWaitHint = 0;
429 globdat.ssStatus.dwCheckPoint = 0;
430 if (!exitCode && globdat.ssStatus.dwCurrentState
431 != SERVICE_STOP_PENDING) {
432 /* An unexpected exit? Better to error! */
436 globdat.ssStatus.dwWin32ExitCode =ERROR_SERVICE_SPECIFIC_ERROR;
437 globdat.ssStatus.dwServiceSpecificExitCode = exitCode;
441 globdat.ssStatus.dwCheckPoint = ++checkPoint;
442 globdat.ssStatus.dwControlsAccepted = 0;
444 globdat.ssStatus.dwWaitHint = waitHint;
447 globdat.ssStatus.dwCurrentState = currentState;
449 rv = SetServiceStatus(globdat.hServiceStatus, &globdat.ssStatus);
454 /* Set the service description regardless of platform.
455 * We revert to set_service_description on NT/9x, the
456 * very long way so any Apache management program can grab the
457 * description. This would be bad on Win2000, since it wouldn't
458 * notify the service control manager of the name change.
461 /* borrowed from mpm_winnt.c */
462 extern apr_pool_t *pconf;
464 /* Windows 2000 alone supports ChangeServiceConfig2 in order to
465 * register our server_version string... so we need some fixups
466 * to avoid binding to that function if we are on WinNT/9x.
468 static void set_service_description(void)
470 const char *full_description;
471 SC_HANDLE schSCManager;
474 /* Nothing to do if we are a console
476 if (!mpm_service_name)
479 /* Time to fix up the description, upon each successful restart
481 full_description = ap_get_server_version();
483 if ((osver.dwPlatformId == VER_PLATFORM_WIN32_NT)
484 && (osver.dwMajorVersion > 4)
485 && (ChangeServiceConfig2)
486 && (schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT)))
488 SC_HANDLE schService = OpenService(schSCManager, mpm_service_name,
489 SERVICE_CHANGE_CONFIG);
491 /* Cast is necessary, ChangeServiceConfig2 handles multiple
492 * object types, some volatile, some not.
495 if (ChangeServiceConfig2(schService,
496 1 /* SERVICE_CONFIG_DESCRIPTION */,
497 (LPVOID) &full_description)) {
498 full_description = NULL;
500 CloseServiceHandle(schService);
502 CloseServiceHandle(schSCManager);
505 if (full_description)
507 char szPath[MAX_PATH];
511 /* Find the Service key that Monitor Applications iterate */
512 apr_snprintf(szPath, sizeof(szPath),
513 "SYSTEM\\CurrentControlSet\\Services\\%s",
515 rv = ap_regkey_open(&svckey, AP_REGKEY_LOCAL_MACHINE, szPath,
516 APR_READ | APR_WRITE, pconf);
517 if (rv != APR_SUCCESS) {
520 /* Attempt to set the Description value for our service */
521 ap_regkey_value_set(svckey, "Description", full_description, 0, pconf);
522 ap_regkey_close(svckey);
526 /* handle the SCM's ControlService() callbacks to our service */
528 static VOID WINAPI service_nt_ctrl(DWORD dwCtrlCode)
530 if (dwCtrlCode == SERVICE_CONTROL_STOP)
532 ap_signal_parent(SIGNAL_PARENT_SHUTDOWN);
533 ReportStatusToSCMgr(SERVICE_STOP_PENDING, NO_ERROR, 30000);
536 if (dwCtrlCode == SERVICE_APACHE_RESTART)
538 ap_signal_parent(SIGNAL_PARENT_RESTART);
539 ReportStatusToSCMgr(SERVICE_START_PENDING, NO_ERROR, 30000);
543 ReportStatusToSCMgr(globdat.ssStatus.dwCurrentState, NO_ERROR, 0);
547 /* service_nt_main_fn is outside of the call stack and outside of the
548 * primary server thread... so now we _really_ need a placeholder!
549 * The winnt_rewrite_args has created and shared mpm_new_argv with us.
551 extern apr_array_header_t *mpm_new_argv;
554 static void __stdcall service_nt_main_fn(DWORD argc, LPTSTR *argv)
558 /* args and service names live in the same pool */
559 mpm_service_set_name(mpm_new_argv->pool, &ignored, argv[0]);
561 memset(&globdat.ssStatus, 0, sizeof(globdat.ssStatus));
562 globdat.ssStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
563 globdat.ssStatus.dwCurrentState = SERVICE_START_PENDING;
564 globdat.ssStatus.dwCheckPoint = 1;
567 if (!(globdat.hServiceStatus = RegisterServiceCtrlHandler(argv[0], service_nt_ctrl)))
569 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, apr_get_os_error(),
570 NULL, "Failure registering service handler");
574 /* Report status, no errors, and buy 3 more seconds */
575 ReportStatusToSCMgr(SERVICE_START_PENDING, NO_ERROR, 30000);
577 /* We need to append all the command arguments passed via StartService()
578 * to our running service... which just got here via the SCM...
579 * but we hvae no interest in argv[0] for the mpm_new_argv list.
585 mpm_new_argv->nalloc = mpm_new_argv->nelts + argc - 1;
586 cmb_data = malloc(mpm_new_argv->nalloc * sizeof(const char *));
588 /* mpm_new_argv remains first (of lower significance) */
589 memcpy (cmb_data, mpm_new_argv->elts,
590 mpm_new_argv->elt_size * mpm_new_argv->nelts);
592 /* Service args follow from StartService() invocation */
593 memcpy (cmb_data + mpm_new_argv->nelts, argv + 1,
594 mpm_new_argv->elt_size * (argc - 1));
596 /* The replacement arg list is complete */
597 mpm_new_argv->elts = (char *)cmb_data;
598 mpm_new_argv->nelts = mpm_new_argv->nalloc;
601 /* Let the main thread continue now... but hang on to the
602 * signal_monitor event so we can take further action
604 SetEvent(globdat.service_init);
606 WaitForSingleObject(globdat.service_term, INFINITE);
610 DWORD WINAPI service_nt_dispatch_thread(LPVOID nada)
612 apr_status_t rv = APR_SUCCESS;
614 SERVICE_TABLE_ENTRY dispatchTable[] =
616 { "", service_nt_main_fn },
621 if (!StartServiceCtrlDispatcher(dispatchTable))
623 /* This is a genuine failure of the SCM. */
624 rv = apr_get_os_error();
625 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, rv, NULL,
626 "Error starting service control dispatcher");
633 apr_status_t mpm_service_set_name(apr_pool_t *p, const char **display_name,
634 const char *set_name)
636 char key_name[MAX_PATH];
640 /* ### Needs improvement, on Win2K the user can _easily_
641 * change the display name to a string that doesn't reflect
642 * the internal service name + whitespace!
644 mpm_service_name = apr_palloc(p, strlen(set_name) + 1);
645 apr_collapse_spaces((char*) mpm_service_name, set_name);
646 apr_snprintf(key_name, sizeof(key_name), SERVICECONFIG, mpm_service_name);
647 rv = ap_regkey_open(&key, AP_REGKEY_LOCAL_MACHINE, key_name, APR_READ, pconf);
648 if (rv == APR_SUCCESS) {
649 rv = ap_regkey_value_get(&mpm_display_name, key, "DisplayName", pconf);
650 ap_regkey_close(key);
652 if (rv != APR_SUCCESS) {
653 /* Take the given literal name if there is no service entry */
654 mpm_display_name = apr_pstrdup(p, set_name);
656 *display_name = mpm_display_name;
661 apr_status_t mpm_merge_service_args(apr_pool_t *p,
662 apr_array_header_t *args,
665 apr_array_header_t *svc_args = NULL;
666 char conf_key[MAX_PATH];
671 apr_snprintf(conf_key, sizeof(conf_key), SERVICEPARAMS, mpm_service_name);
672 rv = ap_regkey_open(&key, AP_REGKEY_LOCAL_MACHINE, conf_key, APR_READ, p);
673 if (rv == APR_SUCCESS) {
674 rv = ap_regkey_value_array_get(&svc_args, key, "ConfigArgs", p);
675 ap_regkey_close(key);
677 if (rv != APR_SUCCESS) {
678 if (rv == ERROR_FILE_NOT_FOUND) {
679 ap_log_error(APLOG_MARK, APLOG_INFO, 0, NULL,
680 "No ConfigArgs registered for %s, perhaps "
681 "this service is not installed?",
689 if (!svc_args || svc_args->nelts == 0) {
690 return (APR_SUCCESS);
693 /* Now we have the mpm_service_name arg, and the mpm_runservice_nt()
694 * call appended the arguments passed by StartService(), so it's
695 * time to _prepend_ the default arguments for the server from
696 * the service's default arguments (all others override them)...
698 args->nalloc = args->nelts + svc_args->nelts;
699 cmb_data = malloc(args->nalloc * sizeof(const char *));
701 /* First three args (argv[0], -f, path) remain first */
702 memcpy(cmb_data, args->elts, args->elt_size * fixed_args);
704 /* Service args follow from service registry array */
705 memcpy(cmb_data + fixed_args, svc_args->elts,
706 svc_args->elt_size * svc_args->nelts);
708 /* Remaining new args follow */
709 memcpy(cmb_data + fixed_args + svc_args->nelts,
710 (const char **)args->elts + fixed_args,
711 args->elt_size * (args->nelts - fixed_args));
713 args->elts = (char *)cmb_data;
714 args->nelts = args->nalloc;
720 void service_stopped(void)
722 /* Still have a thread & window to clean up, so signal now */
723 if (globdat.service_thread)
725 if (osver.dwPlatformId == VER_PLATFORM_WIN32_NT)
727 /* Stop logging to the event log */
728 mpm_nt_eventlog_stderr_flush();
730 /* Cause the service_nt_main_fn to complete */
731 ReleaseMutex(globdat.service_term);
733 ReportStatusToSCMgr(SERVICE_STOPPED, // service state
734 NO_ERROR, // exit code
737 else /* osver.dwPlatformId != VER_PLATFORM_WIN32_NT */
739 RegisterServiceProcess(0, 0);
740 PostThreadMessage(globdat.service_thread_id, WM_CLOSE, 0, 0);
743 WaitForSingleObject(globdat.service_thread, 5000);
744 CloseHandle(globdat.service_thread);
749 apr_status_t mpm_service_to_start(const char **display_name, apr_pool_t *p)
751 HANDLE hProc = GetCurrentProcess();
752 HANDLE hThread = GetCurrentThread();
755 /* Prevent holding open the (hidden) console */
758 /* GetCurrentThread returns a psuedo-handle, we need
759 * a real handle for another thread to wait upon.
761 if (!DuplicateHandle(hProc, hThread, hProc, &(globdat.mpm_thread),
762 0, FALSE, DUPLICATE_SAME_ACCESS)) {
763 return APR_ENOTHREAD;
766 if (osver.dwPlatformId == VER_PLATFORM_WIN32_NT)
768 globdat.service_init = CreateEvent(NULL, FALSE, FALSE, NULL);
769 globdat.service_term = CreateMutex(NULL, TRUE, NULL);
770 if (!globdat.service_init || !globdat.service_term) {
774 globdat.service_thread = CreateThread(NULL, 0, service_nt_dispatch_thread,
775 NULL, 0, &globdat.service_thread_id);
777 else /* osver.dwPlatformId != VER_PLATFORM_WIN32_NT */
779 if (!RegisterServiceProcess(0, 1))
780 return GetLastError();
782 globdat.service_init = CreateEvent(NULL, FALSE, FALSE, NULL);
783 if (!globdat.service_init) {
787 globdat.service_thread = CreateThread(NULL, 0, monitor_service_9x_thread,
788 (LPVOID) mpm_service_name, 0,
789 &globdat.service_thread_id);
792 if (!globdat.service_thread) {
793 return APR_ENOTHREAD;
796 waitfor[0] = globdat.service_init;
797 waitfor[1] = globdat.service_thread;
799 /* Wait for controlling thread init or termination */
800 if (WaitForMultipleObjects(2, waitfor, FALSE, 10000) != WAIT_OBJECT_0) {
801 return APR_ENOTHREAD;
804 atexit(service_stopped);
805 *display_name = mpm_display_name;
810 apr_status_t mpm_service_started(void)
812 set_service_description();
813 if (osver.dwPlatformId == VER_PLATFORM_WIN32_NT)
815 ReportStatusToSCMgr(SERVICE_RUNNING, // service state
816 NO_ERROR, // exit code
823 void mpm_service_stopping(void)
825 if (osver.dwPlatformId == VER_PLATFORM_WIN32_NT)
826 ReportStatusToSCMgr(SERVICE_STOP_PENDING, // service state
827 NO_ERROR, // exit code
832 apr_status_t mpm_service_install(apr_pool_t *ptemp, int argc,
833 const char * const * argv, int reconfig)
835 char key_name[MAX_PATH];
836 char exe_path[MAX_PATH];
841 fprintf(stderr,reconfig ? "Reconfiguring the %s service\n"
842 : "Installing the %s service\n", mpm_display_name);
845 if (GetModuleFileName(NULL, exe_path, sizeof(exe_path)) == 0)
847 apr_status_t rv = apr_get_os_error();
848 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, rv, NULL,
849 "GetModuleFileName failed");
853 if (osver.dwPlatformId == VER_PLATFORM_WIN32_NT)
855 SC_HANDLE schService;
856 SC_HANDLE schSCManager;
858 schSCManager = OpenSCManager(NULL, NULL, /* local, default database */
859 SC_MANAGER_CREATE_SERVICE);
861 rv = apr_get_os_error();
862 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, rv, NULL,
863 "Failed to open the WinNT service manager");
867 launch_cmd = apr_psprintf(ptemp, "\"%s\" -k runservice", exe_path);
871 schService = OpenService(schSCManager, mpm_service_name,
872 SERVICE_CHANGE_CONFIG);
874 ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_ERR,
875 apr_get_os_error(), NULL,
876 "OpenService failed");
879 else if (!ChangeServiceConfig(schService,
880 SERVICE_WIN32_OWN_PROCESS,
882 SERVICE_ERROR_NORMAL,
883 launch_cmd, NULL, NULL,
884 "Tcpip\0Afd\0", NULL, NULL,
886 ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_ERR,
887 apr_get_os_error(), NULL,
888 "ChangeServiceConfig failed");
889 /* !schService aborts configuration below */
890 CloseServiceHandle(schService);
895 /* RPCSS is the Remote Procedure Call (RPC) Locator required
896 * for DCOM communication pipes. I am far from convinced we
897 * should add this to the default service dependencies, but
898 * be warned that future apache modules or ISAPI dll's may
902 schService = CreateService(schSCManager, // SCManager database
903 mpm_service_name, // name of service
904 mpm_display_name, // name to display
905 SERVICE_ALL_ACCESS, // access required
906 SERVICE_WIN32_OWN_PROCESS, // service type
907 SERVICE_AUTO_START, // start type
908 SERVICE_ERROR_NORMAL, // error control type
909 launch_cmd, // service's binary
910 NULL, // no load svc group
911 NULL, // no tag identifier
912 "Tcpip\0Afd\0", // dependencies
913 NULL, // use SYSTEM account
914 NULL); // no password
918 rv = apr_get_os_error();
919 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, rv, NULL,
920 "Failed to create WinNT Service Profile");
921 CloseServiceHandle(schSCManager);
926 CloseServiceHandle(schService);
927 CloseServiceHandle(schSCManager);
929 else /* osver.dwPlatformId != VER_PLATFORM_WIN32_NT */
931 /* Store the launch command in the registry */
932 launch_cmd = apr_psprintf(ptemp, "\"%s\" -n %s -k runservice",
933 exe_path, mpm_service_name);
934 rv = ap_regkey_open(&key, AP_REGKEY_LOCAL_MACHINE, SERVICECONFIG9X,
935 APR_READ | APR_WRITE | APR_CREATE, pconf);
936 if (rv == APR_SUCCESS) {
937 rv = ap_regkey_value_set(key, mpm_service_name,
938 launch_cmd, 0, pconf);
939 ap_regkey_close(key);
941 if (rv != APR_SUCCESS) {
942 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, rv, NULL,
943 "%s: Failed to add the RunServices registry entry.",
948 apr_snprintf(key_name, sizeof(key_name), SERVICECONFIG, mpm_service_name);
949 rv = ap_regkey_open(&key, AP_REGKEY_LOCAL_MACHINE, key_name,
950 APR_READ | APR_WRITE | APR_CREATE, pconf);
951 if (rv != APR_SUCCESS) {
952 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, rv, NULL,
953 "%s: Failed to create the registry service key.",
957 rv = ap_regkey_value_set(key, "ImagePath", launch_cmd, 0, pconf);
958 if (rv != APR_SUCCESS) {
959 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, rv, NULL,
960 "%s: Failed to store ImagePath in the registry.",
962 ap_regkey_close(key);
965 rv = ap_regkey_value_set(key, "DisplayName",
966 mpm_display_name, 0, pconf);
967 ap_regkey_close(key);
968 if (rv != APR_SUCCESS) {
969 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, rv, NULL,
970 "%s: Failed to store DisplayName in the registry.",
976 set_service_description();
978 /* For both WinNT & Win9x store the service ConfigArgs in the registry...
980 apr_snprintf(key_name, sizeof(key_name), SERVICEPARAMS, mpm_service_name);
981 rv = ap_regkey_open(&key, AP_REGKEY_LOCAL_MACHINE, key_name,
982 APR_READ | APR_WRITE | APR_CREATE, pconf);
983 if (rv == APR_SUCCESS) {
984 rv = ap_regkey_value_array_set(key, "ConfigArgs", argc, argv, pconf);
985 ap_regkey_close(key);
987 if (rv != APR_SUCCESS) {
988 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, rv, NULL,
989 "%s: Failed to store the ConfigArgs in the registry.",
993 fprintf(stderr,"The %s service is successfully installed.\n", mpm_display_name);
998 apr_status_t mpm_service_uninstall(void)
1000 char key_name[MAX_PATH];
1003 if (osver.dwPlatformId == VER_PLATFORM_WIN32_NT)
1005 SC_HANDLE schService;
1006 SC_HANDLE schSCManager;
1008 fprintf(stderr,"Removing the %s service\n", mpm_display_name);
1010 schSCManager = OpenSCManager(NULL, NULL, /* local, default database */
1011 SC_MANAGER_CONNECT);
1012 if (!schSCManager) {
1013 rv = apr_get_os_error();
1014 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, rv, NULL,
1015 "Failed to open the WinNT service manager.");
1020 schService = OpenService(schSCManager, mpm_service_name, DELETE);
1023 rv = apr_get_os_error();
1024 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, rv, NULL,
1025 "%s: OpenService failed", mpm_display_name);
1029 /* assure the service is stopped before continuing
1031 * This may be out of order... we might not be able to be
1032 * granted all access if the service is running anyway.
1034 * And do we want to make it *this easy* for them
1035 * to uninstall their service unintentionally?
1037 // ap_stop_service(schService);
1039 if (DeleteService(schService) == 0) {
1040 rv = apr_get_os_error();
1041 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, rv, NULL,
1042 "%s: Failed to delete the service.", mpm_display_name);
1046 CloseServiceHandle(schService);
1047 CloseServiceHandle(schSCManager);
1049 else /* osver.dwPlatformId != VER_PLATFORM_WIN32_NT */
1051 apr_status_t rv2, rv3;
1053 fprintf(stderr,"Removing the %s service\n", mpm_display_name);
1055 /* TODO: assure the service is stopped before continuing */
1057 rv = ap_regkey_open(&key, AP_REGKEY_LOCAL_MACHINE, SERVICECONFIG9X,
1058 APR_READ | APR_WRITE | APR_CREATE, pconf);
1059 if (rv == APR_SUCCESS) {
1060 rv = ap_regkey_value_remove(key, mpm_service_name, pconf);
1061 ap_regkey_close(key);
1063 if (rv != APR_SUCCESS) {
1064 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, rv, NULL,
1065 "%s: Failed to remove the RunServices registry "
1066 "entry.", mpm_display_name);
1069 /* we blast Services/us, not just the Services/us/Parameters branch */
1070 apr_snprintf(key_name, sizeof(key_name), SERVICEPARAMS, mpm_service_name);
1071 rv2 = ap_regkey_remove(AP_REGKEY_LOCAL_MACHINE, key_name, pconf);
1072 apr_snprintf(key_name, sizeof(key_name), SERVICECONFIG, mpm_service_name);
1073 rv3 = ap_regkey_remove(AP_REGKEY_LOCAL_MACHINE, key_name, pconf);
1074 rv2 = (rv2 != APR_SUCCESS) ? rv2 : rv3;
1075 if (rv2 != APR_SUCCESS) {
1076 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, rv2, NULL,
1077 "%s: Failed to remove the service config from the "
1078 "registry.", mpm_display_name);
1080 rv = (rv != APR_SUCCESS) ? rv : rv2;
1081 if (rv != APR_SUCCESS)
1084 fprintf(stderr,"The %s service has been removed successfully.\n", mpm_display_name);
1089 /* signal_service_transition is a simple thunk to signal the service
1090 * and monitor its successful transition. If the signal passed is 0,
1091 * then the caller is assumed to already have performed some service
1092 * operation to be monitored (such as StartService), and no actual
1093 * ControlService signal is sent.
1096 static int signal_service_transition(SC_HANDLE schService, DWORD signal, DWORD pending, DWORD complete)
1098 if (signal && !ControlService(schService, signal, &globdat.ssStatus))
1103 if (!QueryServiceStatus(schService, &globdat.ssStatus))
1105 } while (globdat.ssStatus.dwCurrentState == pending);
1107 return (globdat.ssStatus.dwCurrentState == complete);
1111 apr_status_t mpm_service_start(apr_pool_t *ptemp, int argc,
1112 const char * const * argv)
1116 fprintf(stderr,"Starting the %s service\n", mpm_display_name);
1118 if (osver.dwPlatformId == VER_PLATFORM_WIN32_NT)
1121 SC_HANDLE schService;
1122 SC_HANDLE schSCManager;
1124 schSCManager = OpenSCManager(NULL, NULL, /* local, default database */
1125 SC_MANAGER_CONNECT);
1126 if (!schSCManager) {
1127 rv = apr_get_os_error();
1128 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, rv, NULL,
1129 "Failed to open the WinNT service manager");
1134 schService = OpenService(schSCManager, mpm_service_name,
1135 SERVICE_START | SERVICE_QUERY_STATUS);
1137 rv = apr_get_os_error();
1138 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, rv, NULL,
1139 "%s: Failed to open the service.", mpm_display_name);
1140 CloseServiceHandle(schSCManager);
1144 if (QueryServiceStatus(schService, &globdat.ssStatus)
1145 && (globdat.ssStatus.dwCurrentState == SERVICE_RUNNING)) {
1146 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, 0, NULL,
1147 "Service %s is already started!", mpm_display_name);
1148 CloseServiceHandle(schService);
1149 CloseServiceHandle(schSCManager);
1153 start_argv = malloc((argc + 1) * sizeof(const char **));
1154 memcpy(start_argv, argv, argc * sizeof(const char **));
1155 start_argv[argc] = NULL;
1159 if (StartService(schService, argc, start_argv)
1160 && signal_service_transition(schService, 0, /* test only */
1161 SERVICE_START_PENDING,
1165 if (rv != APR_SUCCESS)
1166 rv = apr_get_os_error();
1168 CloseServiceHandle(schService);
1169 CloseServiceHandle(schSCManager);
1171 else /* osver.dwPlatformId != VER_PLATFORM_WIN32_NT */
1173 STARTUPINFO si; /* Filled in prior to call to CreateProcess */
1174 PROCESS_INFORMATION pi; /* filled in on call to CreateProcess */
1175 char exe_path[MAX_PATH];
1176 char exe_cmd[MAX_PATH * 4];
1180 /* Locate the active top level window named service_name
1181 * provided the class is ApacheWin95ServiceMonitor
1183 if (FindWindow("ApacheWin95ServiceMonitor", mpm_service_name)) {
1184 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, 0, NULL,
1185 "Service %s is already started!", mpm_display_name);
1189 /* This may not appear intuitive, but Win9x will not allow a process
1190 * to detach from the console without releasing the entire console.
1191 * Ergo, we must spawn a new process for the service to get back our
1193 * The config is pre-flighted, so there should be no danger of failure.
1196 if (GetModuleFileName(NULL, exe_path, sizeof(exe_path)) == 0)
1198 apr_status_t rv = apr_get_os_error();
1199 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, rv, NULL,
1200 "GetModuleFileName failed");
1204 apr_snprintf(exe_cmd, sizeof(exe_cmd),
1205 "\"%s\" -n %s -k runservice",
1206 exe_path, mpm_service_name);
1207 next_arg = strchr(exe_cmd, '\0');
1208 for (i = 0; i < argc; ++i) {
1209 apr_snprintf(next_arg, sizeof(exe_cmd) - (next_arg - exe_cmd),
1210 " \"%s\"", argv[i]);
1211 next_arg = strchr(exe_cmd, '\0');
1214 memset(&si, 0, sizeof(si));
1215 memset(&pi, 0, sizeof(pi));
1217 si.dwFlags = STARTF_USESHOWWINDOW;
1218 si.wShowWindow = SW_HIDE; /* This might be redundant */
1221 if (CreateProcess(NULL, exe_cmd, NULL, NULL, FALSE,
1222 DETACHED_PROCESS, /* Creation flags */
1223 NULL, NULL, &si, &pi))
1226 while (GetExitCodeProcess(pi.hProcess, &code) == STILL_ACTIVE) {
1227 if (FindWindow("ApacheWin95ServiceMonitor", mpm_service_name)) {
1235 if (rv != APR_SUCCESS)
1236 rv = apr_get_os_error();
1238 CloseHandle(pi.hProcess);
1239 CloseHandle(pi.hThread);
1242 if (rv == APR_SUCCESS)
1243 fprintf(stderr,"The %s service is running.\n", mpm_display_name);
1245 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, NULL,
1246 "%s: Failed to start the service process.",
1253 /* signal is zero to stop, non-zero for restart */
1255 void mpm_signal_service(apr_pool_t *ptemp, int signal)
1257 int success = FALSE;
1259 if (osver.dwPlatformId == VER_PLATFORM_WIN32_NT)
1261 SC_HANDLE schService;
1262 SC_HANDLE schSCManager;
1264 schSCManager = OpenSCManager(NULL, NULL, // default machine & database
1265 SC_MANAGER_CONNECT);
1267 if (!schSCManager) {
1268 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, apr_get_os_error(), NULL,
1269 "Failed to open the NT Service Manager");
1274 schService = OpenService(schSCManager, mpm_service_name,
1275 SERVICE_INTERROGATE | SERVICE_QUERY_STATUS |
1276 SERVICE_USER_DEFINED_CONTROL |
1277 SERVICE_START | SERVICE_STOP);
1279 if (schService == NULL) {
1280 /* Could not open the service */
1281 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, apr_get_os_error(), NULL,
1282 "Failed to open the %s Service", mpm_display_name);
1283 CloseServiceHandle(schSCManager);
1287 if (!QueryServiceStatus(schService, &globdat.ssStatus)) {
1288 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, apr_get_os_error(), NULL,
1289 "Query of Service %s failed", mpm_display_name);
1290 CloseServiceHandle(schService);
1291 CloseServiceHandle(schSCManager);
1295 if (!signal && (globdat.ssStatus.dwCurrentState == SERVICE_STOPPED)) {
1296 fprintf(stderr,"The %s service is not started.\n", mpm_display_name);
1297 CloseServiceHandle(schService);
1298 CloseServiceHandle(schSCManager);
1302 fprintf(stderr,"The %s service is %s.\n", mpm_display_name,
1303 signal ? "restarting" : "stopping");
1306 success = signal_service_transition(schService,
1307 SERVICE_CONTROL_STOP,
1308 SERVICE_STOP_PENDING,
1310 else if (globdat.ssStatus.dwCurrentState == SERVICE_STOPPED) {
1311 mpm_service_start(ptemp, 0, NULL);
1312 CloseServiceHandle(schService);
1313 CloseServiceHandle(schSCManager);
1317 success = signal_service_transition(schService,
1318 SERVICE_APACHE_RESTART,
1319 SERVICE_START_PENDING,
1322 CloseServiceHandle(schService);
1323 CloseServiceHandle(schSCManager);
1325 else /* !isWindowsNT() */
1330 /* Locate the active top level window named service_name
1331 * provided the class is ApacheWin95ServiceMonitor
1333 hwnd = FindWindow("ApacheWin95ServiceMonitor", mpm_service_name);
1334 if (hwnd && GetWindowThreadProcessId(hwnd, &service_pid))
1335 globdat.ssStatus.dwCurrentState = SERVICE_RUNNING;
1338 globdat.ssStatus.dwCurrentState = SERVICE_STOPPED;
1340 fprintf(stderr,"The %s service is not started.\n", mpm_display_name);
1345 fprintf(stderr,"The %s service is %s.\n", mpm_display_name,
1346 signal ? "restarting" : "stopping");
1348 apr_snprintf(prefix, sizeof(prefix), "ap%ld", (long)service_pid);
1349 setup_signal_names(prefix);
1354 ap_signal_parent(SIGNAL_PARENT_SHUTDOWN);
1357 if (!IsWindow(hwnd)) {
1366 /* TODO: Aught to add a little test to the restart logic, and
1367 * store the restart counter in the window's user dword.
1368 * Then we can hang on and report a successful restart. But
1369 * that's a project for another day.
1371 if (globdat.ssStatus.dwCurrentState == SERVICE_STOPPED) {
1372 mpm_service_start(ptemp, 0, NULL);
1377 ap_signal_parent(SIGNAL_PARENT_RESTART);
1383 fprintf(stderr,"The %s service has %s.\n", mpm_display_name,
1384 signal ? "restarted" : "stopped");
1386 fprintf(stderr,"Failed to %s the %s service.\n",
1387 signal ? "restart" : "stop", mpm_display_name);