2 * Copyright (c) 1995-2003, Index Data
3 * See the file LICENSE for details.
4 * Sebastian Hammer, Adam Dickmeiss
6 * NT threaded server code by
7 * Chas Woodfield, Fretwell Downing Informatics.
9 * $Id: statserv.c,v 1.93 2003-02-17 21:23:31 adam Exp $
34 #include <yaz/comstack.h>
35 #include <yaz/tcpip.h>
36 #include <yaz/options.h>
38 #include <yaz/xmosi.h>
43 #include <yaz/statserv.h>
45 static IOCHAN pListener = NULL;
47 static char *me = "statserver";
51 int check_options(int argc, char **argv);
52 statserv_options_block control_block = {
54 0, /* threaded mode */
55 0, /* one shot (single session) */
56 LOG_DEFAULT_LEVEL, /* log level */
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 */
65 0, /* bend_start handler */
66 0, /* bend_stop handler */
67 check_options, /* Default routine, for checking the run-time arguments */
70 0, /* default value for inet deamon */
71 0, /* handle (for service, etc) */
72 0, /* bend_init handle */
73 0, /* bend_close handle */
75 "Z39.50 Server", /* NT Service Name */
76 "Server", /* NT application Name */
77 "", /* NT Service Dependencies */
78 "Z39.50 Server", /* NT Service Display Name */
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
91 typedef struct _ThreadList ThreadList;
100 static ThreadList *pFirstThread;
101 static CRITICAL_SECTION Thread_CritSect;
102 static BOOL bInitialized = FALSE;
104 static void ThreadList_Initialize()
106 /* Initialize the critical Sections */
107 InitializeCriticalSection(&Thread_CritSect);
109 /* Set the first thraed */
112 /* we have been initialized */
116 static void statserv_add(HANDLE hThread, IOCHAN pIOChannel)
118 /* Only one thread can go through this section at a time */
119 EnterCriticalSection(&Thread_CritSect);
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;
129 /* Lets let somebody else create a new object now */
130 LeaveCriticalSection(&Thread_CritSect);
134 void statserv_remove(IOCHAN pIOChannel)
136 /* Only one thread can go through this section at a time */
137 EnterCriticalSection(&Thread_CritSect);
140 ThreadList *pCurrentThread = pFirstThread;
141 ThreadList *pNextThread;
142 ThreadList *pPrevThread =NULL;
144 /* Step through alll the threads */
145 for (; pCurrentThread != NULL; pCurrentThread = pNextThread)
147 /* We only need to compare on the IO Channel */
148 if (pCurrentThread->pIOChannel == pIOChannel)
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;
155 pPrevThread->pNext = pCurrentThread->pNext;
157 /* All we need todo now is delete the memory */
158 free(pCurrentThread);
160 /* No need to look at any more threads */
165 /* We need to look at another thread */
166 pNextThread = pCurrentThread->pNext;
167 pPrevThread = pCurrentThread;
171 /* Lets let somebody else remove an object now */
172 LeaveCriticalSection(&Thread_CritSect);
176 /* WIN32 statserv_closedown */
177 void statserv_closedown()
179 /* Shouldn't do anything if we are not initialized */
183 HANDLE *pThreadHandles = NULL;
185 /* We need to stop threads adding and removing while we */
186 /* start the closedown process */
187 EnterCriticalSection(&Thread_CritSect);
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;
194 /* Before we do anything else, we need to shutdown the listener */
195 if (pListener != NULL)
196 iochan_destroy(pListener);
198 for (; pCurrentThread != NULL; pCurrentThread = pCurrentThread->pNext)
200 /* Just destroy the IOCHAN, that should do the trick */
201 iochan_destroy(pCurrentThread->pIOChannel);
202 closesocket(pCurrentThread->pIOChannel->fd);
204 /* Keep a running count of our handles */
210 HANDLE *pCurrentHandle ;
212 /* Allocate the thread handle array */
213 pThreadHandles = (HANDLE *)malloc(sizeof(HANDLE) * iHandles);
214 pCurrentHandle = pThreadHandles;
216 for (pCurrentThread = pFirstThread;
217 pCurrentThread != NULL;
218 pCurrentThread = pCurrentThread->pNext, pCurrentHandle++)
220 /* Just the handle */
221 *pCurrentHandle = pCurrentThread->hThread;
225 /* We can now leave the critical section */
226 LeaveCriticalSection(&Thread_CritSect);
229 /* Now we can really do something */
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);
236 /* Free the memory we allocated for the handle array */
237 free(pThreadHandles);
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);
247 void __cdecl event_loop_thread (IOCHAN iochan)
249 event_loop (&iochan);
253 static void listener(IOCHAN h, int event)
255 COMSTACK line = (COMSTACK) iochan_getdata(h);
260 if (event == EVENT_INPUT)
262 if ((res = cs_listen(line, 0, 0)) < 0)
264 yaz_log(LOG_FATAL, "cs_listen failed");
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 */
273 else if (event == EVENT_OUTPUT)
275 COMSTACK new_line = cs_accept(line);
281 yaz_log(LOG_FATAL, "Accept failed.");
282 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT);
285 yaz_log(LOG_DEBUG, "Accept ok");
287 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session,
290 yaz_log(LOG_FATAL, "Failed to create iochan");
295 yaz_log(LOG_DEBUG, "Creating association");
296 if (!(newas = create_association(new_chan, new_line)))
298 yaz_log(LOG_FATAL, "Failed to create new assoc.");
302 newas->cs_get_mask = EVENT_INPUT;
303 newas->cs_put_mask = 0;
304 newas->cs_accept_mask = 0;
306 yaz_log(LOG_DEBUG, "Setting timeout %d", control_block.idle_timeout);
307 iochan_setdata(new_chan, newas);
308 iochan_settimeout(new_chan, 60);
310 /* Now what we need todo is create a new thread with this iochan as
312 newHandle = (HANDLE) _beginthread(event_loop_thread, 0, new_chan);
313 if (newHandle == (HANDLE) -1)
316 yaz_log(LOG_FATAL|LOG_ERRNO, "Failed to create new thread.");
320 /* We successfully created the thread, so add it to the list */
321 statserv_add(newHandle, new_chan);
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 */
328 yaz_log(LOG_FATAL, "Bad event on listener.");
334 int statserv_must_terminate(void)
341 static int term_flag = 0;
342 /* To save having an #ifdef in event_loop we need to
343 define this empty function
345 int statserv_must_terminate(void)
350 void statserv_remove(IOCHAN pIOChannel)
354 void statserv_closedown()
358 if (control_block.bend_stop)
359 (*control_block.bend_stop)(&control_block);
360 for (p = pListener; p; p = p->next)
366 void sigterm(int sig)
371 static void *new_session (void *vp);
372 static int no_sessions = 0;
375 static void listener(IOCHAN h, int event)
377 COMSTACK line = (COMSTACK) iochan_getdata(h);
379 static int child = 0;
382 if (event == EVENT_INPUT)
384 if (control_block.dynamic && !child)
391 yaz_log(LOG_FATAL|LOG_ERRNO, "pipe");
395 if ((res = fork()) < 0)
397 yaz_log(LOG_FATAL|LOG_ERRNO, "fork");
401 else if (res == 0) /* child */
408 for (pp = pListener; pp; pp = iochan_getnext(pp))
412 COMSTACK l = (COMSTACK)iochan_getdata(pp);
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 ..
422 control_block.bend_stop = 0;
427 /* wait for child to take the call */
433 if ((res = read(hand[0], dummy, 1)) < 0 &&
434 yaz_errno() != EINTR)
436 yaz_log(LOG_FATAL|LOG_ERRNO, "handshake read");
442 yaz_log(LOG_DEBUG, "P: Child has taken the call");
447 if ((res = cs_listen_check(line, 0, 0, control_block.check_ip,
448 control_block.daemon_name)) < 0)
450 yaz_log(LOG_WARN|LOG_ERRNO, "cs_listen failed");
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 */
459 /* in dynamic mode, only the child ever comes down here */
460 else if (event == EVENT_OUTPUT)
462 COMSTACK new_line = cs_accept(line);
466 yaz_log(LOG_FATAL, "Accept failed.");
467 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
470 yaz_log(LOG_DEBUG, "accept ok");
471 if (control_block.dynamic)
474 /* close our half of the listener socket */
475 for (pp = pListener; pp; pp = iochan_getnext(pp))
477 COMSTACK l = (COMSTACK)iochan_getdata(pp);
482 yaz_log(LOG_DEBUG, "Releasing parent");
487 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
490 #if YAZ_POSIX_THREADS
491 if (control_block.threads)
493 pthread_t child_thread;
494 pthread_create (&child_thread, 0, new_session, new_line);
495 pthread_detach (child_thread);
498 new_session(new_line);
499 #elif YAZ_GNU_THREADS
500 if (control_block.threads)
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);
515 new_session(new_line);
517 new_session(new_line);
520 else if (event == EVENT_TIMEOUT)
522 yaz_log(LOG_LOG, "Shutting down listener.");
527 yaz_log(LOG_FATAL, "Bad event on listener.");
532 static void *new_session (void *vp)
537 COMSTACK new_line = (COMSTACK) vp;
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);
545 cs_accept_mask = mask; /* accept didn't complete */
550 cs_accept_mask = 0; /* accept completed. */
551 cs_get_mask = mask = EVENT_INPUT;
554 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session, mask)))
556 yaz_log(LOG_FATAL, "Failed to create iochan");
559 if (!(newas = create_association(new_chan, new_line)))
561 yaz_log(LOG_FATAL, "Failed to create new assoc.");
564 newas->cs_accept_mask = cs_accept_mask;
565 newas->cs_get_mask = cs_get_mask;
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)
574 event_loop(&new_chan);
578 new_chan->next = pListener;
579 pListener = new_chan;
587 static void inetd_connection(int what)
594 if ((line = cs_createbysocket(0, tcpip_type, 0, what)))
596 if ((chan = iochan_create(cs_fileno(line), ir_session, EVENT_INPUT)))
598 if ((assoc = create_association(chan, line)))
600 iochan_setdata(chan, assoc);
601 iochan_settimeout(chan, control_block.idle_timeout * 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;
609 yaz_log(LOG_FATAL, "Failed to create association structure");
611 chan->next = pListener;
616 yaz_log(LOG_FATAL, "Failed to create iochan");
621 yaz_log(LOG_ERRNO|LOG_FATAL, "Failed to create comstack on socket 0");
626 * Set up a listening endpoint, and give it to the event-handler.
628 static int add_listener(char *where, int what)
635 if (control_block.dynamic)
637 else if (control_block.threads)
642 yaz_log(LOG_LOG, "Adding %s %s listener on %s", mode,
643 what == PROTO_SR ? "SR" : "Z3950", where);
645 l = cs_create_host(where, 0, &ap);
648 yaz_log(LOG_FATAL|LOG_ERRNO, "Failed to listen on %s", where);
651 if (cs_bind(l, ap, CS_SERVER) < 0)
653 yaz_log(LOG_FATAL|LOG_ERRNO, "Failed to bind to %s", where);
657 if (!(lst = iochan_create(cs_fileno(l), listener, EVENT_INPUT |
660 yaz_log(LOG_FATAL|LOG_ERRNO, "Failed to create IOCHAN-type");
664 iochan_setdata(lst, l);
666 /* Ensure our listener chain is setup properly */
667 lst->next = pListener;
673 /* UNIX only (for windows we don't need to catch the signals) */
674 static void catchchld(int num)
676 while (waitpid(-1, 0, WNOHANG) > 0)
678 signal(SIGCHLD, catchchld);
682 statserv_options_block *statserv_getcontrol(void)
684 static statserv_options_block cb;
686 memcpy(&cb, &control_block, sizeof(cb));
690 void statserv_setcontrol(statserv_options_block *block)
692 memcpy(&control_block, block, sizeof(*block));
695 void statserv_add_soap_handler(int (*h)(struct bend_soap_rr *rr),
698 struct bend_soap_handler *sh = (struct bend_soap_handler *)
699 xmalloc(sizeof(*sh));
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");
708 static void statserv_reset(void)
710 struct bend_soap_handler *sh = control_block.soap_handlers;
712 control_block.soap_handlers = 0;
715 struct bend_soap_handler *sh_next = sh->next;
722 int statserv_start(int argc, char **argv)
727 /* We need to initialize the thread list */
728 ThreadList_Initialize();
733 if ((me = strrchr (argv[0], '\\')))
740 if (control_block.options_func(argc, argv))
743 if (control_block.bend_start)
744 (*control_block.bend_start)(&control_block);
746 yaz_log (LOG_LOG, "Starting server %s", me);
749 if (control_block.inetd)
750 inetd_connection(control_block.default_proto);
753 yaz_log (LOG_LOG, "Starting server %s pid=%d", me, getpid());
755 sigset_t sigs_to_block;
757 sigemptyset(&sigs_to_block);
758 sigaddset (&sigs_to_block, SIGTERM);
759 pthread_sigmask (SIG_BLOCK, &sigs_to_block, 0);
762 if (control_block.dynamic)
763 signal(SIGCHLD, catchchld);
765 signal (SIGPIPE, SIG_IGN);
766 signal (SIGTERM, sigterm);
767 if (*control_block.setuid)
771 if (!(pw = getpwnam(control_block.setuid)))
773 yaz_log(LOG_FATAL, "%s: Unknown user", control_block.setuid);
776 if (setuid(pw->pw_uid) < 0)
778 yaz_log(LOG_FATAL|LOG_ERRNO, "setuid");
786 if ((pListener == NULL) && *control_block.default_listen)
787 add_listener(control_block.default_listen,
788 control_block.default_proto);
790 if (pListener == NULL)
794 yaz_log(LOG_LOG, "Entering event loop.");
795 ret = event_loop(&pListener);
800 int check_options(int argc, char **argv)
805 while ((ret = options("1a:iszSTl:v:u:c:w:t:k:d:", argv, argc, &arg)) != -2)
810 if (add_listener(arg, control_block.default_proto))
811 return 1; /* failed to create listener */
814 control_block.one_shot = 1;
815 control_block.dynamic = 0;
818 control_block.default_proto = PROTO_Z3950;
821 fprintf (stderr, "%s: SR protocol no longer supported\n", me);
825 control_block.dynamic = 0;
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;
835 fprintf(stderr, "%s: Threaded mode not available.\n", me);
840 strcpy(control_block.logfile, arg ? arg : "");
841 yaz_log_init(control_block.loglevel, me, control_block.logfile);
844 control_block.loglevel = yaz_log_mask_str(arg);
845 yaz_log_init(control_block.loglevel, me, control_block.logfile);
848 strcpy(control_block.apdufile, arg ? arg : "");
851 strcpy(control_block.setuid, arg ? arg : "");
854 strcpy(control_block.configname, arg ? arg : "");
857 strcpy(control_block.daemon_name, arg ? arg : "");
860 if (!arg || !(r = atoi(arg)))
862 fprintf(stderr, "%s: Specify positive timeout for -t.\n", me);
865 control_block.idle_timeout = r;
868 if (!arg || !(r = atoi(arg)))
870 fprintf(stderr, "%s: Specify positive size for -k.\n", me);
873 control_block.maxrecordsize = r * 1024;
876 control_block.inetd = 1;
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);
903 static Args ArgDetails;
905 /* name of the executable */
906 #define SZAPPNAME "server"
908 /* list of service dependencies - "dep1\0dep2\0\0" */
909 #define SZDEPENDENCIES ""
911 int statserv_main(int argc, char **argv,
912 bend_initresult *(*bend_init)(bend_initrequest *r),
913 void (*bend_close)(void *handle))
915 statserv_options_block *cb = statserv_getcontrol();
917 cb->bend_init = bend_init;
918 cb->bend_close = bend_close;
920 statserv_setcontrol(cb);
922 /* Lets setup the Arg structure */
923 ArgDetails.argc = argc;
924 ArgDetails.argv = argv;
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 */
934 int StartAppService(void *pHandle, int argc, char **argv)
936 /* Initializes the App */
940 void RunAppService(void *pHandle)
942 Args *pArgs = (Args *)pHandle;
944 /* Starts the app running */
945 statserv_start(pArgs->argc, pArgs->argv);
948 void StopAppService(void *pHandle)
951 statserv_closedown();
957 int statserv_main(int argc, char **argv,
958 bend_initresult *(*bend_init)(bend_initrequest *r),
959 void (*bend_close)(void *handle))
962 statserv_options_block *cb = statserv_getcontrol();
964 cb->bend_init = bend_init;
965 cb->bend_close = bend_close;
967 statserv_setcontrol(cb);
968 ret = statserv_start (argc, argv);
969 statserv_closedown ();