CQL w/bison on WIN32
[yaz-moved-to-github.git] / server / statserv.c
1 /*
2  * Copyright (c) 1995-2003, Index Data
3  * See the file LICENSE for details.
4  * Sebastian Hammer, Adam Dickmeiss
5  *
6  * NT threaded server code by
7  *   Chas Woodfield, Fretwell Downing Informatics.
8  *
9  * $Id: statserv.c,v 1.94 2003-02-18 21:27:53 adam Exp $
10  */
11
12 #include <stdio.h>
13 #include <string.h>
14 #ifdef WIN32
15 #include <process.h>
16 #include <winsock.h>
17 #include <direct.h>
18 #include "service.h"
19 #else
20 #include <unistd.h>
21 #include <pwd.h>
22 #endif
23
24 #if YAZ_POSIX_THREADS
25 #include <pthread.h>
26 #elif YAZ_GNU_THREADS
27 #include <pth.h>
28 #endif
29
30 #include <fcntl.h>
31 #include <signal.h>
32 #include <errno.h>
33
34 #include <yaz/comstack.h>
35 #include <yaz/tcpip.h>
36 #include <yaz/options.h>
37 #ifdef USE_XTIMOSI
38 #include <yaz/xmosi.h>
39 #endif
40 #include <yaz/log.h>
41 #include "eventl.h"
42 #include "session.h"
43 #include <yaz/statserv.h>
44
45 static IOCHAN pListener = NULL;
46
47 static char *me = "statserver";
48 /*
49  * default behavior.
50  */
51 int check_options(int argc, char **argv);
52 statserv_options_block control_block = {
53     1,                          /* dynamic mode */
54     0,                          /* threaded mode */
55     0,                          /* one shot (single session) */
56     LOG_DEFAULT_LEVEL,          /* log level */
57     "",                         /* no PDUs */
58     "",                         /* diagnostic output to stderr */
59     "tcp:@:9999",               /* default listener port */
60     PROTO_Z3950,                /* default application protocol */
61     15,                         /* idle timeout (minutes) */
62     1024*1024,                  /* maximum PDU size (approx.) to allow */
63     "default-config",           /* configuration name to pass to backend */
64     "",                         /* set user id */
65     0,                          /* bend_start handler */
66     0,                          /* bend_stop handler */
67     check_options,              /* Default routine, for checking the run-time arguments */
68     check_ip_tcpd,
69     "",
70     0,                          /* default value for inet deamon */
71     0,                          /* handle (for service, etc) */
72     0,                          /* bend_init handle */
73     0,                          /* bend_close handle */
74 #ifdef WIN32
75     "Z39.50 Server",            /* NT Service Name */
76     "Server",                   /* NT application Name */
77     "",                         /* NT Service Dependencies */
78     "Z39.50 Server",            /* NT Service Display Name */
79 #endif /* WIN32 */
80     0                           /* SOAP handlers */
81 };
82
83 /*
84  * handle incoming connect requests.
85  * The dynamic mode is a bit tricky mostly because we want to avoid
86  * doing all of the listening and accepting in the parent - it's
87  * safer that way.
88  */
89 #ifdef WIN32
90
91 typedef struct _ThreadList ThreadList;
92
93 struct _ThreadList
94 {
95     HANDLE hThread;
96     IOCHAN pIOChannel;
97     ThreadList *pNext;
98 };
99
100 static ThreadList *pFirstThread;
101 static CRITICAL_SECTION Thread_CritSect;
102 static BOOL bInitialized = FALSE;
103
104 static void ThreadList_Initialize()
105 {
106     /* Initialize the critical Sections */
107     InitializeCriticalSection(&Thread_CritSect);
108
109      /* Set the first thraed */
110     pFirstThread = NULL;
111
112     /* we have been initialized */
113     bInitialized = TRUE;
114 }
115
116 static void statserv_add(HANDLE hThread, IOCHAN pIOChannel)
117 {
118     /* Only one thread can go through this section at a time */
119     EnterCriticalSection(&Thread_CritSect);
120
121     {
122         /* Lets create our new object */
123         ThreadList *pNewThread = (ThreadList *)malloc(sizeof(ThreadList));
124         pNewThread->hThread = hThread;
125         pNewThread->pIOChannel = pIOChannel;
126         pNewThread->pNext = pFirstThread;
127         pFirstThread = pNewThread;
128
129         /* Lets let somebody else create a new object now */
130         LeaveCriticalSection(&Thread_CritSect);
131     }
132 }
133
134 void statserv_remove(IOCHAN pIOChannel)
135 {
136     /* Only one thread can go through this section at a time */
137     EnterCriticalSection(&Thread_CritSect);
138
139     {
140         ThreadList *pCurrentThread = pFirstThread;
141         ThreadList *pNextThread;
142         ThreadList *pPrevThread =NULL;
143
144         /* Step through alll the threads */
145         for (; pCurrentThread != NULL; pCurrentThread = pNextThread)
146         {
147             /* We only need to compare on the IO Channel */
148             if (pCurrentThread->pIOChannel == pIOChannel)
149             {
150                 /* We have found the thread we want to delete */
151                 /* First of all reset the next pointers */
152                 if (pPrevThread == NULL)
153                     pFirstThread = pCurrentThread->pNext;
154                 else
155                     pPrevThread->pNext = pCurrentThread->pNext;
156
157                 /* All we need todo now is delete the memory */
158                 free(pCurrentThread);
159
160                 /* No need to look at any more threads */
161                 pNextThread = NULL;
162             }
163             else
164             {
165                 /* We need to look at another thread */
166                 pNextThread = pCurrentThread->pNext;
167                 pPrevThread = pCurrentThread;
168             }
169         }
170
171         /* Lets let somebody else remove an object now */
172         LeaveCriticalSection(&Thread_CritSect);
173     }
174 }
175
176 /* WIN32 statserv_closedown */
177 void statserv_closedown()
178 {
179     /* Shouldn't do anything if we are not initialized */
180     if (bInitialized)
181     {
182         int iHandles = 0;
183         HANDLE *pThreadHandles = NULL;
184
185         /* We need to stop threads adding and removing while we */
186         /* start the closedown process */
187         EnterCriticalSection(&Thread_CritSect);
188
189         {
190             /* We have exclusive access to the thread stuff now */
191             /* Y didn't i use a semaphore - Oh well never mind */
192             ThreadList *pCurrentThread = pFirstThread;
193
194             /* Before we do anything else, we need to shutdown the listener */
195             if (pListener != NULL)
196                 iochan_destroy(pListener);
197
198             for (; pCurrentThread != NULL; pCurrentThread = pCurrentThread->pNext)
199             {
200                 /* Just destroy the IOCHAN, that should do the trick */
201                 iochan_destroy(pCurrentThread->pIOChannel);
202                 closesocket(pCurrentThread->pIOChannel->fd);
203
204                 /* Keep a running count of our handles */
205                 iHandles++;
206             }
207
208             if (iHandles > 0)
209             {
210                 HANDLE *pCurrentHandle ;
211
212                 /* Allocate the thread handle array */
213                 pThreadHandles = (HANDLE *)malloc(sizeof(HANDLE) * iHandles);
214                 pCurrentHandle = pThreadHandles; 
215
216                 for (pCurrentThread = pFirstThread;
217                      pCurrentThread != NULL;
218                      pCurrentThread = pCurrentThread->pNext, pCurrentHandle++)
219                 {
220                     /* Just the handle */
221                     *pCurrentHandle = pCurrentThread->hThread;
222                 }
223             }
224
225             /* We can now leave the critical section */
226             LeaveCriticalSection(&Thread_CritSect);
227         }
228
229         /* Now we can really do something */
230         if (iHandles > 0)
231         {
232             logf (LOG_LOG, "waiting for %d to die", iHandles);
233             /* This will now wait, until all the threads close */
234             WaitForMultipleObjects(iHandles, pThreadHandles, TRUE, INFINITE);
235
236             /* Free the memory we allocated for the handle array */
237             free(pThreadHandles);
238         }
239
240         if (control_block.bend_stop)
241             (*control_block.bend_stop)(&control_block);
242         /* No longer require the critical section, since all threads are dead */
243         DeleteCriticalSection(&Thread_CritSect);
244     }
245 }
246
247 void __cdecl event_loop_thread (IOCHAN iochan)
248 {
249     event_loop (&iochan);
250 }
251
252 /* WIN32 listener */
253 static void listener(IOCHAN h, int event)   
254 {
255     COMSTACK line = (COMSTACK) iochan_getdata(h);
256     association *newas;
257     int res;
258     HANDLE newHandle;
259
260     if (event == EVENT_INPUT)
261     {
262         if ((res = cs_listen(line, 0, 0)) < 0)
263         {
264             yaz_log(LOG_FATAL, "cs_listen failed");
265             return;
266         }
267         else if (res == 1)
268             return;
269         yaz_log(LOG_DEBUG, "listen ok");
270         iochan_setevent(h, EVENT_OUTPUT);
271         iochan_setflags(h, EVENT_OUTPUT | EVENT_EXCEPT); /* set up for acpt */
272     }
273     else if (event == EVENT_OUTPUT)
274     {
275         COMSTACK new_line = cs_accept(line);
276         IOCHAN new_chan;
277         char *a = NULL;
278
279         if (!new_line)
280         {
281             yaz_log(LOG_FATAL, "Accept failed.");
282             iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT);
283             return;
284         }
285         yaz_log(LOG_DEBUG, "Accept ok");
286
287         if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session,
288                                        EVENT_INPUT)))
289         {
290             yaz_log(LOG_FATAL, "Failed to create iochan");
291             iochan_destroy(h);
292             return;
293         }
294
295         yaz_log(LOG_DEBUG, "Creating association");
296         if (!(newas = create_association(new_chan, new_line)))
297         {
298             yaz_log(LOG_FATAL, "Failed to create new assoc.");
299             iochan_destroy(h);
300             return;
301         }
302         newas->cs_get_mask = EVENT_INPUT;
303         newas->cs_put_mask = 0;
304         newas->cs_accept_mask = 0;
305
306         yaz_log(LOG_DEBUG, "Setting timeout %d", control_block.idle_timeout);
307         iochan_setdata(new_chan, newas);
308         iochan_settimeout(new_chan, 60);
309
310         /* Now what we need todo is create a new thread with this iochan as
311            the parameter */
312         newHandle = (HANDLE) _beginthread(event_loop_thread, 0, new_chan);
313         if (newHandle == (HANDLE) -1)
314         {
315             
316             yaz_log(LOG_FATAL|LOG_ERRNO, "Failed to create new thread.");
317             iochan_destroy(h);
318             return;
319         }
320         /* We successfully created the thread, so add it to the list */
321         statserv_add(newHandle, new_chan);
322
323         yaz_log(LOG_DEBUG, "Created new thread, id = %ld iochan %p",(long) newHandle, new_chan);
324         iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
325     }
326     else
327     {
328         yaz_log(LOG_FATAL, "Bad event on listener.");
329         iochan_destroy(h);
330         return;
331     }
332 }
333
334 int statserv_must_terminate(void)
335 {
336     return 0;
337 }
338
339 #else /* ! WIN32 */
340
341 static int term_flag = 0;
342 /* To save having an #ifdef in event_loop we need to
343    define this empty function 
344 */
345 int statserv_must_terminate(void)
346 {
347     return term_flag;
348 }
349
350 void statserv_remove(IOCHAN pIOChannel)
351 {
352 }
353
354 void statserv_closedown()
355 {
356     IOCHAN p;
357
358     if (control_block.bend_stop)
359         (*control_block.bend_stop)(&control_block);
360     for (p = pListener; p; p = p->next)
361     {
362         iochan_destroy(p);
363     }
364 }
365
366 void sigterm(int sig)
367 {
368     term_flag = 1;
369 }
370
371 static void *new_session (void *vp);
372 static int no_sessions = 0;
373
374 /* UNIX listener */
375 static void listener(IOCHAN h, int event)
376 {
377     COMSTACK line = (COMSTACK) iochan_getdata(h);
378     static int hand[2];
379     static int child = 0;
380     int res;
381
382     if (event == EVENT_INPUT)
383     {
384         if (control_block.dynamic && !child) 
385         {
386             int res;
387
388             ++no_sessions;
389             if (pipe(hand) < 0)
390             {
391                 yaz_log(LOG_FATAL|LOG_ERRNO, "pipe");
392                 iochan_destroy(h);
393                 return;
394             }
395             if ((res = fork()) < 0)
396             {
397                 yaz_log(LOG_FATAL|LOG_ERRNO, "fork");
398                 iochan_destroy(h);
399                 return;
400             }
401             else if (res == 0) /* child */
402             {
403                 char nbuf[100];
404                 IOCHAN pp;
405
406                 close(hand[0]);
407                 child = 1;
408                 for (pp = pListener; pp; pp = iochan_getnext(pp))
409                 {
410                     if (pp != h)
411                     {
412                         COMSTACK l = (COMSTACK)iochan_getdata(pp);
413                         cs_close(l);
414                         iochan_destroy(pp);
415                     }
416                 }
417                 sprintf(nbuf, "%s(%d)", me, getpid());
418                 yaz_log_init(control_block.loglevel, nbuf, 0);
419                 /* ensure that bend_stop is not called when each child exits -
420                    only for the main process .. 
421                 */
422                 control_block.bend_stop = 0;
423             }
424             else /* parent */
425             {
426                 close(hand[1]);
427                 /* wait for child to take the call */
428                 for (;;)
429                 {
430                     char dummy[1];
431                     int res;
432                     
433                     if ((res = read(hand[0], dummy, 1)) < 0 &&
434                                      yaz_errno() != EINTR)
435                     {
436                         yaz_log(LOG_FATAL|LOG_ERRNO, "handshake read");
437                         return;
438                     }
439                     else if (res >= 0)
440                         break;
441                 }
442                 yaz_log(LOG_DEBUG, "P: Child has taken the call");
443                 close(hand[0]);
444                 return;
445             }
446         }
447         if ((res = cs_listen_check(line, 0, 0, control_block.check_ip,
448                                    control_block.daemon_name)) < 0)
449         {
450             yaz_log(LOG_WARN|LOG_ERRNO, "cs_listen failed");
451             return;
452         }
453         else if (res == 1)
454             return;
455         yaz_log(LOG_DEBUG, "listen ok");
456         iochan_setevent(h, EVENT_OUTPUT);
457         iochan_setflags(h, EVENT_OUTPUT | EVENT_EXCEPT); /* set up for acpt */
458     }
459     /* in dynamic mode, only the child ever comes down here */
460     else if (event == EVENT_OUTPUT)
461     {
462         COMSTACK new_line = cs_accept(line);
463
464         if (!new_line)
465         {
466             yaz_log(LOG_FATAL, "Accept failed.");
467             iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
468             return;
469         }
470         yaz_log(LOG_DEBUG, "accept ok");
471         if (control_block.dynamic)
472         {
473             IOCHAN pp;
474             /* close our half of the listener socket */
475             for (pp = pListener; pp; pp = iochan_getnext(pp))
476             {
477                 COMSTACK l = (COMSTACK)iochan_getdata(pp);
478                 cs_close(l);
479                 iochan_destroy(pp);
480             }
481             /* release dad */
482             yaz_log(LOG_DEBUG, "Releasing parent");
483             close(hand[1]);
484         }
485         else
486         {
487             iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
488             ++no_sessions;
489         }
490 #if YAZ_POSIX_THREADS
491         if (control_block.threads)
492         {
493             pthread_t child_thread;
494             pthread_create (&child_thread, 0, new_session, new_line);
495             pthread_detach (child_thread);
496         }
497         else
498             new_session(new_line);
499 #elif YAZ_GNU_THREADS
500         if (control_block.threads)
501         {
502             pth_attr_t attr;
503             pth_t child_thread;
504
505             attr = pth_attr_new ();
506             pth_attr_set (attr, PTH_ATTR_JOINABLE, FALSE);
507             pth_attr_set (attr, PTH_ATTR_STACK_SIZE, 32*1024);
508             pth_attr_set (attr, PTH_ATTR_NAME, "session");
509             yaz_log (LOG_LOG, "pth_spawn begin");
510             child_thread = pth_spawn (attr, new_session, new_line);
511             yaz_log (LOG_LOG, "pth_spawn finish");
512             pth_attr_destroy (attr);
513         }
514         else
515             new_session(new_line);
516 #else
517         new_session(new_line);
518 #endif
519     }
520     else if (event == EVENT_TIMEOUT)
521     {
522         yaz_log(LOG_LOG, "Shutting down listener.");
523         iochan_destroy(h);
524     }
525     else
526     {
527         yaz_log(LOG_FATAL, "Bad event on listener.");
528         iochan_destroy(h);
529     }
530 }
531
532 static void *new_session (void *vp)
533 {
534     char *a;
535     association *newas;
536     IOCHAN new_chan;
537     COMSTACK new_line = (COMSTACK) vp;
538
539     unsigned cs_get_mask, cs_accept_mask, mask =  
540         ((new_line->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
541         ((new_line->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
542
543     if (mask)    
544     {
545         cs_accept_mask = mask;  /* accept didn't complete */
546         cs_get_mask = 0;
547     }
548     else
549     {
550         cs_accept_mask = 0;     /* accept completed.  */
551         cs_get_mask = mask = EVENT_INPUT;
552     }
553
554     if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session, mask)))
555     {
556         yaz_log(LOG_FATAL, "Failed to create iochan");
557         return 0;
558     }
559     if (!(newas = create_association(new_chan, new_line)))
560     {
561         yaz_log(LOG_FATAL, "Failed to create new assoc.");
562         return 0;
563     }
564     newas->cs_accept_mask = cs_accept_mask;
565     newas->cs_get_mask = cs_get_mask;
566
567     iochan_setdata(new_chan, newas);
568     iochan_settimeout(new_chan, 60);
569     a = cs_addrstr(new_line);
570     yaz_log(LOG_LOG, "Starting session %d from %s",
571         no_sessions, a ? a : "[Unknown]");
572     if (control_block.threads)
573     {
574         event_loop(&new_chan);
575     }
576     else
577     {
578         new_chan->next = pListener;
579         pListener = new_chan;
580     }
581     return 0;
582 }
583
584 /* UNIX */
585 #endif
586
587 static void inetd_connection(int what)
588 {
589     COMSTACK line;
590     IOCHAN chan;
591     association *assoc;
592     char *addr;
593
594     if ((line = cs_createbysocket(0, tcpip_type, 0, what)))
595     {
596         if ((chan = iochan_create(cs_fileno(line), ir_session, EVENT_INPUT)))
597         {
598             if ((assoc = create_association(chan, line)))
599             {
600                 iochan_setdata(chan, assoc);
601                 iochan_settimeout(chan, 60);
602                 addr = cs_addrstr(line);
603                 yaz_log(LOG_LOG, "Inetd association from %s",
604                         addr ? addr : "[UNKNOWN]");
605                 assoc->cs_get_mask = EVENT_INPUT;
606             }
607             else
608             {
609                 yaz_log(LOG_FATAL, "Failed to create association structure");
610             }
611             chan->next = pListener;
612             pListener = chan;
613         }
614         else
615         {
616             yaz_log(LOG_FATAL, "Failed to create iochan");
617         }
618     }
619     else
620     {
621         yaz_log(LOG_ERRNO|LOG_FATAL, "Failed to create comstack on socket 0");
622     }
623 }
624
625 /*
626  * Set up a listening endpoint, and give it to the event-handler.
627  */
628 static int add_listener(char *where, int what)
629 {
630     COMSTACK l;
631     void *ap;
632     IOCHAN lst = NULL;
633     const char *mode;
634
635     if (control_block.dynamic)
636         mode = "dynamic";
637     else if (control_block.threads)
638         mode = "threaded";
639     else
640         mode = "static";
641
642     yaz_log(LOG_LOG, "Adding %s %s listener on %s", mode,
643             what == PROTO_SR ? "SR" : "Z3950", where);
644
645     l = cs_create_host(where, 0, &ap);
646     if (!l)
647     {
648         yaz_log(LOG_FATAL|LOG_ERRNO, "Failed to listen on %s", where);
649         return -1;
650     }
651     if (cs_bind(l, ap, CS_SERVER) < 0)
652     {
653         yaz_log(LOG_FATAL|LOG_ERRNO, "Failed to bind to %s", where);
654         cs_close (l);
655         return -1;
656     }
657     if (!(lst = iochan_create(cs_fileno(l), listener, EVENT_INPUT |
658          EVENT_EXCEPT)))
659     {
660         yaz_log(LOG_FATAL|LOG_ERRNO, "Failed to create IOCHAN-type");
661         cs_close (l);
662         return -1;
663     }
664     iochan_setdata(lst, l);
665
666     /* Ensure our listener chain is setup properly */
667     lst->next = pListener;
668     pListener = lst;
669     return 0; /* OK */
670 }
671
672 #ifndef WIN32
673 /* UNIX only (for windows we don't need to catch the signals) */
674 static void catchchld(int num)
675 {
676     while (waitpid(-1, 0, WNOHANG) > 0)
677         ;
678     signal(SIGCHLD, catchchld);
679 }
680 #endif
681
682 statserv_options_block *statserv_getcontrol(void)
683 {
684     static statserv_options_block cb;
685
686     memcpy(&cb, &control_block, sizeof(cb));
687     return &cb;
688 }
689
690 void statserv_setcontrol(statserv_options_block *block)
691 {
692     memcpy(&control_block, block, sizeof(*block));
693 }
694
695 void statserv_add_soap_handler(int (*h)(struct bend_soap_rr *rr),
696                                const char *ns)
697 {
698     struct bend_soap_handler *sh = (struct bend_soap_handler *)
699             xmalloc(sizeof(*sh));
700
701     sh->handler = h;
702     sh->ns = xstrdup(ns);
703     sh->next = control_block.soap_handlers;
704     control_block.soap_handlers = sh;
705     yaz_log(LOG_LOG, "soap handler added");
706 }
707
708 static void statserv_reset(void)
709 {
710     struct bend_soap_handler *sh = control_block.soap_handlers;
711
712     control_block.soap_handlers = 0;
713     while (sh)
714     {
715         struct bend_soap_handler *sh_next = sh->next;
716         xfree (sh->ns);
717         xfree (sh);
718         sh = sh_next;
719     }
720 }
721
722 int statserv_start(int argc, char **argv)
723 {
724     int ret;
725
726 #ifdef WIN32
727     /* We need to initialize the thread list */
728     ThreadList_Initialize();
729 /* WIN32 */
730 #endif
731     
732 #ifdef WIN32
733     if ((me = strrchr (argv[0], '\\')))
734         me++;
735     else
736         me = argv[0];
737 #else
738     me = argv[0];
739 #endif
740     if (control_block.options_func(argc, argv))
741         return(1);
742     
743     if (control_block.bend_start)
744         (*control_block.bend_start)(&control_block);
745 #ifdef WIN32
746     yaz_log (LOG_LOG, "Starting server %s", me);
747 #else
748 /* UNIX */
749     if (control_block.inetd)
750         inetd_connection(control_block.default_proto);
751     else
752     {
753         yaz_log (LOG_LOG, "Starting server %s pid=%d", me, getpid());
754 #if 0
755         sigset_t sigs_to_block;
756         
757         sigemptyset(&sigs_to_block);
758         sigaddset (&sigs_to_block, SIGTERM);
759         pthread_sigmask (SIG_BLOCK, &sigs_to_block, 0);
760         /* missing... */
761 #endif
762         if (control_block.dynamic)
763             signal(SIGCHLD, catchchld);
764     }
765     signal (SIGPIPE, SIG_IGN);
766     signal (SIGTERM, sigterm);
767     if (*control_block.setuid)
768     {
769         struct passwd *pw;
770         
771         if (!(pw = getpwnam(control_block.setuid)))
772         {
773             yaz_log(LOG_FATAL, "%s: Unknown user", control_block.setuid);
774             return(1);
775         }
776         if (setuid(pw->pw_uid) < 0)
777         {
778             yaz_log(LOG_FATAL|LOG_ERRNO, "setuid");
779             exit(1);
780         }
781     }
782 /* UNIX */
783 #endif
784     
785     
786     if ((pListener == NULL) && *control_block.default_listen)
787         add_listener(control_block.default_listen,
788                      control_block.default_proto);
789         
790     if (pListener == NULL)
791         ret = 1;
792     else
793     {
794         yaz_log(LOG_LOG, "Entering event loop.");
795         ret = event_loop(&pListener);
796     }
797     return ret;
798 }
799
800 int check_options(int argc, char **argv)
801 {
802     int ret = 0, r;
803     char *arg;
804
805     while ((ret = options("1a:iszSTl:v:u:c:w:t:k:d:", argv, argc, &arg)) != -2)
806     {
807         switch (ret)
808         {
809         case 0:
810             if (add_listener(arg, control_block.default_proto))
811                 return 1;  /* failed to create listener */
812             break;
813         case '1':        
814             control_block.one_shot = 1;
815             control_block.dynamic = 0;
816             break;
817         case 'z':
818             control_block.default_proto = PROTO_Z3950;
819             break;
820         case 's':
821             fprintf (stderr, "%s: SR protocol no longer supported\n", me);
822             exit (1);
823             break;
824         case 'S':
825             control_block.dynamic = 0;
826             break;
827         case 'T':
828 #if YAZ_POSIX_THREADS
829             control_block.dynamic = 0;
830             control_block.threads = 1;
831 #elif YAZ_GNU_THREADS
832             control_block.dynamic = 0;
833             control_block.threads = 1;
834 #else
835             fprintf(stderr, "%s: Threaded mode not available.\n", me);
836             return 1;
837 #endif
838             break;
839         case 'l':
840             strcpy(control_block.logfile, arg ? arg : "");
841             yaz_log_init(control_block.loglevel, me, control_block.logfile);
842             break;
843         case 'v':
844             control_block.loglevel = yaz_log_mask_str(arg);
845             yaz_log_init(control_block.loglevel, me, control_block.logfile);
846             break;
847         case 'a':
848             strcpy(control_block.apdufile, arg ? arg : "");
849             break;
850         case 'u':
851             strcpy(control_block.setuid, arg ? arg : "");
852             break;
853         case 'c':
854             strcpy(control_block.configname, arg ? arg : "");
855             break;
856         case 'd':
857             strcpy(control_block.daemon_name, arg ? arg : "");
858             break;
859         case 't':
860             if (!arg || !(r = atoi(arg)))
861             {
862                 fprintf(stderr, "%s: Specify positive timeout for -t.\n", me);
863                 return(1);
864             }
865             control_block.idle_timeout = r;
866             break;
867         case  'k':
868             if (!arg || !(r = atoi(arg)))
869             {
870                 fprintf(stderr, "%s: Specify positive size for -k.\n", me);
871                 return(1);
872             }
873             control_block.maxrecordsize = r * 1024;
874             break;
875         case 'i':
876             control_block.inetd = 1;
877             break;
878         case 'w':
879             if (chdir(arg))
880             {
881                 perror(arg);            
882                 return 1;
883             }
884             break;
885         default:
886             fprintf(stderr, "Usage: %s [ -a <pdufile> -v <loglevel>"
887                     " -l <logfile> -u <user> -c <config> -t <minutes>"
888                     " -k <kilobytes> -d <daemon>"
889                         " -ziST1 -w <directory> <listender-addr>... ]\n", me);
890             return 1;
891         }
892     }
893     return 0;
894 }
895
896 #ifdef WIN32
897 typedef struct _Args
898 {
899     char **argv;
900     int argc;
901 } Args; 
902
903 static Args ArgDetails;
904
905 /* name of the executable */
906 #define SZAPPNAME            "server"
907
908 /* list of service dependencies - "dep1\0dep2\0\0" */
909 #define SZDEPENDENCIES       ""
910
911 int statserv_main(int argc, char **argv,
912                   bend_initresult *(*bend_init)(bend_initrequest *r),
913                   void (*bend_close)(void *handle))
914 {
915     statserv_options_block *cb = statserv_getcontrol();
916     
917     cb->bend_init = bend_init;
918     cb->bend_close = bend_close;
919
920     statserv_setcontrol(cb);
921
922     /* Lets setup the Arg structure */
923     ArgDetails.argc = argc;
924     ArgDetails.argv = argv;
925     
926     /* Now setup the service with the service controller */
927     SetupService(argc, argv, &ArgDetails, SZAPPNAME,
928                  cb->service_name, /* internal service name */
929                  cb->service_display_name, /* displayed name */
930                  SZDEPENDENCIES);
931     return 0;
932 }
933
934 int StartAppService(void *pHandle, int argc, char **argv)
935 {
936     /* Initializes the App */
937     return 1;
938 }
939
940 void RunAppService(void *pHandle)
941 {
942     Args *pArgs = (Args *)pHandle;
943     
944     /* Starts the app running */
945     statserv_start(pArgs->argc, pArgs->argv);
946 }
947
948 void StopAppService(void *pHandle)
949 {
950     /* Stops the app */
951     statserv_closedown();
952     statserv_reset();
953 }
954 /* WIN32 */
955 #else
956 /* UNIX */
957 int statserv_main(int argc, char **argv,
958                   bend_initresult *(*bend_init)(bend_initrequest *r),
959                   void (*bend_close)(void *handle))
960 {
961     int ret;
962     statserv_options_block *cb = statserv_getcontrol();
963     
964     cb->bend_init = bend_init;
965     cb->bend_close = bend_close;
966
967     statserv_setcontrol(cb);
968     ret = statserv_start (argc, argv);
969     statserv_closedown ();
970     statserv_reset();
971     return ret;
972 }
973 #endif