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