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