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