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