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