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