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