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