]> granicus.if.org Git - apache/blob - server/mpm/winnt/service.c
update license to 2004.
[apache] / server / mpm / winnt / service.c
1 /* ====================================================================
2  * The Apache Software License, Version 1.1
3  *
4  * Copyright (c) 2000-2004 The Apache Software Foundation.  All rights
5  * reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  *
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
17  *    distribution.
18  *
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.
25  *
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.
30  *
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.
34  *
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
46  * SUCH DAMAGE.
47  * ====================================================================
48  *
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/>.
53  *
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.
57  */
58
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...
62  */
63
64 #define CORE_PRIVATE 
65 #define _WINUSER_
66
67 #include "httpd.h"
68 #include "http_log.h"
69 #include "mpm_winnt.h"
70 #include "apr_strings.h"
71 #include "apr_lib.h"
72 #include "ap_regkey.h"
73
74 #ifdef NOUSER
75 #undef NOUSER
76 #endif
77 #undef _WINUSER_
78 #include <winuser.h>
79
80 static char *mpm_service_name = NULL;
81 static char *mpm_display_name = NULL;
82
83 static struct
84 {
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;
92 } globdat;
93
94 static int ReportStatusToSCMgr(int currentState, int exitCode, int waitHint);
95
96
97 #define PRODREGKEY "SOFTWARE\\" AP_SERVER_BASEVENDOR "\\" \
98                    AP_SERVER_BASEPRODUCT "\\" AP_SERVER_BASEREVISION
99
100 /*
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.
106  */
107 apr_status_t ap_registry_get_server_root(apr_pool_t *p, char **buf)
108 {
109     apr_status_t rv;
110     ap_regkey_t *key;
111
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) 
117             return rv;
118     }
119
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) 
125             return rv;
126     }
127
128     *buf = NULL;
129     return rv;
130 }
131
132
133 /* The service configuration's is stored under the following trees:
134  *
135  * HKLM\System\CurrentControlSet\Services\[service name]
136  *
137  *     \DisplayName
138  *     \ImagePath
139  *     \Parameters\ConfigArgs
140  *
141  * For Win9x, the launch service command is stored under:
142  *
143  * HKLM\Software\Microsoft\Windows\CurrentVersion\RunServices\[service name]
144  */
145
146
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.
150  *
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.
154  *
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.
158  */
159 AP_DECLARE_DATA int real_exit_code = 1;
160
161 void hold_console_open_on_error(void)
162 {
163     HANDLE hConIn;
164     HANDLE hConErr;
165     DWORD result;
166     time_t start;
167     time_t remains;
168     char *msg = "Note the errors or messages above, "
169                 "and press the <ESC> key to exit.  ";
170     CONSOLE_SCREEN_BUFFER_INFO coninfo;
171     INPUT_RECORD in;
172     char count[16];
173     
174     if (!real_exit_code)
175         return;
176     hConIn = GetStdHandle(STD_INPUT_HANDLE);
177     hConErr = GetStdHandle(STD_ERROR_HANDLE);
178     if ((hConIn == INVALID_HANDLE_VALUE) || (hConErr == INVALID_HANDLE_VALUE))
179         return;
180     if (!WriteConsole(hConErr, msg, strlen(msg), &result, NULL) || !result)
181         return;
182     if (!GetConsoleScreenBufferInfo(hConErr, &coninfo))
183         return;
184     if (!SetConsoleMode(hConIn, ENABLE_MOUSE_INPUT | 0x80))
185         return;
186         
187     start = time(NULL);
188     do
189     {
190         while (PeekConsoleInput(hConIn, &in, 1, &result) && result)
191         {
192             if (!ReadConsoleInput(hConIn, &in, 1, &result) || !result)
193                 return;
194             if ((in.EventType == KEY_EVENT) && in.Event.KeyEvent.bKeyDown 
195                     && (in.Event.KeyEvent.uChar.AsciiChar == 27))
196                 return;
197             if (in.EventType == MOUSE_EVENT 
198                     && (in.Event.MouseEvent.dwEventFlags == DOUBLE_CLICK))
199                 return;
200         }
201         remains = ((start + 30) - time(NULL)); 
202         sprintf (count, "%d...", remains);
203         if (!SetConsoleCursorPosition(hConErr, coninfo.dwCursorPosition))
204             return;
205         if (!WriteConsole(hConErr, count, strlen(count), &result, NULL) 
206                 || !result)
207             return;
208     }
209     while ((remains > 0) && WaitForSingleObject(hConIn, 1000) != WAIT_FAILED);
210 }
211
212 static BOOL  die_on_logoff = FALSE;
213
214 static LRESULT CALLBACK monitor_service_9x_proc(HWND hWnd, UINT msg, 
215                                                 WPARAM wParam, LPARAM lParam)
216 {
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.
221  */
222     if ((msg == WM_ENDSESSION) 
223             && (die_on_logoff || (lParam != ENDSESSION_LOGOFF)))
224     {
225         ap_signal_parent(SIGNAL_PARENT_SHUTDOWN);
226         if (wParam)
227             /* Don't leave this message until we are dead! */
228             WaitForSingleObject(globdat.mpm_thread, 30000);
229         return 0;
230     }
231     return (DefWindowProc(hWnd, msg, wParam, lParam));
232 }
233
234 static DWORD WINAPI monitor_service_9x_thread(void *service_name)
235 {
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.
244      */
245     WNDCLASS wc;
246     HWND hwndMain;
247     MSG msg;
248     
249     wc.style         = CS_GLOBALCLASS;
250     wc.lpfnWndProc   = monitor_service_9x_proc; 
251     wc.cbClsExtra    = 0;
252     wc.cbWndExtra    = 0; 
253     wc.hInstance     = NULL;
254     wc.hIcon         = NULL;
255     wc.hCursor       = NULL;
256     wc.hbrBackground = NULL;
257     wc.lpszMenuName  = NULL;
258     if (service_name)
259         wc.lpszClassName = "ApacheWin95ServiceMonitor";
260     else
261         wc.lpszClassName = "ApacheWin95SystemMonitor";
262  
263     die_on_logoff = service_name ? FALSE : TRUE;
264
265     if (!RegisterClass(&wc)) 
266     {
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;
270         return 0;
271     }
272     
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);
279                             
280     if (!hwndMain)
281     {
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;
285         return 0;
286     }
287
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.
291      */
292     FreeConsole();
293     SetEvent(globdat.service_init);
294
295     while (GetMessage(&msg, NULL, 0, 0)) 
296     {
297         if (msg.message == WM_CLOSE)
298             DestroyWindow(hwndMain); 
299         else {
300             TranslateMessage(&msg);
301             DispatchMessage(&msg);
302         }
303     }
304     globdat.service_thread_id = 0;
305     return 0;
306 }
307
308
309 static BOOL CALLBACK console_control_handler(DWORD ctrl_type)
310 {
311     switch (ctrl_type)
312     {
313         case CTRL_BREAK_EVENT:
314             fprintf(stderr, "Apache server restarting...\n");
315             ap_signal_parent(SIGNAL_PARENT_RESTART);
316             return TRUE;
317         case CTRL_C_EVENT:
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.
322              */
323             ap_signal_parent(SIGNAL_PARENT_SHUTDOWN);
324             return TRUE;
325
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!
334              */
335             fprintf(stderr, "Apache server shutdown initiated...\n");
336             ap_signal_parent(SIGNAL_PARENT_SHUTDOWN);
337             Sleep(30000);
338             return TRUE;
339     }
340  
341     /* We should never get here, but this is (mostly) harmless */
342     return FALSE;
343 }
344
345
346 static void stop_console_handler(void)
347 {
348     SetConsoleCtrlHandler(console_control_handler, FALSE);
349 }
350
351
352 void mpm_start_console_handler(void)
353 {
354     SetConsoleCtrlHandler(console_control_handler, TRUE);
355     atexit(stop_console_handler);
356 }
357
358
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...
362  */
363
364 static BOOL CALLBACK child_control_handler(DWORD ctrl_type)
365 {
366     switch (ctrl_type)
367     {
368         case CTRL_C_EVENT:
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.
373              */
374             return TRUE;
375
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.
382              */
383             Sleep(30000);
384             return TRUE;
385     }
386  
387     /* We should never get here, but this is (mostly) harmless */
388     return FALSE;
389 }
390
391
392 static void stop_child_console_handler(void)
393 {
394     SetConsoleCtrlHandler(child_control_handler, FALSE);
395 }
396
397
398 void mpm_start_child_console_handler(void)
399 {
400     if (osver.dwPlatformId == VER_PLATFORM_WIN32_NT) {
401         FreeConsole();
402     }
403     else
404     {
405         SetConsoleCtrlHandler(child_control_handler, TRUE);
406         atexit(stop_child_console_handler);
407     }
408 }
409
410
411 /**********************************
412   WinNT service control management
413  **********************************/
414
415 static int ReportStatusToSCMgr(int currentState, int exitCode, int waitHint)
416 {
417     static int checkPoint = 1;
418     int rv = APR_SUCCESS;
419     
420     if (globdat.hServiceStatus)
421     {
422         if (currentState == SERVICE_RUNNING) {
423             globdat.ssStatus.dwWaitHint = 0;
424             globdat.ssStatus.dwCheckPoint = 0;
425             globdat.ssStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;
426         }
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! */
433                 exitCode = 1;
434             }
435             if (exitCode) {
436                 globdat.ssStatus.dwWin32ExitCode =ERROR_SERVICE_SPECIFIC_ERROR;
437                 globdat.ssStatus.dwServiceSpecificExitCode = exitCode;
438             }
439         }
440         else {
441             globdat.ssStatus.dwCheckPoint = ++checkPoint;
442             globdat.ssStatus.dwControlsAccepted = 0;
443             if(waitHint)
444                 globdat.ssStatus.dwWaitHint = waitHint;
445         }
446
447         globdat.ssStatus.dwCurrentState = currentState;
448         
449         rv = SetServiceStatus(globdat.hServiceStatus, &globdat.ssStatus);
450     }
451     return(rv);
452 }
453
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.
459  */
460
461 /* borrowed from mpm_winnt.c */
462 extern apr_pool_t *pconf;
463
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.
467  */
468 static void set_service_description(void)
469 {
470     const char *full_description;
471     SC_HANDLE schSCManager;
472     BOOL ret = 0;
473
474     /* Nothing to do if we are a console
475      */
476     if (!mpm_service_name)
477         return;
478
479     /* Time to fix up the description, upon each successful restart
480      */
481     full_description = ap_get_server_version();
482
483     if ((osver.dwPlatformId == VER_PLATFORM_WIN32_NT) 
484           && (osver.dwMajorVersion > 4) 
485           && (ChangeServiceConfig2)
486           && (schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT)))
487     {    
488         SC_HANDLE schService = OpenService(schSCManager, mpm_service_name,
489                                            SERVICE_CHANGE_CONFIG);
490         if (schService) {
491             /* Cast is necessary, ChangeServiceConfig2 handles multiple
492              * object types, some volatile, some not.
493              */
494             /* ###: utf-ize */
495             if (ChangeServiceConfig2(schService,
496                                      1 /* SERVICE_CONFIG_DESCRIPTION */,
497                                      (LPVOID) &full_description)) {
498                 full_description = NULL;
499             }
500             CloseServiceHandle(schService);
501         }
502         CloseServiceHandle(schSCManager);
503     }
504
505     if (full_description) 
506     {
507         char szPath[MAX_PATH];
508         ap_regkey_t *svckey;
509         apr_status_t rv;
510
511         /* Find the Service key that Monitor Applications iterate */
512         apr_snprintf(szPath, sizeof(szPath), 
513                      "SYSTEM\\CurrentControlSet\\Services\\%s", 
514                      mpm_service_name);
515         rv = ap_regkey_open(&svckey, AP_REGKEY_LOCAL_MACHINE, szPath,
516                             APR_READ | APR_WRITE, pconf);
517         if (rv != APR_SUCCESS) {
518             return;
519         }
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);
523     }
524 }
525
526 /* handle the SCM's ControlService() callbacks to our service */
527
528 static VOID WINAPI service_nt_ctrl(DWORD dwCtrlCode)
529 {
530     if (dwCtrlCode == SERVICE_CONTROL_STOP)
531     {
532         ap_signal_parent(SIGNAL_PARENT_SHUTDOWN);
533         ReportStatusToSCMgr(SERVICE_STOP_PENDING, NO_ERROR, 30000);
534         return;
535     }
536     if (dwCtrlCode == SERVICE_APACHE_RESTART)
537     {
538         ap_signal_parent(SIGNAL_PARENT_RESTART);
539         ReportStatusToSCMgr(SERVICE_START_PENDING, NO_ERROR, 30000);
540         return;
541     }
542     
543     ReportStatusToSCMgr(globdat.ssStatus.dwCurrentState, NO_ERROR, 0);            
544 }
545
546
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.
550  */
551 extern apr_array_header_t *mpm_new_argv;
552
553 /* ###: utf-ize */
554 static void __stdcall service_nt_main_fn(DWORD argc, LPTSTR *argv)
555 {
556     const char *ignored;
557
558     /* args and service names live in the same pool */
559     mpm_service_set_name(mpm_new_argv->pool, &ignored, argv[0]);
560
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;
565
566     /* ###: utf-ize */
567     if (!(globdat.hServiceStatus = RegisterServiceCtrlHandler(argv[0], service_nt_ctrl)))
568     {
569         ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, apr_get_os_error(), 
570                      NULL, "Failure registering service handler");
571         return;
572     }
573
574     /* Report status, no errors, and buy 3 more seconds */
575     ReportStatusToSCMgr(SERVICE_START_PENDING, NO_ERROR, 30000);
576
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.
580      */
581     if (argc > 1) 
582     {
583         char **cmb_data;
584
585         mpm_new_argv->nalloc = mpm_new_argv->nelts + argc - 1;
586         cmb_data = malloc(mpm_new_argv->nalloc * sizeof(const char *));
587
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);
591         
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));
595         
596         /* The replacement arg list is complete */
597         mpm_new_argv->elts = (char *)cmb_data;
598         mpm_new_argv->nelts = mpm_new_argv->nalloc;
599     }
600
601     /* Let the main thread continue now... but hang on to the
602      * signal_monitor event so we can take further action
603      */
604     SetEvent(globdat.service_init);
605
606     WaitForSingleObject(globdat.service_term, INFINITE);
607 }
608
609
610 DWORD WINAPI service_nt_dispatch_thread(LPVOID nada)
611 {
612     apr_status_t rv = APR_SUCCESS;
613
614     SERVICE_TABLE_ENTRY dispatchTable[] =
615     {
616         { "", service_nt_main_fn },
617         { NULL, NULL }
618     };
619
620     /* ###: utf-ize */
621     if (!StartServiceCtrlDispatcher(dispatchTable))
622     {
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");
627     }
628
629     return (rv);
630 }
631
632
633 apr_status_t mpm_service_set_name(apr_pool_t *p, const char **display_name, 
634                                   const char *set_name)
635 {
636     char key_name[MAX_PATH];
637     ap_regkey_t *key;
638     apr_status_t rv;
639
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!
643      */
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);
651     }
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);
655     } 
656     *display_name = mpm_display_name;
657     return rv;
658 }
659
660
661 apr_status_t mpm_merge_service_args(apr_pool_t *p, 
662                                    apr_array_header_t *args, 
663                                    int fixed_args)
664 {
665     apr_array_header_t *svc_args = NULL;
666     char conf_key[MAX_PATH];
667     char **cmb_data;
668     apr_status_t rv;
669     ap_regkey_t *key;
670
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);
676     }
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?", 
682                          mpm_service_name);
683             return APR_SUCCESS;
684         }
685         else
686             return (rv);        
687     }
688
689     if (!svc_args || svc_args->nelts == 0) {
690         return (APR_SUCCESS);
691     }
692
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)...
697      */
698     args->nalloc = args->nelts + svc_args->nelts;
699     cmb_data = malloc(args->nalloc * sizeof(const char *));
700
701     /* First three args (argv[0], -f, path) remain first */
702     memcpy(cmb_data, args->elts, args->elt_size * fixed_args);
703     
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);
707     
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));
712     
713     args->elts = (char *)cmb_data;
714     args->nelts = args->nalloc;
715
716     return APR_SUCCESS;
717 }
718
719
720 void service_stopped(void)
721 {
722     /* Still have a thread & window to clean up, so signal now */
723     if (globdat.service_thread)
724     {
725         if (osver.dwPlatformId == VER_PLATFORM_WIN32_NT)
726         {
727             /* Stop logging to the event log */
728             mpm_nt_eventlog_stderr_flush();
729
730             /* Cause the service_nt_main_fn to complete */
731             ReleaseMutex(globdat.service_term);
732
733             ReportStatusToSCMgr(SERVICE_STOPPED, // service state
734                                 NO_ERROR,        // exit code
735                                 0);              // wait hint
736         }
737         else /* osver.dwPlatformId != VER_PLATFORM_WIN32_NT */
738         {
739             RegisterServiceProcess(0, 0);
740             PostThreadMessage(globdat.service_thread_id, WM_CLOSE, 0, 0);
741         }
742
743         WaitForSingleObject(globdat.service_thread, 5000);
744         CloseHandle(globdat.service_thread);
745     }
746 }
747
748
749 apr_status_t mpm_service_to_start(const char **display_name, apr_pool_t *p)
750 {
751     HANDLE hProc = GetCurrentProcess();
752     HANDLE hThread = GetCurrentThread();
753     HANDLE waitfor[2];
754
755     /* Prevent holding open the (hidden) console */
756     real_exit_code = 0;
757
758      /* GetCurrentThread returns a psuedo-handle, we need
759       * a real handle for another thread to wait upon.
760       */
761     if (!DuplicateHandle(hProc, hThread, hProc, &(globdat.mpm_thread),
762                          0, FALSE, DUPLICATE_SAME_ACCESS)) {
763         return APR_ENOTHREAD;
764     }
765     
766     if (osver.dwPlatformId == VER_PLATFORM_WIN32_NT)
767     {
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) {
771              return APR_EGENERAL;
772         }
773
774         globdat.service_thread = CreateThread(NULL, 0, service_nt_dispatch_thread, 
775                                               NULL, 0, &globdat.service_thread_id);
776     }
777     else /* osver.dwPlatformId != VER_PLATFORM_WIN32_NT */
778     {
779         if (!RegisterServiceProcess(0, 1)) 
780             return GetLastError();
781
782         globdat.service_init = CreateEvent(NULL, FALSE, FALSE, NULL);
783         if (!globdat.service_init) {
784             return APR_EGENERAL;
785         }
786
787         globdat.service_thread = CreateThread(NULL, 0, monitor_service_9x_thread, 
788                                               (LPVOID) mpm_service_name, 0,
789                                               &globdat.service_thread_id);
790     }
791
792     if (!globdat.service_thread) {
793         return APR_ENOTHREAD;
794     }
795
796     waitfor[0] = globdat.service_init;
797     waitfor[1] = globdat.service_thread;
798
799     /* Wait for controlling thread init or termination */
800     if (WaitForMultipleObjects(2, waitfor, FALSE, 10000) != WAIT_OBJECT_0) {
801         return APR_ENOTHREAD;
802     }
803
804     atexit(service_stopped);
805     *display_name = mpm_display_name; 
806     return APR_SUCCESS;
807 }
808
809
810 apr_status_t mpm_service_started(void)
811 {
812     set_service_description();
813     if (osver.dwPlatformId == VER_PLATFORM_WIN32_NT)
814     {
815         ReportStatusToSCMgr(SERVICE_RUNNING,    // service state
816                             NO_ERROR,           // exit code
817                             0);                 // wait hint
818     }
819     return APR_SUCCESS;
820 }
821
822
823 void mpm_service_stopping(void)
824 {
825     if (osver.dwPlatformId == VER_PLATFORM_WIN32_NT)
826         ReportStatusToSCMgr(SERVICE_STOP_PENDING, // service state
827                             NO_ERROR,             // exit code
828                             30000);               // wait hint
829 }
830
831
832 apr_status_t mpm_service_install(apr_pool_t *ptemp, int argc, 
833                                  const char * const * argv, int reconfig)
834 {
835     char key_name[MAX_PATH];
836     char exe_path[MAX_PATH];
837     char *launch_cmd;
838     ap_regkey_t *key;
839     apr_status_t rv;
840     
841     fprintf(stderr,reconfig ? "Reconfiguring the %s service\n"
842                    : "Installing the %s service\n", mpm_display_name);
843
844     /* ###: utf-ize */
845     if (GetModuleFileName(NULL, exe_path, sizeof(exe_path)) == 0)
846     {
847         apr_status_t rv = apr_get_os_error();
848         ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, rv, NULL,
849                      "GetModuleFileName failed");
850         return rv;
851     }
852
853     if (osver.dwPlatformId == VER_PLATFORM_WIN32_NT)
854     {
855         SC_HANDLE   schService;
856         SC_HANDLE   schSCManager;
857
858         schSCManager = OpenSCManager(NULL, NULL, /* local, default database */
859                                      SC_MANAGER_CREATE_SERVICE);
860         if (!schSCManager) {
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");
864             return (rv);
865         }
866
867         launch_cmd = apr_psprintf(ptemp, "\"%s\" -k runservice", exe_path);
868
869         if (reconfig) {
870             /* ###: utf-ize */
871             schService = OpenService(schSCManager, mpm_service_name, 
872                                      SERVICE_CHANGE_CONFIG);
873             if (!schService) {
874                 ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_ERR, 
875                              apr_get_os_error(), NULL,
876                              "OpenService failed");
877             }
878             /* ###: utf-ize */
879             else if (!ChangeServiceConfig(schService, 
880                                           SERVICE_WIN32_OWN_PROCESS,
881                                           SERVICE_AUTO_START,
882                                           SERVICE_ERROR_NORMAL,
883                                           launch_cmd, NULL, NULL, 
884                                           "Tcpip\0Afd\0", NULL, NULL,
885                                           mpm_display_name)) {
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);
891                 schService = NULL;
892             }
893         }
894         else {
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 
899              * depend on it.
900              */
901             /* ###: utf-ize */
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
915
916             if (!schService) 
917             {
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);
922                 return (rv);
923             }
924         }
925         
926         CloseServiceHandle(schService);
927         CloseServiceHandle(schSCManager);
928     }
929     else /* osver.dwPlatformId != VER_PLATFORM_WIN32_NT */
930     {
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);
940         }
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.", 
944                          mpm_display_name);
945             return (rv);
946         }
947
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.", 
954                          mpm_display_name);
955             return (rv);
956         }
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.", 
961                          mpm_display_name);
962             ap_regkey_close(key);
963             return (rv);
964         }
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.", 
971                          mpm_display_name);
972             return (rv);
973         }
974     }
975
976     set_service_description();
977
978     /* For both WinNT & Win9x store the service ConfigArgs in the registry...
979      */
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);
986     }
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.", 
990                      mpm_display_name);
991         return (rv);
992     }
993     fprintf(stderr,"The %s service is successfully installed.\n", mpm_display_name);
994     return APR_SUCCESS;
995 }
996
997
998 apr_status_t mpm_service_uninstall(void)
999 {
1000     char key_name[MAX_PATH];
1001     apr_status_t rv;
1002
1003     if (osver.dwPlatformId == VER_PLATFORM_WIN32_NT)
1004     {
1005         SC_HANDLE schService;
1006         SC_HANDLE schSCManager;
1007
1008         fprintf(stderr,"Removing the %s service\n", mpm_display_name);
1009
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.");
1016             return (rv);
1017         }
1018         
1019         /* ###: utf-ize */
1020         schService = OpenService(schSCManager, mpm_service_name, DELETE);
1021
1022         if (!schService) {
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);
1026            return (rv);
1027         }
1028         
1029         /* assure the service is stopped before continuing
1030          *
1031          * This may be out of order... we might not be able to be
1032          * granted all access if the service is running anyway.
1033          *
1034          * And do we want to make it *this easy* for them
1035          * to uninstall their service unintentionally?
1036          */
1037         // ap_stop_service(schService);
1038
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);
1043             return (rv);
1044         }
1045         
1046         CloseServiceHandle(schService);        
1047         CloseServiceHandle(schSCManager);
1048     }
1049     else /* osver.dwPlatformId != VER_PLATFORM_WIN32_NT */
1050     {
1051         apr_status_t rv2, rv3;
1052         ap_regkey_t *key;
1053         fprintf(stderr,"Removing the %s service\n", mpm_display_name);
1054
1055         /* TODO: assure the service is stopped before continuing */
1056
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);
1062         }
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);
1067         }
1068         
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);
1079         }
1080         rv = (rv != APR_SUCCESS) ? rv : rv2;
1081         if (rv != APR_SUCCESS)
1082             return rv;
1083     }
1084     fprintf(stderr,"The %s service has been removed successfully.\n", mpm_display_name);
1085     return APR_SUCCESS;
1086 }
1087
1088
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.
1094  */
1095
1096 static int signal_service_transition(SC_HANDLE schService, DWORD signal, DWORD pending, DWORD complete)
1097 {
1098     if (signal && !ControlService(schService, signal, &globdat.ssStatus)) 
1099         return FALSE;
1100     
1101     do {
1102         Sleep(1000);    
1103         if (!QueryServiceStatus(schService, &globdat.ssStatus))
1104             return FALSE;
1105     } while (globdat.ssStatus.dwCurrentState == pending);
1106         
1107     return (globdat.ssStatus.dwCurrentState == complete);
1108 }
1109
1110
1111 apr_status_t mpm_service_start(apr_pool_t *ptemp, int argc, 
1112                                const char * const * argv)
1113 {
1114     apr_status_t rv;
1115     
1116     fprintf(stderr,"Starting the %s service\n", mpm_display_name);
1117
1118     if (osver.dwPlatformId == VER_PLATFORM_WIN32_NT)
1119     {
1120         char **start_argv;
1121         SC_HANDLE   schService;
1122         SC_HANDLE   schSCManager;
1123
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");
1130             return (rv);
1131         }
1132
1133         /* ###: utf-ize */
1134         schService = OpenService(schSCManager, mpm_service_name, 
1135                                  SERVICE_START | SERVICE_QUERY_STATUS);
1136         if (!schService) {
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);
1141             return (rv);
1142         }
1143
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);
1150             return 0;
1151         }
1152         
1153         start_argv = malloc((argc + 1) * sizeof(const char **));
1154         memcpy(start_argv, argv, argc * sizeof(const char **));
1155         start_argv[argc] = NULL;
1156
1157         rv = APR_EINIT;
1158         /* ###: utf-ize */
1159         if (StartService(schService, argc, start_argv)
1160             && signal_service_transition(schService, 0, /* test only */
1161                                          SERVICE_START_PENDING, 
1162                                          SERVICE_RUNNING))
1163                 rv = APR_SUCCESS;
1164
1165         if (rv != APR_SUCCESS)
1166             rv = apr_get_os_error();
1167         
1168         CloseServiceHandle(schService);
1169         CloseServiceHandle(schSCManager);
1170     }
1171     else /* osver.dwPlatformId != VER_PLATFORM_WIN32_NT */
1172     {
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];
1177         char *next_arg;
1178         int i;
1179
1180         /* Locate the active top level window named service_name
1181          * provided the class is ApacheWin95ServiceMonitor
1182          */
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);
1186             return 0;
1187         }
1188
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
1192          * console window.
1193          * The config is pre-flighted, so there should be no danger of failure.
1194          */
1195         
1196         if (GetModuleFileName(NULL, exe_path, sizeof(exe_path)) == 0)
1197         {
1198             apr_status_t rv = apr_get_os_error();
1199             ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, rv, NULL,
1200                          "GetModuleFileName failed");
1201             return rv;
1202         }
1203         
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');
1212         }
1213         
1214         memset(&si, 0, sizeof(si));
1215         memset(&pi, 0, sizeof(pi));
1216         si.cb = sizeof(si);
1217         si.dwFlags     = STARTF_USESHOWWINDOW;
1218         si.wShowWindow = SW_HIDE;   /* This might be redundant */
1219         
1220         rv = APR_EINIT;
1221         if (CreateProcess(NULL, exe_cmd, NULL, NULL, FALSE, 
1222                            DETACHED_PROCESS, /* Creation flags */
1223                            NULL, NULL, &si, &pi)) 
1224         {
1225             DWORD code;
1226             while (GetExitCodeProcess(pi.hProcess, &code) == STILL_ACTIVE) {
1227                 if (FindWindow("ApacheWin95ServiceMonitor", mpm_service_name)) {
1228                     rv = APR_SUCCESS;
1229                     break;
1230                 }
1231                 Sleep (1000);
1232             }
1233         }
1234         
1235         if (rv != APR_SUCCESS)
1236             rv = apr_get_os_error();
1237         
1238         CloseHandle(pi.hProcess);
1239         CloseHandle(pi.hThread);
1240     }    
1241
1242     if (rv == APR_SUCCESS)
1243         fprintf(stderr,"The %s service is running.\n", mpm_display_name);
1244     else
1245         ap_log_error(APLOG_MARK, APLOG_CRIT, rv, NULL,
1246                      "%s: Failed to start the service process.",
1247                      mpm_display_name);
1248         
1249     return rv;
1250 }
1251
1252
1253 /* signal is zero to stop, non-zero for restart */
1254
1255 void mpm_signal_service(apr_pool_t *ptemp, int signal)
1256 {
1257     int success = FALSE;
1258     
1259     if (osver.dwPlatformId == VER_PLATFORM_WIN32_NT) 
1260     {
1261         SC_HANDLE   schService;
1262         SC_HANDLE   schSCManager;
1263
1264         schSCManager = OpenSCManager(NULL, NULL, // default machine & database
1265                                      SC_MANAGER_CONNECT);
1266         
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");
1270             return;
1271         }
1272
1273         /* ###: utf-ize */
1274         schService = OpenService(schSCManager, mpm_service_name, 
1275                                  SERVICE_INTERROGATE | SERVICE_QUERY_STATUS | 
1276                                  SERVICE_USER_DEFINED_CONTROL |
1277                                  SERVICE_START | SERVICE_STOP);
1278
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);
1284             return;
1285         }
1286         
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);
1292             return;
1293         }
1294
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);
1299             return;
1300         }
1301         
1302         fprintf(stderr,"The %s service is %s.\n", mpm_display_name, 
1303                signal ? "restarting" : "stopping");
1304
1305         if (!signal)
1306             success = signal_service_transition(schService, 
1307                                                 SERVICE_CONTROL_STOP, 
1308                                                 SERVICE_STOP_PENDING, 
1309                                                 SERVICE_STOPPED);
1310         else if (globdat.ssStatus.dwCurrentState == SERVICE_STOPPED) {
1311             mpm_service_start(ptemp, 0, NULL);
1312             CloseServiceHandle(schService);
1313             CloseServiceHandle(schSCManager);
1314             return;
1315         }
1316         else
1317             success = signal_service_transition(schService, 
1318                                                 SERVICE_APACHE_RESTART, 
1319                                                 SERVICE_START_PENDING, 
1320                                                 SERVICE_RUNNING);
1321
1322         CloseServiceHandle(schService);
1323         CloseServiceHandle(schSCManager);
1324     }
1325     else /* !isWindowsNT() */
1326     {
1327         DWORD       service_pid;
1328         HANDLE      hwnd;
1329         char prefix[20];
1330         /* Locate the active top level window named service_name
1331          * provided the class is ApacheWin95ServiceMonitor
1332          */
1333         hwnd = FindWindow("ApacheWin95ServiceMonitor", mpm_service_name);
1334         if (hwnd && GetWindowThreadProcessId(hwnd, &service_pid))
1335             globdat.ssStatus.dwCurrentState = SERVICE_RUNNING;
1336         else
1337         {
1338             globdat.ssStatus.dwCurrentState = SERVICE_STOPPED;
1339             if (!signal) {
1340                 fprintf(stderr,"The %s service is not started.\n", mpm_display_name);
1341                 return;
1342             }
1343         }
1344
1345         fprintf(stderr,"The %s service is %s.\n", mpm_display_name, 
1346                signal ? "restarting" : "stopping");
1347
1348         apr_snprintf(prefix, sizeof(prefix), "ap%ld", (long)service_pid);
1349         setup_signal_names(prefix);
1350
1351         if (!signal) 
1352         {
1353             int ticks = 60;
1354             ap_signal_parent(SIGNAL_PARENT_SHUTDOWN);
1355             while (--ticks)
1356             {
1357                 if (!IsWindow(hwnd)) {
1358                     success = TRUE;
1359                     break;
1360                 }
1361                 Sleep(1000);
1362             }
1363         }
1364         else /* !stop */
1365         {   
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.
1370              */
1371             if (globdat.ssStatus.dwCurrentState == SERVICE_STOPPED) {
1372                 mpm_service_start(ptemp, 0, NULL);
1373                 return;
1374             }
1375             else {
1376                 success = TRUE;
1377                 ap_signal_parent(SIGNAL_PARENT_RESTART);
1378             }
1379         }
1380     }
1381
1382     if (success)
1383         fprintf(stderr,"The %s service has %s.\n", mpm_display_name, 
1384                signal ? "restarted" : "stopped");
1385     else
1386         fprintf(stderr,"Failed to %s the %s service.\n", 
1387                signal ? "restart" : "stop", mpm_display_name);
1388 }