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