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