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