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