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