b514f291520588fb8f31142be114178f446a8145
[yaz-moved-to-github.git] / server / statserv.c
1 /*
2  * Copyright (c) 1995-1998, Index Data
3  * See the file LICENSE for details.
4  * Sebastian Hammer, Adam Dickmeiss
5  *
6  * NT server based on threads by
7  *   Chas Woodfield, Fretwell Downing Datasystems.
8  *
9  * $Log: statserv.c,v $
10  * Revision 1.47  1998-02-10 10:28:57  adam
11  * Added app_name, service_dependencies, service_display_name and
12  * options_func. options_func allows us to specify a different function
13  * to interogate the command line arguments. The other members allow us
14  * to pass the full service details accross to the service manager (CW).
15  *
16  *
17  * Revision 1.46  1998/01/30 15:24:57  adam
18  * Fixed bug in inetd code. The server listened on tcp:@:9999 even
19  * though it was started in inetd mode.
20  *
21  * Revision 1.45  1998/01/29 13:30:23  adam
22  * Better event handle system for NT/Unix.
23  *
24  * Revision 1.44  1997/11/07 13:31:52  adam
25  * Added NT Service name part of statserv_options_block. Moved NT
26  * service utility to server library.
27  *
28  * Revision 1.43  1997/10/31 12:20:09  adam
29  * Improved memory debugging for xmalloc/nmem.c. References to NMEM
30  * instead of ODR in n ESPEC-1 handling in source d1_espec.c.
31  * Bug fix: missing fclose in data1_read_espec1.
32  *
33  * Revision 1.42  1997/10/27 14:03:02  adam
34  * Added new member to statserver_options_block, pre_init, which
35  * specifies a callback to be invoked after command line parsing and
36  * before the server listens for the first time.
37  *
38  * Revision 1.41  1997/09/29 07:19:32  adam
39  * Server library uses nmem_init/nmem_exit. The log prefix no longer
40  * includes leading path on NT.
41  *
42  * Revision 1.40  1997/09/17 12:10:41  adam
43  * YAZ version 1.4.
44  *
45  * Revision 1.39  1997/09/09 10:10:19  adam
46  * Another MSV5.0 port. Changed projects to include proper
47  * library/include paths.
48  * Server starts server in test-mode when no options are given.
49  *
50  * Revision 1.38  1997/09/04 14:19:14  adam
51  * Added credits.
52  *
53  * Revision 1.37  1997/09/01 08:53:01  adam
54  * New windows NT/95 port using MSV5.0. The test server 'ztest' was
55  * moved a separate directory. MSV5.0 project server.dsp created.
56  * As an option, the server can now operate as an NT service.
57  *
58  * Revision 1.36  1996/07/06 19:58:36  quinn
59  * System headerfiles gathered in yconfig
60  *
61  * Revision 1.35  1996/05/29  10:03:28  quinn
62  * Options work
63  *
64  * Revision 1.34  1996/02/21  13:12:07  quinn
65  * *** empty log message ***
66  *
67  * Revision 1.33  1996/02/10  12:23:49  quinn
68  * Enable inetd operations fro TCP/IP stack
69  *
70  * Revision 1.32  1996/01/19  15:41:52  quinn
71  * *** empty log message ***
72  *
73  * Revision 1.31  1995/11/17  11:09:39  adam
74  * Added new option '-c' to specify configuration name in control block.
75  *
76  * Revision 1.30  1995/11/01  13:54:59  quinn
77  * Minor adjustments
78  *
79  * Revision 1.29  1995/10/30  12:41:29  quinn
80  * Added hostname lookup for server.
81  *
82  * Revision 1.28  1995/09/29  17:12:30  quinn
83  * Smallish
84  *
85  * Revision 1.27  1995/09/27  15:03:02  quinn
86  * Modified function heads & prototypes.
87  *
88  * Revision 1.26  1995/08/29  14:44:51  quinn
89  * Reset timeouts.
90  *
91  * Revision 1.25  1995/08/29  11:18:02  quinn
92  * Added code to receive close
93  *
94  * Revision 1.24  1995/06/16  10:31:39  quinn
95  * Added session timeout.
96  *
97  * Revision 1.23  1995/06/15  12:30:48  quinn
98  * Setuid-facility.
99  *
100  * Revision 1.22  1995/06/15  07:45:17  quinn
101  * Moving to v3.
102  *
103  * Revision 1.21  1995/06/06  08:15:40  quinn
104  * Cosmetic.
105  *
106  * Revision 1.20  1995/05/29  08:12:09  quinn
107  * Moved oid to util
108  *
109  * Revision 1.19  1995/05/16  09:37:27  quinn
110  * Fixed bug
111  *
112  * Revision 1.18  1995/05/16  08:51:09  quinn
113  * License, documentation, and memory fixes
114  *
115  * Revision 1.17  1995/05/15  11:56:42  quinn
116  * Asynchronous facilities. Restructuring of seshigh code.
117  *
118  * Revision 1.16  1995/04/10  10:23:40  quinn
119  * Some work to add scan and other things.
120  *
121  * Revision 1.15  1995/03/31  10:16:51  quinn
122  * Fixed logging.
123  *
124  * Revision 1.14  1995/03/31  09:18:58  quinn
125  * Added logging.
126  *
127  * Revision 1.13  1995/03/30  16:08:39  quinn
128  * Little mods.
129  *
130  * Revision 1.12  1995/03/30  13:29:02  quinn
131  * Smallish
132  *
133  * Revision 1.11  1995/03/30  12:18:17  quinn
134  * Fixed bug.
135  *
136  * Revision 1.10  1995/03/29  15:40:16  quinn
137  * Ongoing work. Statserv is now dynamic by default
138  *
139  * Revision 1.9  1995/03/27  08:34:30  quinn
140  * Added dynamic server functionality.
141  * Released bindings to session.c (is now redundant)
142  *
143  * Revision 1.8  1995/03/20  09:46:26  quinn
144  * Added osi support.
145  *
146  * Revision 1.7  1995/03/16  13:29:04  quinn
147  * Partitioned server.
148  *
149  * Revision 1.6  1995/03/15  15:18:52  quinn
150  * Little changes to better support nonblocking I/O
151  * Added backend.h
152  *
153  * Revision 1.5  1995/03/15  08:37:45  quinn
154  * Now we're pretty much set for nonblocking I/O.
155  *
156  * Revision 1.4  1995/03/14  16:59:48  quinn
157  * Bug-fixes
158  *
159  * Revision 1.3  1995/03/14  11:30:15  quinn
160  * Works better now.
161  *
162  * Revision 1.2  1995/03/14  10:28:03  quinn
163  * More work on demo server.
164  *
165  * Revision 1.1  1995/03/10  18:22:45  quinn
166  * The rudiments of an asynchronous server.
167  *
168  */
169
170 #include <yconfig.h>
171 #include <stdio.h>
172 #include <string.h>
173 #ifdef WINDOWS
174 #include <process.h>
175 #include <winsock.h>
176 #include <direct.h>
177 #include "service.h"
178 #else
179 #include <unistd.h>
180 #include <pwd.h>
181 #endif
182 #include <fcntl.h>
183 #include <signal.h>
184 #include <errno.h>
185
186 #include <options.h>
187 #include <comstack.h>
188 #include <tcpip.h>
189 #ifdef USE_XTIMOSI
190 #include <xmosi.h>
191 #endif
192 #include <log.h>
193 #include "eventl.h"
194 #include "session.h"
195 #include <statserv.h>
196
197 static IOCHAN pListener = NULL;
198
199 static char *me = "statserver";
200 /*
201  * default behavior.
202  */
203 int check_options(int argc, char **argv);
204 statserv_options_block control_block = {
205     1,                          /* dynamic mode */
206     LOG_DEFAULT_LEVEL,          /* log level */
207     "",                         /* no PDUs */
208     "",                         /* diagnostic output to stderr */
209     "tcp:@:9999",               /* default listener port */
210     PROTO_Z3950,                /* default application protocol */
211     60,                         /* idle timeout (minutes) */
212     1024*1024,                  /* maximum PDU size (approx.) to allow */
213     "default-config",           /* configuration name to pass to backend */
214     "",                         /* set user id */
215     NULL,                       /* pre init handler */
216     check_options,              /* Default routine, for checking the run-time arguments */
217     0                           /* default value for inet deamon */
218
219 #ifdef WINDOWS
220     ,"Z39.50 Server",           /* NT Service Name */
221     "Server",                   /* NT application Name */
222     "",                         /* NT Service Dependencies */
223     "Z39.50 Server"             /* NT Service Display Name */
224 #endif /* WINDOWS */
225 };
226
227 /*
228  * handle incoming connect requests.
229  * The dynamic mode is a bit tricky mostly because we want to avoid
230  * doing all of the listening and accepting in the parent - it's
231  * safer that way.
232  */
233 #ifdef WINDOWS
234
235 typedef struct _ThreadList ThreadList;
236
237 struct _ThreadList
238 {
239     HANDLE hThread;
240     IOCHAN pIOChannel;
241     ThreadList *pNext;
242 };
243
244 static ThreadList *pFirstThread;
245 static CRITICAL_SECTION Thread_CritSect;
246 static BOOL bInitialized = FALSE;
247
248 static void ThreadList_Initialize()
249 {
250     /* Initialize the critical Sections */
251     InitializeCriticalSection(&Thread_CritSect);
252
253      /* Set the first thraed */
254     pFirstThread = NULL;
255
256     /* we have been initialized */
257     bInitialized = TRUE;
258 }
259
260 static void statserv_add(HANDLE hThread, IOCHAN pIOChannel)
261 {
262     /* Only one thread can go through this section at a time */
263     EnterCriticalSection(&Thread_CritSect);
264
265     {
266         /* Lets create our new object */
267         ThreadList *pNewThread = (ThreadList *)malloc(sizeof(ThreadList));
268         pNewThread->hThread = hThread;
269         pNewThread->pIOChannel = pIOChannel;
270         pNewThread->pNext = pFirstThread;
271         pFirstThread = pNewThread;
272
273         /* Lets let somebody else create a new object now */
274         LeaveCriticalSection(&Thread_CritSect);
275     }
276 }
277
278 void statserv_remove(IOCHAN pIOChannel)
279 {
280     /* Only one thread can go through this section at a time */
281     EnterCriticalSection(&Thread_CritSect);
282
283     {
284         ThreadList *pCurrentThread = pFirstThread;
285         ThreadList *pNextThread;
286         ThreadList *pPrevThread =NULL;
287
288         /* Step through alll the threads */
289         for (; pCurrentThread != NULL; pCurrentThread = pNextThread)
290         {
291             /* We only need to compare on the IO Channel */
292             if (pCurrentThread->pIOChannel == pIOChannel)
293             {
294                 /* We have found the thread we want to delete */
295                 /* First of all reset the next pointers */
296                 if (pPrevThread == NULL)
297                     pFirstThread = pCurrentThread->pNext;
298                 else
299                     pPrevThread->pNext = pCurrentThread->pNext;
300
301                 /* All we need todo now is delete the memory */
302                 free(pCurrentThread);
303
304                 /* No need to look at any more threads */
305                 pNextThread = NULL;
306             }
307             else
308             {
309                 /* We need to look at another thread */
310                 pNextThread = pCurrentThread->pNext;
311             }
312         }
313
314         /* Lets let somebody else remove an object now */
315         LeaveCriticalSection(&Thread_CritSect);
316     }
317 }
318
319 void statserv_closedown()
320 {
321     /* Shouldn't do anything if we are not initialized */
322     if (bInitialized)
323     {
324         int iHandles = 0;
325         HANDLE *pThreadHandles = NULL;
326
327         /* We need to stop threads adding and removing while we */
328         /* start the closedown process */
329         EnterCriticalSection(&Thread_CritSect);
330
331         {
332             /* We have exclusive access to the thread stuff now */
333             /* Y didn't i use a semaphore - Oh well never mind */
334             ThreadList *pCurrentThread = pFirstThread;
335
336             /* Before we do anything else, we need to shutdown the listener */
337             if (pListener != NULL)
338                 iochan_destroy(pListener);
339
340             for (; pCurrentThread != NULL; pCurrentThread = pCurrentThread->pNext)
341             {
342                 /* Just destroy the IOCHAN, that should do the trick */
343                 iochan_destroy(pCurrentThread->pIOChannel);
344
345                 /* Keep a running count of our handles */
346                 iHandles++;
347             }
348
349             if (iHandles > 0)
350             {
351                 HANDLE *pCurrentHandle ;
352
353                 /* Allocate the thread handle array */
354                 pThreadHandles = (HANDLE *)malloc(sizeof(HANDLE) * iHandles);
355                 pCurrentHandle = pThreadHandles; 
356
357                 for (pCurrentThread = pFirstThread;
358                      pCurrentThread != NULL;
359                      pCurrentThread = pCurrentThread->pNext, pCurrentHandle++)
360                 {
361                     /* Just the handle */
362                     *pCurrentHandle = pCurrentThread->hThread;
363                 }
364             }
365
366             /* We can now leave the critical section */
367             LeaveCriticalSection(&Thread_CritSect);
368         }
369
370         /* Now we can really do something */
371         if (iHandles > 0)
372         {
373             /* This will now wait, until all the threads close */
374             WaitForMultipleObjects(iHandles, pThreadHandles, TRUE, INFINITE);
375
376             /* Free the memory we allocated for the handle array */
377             free(pThreadHandles);
378         }
379
380         /* No longer require the critical section, since all threads are dead */
381         DeleteCriticalSection(&Thread_CritSect);
382     }
383 }
384
385 int __stdcall event_loop_thread (IOCHAN iochan)
386 {
387     return event_loop (&iochan);
388 }
389
390 static void listener(IOCHAN h, int event)
391 {
392     COMSTACK line = (COMSTACK) iochan_getdata(h);
393     association *newas;
394     int res;
395     HANDLE NewHandle;
396
397     if (event == EVENT_INPUT)
398     {
399         if ((res = cs_listen(line, 0, 0)) < 0)
400         {
401             logf(LOG_FATAL, "cs_listen failed.");
402             return;
403         }
404         else if (res == 1)
405             return;
406         logf(LOG_DEBUG, "listen ok");
407         iochan_setevent(h, EVENT_OUTPUT);
408         iochan_setflags(h, EVENT_OUTPUT | EVENT_EXCEPT); /* set up for acpt */
409     }
410     else if (event == EVENT_OUTPUT)
411     {
412         COMSTACK new_line;
413         IOCHAN new_chan;
414         char *a = NULL;
415         DWORD ThreadId;
416
417         if (!(new_line = cs_accept(line)))
418         {
419             logf(LOG_FATAL, "Accept failed.");
420             iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
421             return;
422         }
423         logf(LOG_DEBUG, "Accept ok");
424
425         if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session,
426                                        EVENT_INPUT)))
427         {
428             logf(LOG_FATAL, "Failed to create iochan");
429             iochan_destroy(h);
430             return;
431         }
432
433         logf(LOG_DEBUG, "Creating association");
434         if (!(newas = create_association(new_chan, new_line)))
435         {
436             logf(LOG_FATAL, "Failed to create new assoc.");
437             iochan_destroy(h);
438             return;
439         }
440         logf(LOG_DEBUG, "Setting timeout %d", control_block.idle_timeout);
441         iochan_setdata(new_chan, newas);
442         iochan_settimeout(new_chan, control_block.idle_timeout * 60);
443 #ifndef WINDOWS
444         logf(LOG_DEBUG, "Determining client address");
445         a = cs_addrstr(new_line);
446         logf(LOG_LOG, "Accepted connection from %s", a ? a : "[Unknown]");
447 #endif
448         /* Now what we need todo is create a new thread with this iochan as
449            the parameter */
450         /* if (CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)event_loop_thread,
451            new_chan, 0, &ThreadId) == NULL) */
452         /* Somehow, somewhere we need to store this thread id, otherwise we
453            won't be able to close cleanly */
454         NewHandle = (HANDLE)_beginthreadex(NULL, 0, event_loop_thread,
455                                            new_chan, 0, &ThreadId);
456         if (NewHandle == (HANDLE)-1)
457         {
458             
459             logf(LOG_FATAL|LOG_ERRNO, "Failed to create new thread.");
460             iochan_destroy(h);
461             return;
462         }
463         /* We successfully created the thread, so add it to the list */
464         statserv_add(NewHandle, new_chan);
465
466         logf(LOG_DEBUG, "Created new thread, iochan %p", new_chan);
467         iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
468     }
469     else
470     {
471         logf(LOG_FATAL, "Bad event on listener.");
472         iochan_destroy(h);
473         return;
474     }
475 }
476
477 #else /* WINDOWS */
478
479 /* To save having an #ifdef in event_loop we need to define this empty function */
480 void statserv_remove(IOCHAN pIOChannel)
481 {
482 }
483
484 void statserv_closedown()
485 {
486     IOCHAN p;
487     for (p = pListener; p; p = p->next)
488         iochan_destroy(p);
489 }
490
491 static void listener(IOCHAN h, int event)
492 {
493     COMSTACK line = (COMSTACK) iochan_getdata(h);
494     association *newas;
495     static int hand[2];
496     static int child = 0;
497     int res;
498
499     if (event == EVENT_INPUT)
500     {
501         if (control_block.dynamic && !child) 
502         {
503             int res;
504
505             if (pipe(hand) < 0)
506             {
507                 logf(LOG_FATAL|LOG_ERRNO, "pipe");
508                 iochan_destroy(h);
509                 return;
510             }
511             if ((res = fork()) < 0)
512             {
513                 logf(LOG_FATAL|LOG_ERRNO, "fork");
514                 iochan_destroy(h);
515                 return;
516             }
517             else if (res == 0) /* child */
518             {
519                 char nbuf[100];
520                 IOCHAN pp;
521
522                 close(hand[0]);
523                 child = 1;
524                 for (pp = pListener; pp; pp = iochan_getnext(pp))
525                 {
526                     if (pp != h)
527                     {
528                         COMSTACK l = iochan_getdata(pp);
529                         cs_close(l);
530                         iochan_destroy(pp);
531                     }
532                 }
533                 sprintf(nbuf, "%s(%d)", me, getpid());
534                 log_init(control_block.loglevel, nbuf, 0);
535             }
536             else /* parent */
537             {
538                 close(hand[1]);
539                 /* wait for child to take the call */
540                 for (;;)
541                 {
542                     char dummy[1];
543                     int res;
544                     
545                     if ((res = read(hand[0], dummy, 1)) < 0 && errno != EINTR)
546                     {
547                         logf(LOG_FATAL|LOG_ERRNO, "handshake read");
548                         return;
549                     }
550                     else if (res >= 0)
551                         break;
552                 }
553                 logf(LOG_DEBUG, "P: Child has taken the call");
554                 close(hand[0]);
555                 return;
556             }
557         }
558         if ((res = cs_listen(line, 0, 0)) < 0)
559         {
560             logf(LOG_FATAL, "cs_listen failed.");
561             return;
562         }
563         else if (res == 1)
564             return;
565         logf(LOG_DEBUG, "listen ok");
566         iochan_setevent(h, EVENT_OUTPUT);
567         iochan_setflags(h, EVENT_OUTPUT | EVENT_EXCEPT); /* set up for acpt */
568     }
569     /* in dynamic mode, only the child ever comes down here */
570     else if (event == EVENT_OUTPUT)
571     {
572         COMSTACK new_line;
573         IOCHAN new_chan;
574         char *a;
575
576         if (!(new_line = cs_accept(line)))
577         {
578             logf(LOG_FATAL, "Accept failed.");
579             iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
580             return;
581         }
582         logf(LOG_DEBUG, "accept ok");
583         if (control_block.dynamic)
584         {
585             IOCHAN pp;
586             /* close our half of the listener socket */
587             for (pp = pListener; pp; pp = iochan_getnext(pp))
588             {
589                 COMSTACK l = iochan_getdata(pp);
590                 cs_close(l);
591                 iochan_destroy(pp);
592             }
593             /* release dad */
594             logf(LOG_DEBUG, "Releasing parent");
595             close(hand[1]);
596         }
597         else
598             iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
599         
600         if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session,
601             EVENT_INPUT)))
602         {
603             logf(LOG_FATAL, "Failed to create iochan");
604             iochan_destroy(h);
605             return;
606         }
607         new_chan->next = pListener;
608         pListener = new_chan;
609         if (!(newas = create_association(new_chan, new_line)))
610         {
611             logf(LOG_FATAL, "Failed to create new assoc.");
612             iochan_destroy(h);
613             return;
614         }
615         iochan_setdata(new_chan, newas);
616         iochan_settimeout(new_chan, control_block.idle_timeout * 60);
617         a = cs_addrstr(new_line);
618         logf(LOG_LOG, "Accepted connection from %s", a ? a : "[Unknown]");
619     }
620     else
621     {
622         logf(LOG_FATAL, "Bad event on listener.");
623         iochan_destroy(h);
624         return;
625     }
626 }
627
628 #endif /* WINDOWS */
629
630 static void inetd_connection(int what)
631 {
632     COMSTACK line;
633     IOCHAN chan;
634     association *assoc;
635     char *addr;
636
637     if ((line = cs_createbysocket(0, tcpip_type, 0, what)))
638     {
639         if ((chan = iochan_create(cs_fileno(line), ir_session, EVENT_INPUT)))
640         {
641             if ((assoc = create_association(chan, line)))
642             {
643                 iochan_setdata(chan, assoc);
644                 iochan_settimeout(chan, control_block.idle_timeout * 60);
645                 addr = cs_addrstr(line);
646                 logf(LOG_LOG, "Inetd association from %s", addr ? addr : "[UNKNOWN]");
647             }
648             else
649             {
650                 logf(LOG_FATAL, "Failed to create association structure");
651             }
652             chan->next = pListener;
653             pListener = chan;
654         }
655         else
656         {
657             logf(LOG_FATAL, "Failed to create iochan");
658         }
659     }
660     else
661     {
662         logf(LOG_ERRNO|LOG_FATAL, "Failed to create comstack on socket 0");
663     }
664 }
665
666 /*
667  * Set up a listening endpoint, and give it to the event-handler.
668  */
669 static void add_listener(char *where, int what)
670 {
671     COMSTACK l;
672     CS_TYPE type;
673     char mode[100], addr[100];
674     void *ap;
675     IOCHAN lst = NULL;
676
677     if (!where || sscanf(where, "%[^:]:%s", mode, addr) != 2)
678     {
679         logf (LOG_WARN, "%s: Address format: ('tcp'|'osi')':'<address>", me);
680         return;
681     }
682     if (!strcmp(mode, "tcp"))
683         type = tcpip_type;
684     else if (!strcmp(mode, "osi"))
685     {
686 #ifdef USE_XTIMOSI
687         type = mosi_type;
688 #else
689         logf (LOG_WARN, "OSI Transport not allowed by configuration.");
690         return;
691 #endif
692     }
693     else
694     {
695         logf (LOG_WARN, "You must specify either 'osi:' or 'tcp:'");
696         return;
697     }
698     logf(LOG_LOG, "Adding %s %s listener on %s",
699         control_block.dynamic ? "dynamic" : "static",
700         what == PROTO_SR ? "SR" : "Z3950", where);
701     if (!(l = cs_create(type, 0, what)))
702     {
703         logf(LOG_FATAL|LOG_ERRNO, "Failed to create listener");
704     }
705     ap = cs_straddr (l, addr);
706     if (!ap)
707     {
708         fprintf(stderr, "Address resolution failed.\n");
709         cs_close (l);
710         return;
711     }
712     if (cs_bind(l, ap, CS_SERVER) < 0)
713     {
714         logf(LOG_FATAL|LOG_ERRNO, "Failed to bind to %s", where);
715     }
716     if (!(lst = iochan_create(cs_fileno(l), listener, EVENT_INPUT |
717          EVENT_EXCEPT)))
718     {
719         logf(LOG_FATAL|LOG_ERRNO, "Failed to create IOCHAN-type");
720     }
721     iochan_setdata(lst, l);
722
723     /* Ensure our listener chain is setup properly */
724     lst->next = pListener;
725     pListener = lst;
726 }
727
728 #ifndef WINDOWS
729 /* For windows we don't need to catch the signals */
730 static void catchchld(int num)
731 {
732     while (waitpid(-1, 0, WNOHANG) > 0)
733         ;
734     signal(SIGCHLD, catchchld);
735 }
736 #endif /* WINDOWS */
737
738 statserv_options_block *statserv_getcontrol(void)
739 {
740     static statserv_options_block cb;
741
742     memcpy(&cb, &control_block, sizeof(cb));
743     return &cb;
744 }
745
746 void statserv_setcontrol(statserv_options_block *block)
747 {
748     memcpy(&control_block, block, sizeof(*block));
749 }
750
751 int statserv_start(int argc, char **argv)
752 {
753     int ret;
754
755     nmem_init ();
756 #ifdef WINDOWS
757     /* We need to initialize the thread list */
758     ThreadList_Initialize();
759 #endif /* WINDOWS */
760
761 #ifdef WINDOWS
762     if ((me = strrchr (argv[0], '\\')))
763         me++;
764     else
765         me = argv[0];
766 #else
767     me = argv[0];
768 #endif
769     if (control_block.options_func(argc, argv))
770         return(1);
771
772 #ifndef WINDOWS
773     if (control_block.inetd)
774         inetd_connection(control_block.default_proto);
775     else
776     {
777         if (control_block.pre_init)
778             (*control_block.pre_init)(&control_block);
779         if (control_block.dynamic)
780             signal(SIGCHLD, catchchld);
781     }
782     if (*control_block.setuid)
783     {
784         struct passwd *pw;
785         
786         if (!(pw = getpwnam(control_block.setuid)))
787         {
788             logf(LOG_FATAL, "%s: Unknown user", control_block.setuid);
789             return(1);
790         }
791         if (setuid(pw->pw_uid) < 0)
792         {
793             logf(LOG_FATAL|LOG_ERRNO, "setuid");
794             exit(1);
795         }
796     }
797 #endif /* WINDOWS */
798
799     if ((pListener == NULL) && *control_block.default_listen)
800         add_listener(control_block.default_listen,
801                      control_block.default_proto);
802     logf(LOG_LOG, "Entering event loop.");
803         
804     if (pListener == NULL)
805         ret = 1;
806     else
807         ret = event_loop(&pListener);
808     nmem_exit ();
809     return ret;
810 }
811
812 int check_options(int argc, char **argv)
813 {
814     int ret = 0, r;
815     char *arg;
816
817     while ((ret = options("a:iszSl:v:u:c:w:t:k:", argv, argc, &arg)) != -2)
818     {
819         switch (ret)
820         {
821         case 0:
822             add_listener(arg, control_block.default_proto);
823             break;
824         case 'z':
825             control_block.default_proto = PROTO_Z3950;
826             break;
827         case 's':
828             control_block.default_proto = PROTO_SR;
829             break;
830         case 'S':
831             control_block.dynamic = 0;
832             break;
833         case 'l':
834             strcpy(control_block.logfile, arg ? arg : "");
835             log_init(control_block.loglevel, me, control_block.logfile);
836             break;
837         case 'v':
838             control_block.loglevel = log_mask_str(arg);
839             log_init(control_block.loglevel, me, control_block.logfile);
840             break;
841         case 'a':
842             strcpy(control_block.apdufile, arg ? arg : "");
843             break;
844         case 'u':
845             strcpy(control_block.setuid, arg ? arg : "");
846             break;
847         case 'c':
848             strcpy(control_block.configname, arg ? arg : "");
849             break;
850         case 't':
851             if (!arg || !(r = atoi(arg)))
852             {
853                 fprintf(stderr, "%s: Specify positive timeout for -t.\n", me);
854                 return(1);
855             }
856             control_block.idle_timeout = r;
857             break;
858         case  'k':
859             if (!arg || !(r = atoi(arg)))
860             {
861                 fprintf(stderr, "%s: Specify positive timeout for -t.\n", me);
862                 return(1);
863             }
864             control_block.maxrecordsize = r * 1024;
865             break;
866         case 'i':
867             control_block.inetd = 1;
868             break;
869         case 'w':
870             if (chdir(arg))
871             {
872                 perror(arg);            
873                 return(1);
874             }
875             break;
876         default:
877             fprintf(stderr, "Usage: %s [ -i -a <pdufile> -v <loglevel>"
878                     " -l <logfile> -u <user> -c <config> -t <minutes>"
879                     " -k <kilobytes>"
880                         " -zsS <listener-addr> -w <directory> ... ]\n", me);
881             return(1);
882         }
883     }
884     return 0;
885 }
886
887 #ifdef WINDOWS
888 typedef struct _Args
889 {
890     char **argv;
891     int argc;
892 } Args; 
893
894 static Args ArgDetails;
895
896 /* name of the executable */
897 #define SZAPPNAME            "server"
898
899 /* list of service dependencies - "dep1\0dep2\0\0" */
900 #define SZDEPENDENCIES       ""
901
902 int statserv_main(int argc, char **argv)
903 {
904     statserv_options_block *cb = statserv_getcontrol();
905     
906     /* Lets setup the Arg structure */
907     ArgDetails.argc = argc;
908     ArgDetails.argv = argv;
909     
910     /* Now setup the service with the service controller */
911     SetupService(argc, argv, &ArgDetails, SZAPPNAME,
912                  cb->service_name, /* internal service name */
913                  cb->service_name, /* displayed name of the service */
914                  SZDEPENDENCIES);
915     return 0;
916 }
917
918 int StartAppService(void *pHandle, int argc, char **argv)
919 {
920     /* Initializes the App */
921     return 1;
922 }
923
924 void RunAppService(void *pHandle)
925 {
926     Args *pArgs = (Args *)pHandle;
927     
928     /* Starts the app running */
929     statserv_start(pArgs->argc, pArgs->argv);
930 }
931
932 void StopAppService(void *pHandle)
933 {
934     /* Stops the app */
935     statserv_closedown();
936 }
937 #else
938 int statserv_main(int argc, char **argv)
939 {
940     int ret = statserv_start (argc, argv);
941     statserv_closedown ();
942     return ret;
943 }
944 #endif