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