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