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