findlanabyname-20040228
[openafs.git] / src / WINNT / bosctlsvc / bosctlsvc.c
1 /*
2  * Copyright 2000, International Business Machines Corporation and others.
3  * All Rights Reserved.
4  * 
5  * This software has been released under the terms of the IBM Public
6  * License.  For details, see the LICENSE file in the top-level source
7  * directory or online at http://www.openafs.org/dl/license10.html
8  */
9
10 /* This file implements the AFS BOS control service.  Basically, it provides
11  * a mechanism to start and stop the AFS bosserver via the NT SCM; it also
12  * supports bosserver restart.
13  */
14
15
16 #include <afs/param.h>
17 #include <afs/stds.h>
18
19 #include <param.h>
20 #include <stddef.h>
21 #include <stdlib.h>
22 #include <stdio.h>
23 #include <errno.h>
24 #include <windows.h>
25 #include <time.h>
26 #include <process.h>
27
28 #include <WINNT/afsevent.h>
29 #include <WINNT/afsreg.h>
30 #include <afs/procmgmt.h>
31 #include <afs/dirpath.h>
32 #include <afs/bnode.h>
33
34
35 /* Define globals */
36
37 #define BOSSERVER_STARTMSG_EXE  "afslegal.exe"
38
39 #define BOSSERVER_RESTART_ARG_MAX  2  /* "-noauth", "-log" */
40 #define BOSSERVER_WAIT_TIME_HINT  60  /* seconds */
41 #define BOSSERVER_STOP_TIME_MAX  (FSSDTIME + 60)  /* seconds */
42
43 #define BOS_CONTROLS_ACCEPTED  SERVICE_ACCEPT_STOP
44
45 static CRITICAL_SECTION bosCtlStatusLock;  /* protects bosCtlStatus */
46 static SERVICE_STATUS bosCtlStatus;
47 static SERVICE_STATUS_HANDLE bosCtlStatusHandle;
48
49 /* note: events arranged in priority order in case multiple signaled */
50 #define BOS_STOP_EVENT 0
51 #define BOS_EXIT_EVENT 1
52 #define BOS_EVENT_COUNT 2
53 static HANDLE bosCtlEvent[BOS_EVENT_COUNT];
54
55
56 /* Declare local functions */
57
58 static void AsyncSignalCatcher(int signo);
59
60 static void BosCtlStatusInit(DWORD initState);
61
62 static DWORD BosCtlStatusUpdate(DWORD newState,
63                                 DWORD exitCode,
64                                 BOOL isWin32Code);
65
66 static DWORD BosCtlStatusReport(void);
67
68 static void WINAPI BosCtlHandler(DWORD controlCode);
69
70 static void WINAPI BosCtlMain(DWORD argc,
71                               LPTSTR *argv);
72
73 static void BosserverDoStopEvent(pid_t cpid,
74                                  DWORD *stopStatus,
75                                  BOOL *isWin32Code);
76
77 static void BosserverDoExitEvent(pid_t cpid,
78                                  BOOL *doWait,
79                                  BOOL *doRestart,
80                                  char **restartArgv,
81                                  DWORD *stopStatus,
82                                  BOOL *isWin32Code);
83
84 static void BosserverRun(DWORD argc,
85                          LPTSTR *argv,
86                          DWORD *stopStatus,
87                          BOOL *isWin32Code);
88
89 static void BosserverStartupMsgDisplay(void);
90
91
92
93
94 /*
95  * AsyncSignalCatcher() -- Handle asynchronous signals sent to process
96  */
97 static void
98 AsyncSignalCatcher(int signo)
99 {
100     if (signo == SIGCHLD) {
101         (void) SetEvent(bosCtlEvent[BOS_EXIT_EVENT]);
102     }
103 }
104
105
106 /*
107  * BosCtlStatusInit() -- initialize BOS control service status structure
108  */
109 static void
110 BosCtlStatusInit(DWORD initState)
111 {
112     bosCtlStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
113     bosCtlStatus.dwCurrentState = initState;
114
115     if (initState == SERVICE_RUNNING) {
116         bosCtlStatus.dwControlsAccepted = BOS_CONTROLS_ACCEPTED;
117     } else {
118         bosCtlStatus.dwControlsAccepted = 0;
119     }
120
121     bosCtlStatus.dwWin32ExitCode = 0;
122     bosCtlStatus.dwServiceSpecificExitCode = 0;
123     bosCtlStatus.dwCheckPoint = 0;
124     bosCtlStatus.dwWaitHint = BOSSERVER_WAIT_TIME_HINT * 1000; /* millisecs */
125
126     InitializeCriticalSection(&bosCtlStatusLock);
127 }
128
129
130 /*
131  * BosCtlStatusUpdate() -- update BOS control service status and report to SCM
132  */
133 static DWORD
134 BosCtlStatusUpdate(DWORD newState, DWORD exitCode, BOOL isWin32Code)
135 {
136     DWORD rc = 0;
137
138     EnterCriticalSection(&bosCtlStatusLock);
139
140     /* SERVICE_STOPPED is a terminal state; never transition out of it */
141     if (bosCtlStatus.dwCurrentState != SERVICE_STOPPED) {
142
143         if ((bosCtlStatus.dwCurrentState == newState) &&
144             (newState == SERVICE_START_PENDING ||
145              newState == SERVICE_STOP_PENDING)) {
146             /* continuing a pending state; increment checkpoint value */
147             bosCtlStatus.dwCheckPoint++;
148         } else {
149             /* not continuing a pending state; reset checkpoint value */
150             bosCtlStatus.dwCheckPoint = 0;
151         }
152
153         bosCtlStatus.dwCurrentState = newState;
154
155         if (newState == SERVICE_RUNNING) {
156             bosCtlStatus.dwControlsAccepted = BOS_CONTROLS_ACCEPTED;
157         } else {
158             bosCtlStatus.dwControlsAccepted = 0;
159         }
160
161         if (isWin32Code) {
162             bosCtlStatus.dwWin32ExitCode = exitCode;
163             bosCtlStatus.dwServiceSpecificExitCode = 0;
164         } else {
165             bosCtlStatus.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR;
166             bosCtlStatus.dwServiceSpecificExitCode = exitCode;
167         }
168     }
169
170     if (!SetServiceStatus(bosCtlStatusHandle, &bosCtlStatus)) {
171         rc = GetLastError();
172     }
173
174     LeaveCriticalSection(&bosCtlStatusLock);
175
176     return rc;
177 }
178
179
180 /*
181  * BosCtlStatusReport() -- report current BOS control service status to SCM
182  */
183 static DWORD
184 BosCtlStatusReport(void)
185 {
186     DWORD rc = 0;
187
188     EnterCriticalSection(&bosCtlStatusLock);
189
190     if (!SetServiceStatus(bosCtlStatusHandle, &bosCtlStatus)) {
191         rc = GetLastError();
192     }
193
194     LeaveCriticalSection(&bosCtlStatusLock);
195
196     return rc;
197 }
198
199
200 /*
201  * BosCtlHandler() -- control handler for BOS control service
202  */
203 static void WINAPI
204 BosCtlHandler(DWORD controlCode)
205 {
206     switch (controlCode) {
207       case SERVICE_CONTROL_STOP:
208         (void) SetEvent(bosCtlEvent[BOS_STOP_EVENT]);
209         (void) BosCtlStatusUpdate(SERVICE_STOP_PENDING, 0, TRUE);
210         break;
211
212       default:
213         (void) BosCtlStatusReport();
214         break;
215     }
216 }
217
218
219 /*
220  * BosCtlMain() -- main function for BOS control service
221  */
222 static void WINAPI
223 BosCtlMain(DWORD argc, LPTSTR *argv)
224 {
225     DWORD status;
226     BOOL isWin32Code;
227     struct sigaction childAction;
228
229     /* Initialize status structure */
230     BosCtlStatusInit(SERVICE_START_PENDING);
231
232     /* Create events used by service control handler and signal handler */
233     if ((bosCtlEvent[BOS_STOP_EVENT] = CreateEvent(NULL,
234                                                    FALSE /* manual reset */,
235                                                    FALSE /* initial state */,
236                                                    NULL)) == NULL) {
237         status = GetLastError();
238     }
239
240     if ((bosCtlEvent[BOS_EXIT_EVENT] = CreateEvent(NULL,
241                                                    FALSE /* manual reset */,
242                                                    FALSE /* initial state */,
243                                                    NULL)) == NULL) {
244         status = GetLastError();
245     }
246
247     /* Register service control handler */
248     bosCtlStatusHandle = RegisterServiceCtrlHandler(AFSREG_SVR_SVC_NAME,
249                                                     BosCtlHandler);
250     if (bosCtlStatusHandle == 0) {
251         /* failed to register control handler for service; can not continue */
252         (void) ReportErrorEventAlt(AFSEVT_SVR_BCS_HANDLER_REG_FAILED,
253                                    (int)GetLastError(), NULL);
254         /* can not report status to SCM w/o a valid bosCtlStatusHandle */
255         return;
256     }
257
258     /* Stop immediately if required system resources could not be obtained */
259     if (bosCtlEvent[BOS_STOP_EVENT] == NULL ||
260         bosCtlEvent[BOS_EXIT_EVENT] == NULL) {
261         (void) ReportErrorEventAlt(AFSEVT_SVR_BCS_INSUFFICIENT_RESOURCES,
262                                    (int)status, NULL);
263         (void) BosCtlStatusUpdate(SERVICE_STOPPED, status, TRUE);
264         return;
265     }
266
267     /* Report pending start status */
268     if (status = BosCtlStatusUpdate(SERVICE_START_PENDING, 0, TRUE)) {
269         /* can't inform SCM of pending start; give up before really start */
270         (void) ReportErrorEventAlt(AFSEVT_SVR_BCS_SCM_COMM_FAILED,
271                                    (int)status, NULL);
272         (void) BosCtlStatusUpdate(SERVICE_STOPPED, status, TRUE);
273         return;
274     }
275
276     /* Initialize the dirpath package so can access local bosserver binary */
277     if (!(initAFSDirPath() & AFSDIR_SERVER_PATHS_OK)) {
278         /* sw install directory probably not in registry; can not continue */
279         (void) ReportErrorEventAlt(AFSEVT_SVR_BCS_NO_INSTALL_DIR, 0, NULL);
280         (void) BosCtlStatusUpdate(SERVICE_STOPPED, 0, TRUE);
281         return;
282     }
283
284     /* Install SIGCHLD handler to catch bosserver restarts and failures */
285     childAction.sa_handler = AsyncSignalCatcher;
286     sigfillset(&childAction.sa_mask);
287     childAction.sa_flags = 0;
288
289     if (sigaction(SIGCHLD, &childAction, NULL)) {
290         /* handler install should never fail, but can't continue if it does */
291         status = errno;
292         (void) ReportErrorEventAlt(AFSEVT_SVR_BCS_INTERNAL_ERROR,
293                                    (int)status, NULL);
294         (void) BosCtlStatusUpdate(SERVICE_STOPPED, status, FALSE);
295         return;
296     }
297
298     /* Run the AFS bosserver, handling stop and exit events */
299     BosserverRun(argc, argv, &status, &isWin32Code);
300
301     (void) BosCtlStatusUpdate(SERVICE_STOPPED, status, isWin32Code);
302 }
303
304
305 /*
306  * BosserverDoStopEvent() -- Handle a stop event for the AFS bosserver.
307  */
308 static void
309 BosserverDoStopEvent(pid_t cpid, DWORD *stopStatus, BOOL *isWin32Code)
310 {
311     (void) BosCtlStatusUpdate(SERVICE_STOP_PENDING, 0, TRUE);
312
313     if (kill(cpid, SIGQUIT) == 0) {
314         /* bosserver has been told to stop; wait for this to happen */
315         BOOL gotWaitStatus = FALSE;
316         time_t timeStart = time(NULL);
317
318         do {
319             int waitStatus;
320             DWORD status;
321
322             if (waitpid(cpid, &waitStatus, WNOHANG) == cpid) {
323                 /* bosserver status available */
324                 if (WIFEXITED(waitStatus) && WEXITSTATUS(waitStatus) == 0) {
325                     /* bosserver exited w/o any error */
326                     *stopStatus = 0;
327                     *isWin32Code = TRUE;
328                 } else {
329                     *stopStatus = waitStatus;
330                     *isWin32Code = FALSE;
331                 }
332                 gotWaitStatus = TRUE;
333                 break;
334             }
335
336             /* wait for bosserver status to become available;
337              * update BOS control service status periodically.
338              */
339             status = WaitForSingleObject(bosCtlEvent[BOS_EXIT_EVENT],
340                                          BOSSERVER_WAIT_TIME_HINT * 1000 / 2);
341             if (status == WAIT_FAILED) {
342                 /* failed to wait on event; should never happen */
343                 Sleep(2000);  /* sleep to avoid tight loop if event problem */
344             }
345             (void) BosCtlStatusUpdate(SERVICE_STOP_PENDING, 0, TRUE);
346         } while (difftime(time(NULL), timeStart) < BOSSERVER_STOP_TIME_MAX);
347
348         if (!gotWaitStatus) {
349             /* timed out waiting to get bosserver status */
350             *stopStatus = EBUSY;
351             *isWin32Code = FALSE;
352
353             (void) ReportWarningEventAlt(AFSEVT_SVR_BCS_BOSSERVER_STOP_TIMEOUT,
354                                          (int)*stopStatus, NULL);
355         }
356
357     } else {
358         /* can't tell bosserver to stop; should never happen */
359         *stopStatus = errno;
360         *isWin32Code = FALSE;
361
362         (void) ReportErrorEventAlt(AFSEVT_SVR_BCS_BOSSERVER_STOP_FAILED,
363                                    (int)*stopStatus, NULL);
364     }
365 }
366
367
368 /*
369  * BosserverDoExitEvent() -- Handle an exit event for the AFS bosserver.
370  *
371  *     The output arguments for this function are set as follows:
372  *         Case 1: bosserver did not exit (spurious SIGCHLD);
373  *                 *doWait is set to TRUE.
374  *         Case 2: bosserver exited with restart code;
375  *                 *doRestart is set to TRUE, restartArgv[] is defined.
376  *         Case 3: bosserver exited with non-restart code;
377  *                 *stopStatus and *isWin32Code are defined.
378  */
379 static void
380 BosserverDoExitEvent(pid_t cpid,
381                      BOOL *doWait,
382                      BOOL *doRestart,
383                      char **restartArgv,
384                      DWORD *stopStatus,
385                      BOOL *isWin32Code)
386 {
387     int waitStatus;
388
389     *doWait = FALSE;
390     *doRestart = FALSE;
391
392     if (waitpid(cpid, &waitStatus, WNOHANG) == cpid) {
393         /* bosserver status available */
394
395         if (WIFEXITED(waitStatus)) {
396             /* bosserver exited normally; check for restart code */
397             int exitCode = WEXITSTATUS(waitStatus);
398
399             if (BOSEXIT_DORESTART(exitCode)) {
400                 /* bosserver requests restart */
401                 int i;
402                 *doRestart = TRUE;
403
404                 /* set up bosserver argument list */
405                 restartArgv[0] = (char *)AFSDIR_SERVER_BOSVR_FILEPATH;
406                 i = 1;
407
408                 if (exitCode & BOSEXIT_NOAUTH_FLAG) {
409                     /* pass "-noauth" to new bosserver */
410                     restartArgv[i] = "-noauth";
411                     i++;
412                 }
413                 if (exitCode & BOSEXIT_LOGGING_FLAG) {
414                     /* pass "-log" to new bosserver */
415                     restartArgv[i] = "-log";
416                     i++;
417                 }
418                 restartArgv[i] = NULL;
419             }
420         }
421
422         if (!(*doRestart)) {
423             /* bosserver exited with non-restart code; set status */
424             *stopStatus = waitStatus;
425             *isWin32Code = FALSE;
426
427             (void) ReportWarningEventAlt(AFSEVT_SVR_BCS_BOSSERVER_EXIT,
428                                          (int)*stopStatus, NULL);
429         }
430
431     } else {
432         /* bosserver status NOT available; assume spurious SIGCHLD */
433         *doWait = TRUE;
434     }
435 }
436
437
438 /*
439  * BosserverRun() -- Run the AFS bosserver, handling stop and exit events.
440  *
441  *     Input args are those passed to the service's main function (BosCtlMain).
442  *     Output args are the stop status and status type of the bosserver.
443  */
444 static void
445 BosserverRun(DWORD argc,
446              LPTSTR *argv,
447              DWORD *stopStatus,
448              BOOL *isWin32Code)
449 {
450     DWORD status, i;
451     BOOL doRestart, doWait;
452     char **spawn_argv;
453
454     /* Display bosserver startup (legal) message; first start only */
455     BosserverStartupMsgDisplay();
456
457     /* Set env variable forcing process mgmt lib to spawn processes detached */
458     (void)putenv(PMGT_SPAWN_DETACHED_ENV_NAME "=1");
459
460     /* Alloc block with room for at least BOSSERVER_RESTART_ARG_MAX args */
461     i = max((argc + 1), (BOSSERVER_RESTART_ARG_MAX + 2));
462     spawn_argv = (char **)malloc(i * sizeof(char *));
463
464     if (spawn_argv == NULL) {
465         /* failed to malloc required space; can not continue */
466         *stopStatus = ENOMEM;
467         *isWin32Code = FALSE;
468
469         (void) ReportErrorEventAlt(AFSEVT_SVR_BCS_INSUFFICIENT_RESOURCES,
470                                    (int)*stopStatus, NULL);
471         return;
472     }
473
474     /* Set initial bosserver args to those supplied via StartService() */
475     spawn_argv[0] = (char *)AFSDIR_SERVER_BOSVR_FILEPATH;
476
477     for (i = 1; i < argc; i++) {
478         spawn_argv[i] = argv[i];
479     }
480     spawn_argv[i] = NULL;
481
482     /* Start/restart bosserver and wait for either a stop or exit event */
483     doRestart = FALSE;
484
485     do {
486         pid_t cpid;
487
488         if (doRestart) {
489             /* restarting bosserver; log informational message */
490             (void) ReportInformationEventAlt(AFSEVT_SVR_BCS_BOSSERVER_RESTART,
491                                              NULL);
492             doRestart = FALSE;
493         }
494
495         cpid = spawnprocve(spawn_argv[0], spawn_argv, NULL, 0);
496
497         if (cpid == (pid_t)-1) {
498             /* failed to start/restart the bosserver process */
499             *stopStatus = errno;
500             *isWin32Code = FALSE;
501
502             (void) ReportErrorEventAlt(AFSEVT_SVR_BCS_BOSSERVER_START_FAILED,
503                                        (int)*stopStatus, NULL);
504             break;
505         }
506
507         if (status = BosCtlStatusUpdate(SERVICE_RUNNING, 0, TRUE)) {
508             /* can't tell SCM we're running so quit; should never occur */
509             (void) ReportErrorEventAlt(AFSEVT_SVR_BCS_SCM_COMM_FAILED,
510                                        (int)status, NULL);
511             (void) SetEvent(bosCtlEvent[BOS_STOP_EVENT]);
512         }
513
514         /* bosserver is running; wait for an event of interest */
515
516         Sleep(5000);  /* bosserver needs time to register signal handler */
517
518         do {
519             doWait = FALSE;
520
521             status = WaitForMultipleObjects(BOS_EVENT_COUNT,
522                                             bosCtlEvent, FALSE, INFINITE);
523
524             if ((status - WAIT_OBJECT_0) == BOS_STOP_EVENT) {
525                 /* stop event signaled */
526                 BosserverDoStopEvent(cpid, stopStatus, isWin32Code);
527
528             } else if ((status - WAIT_OBJECT_0) == BOS_EXIT_EVENT) {
529                 /* exit event signaled; see function comment for outcomes */
530                 BosserverDoExitEvent(cpid,
531                                      &doWait,
532                                      &doRestart, spawn_argv,
533                                      stopStatus, isWin32Code);
534
535             } else {
536                 /* failed to wait on events; should never happen */
537                 Sleep(2000);  /* sleep to avoid tight loop if event problem */
538                 doWait = TRUE;
539             }
540         } while (doWait);
541     } while(doRestart);
542
543     return;
544 }
545
546
547 /*
548  * BosserverStartupMsgDisplay() -- display Windows version of AFS bosserver
549  *     startup (legal) message.
550  */
551 static void
552 BosserverStartupMsgDisplay(void)
553 {
554     char *msgPath;
555
556     if (!ConstructLocalBinPath(BOSSERVER_STARTMSG_EXE, &msgPath)) {
557         /* Use C runtime spawn; don't need all the machinery in the
558          * process management library.
559          */
560         (void)_spawnl(_P_DETACH, msgPath, BOSSERVER_STARTMSG_EXE, NULL);
561         free(msgPath);
562     }
563 }
564
565
566 /*
567  * main() -- start dispatcher thread for BOS control service
568  */
569 int main(void)
570 {
571     SERVICE_TABLE_ENTRY dispatchTable[] = {{AFSREG_SVR_SVC_NAME, BosCtlMain},
572                                            {NULL, NULL}};
573
574     (void) ReportInformationEventAlt(AFSEVT_SVR_BCS_STARTED, NULL);
575
576     if (!StartServiceCtrlDispatcher(dispatchTable)) {
577         /* unable to connect to SCM */
578         (void) ReportErrorEventAlt(AFSEVT_SVR_BCS_SCM_COMM_FAILED,
579                                    (int)GetLastError(), NULL);
580     }
581
582     (void) ReportInformationEventAlt(AFSEVT_SVR_BCS_STOPPED, NULL);
583     return 0;
584 }