1 /* ====================================================================
2 * The Apache Software License, Version 1.1
4 * Copyright (c) 2000 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...
65 #define _WIN32_WINNT 0x0400
87 #include "mpm_winnt.h"
88 #include "apr_strings.h"
90 static const char * service_name = NULL;
92 /* ### should be namespace-protected */
93 const char * display_name = NULL;
97 HANDLE mpm_thread; /* primary thread handle of the apache server */
98 HANDLE service_thread; /* thread service/monitor handle */
99 DWORD service_thread_id;/* thread service/monitor ID */
100 HANDLE signal_monitor; /* service monitor thread signal event */
101 SERVICE_STATUS ssStatus;
102 SERVICE_STATUS_HANDLE hServiceStatus;
105 static int ReportStatusToSCMgr(int currentState, int exitCode, int waitHint);
107 /* The service configuration's is stored under the following trees:
109 * HKLM\System\CurrentControlSet\Services\[service name]
112 * \ImagePath (NT Only)
113 * \Parameters\ConfigArgs
115 * For Win9x, the launch service command is stored under:
117 * HKLM\Software\Microsoft\Windows\CurrentVersion\RunServices\[service name]
121 /* exit() for Win32 is macro mapped (horrible, we agree) that allows us
122 * to catch the non-zero conditions and inform the console process that
123 * the application died, and hang on to the console a bit longer.
125 * The macro only maps for http_main.c and other sources that include
126 * the service.h header, so we best assume it's an error to exit from
127 * _any_ other module.
129 * If real_exit_code is reset to 0, it will not be set or trigger this
130 * behavior on exit. All service and child processes are expected to
131 * reset this flag to zero to avoid undesireable side effects.
133 int real_exit_code = 1;
135 void hold_console_open_on_error(void)
142 char *msg = "Note the errors or messages above, "
143 "and press the <ESC> key to exit. ";
144 CONSOLE_SCREEN_BUFFER_INFO coninfo;
150 hConIn = GetStdHandle(STD_INPUT_HANDLE);
151 hConErr = GetStdHandle(STD_ERROR_HANDLE);
152 if ((hConIn == INVALID_HANDLE_VALUE) || (hConErr == INVALID_HANDLE_VALUE))
154 if (!WriteConsole(hConErr, msg, strlen(msg), &result, NULL) || !result)
156 if (!GetConsoleScreenBufferInfo(hConErr, &coninfo))
158 if (!SetConsoleMode(hConIn, ENABLE_MOUSE_INPUT | 0x80))
164 while (PeekConsoleInput(hConIn, &in, 1, &result) && result)
166 if (!ReadConsoleInput(hConIn, &in, 1, &result) || !result)
168 if ((in.EventType == KEY_EVENT) && in.Event.KeyEvent.bKeyDown
169 && (in.Event.KeyEvent.uChar.AsciiChar == 27))
171 if (in.EventType == MOUSE_EVENT
172 && (in.Event.MouseEvent.dwEventFlags == DOUBLE_CLICK))
175 remains = ((start + 30) - time(NULL));
176 sprintf (count, "%d...", remains);
177 if (!SetConsoleCursorPosition(hConErr, coninfo.dwCursorPosition))
179 if (!WriteConsole(hConErr, count, strlen(count), &result, NULL)
183 while ((remains > 0) && WaitForSingleObject(hConIn, 1000) != WAIT_FAILED);
186 static BOOL die_on_logoff = FALSE;
188 static LRESULT CALLBACK monitor_service_9x_proc(HWND hWnd, UINT msg,
189 WPARAM wParam, LPARAM lParam)
191 /* This is the WndProc procedure for our invisible window.
192 * When the user shuts down the system, this window is sent
193 * a signal WM_ENDSESSION. We clean up by signaling Apache
194 * to shut down, and idle until Apache's primary thread quits.
196 if ((msg == WM_ENDSESSION)
197 && (die_on_logoff || (lParam != ENDSESSION_LOGOFF)))
201 /* Don't leave this message until we are dead! */
202 WaitForSingleObject(globdat.mpm_thread, 30000);
205 return (DefWindowProc(hWnd, msg, wParam, lParam));
208 static DWORD WINAPI monitor_service_9x_thread(void *service_name)
210 /* When running as a service under Windows 9x, there is no console
211 * window present, and no ConsoleCtrlHandler to call when the system
212 * is shutdown. If the WatchWindow thread is created with a NULL
213 * service_name argument, then the ...SystemMonitor window class is
214 * used to create the "Apache" window to watch for logoff and shutdown.
215 * If the service_name is provided, the ...ServiceMonitor window class
216 * is used to create the window named by the service_name argument,
217 * and the logoff message is ignored.
223 wc.style = CS_GLOBALCLASS;
224 wc.lpfnWndProc = monitor_service_9x_proc;
230 wc.hbrBackground = NULL;
231 wc.lpszMenuName = NULL;
233 wc.lpszClassName = "ApacheWin95ServiceMonitor";
235 wc.lpszClassName = "ApacheWin95SystemMonitor";
237 die_on_logoff = service_name ? FALSE : TRUE;
239 if (!RegisterClass(&wc))
241 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, apr_get_os_error(),
242 NULL, "Could not register window class for WatchWindow");
243 SetEvent(globdat.signal_monitor);
244 globdat.service_thread_id = 0;
248 /* Create an invisible window */
249 hwndMain = CreateWindow(wc.lpszClassName,
250 service_name ? (char *) service_name : "Apache",
251 WS_OVERLAPPEDWINDOW & ~WS_VISIBLE,
252 CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
253 CW_USEDEFAULT, NULL, NULL, NULL, NULL);
257 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, apr_get_os_error(),
258 NULL, "Could not create WatchWindow");
259 SetEvent(globdat.signal_monitor);
260 globdat.service_thread_id = 0;
264 /* If we succeed, eliminate the console window.
265 * Signal the parent we are all set up, and
266 * watch the message queue while the window lives.
269 SetEvent((HANDLE) globdat.signal_monitor);
270 while (GetMessage(&msg, NULL, 0, 0))
272 if (msg.message == WM_CLOSE)
273 DestroyWindow(hwndMain);
275 TranslateMessage(&msg);
276 DispatchMessage(&msg);
279 globdat.service_thread_id = 0;
284 static BOOL CALLBACK console_control_handler(DWORD ctrl_type)
288 case CTRL_BREAK_EVENT:
289 fprintf(stderr, "Apache server restarting...\n");
293 fprintf(stderr, "Apache server interrupted...\n");
294 /* for Interrupt signals, shut down the server.
295 * Tell the system we have dealt with the signal
296 * without waiting for Apache to terminate.
301 case CTRL_CLOSE_EVENT:
302 case CTRL_LOGOFF_EVENT:
303 case CTRL_SHUTDOWN_EVENT:
304 /* for Terminate signals, shut down the server.
305 * Wait for Apache to terminate, but respond
306 * after a reasonable time to tell the system
307 * that we did attempt to shut ourself down.
308 * THESE EVENTS WILL NOT OCCUR UNDER WIN9x!
310 fprintf(stderr, "Apache server shutdown initiated...\n");
316 /* We should never get here, but this is (mostly) harmless */
321 static void stop_console_handler(void)
323 SetConsoleCtrlHandler(console_control_handler, FALSE);
327 void mpm_start_console_handler(void)
329 SetConsoleCtrlHandler(console_control_handler, TRUE);
330 atexit(stop_console_handler);
334 /* Special situation - children of services need to mind their
335 * P's & Q's and wait quietly, ignoring the mean OS signaling
336 * shutdown and other horrors, to kill them gracefully...
339 static BOOL CALLBACK child_control_handler(DWORD ctrl_type)
344 case CTRL_BREAK_EVENT:
345 /* for Interrupt signals, ignore them.
346 * The system will also signal the parent process,
347 * which will terminate Apache.
351 case CTRL_CLOSE_EVENT:
352 case CTRL_LOGOFF_EVENT:
353 case CTRL_SHUTDOWN_EVENT:
354 /* for Shutdown signals, ignore them, but... .
355 * The system will also signal the parent process,
356 * which will terminate Apache, so we need to wait.
362 /* We should never get here, but this is (mostly) harmless */
367 static void stop_child_console_handler(void)
369 SetConsoleCtrlHandler(child_control_handler, FALSE);
373 void mpm_start_child_console_handler(void)
375 if (osver.dwPlatformId == VER_PLATFORM_WIN32_NT) {
380 SetConsoleCtrlHandler(child_control_handler, TRUE);
381 atexit(stop_child_console_handler);
386 /**********************************
387 WinNT service control management
388 **********************************/
390 static int ReportStatusToSCMgr(int currentState, int exitCode, int waitHint)
392 static int checkPoint = 1;
393 int rv = APR_SUCCESS;
395 if (globdat.hServiceStatus)
397 if (currentState == SERVICE_RUNNING)
398 globdat.ssStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;
400 globdat.ssStatus.dwControlsAccepted = 0;
402 globdat.ssStatus.dwCurrentState = currentState;
403 globdat.ssStatus.dwWin32ExitCode = exitCode;
405 if ( ( currentState == SERVICE_RUNNING ) ||
406 ( currentState == SERVICE_STOPPED ) )
408 globdat.ssStatus.dwWaitHint = 0;
409 globdat.ssStatus.dwCheckPoint = 0;
414 globdat.ssStatus.dwWaitHint = waitHint;
415 globdat.ssStatus.dwCheckPoint = ++checkPoint;
417 rv = SetServiceStatus(globdat.hServiceStatus, &globdat.ssStatus);
423 /* handle the SCM's ControlService() callbacks to our service */
425 static VOID WINAPI service_nt_ctrl(DWORD dwCtrlCode)
427 if (dwCtrlCode == SERVICE_CONTROL_STOP)
430 globdat.ssStatus.dwCurrentState = SERVICE_STOP_PENDING;
431 ReportStatusToSCMgr(SERVICE_STOP_PENDING, NO_ERROR, 3000);
434 if (dwCtrlCode == SERVICE_APACHE_RESTART)
437 globdat.ssStatus.dwCurrentState = SERVICE_START_PENDING;
438 ReportStatusToSCMgr(SERVICE_START_PENDING, NO_ERROR, 3000);
442 ReportStatusToSCMgr(globdat.ssStatus.dwCurrentState, NO_ERROR, 0);
446 long __stdcall service_stderr_thread(LPVOID hPipe)
448 HANDLE hPipeRead = (HANDLE) hPipe;
451 char *errmsg = errbuf;
452 const char *errarg[9];
457 errarg[0] = "The Apache service named";
458 errarg[1] = display_name;
459 errarg[2] = "reported the following error:\r\n>>>";
461 errarg[4] = "<<<\r\n before the error.log file could be opened.\r\n";
462 errarg[5] = "More information may be available in the error.log file.";
467 /* What are we going to do in here, bail on the user? not. */
468 if (!RegCreateKey(HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Services"
469 "\\EventLog\\Application\\Apache Service", &hk))
471 /* The stock message file */
472 char *netmsgkey = "%SystemRoot%\\System32\\netmsg.dll";
473 DWORD dwData = EVENTLOG_ERROR_TYPE | EVENTLOG_WARNING_TYPE |
474 EVENTLOG_INFORMATION_TYPE;
476 RegSetValueEx(hk, "EventMessageFile", 0, REG_EXPAND_SZ,
477 (LPBYTE) netmsgkey, strlen(netmsgkey) + 1);
479 RegSetValueEx(hk, "TypesSupported", 0, REG_DWORD,
480 (LPBYTE) &dwData, sizeof(dwData));
484 hEventSource = RegisterEventSource(NULL, "Apache Service");
486 while (ReadFile(hPipeRead, errmsg, 1, &errres, NULL) && (errres == 1))
488 if ((errmsg > errbuf) || !isspace(*errmsg))
492 if ((*(errmsg - 1) == '\n') || (errlen == sizeof(errbuf) - 1))
494 while (errlen && isspace(errbuf[errlen - 1]))
496 errbuf[errlen] = '\0';
498 /* Generic message: '%1 %2 %3 %4 %5 %6 %7 %8 %9'
499 * The event code in netmsg.dll is 3299
501 ReportEvent(hEventSource, EVENTLOG_ERROR_TYPE, 0,
502 3299, NULL, 9, 0, errarg, NULL);
509 CloseHandle(hPipeRead);
514 /* service_nt_main_fn is outside of the call stack and outside of the
515 * primary server thread... so now we _really_ need a placeholder!
516 * The winnt_rewrite_args has created and shared mpm_new_argv with us.
518 extern apr_array_header_t *mpm_new_argv;
520 static void __stdcall service_nt_main_fn(DWORD argc, LPTSTR *argv)
523 HANDLE hCurrentProcess;
524 HANDLE hPipeRead = NULL;
525 HANDLE hPipeWrite = NULL;
529 SECURITY_ATTRIBUTES sa = {0};
531 /* args and service names live in the same pool */
532 mpm_service_set_name(mpm_new_argv->cont, argv[0]);
534 globdat.ssStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
535 globdat.ssStatus.dwCurrentState = SERVICE_START_PENDING;
536 globdat.ssStatus.dwServiceSpecificExitCode = 0;
537 globdat.ssStatus.dwCheckPoint = 1;
539 if (!(globdat.hServiceStatus = RegisterServiceCtrlHandler(argv[0], service_nt_ctrl)))
541 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, apr_get_os_error(),
542 NULL, "Failure registering service handler");
543 PulseEvent(globdat.signal_monitor);
547 ReportStatusToSCMgr(globdat.ssStatus.dwCurrentState, // service state
548 NO_ERROR, // exit code
549 3000); // wait hint, 3 seconds more
551 /* Create a pipe to send stderr messages to the system error log */
552 hCurrentProcess = GetCurrentProcess();
553 if (CreatePipe(&hPipeRead, &hPipeWrite, &sa, 0))
555 if (DuplicateHandle(hCurrentProcess, hPipeRead, hCurrentProcess,
556 &hPipeReadDup, 0, FALSE, DUPLICATE_SAME_ACCESS))
558 CloseHandle(hPipeRead);
559 hPipeRead = hPipeReadDup;
560 thread = CreateThread(NULL, 0, service_stderr_thread,
561 (LPVOID) hPipeRead, 0, &threadid);
568 SetStdHandle(STD_ERROR_HANDLE, hPipeWrite);
570 fh = _open_osfhandle((long) STD_ERROR_HANDLE,
571 _O_WRONLY | _O_BINARY);
572 dup2(fh, STDERR_FILENO);
573 fl = _fdopen(STDERR_FILENO, "wcb");
574 memcpy(stderr, fl, sizeof(FILE));
578 CloseHandle(hPipeRead);
579 CloseHandle(hPipeWrite);
585 CloseHandle(hPipeRead);
586 CloseHandle(hPipeWrite);
591 /* We need to append all the command arguments passed via StartService()
592 * to our running service... which just got here via the SCM...
593 * but we hvae no interest in argv[0] for the mpm_new_argv list.
599 mpm_new_argv->nalloc = mpm_new_argv->nelts + argc - 1;
600 cmb_data = apr_palloc(mpm_new_argv->cont,
601 mpm_new_argv->nalloc * sizeof(const char *));
603 /* mpm_new_argv remains first (of lower significance) */
604 memcpy (cmb_data, mpm_new_argv->elts,
605 mpm_new_argv->elt_size * mpm_new_argv->nelts);
607 /* Service args follow from StartService() invocation */
608 memcpy (cmb_data + mpm_new_argv->nelts, argv + 1,
609 mpm_new_argv->elt_size * (argc - 1));
611 /* The replacement arg list is complete */
612 mpm_new_argv->elts = (char *)cmb_data;
613 mpm_new_argv->nelts = mpm_new_argv->nalloc;
616 /* Let the main thread continue now... but hang on to the
617 * signal_monitor event so we can take further action
619 SetEvent(globdat.signal_monitor);
621 waitfor[0] = globdat.signal_monitor;
622 waitfor[1] = globdat.mpm_thread;
623 WaitForMultipleObjects(2, waitfor, FALSE, INFINITE);
624 /* The process is ready to terminate, or already has */
626 CloseHandle(hPipeWrite);
630 DWORD WINAPI service_nt_dispatch_thread(LPVOID nada)
632 apr_status_t rv = APR_SUCCESS;
634 SERVICE_TABLE_ENTRY dispatchTable[] =
636 { "", service_nt_main_fn },
640 if (!StartServiceCtrlDispatcher(dispatchTable))
642 /* This is a genuine failure of the SCM. */
643 rv = apr_get_os_error();
644 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, rv, NULL,
645 "Error starting service control dispatcher");
648 globdat.service_thread_id = 0;
653 apr_status_t mpm_service_set_name(apr_pool_t *p, const char *name)
657 service_name = apr_palloc(p, strlen(name) + 1);
658 apr_collapse_spaces((char*) service_name, name);
659 key_name = apr_psprintf(p, SERVICECONFIG, service_name);
660 if (ap_registry_get_value(p, key_name, "DisplayName", (char**)&display_name) == APR_SUCCESS)
663 /* Take the given literal name if there is no service entry */
664 display_name = apr_pstrdup(p, name);
669 apr_status_t mpm_merge_service_args(apr_pool_t *p,
670 apr_array_header_t *args,
673 apr_array_header_t *svc_args = NULL;
674 char conf_key[MAX_PATH];
678 apr_snprintf(conf_key, sizeof(conf_key), SERVICEPARAMS, service_name);
679 rv = ap_registry_get_array(p, conf_key, "ConfigArgs", &svc_args);
680 if (rv != APR_SUCCESS) {
681 if (rv == ERROR_FILE_NOT_FOUND) {
682 ap_log_error(APLOG_MARK, APLOG_INFO|APLOG_NOERRNO, 0, NULL,
683 "No ConfigArgs registered for %s, perhaps "
684 "this service is not installed?",
692 if (!svc_args || svc_args->nelts == 0) {
693 return (APR_SUCCESS);
696 /* Now we have the service_name arg, and the mpm_runservice_nt()
697 * call appended the arguments passed by StartService(), so it's
698 * time to _prepend_ the default arguments for the server from
699 * the service's default arguments (all others override them)...
701 args->nalloc = args->nelts + svc_args->nelts;
702 cmb_data = apr_palloc(p, args->nalloc * sizeof(const char *));
704 /* First three args (argv[0], -f, path) remain first */
705 memcpy(cmb_data, args->elts, args->elt_size * fixed_args);
707 /* Service args follow from service registry array */
708 memcpy(cmb_data + fixed_args, svc_args->elts,
709 svc_args->elt_size * svc_args->nelts);
711 /* Remaining new args follow */
712 memcpy(cmb_data + fixed_args + svc_args->nelts,
713 (const char **)args->elts + fixed_args,
714 args->elt_size * (args->nelts - fixed_args));
716 args->elts = (char *)cmb_data;
717 args->nelts = args->nalloc;
723 void service_stopped(void)
725 /* Still have a thread & window to clean up, so signal now */
726 if (globdat.service_thread_id)
728 if (osver.dwPlatformId == VER_PLATFORM_WIN32_NT)
730 ReportStatusToSCMgr(SERVICE_STOPPED, // service state
731 NO_ERROR, // exit code
734 /* Cause the service_nt_main_fn to complete */
735 SetEvent(globdat.signal_monitor);
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(void)
753 globdat.mpm_thread = GetCurrentThread();
755 if (osver.dwPlatformId == VER_PLATFORM_WIN32_NT)
757 globdat.signal_monitor = CreateEvent(NULL, FALSE, FALSE, NULL);
758 if (globdat.signal_monitor)
759 globdat.service_thread = CreateThread(NULL, 0,
760 service_nt_dispatch_thread,
762 &globdat.service_thread_id);
764 else /* osver.dwPlatformId != VER_PLATFORM_WIN32_NT */
766 if (!RegisterServiceProcess(0, 1))
767 return GetLastError();
769 globdat.signal_monitor = CreateEvent(NULL, FALSE, FALSE, NULL);
770 if (globdat.signal_monitor)
771 globdat.service_thread = CreateThread(NULL, 0,
772 monitor_service_9x_thread,
773 (LPVOID) service_name, 0,
774 &globdat.service_thread_id);
777 if (globdat.signal_monitor && globdat.service_thread)
779 waitfor[0] = globdat.signal_monitor;
780 waitfor[1] = globdat.service_thread;
782 /* SetEvent(globdat.signal_monitor) to clean up the SCM thread */
783 if (WaitForMultipleObjects(2, waitfor, FALSE, 10000) != WAIT_OBJECT_0) {
784 CloseHandle(globdat.service_thread);
785 return APR_ENOTHREAD;
789 if (globdat.service_thread_id)
790 atexit(service_stopped);
791 else if (globdat.service_thread)
792 CloseHandle(globdat.service_thread);
798 apr_status_t mpm_service_started(void)
800 if (osver.dwPlatformId == VER_PLATFORM_WIN32_NT)
802 ReportStatusToSCMgr(SERVICE_RUNNING, // service state
803 NO_ERROR, // exit code
810 void mpm_service_stopping(void)
812 if (osver.dwPlatformId == VER_PLATFORM_WIN32_NT)
813 ReportStatusToSCMgr(SERVICE_STOP_PENDING, // service state
814 NO_ERROR, // exit code
819 apr_status_t mpm_service_install(apr_pool_t *ptemp, int argc,
820 const char * const * argv)
822 char key_name[MAX_PATH];
823 char exe_path[MAX_PATH];
827 printf("Installing the %s service\n", display_name);
829 if (GetModuleFileName(NULL, exe_path, sizeof(exe_path)) == 0)
831 apr_status_t rv = apr_get_os_error();
832 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, rv, NULL,
833 "GetModuleFileName failed");
837 if (osver.dwPlatformId == VER_PLATFORM_WIN32_NT)
839 SC_HANDLE schService;
840 SC_HANDLE schSCManager;
842 // TODO: Determine the minimum permissions required for security
843 schSCManager = OpenSCManager(NULL, NULL, /* local, default database */
844 SC_MANAGER_ALL_ACCESS);
846 rv = apr_get_os_error();
847 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, rv, NULL,
848 "Failed to open the WinNT service manager");
852 launch_cmd = apr_psprintf(ptemp, "\"%s\" -k runservice", exe_path);
854 /* RPCSS is the Remote Procedure Call (RPC) Locator required for DCOM
855 * communication pipes. I am far from convinced we should add this to
856 * the default service dependencies, but be warned that future apache
857 * modules or ISAPI dll's may depend on it.
859 schService = CreateService(schSCManager, // SCManager database
860 service_name, // name of service
861 display_name, // name to display
862 SERVICE_ALL_ACCESS, // access required
863 SERVICE_WIN32_OWN_PROCESS, // service type
864 SERVICE_AUTO_START, // start type
865 SERVICE_ERROR_NORMAL, // error control type
866 launch_cmd, // service's binary
867 NULL, // no load svc group
868 NULL, // no tag identifier
869 "Tcpip\0Afd\0", // dependencies
870 NULL, // use SYSTEM account
871 NULL); // no password
875 rv = apr_get_os_error();
876 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, rv, NULL,
877 "Failed to create WinNT Service Profile");
878 CloseServiceHandle(schSCManager);
882 CloseServiceHandle(schService);
883 CloseServiceHandle(schSCManager);
885 else /* osver.dwPlatformId != VER_PLATFORM_WIN32_NT */
887 /* Store the launch command in the registry */
888 launch_cmd = apr_psprintf(ptemp, "\"%s\" -n %s -k runservice",
889 exe_path, service_name);
890 rv = ap_registry_store_value(SERVICECONFIG9X, service_name, launch_cmd);
891 if (rv != APR_SUCCESS) {
892 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, rv, NULL,
893 "%s: Failed to add the RunServices registry entry.",
898 apr_snprintf(key_name, sizeof(key_name), SERVICECONFIG, service_name);
899 rv = ap_registry_store_value(key_name, "DisplayName", display_name);
900 if (rv != APR_SUCCESS) {
901 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, rv, NULL,
902 "%s: Failed to store DisplayName in the registry.",
908 /* For both WinNT & Win9x store the service ConfigArgs in the registry...
910 apr_snprintf(key_name, sizeof(key_name), SERVICEPARAMS, service_name);
911 rv = ap_registry_store_array(ptemp, key_name, "ConfigArgs", argc, argv);
912 if (rv != APR_SUCCESS) {
913 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, rv, NULL,
914 "%s: Failed to store the ConfigArgs in the registry.",
918 printf("The %s service is successfully installed.\n", display_name);
922 apr_status_t mpm_service_uninstall(void)
924 char key_name[MAX_PATH];
927 if (osver.dwPlatformId == VER_PLATFORM_WIN32_NT)
929 SC_HANDLE schService;
930 SC_HANDLE schSCManager;
932 printf("Removing the %s service\n", display_name);
934 // TODO: Determine the minimum permissions required for security
935 schSCManager = OpenSCManager(NULL, NULL, /* local, default database */
936 SC_MANAGER_ALL_ACCESS);
938 rv = apr_get_os_error();
939 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, rv, NULL,
940 "Failed to open the WinNT service manager.");
944 schService = OpenService(schSCManager, service_name, SERVICE_ALL_ACCESS);
947 rv = apr_get_os_error();
948 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, rv, NULL,
949 "%s: OpenService failed", display_name);
953 /* assure the service is stopped before continuing
955 * This may be out of order... we might not be able to be
956 * granted all access if the service is running anyway.
958 * And do we want to make it *this easy* for them
959 * to uninstall their service unintentionally?
961 // ap_stop_service(schService);
963 if (DeleteService(schService) == 0) {
964 rv = apr_get_os_error();
965 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, rv, NULL,
966 "%s: Failed to delete the service.", display_name);
970 CloseServiceHandle(schService);
971 CloseServiceHandle(schSCManager);
973 else /* osver.dwPlatformId != VER_PLATFORM_WIN32_NT */
975 printf("Removing the %s service\n", display_name);
977 /* TODO: assure the service is stopped before continuing */
979 if (ap_registry_delete_value(SERVICECONFIG9X, service_name)) {
980 rv = apr_get_os_error();
981 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, rv, NULL,
982 "%s: Failed to remove the RunServices registry "
983 "entry.", display_name);
987 /* we blast Services/us, not just the Services/us/Parameters branch */
988 apr_snprintf(key_name, sizeof(key_name), SERVICECONFIG, service_name);
989 if (ap_registry_delete_key(key_name))
991 rv = apr_get_os_error();
992 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, rv, NULL,
993 "%s: Failed to remove the service config from the "
994 "registry.", display_name);
998 printf("The %s service has been removed successfully.\n", display_name);
1003 /* signal_service_transition is a simple thunk to signal the service
1004 * and monitor it's successful transition. If the signal passed is 0,
1005 * then the caller is assumed to already have performed some service
1006 * operation to be monitored (such as StartService), and no actual
1007 * ControlService signal is sent.
1010 static int signal_service_transition(SC_HANDLE schService, DWORD signal, DWORD pending, DWORD complete)
1012 if (signal && !ControlService(schService, signal, &globdat.ssStatus))
1017 if (!QueryServiceStatus(schService, &globdat.ssStatus))
1019 } while (globdat.ssStatus.dwCurrentState == pending);
1021 return (globdat.ssStatus.dwCurrentState == complete);
1025 apr_status_t mpm_service_start(apr_pool_t *ptemp, int argc,
1026 const char * const * argv)
1030 printf("Starting the %s service\n", display_name);
1032 if (osver.dwPlatformId == VER_PLATFORM_WIN32_NT)
1035 SC_HANDLE schService;
1036 SC_HANDLE schSCManager;
1038 // TODO: Determine the minimum permissions required for security
1039 schSCManager = OpenSCManager(NULL, NULL, /* local, default database */
1040 SC_MANAGER_ALL_ACCESS);
1041 if (!schSCManager) {
1042 rv = apr_get_os_error();
1043 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, rv, NULL,
1044 "Failed to open the WinNT service manager");
1048 schService = OpenService(schSCManager, service_name,
1049 SERVICE_START | SERVICE_QUERY_STATUS);
1051 rv = apr_get_os_error();
1052 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, rv, NULL,
1053 "%s: Failed to open the service.", display_name);
1054 CloseServiceHandle(schSCManager);
1058 if (QueryServiceStatus(schService, &globdat.ssStatus)
1059 && (globdat.ssStatus.dwCurrentState == SERVICE_RUNNING)) {
1060 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, 0, NULL,
1061 "Service %s is already started!", display_name);
1062 CloseServiceHandle(schService);
1063 CloseServiceHandle(schSCManager);
1068 start_argv = apr_palloc(ptemp, argc * sizeof(const char **));
1069 start_argv[0] = service_name;
1071 memcpy(start_argv + 1, argv, (argc - 1) * sizeof(const char **));
1074 if (StartService(schService, argc, start_argv)
1075 && signal_service_transition(schService, 0, /* test only */
1076 SERVICE_START_PENDING,
1080 if (rv != APR_SUCCESS)
1081 rv = apr_get_os_error();
1083 CloseServiceHandle(schService);
1084 CloseServiceHandle(schSCManager);
1086 else /* osver.dwPlatformId != VER_PLATFORM_WIN32_NT */
1088 STARTUPINFO si; /* Filled in prior to call to CreateProcess */
1089 PROCESS_INFORMATION pi; /* filled in on call to CreateProcess */
1090 char exe_path[MAX_PATH];
1094 /* Locate the active top level window named service_name
1095 * provided the class is ApacheWin95ServiceMonitor
1097 if (FindWindow("ApacheWin95ServiceMonitor", service_name)) {
1098 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, 0, NULL,
1099 "Service %s is already started!", display_name);
1103 /* This may not appear intuitive, but Win9x will not allow a process
1104 * to detach from the console without releasing the entire console.
1105 * Ergo, we must spawn a new process for the service to get back our
1107 * The config is pre-flighted, so there should be no danger of failure.
1110 if (GetModuleFileName(NULL, exe_path, sizeof(exe_path)) == 0)
1112 apr_status_t rv = apr_get_os_error();
1113 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, rv, NULL,
1114 "GetModuleFileName failed");
1118 pCommand = apr_psprintf(ptemp, "\"%s\" -n %s -k runservice",
1119 exe_path, service_name);
1120 for (i = 0; i < argc; ++i) {
1121 pCommand = apr_pstrcat(ptemp, pCommand,
1122 " \"", argv[i], "\"", NULL);
1125 memset(&si, 0, sizeof(si));
1126 memset(&pi, 0, sizeof(pi));
1128 si.dwFlags = STARTF_USESHOWWINDOW;
1129 si.wShowWindow = SW_HIDE; /* This might be redundant */
1132 if (CreateProcess(NULL, pCommand, NULL, NULL, FALSE,
1133 DETACHED_PROCESS, /* Creation flags */
1134 NULL, NULL, &si, &pi))
1137 while (GetExitCodeProcess(pi.hProcess, &code) == STILL_ACTIVE) {
1138 if (FindWindow("ApacheWin95ServiceMonitor", service_name)) {
1146 if (rv != APR_SUCCESS)
1147 rv = apr_get_os_error();
1149 CloseHandle(pi.hProcess);
1150 CloseHandle(pi.hThread);
1153 if (rv == APR_SUCCESS)
1154 printf("The %s service is running.\n", display_name);
1156 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, NULL,
1157 "%s: Failed to start the service process.",
1164 /* signal is zero to stop, non-zero for restart */
1166 void mpm_signal_service(apr_pool_t *ptemp, int signal)
1168 int success = FALSE;
1170 if (osver.dwPlatformId == VER_PLATFORM_WIN32_NT)
1172 SC_HANDLE schService;
1173 SC_HANDLE schSCManager;
1175 schSCManager = OpenSCManager(NULL, NULL, // default machine & database
1176 SC_MANAGER_ALL_ACCESS);
1178 if (!schSCManager) {
1179 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, apr_get_os_error(), NULL,
1180 "Failed to open the NT Service Manager");
1184 schService = OpenService(schSCManager, service_name,
1185 SERVICE_ALL_ACCESS);
1187 if (schService == NULL) {
1188 /* Could not open the service */
1189 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, apr_get_os_error(), NULL,
1190 "Failed to open the %s Service", display_name);
1191 CloseServiceHandle(schSCManager);
1195 if (!QueryServiceStatus(schService, &globdat.ssStatus)) {
1196 ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, apr_get_os_error(), NULL,
1197 "Query of Service %s failed", display_name);
1198 CloseServiceHandle(schService);
1199 CloseServiceHandle(schSCManager);
1203 if (!signal && (globdat.ssStatus.dwCurrentState == SERVICE_STOPPED)) {
1204 printf("The %s service is not started.\n", display_name);
1205 CloseServiceHandle(schService);
1206 CloseServiceHandle(schSCManager);
1210 printf("The %s service is %s.\n", display_name,
1211 signal ? "restarting" : "stopping");
1214 success = signal_service_transition(schService,
1215 SERVICE_CONTROL_STOP,
1216 SERVICE_STOP_PENDING,
1218 else if (globdat.ssStatus.dwCurrentState == SERVICE_STOPPED) {
1219 mpm_service_start(ptemp, 0, NULL);
1220 CloseServiceHandle(schService);
1221 CloseServiceHandle(schSCManager);
1225 success = signal_service_transition(schService,
1226 SERVICE_APACHE_RESTART,
1227 SERVICE_START_PENDING,
1230 CloseServiceHandle(schService);
1231 CloseServiceHandle(schSCManager);
1233 else /* !isWindowsNT() */
1238 /* Locate the active top level window named service_name
1239 * provided the class is ApacheWin95ServiceMonitor
1241 hwnd = FindWindow("ApacheWin95ServiceMonitor", service_name);
1242 if (hwnd && GetWindowThreadProcessId(hwnd, &service_pid))
1243 globdat.ssStatus.dwCurrentState = SERVICE_RUNNING;
1246 globdat.ssStatus.dwCurrentState = SERVICE_STOPPED;
1248 printf("The %s service is not started.\n", display_name);
1253 printf("The %s service is %s.\n", display_name,
1254 signal ? "restarting" : "stopping");
1256 apr_snprintf(prefix, sizeof(prefix), "ap%ld", (long)service_pid);
1257 setup_signal_names(prefix);
1262 ap_start_shutdown();
1265 if (!IsWindow(hwnd)) {
1274 /* TODO: Aught to add a little test to the restart logic, and
1275 * store the restart counter in the window's user dword.
1276 * Then we can hang on and report a successful restart. But
1277 * that's a project for another day.
1279 if (globdat.ssStatus.dwCurrentState == SERVICE_STOPPED) {
1280 mpm_service_start(ptemp, 0, NULL);
1285 ap_start_restart(1);
1291 printf("The %s service has %s.\n", display_name,
1292 signal ? "restarted" : "stopped");
1294 printf("Failed to %s the %s service.\n",
1295 signal ? "restart" : "stop", display_name);