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