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.3 2004-01-15 10:05:56 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 */
83 static int max_sessions = 0;
86 * handle incoming connect requests.
87 * The dynamic mode is a bit tricky mostly because we want to avoid
88 * doing all of the listening and accepting in the parent - it's
93 typedef struct _ThreadList ThreadList;
102 static ThreadList *pFirstThread;
103 static CRITICAL_SECTION Thread_CritSect;
104 static BOOL bInitialized = FALSE;
106 static void ThreadList_Initialize()
108 /* Initialize the critical Sections */
109 InitializeCriticalSection(&Thread_CritSect);
111 /* Set the first thraed */
114 /* we have been initialized */
118 static void statserv_add(HANDLE hThread, IOCHAN pIOChannel)
120 /* Only one thread can go through this section at a time */
121 EnterCriticalSection(&Thread_CritSect);
124 /* Lets create our new object */
125 ThreadList *pNewThread = (ThreadList *)malloc(sizeof(ThreadList));
126 pNewThread->hThread = hThread;
127 pNewThread->pIOChannel = pIOChannel;
128 pNewThread->pNext = pFirstThread;
129 pFirstThread = pNewThread;
131 /* Lets let somebody else create a new object now */
132 LeaveCriticalSection(&Thread_CritSect);
136 void statserv_remove(IOCHAN pIOChannel)
138 /* Only one thread can go through this section at a time */
139 EnterCriticalSection(&Thread_CritSect);
142 ThreadList *pCurrentThread = pFirstThread;
143 ThreadList *pNextThread;
144 ThreadList *pPrevThread =NULL;
146 /* Step through alll the threads */
147 for (; pCurrentThread != NULL; pCurrentThread = pNextThread)
149 /* We only need to compare on the IO Channel */
150 if (pCurrentThread->pIOChannel == pIOChannel)
152 /* We have found the thread we want to delete */
153 /* First of all reset the next pointers */
154 if (pPrevThread == NULL)
155 pFirstThread = pCurrentThread->pNext;
157 pPrevThread->pNext = pCurrentThread->pNext;
159 /* All we need todo now is delete the memory */
160 free(pCurrentThread);
162 /* No need to look at any more threads */
167 /* We need to look at another thread */
168 pNextThread = pCurrentThread->pNext;
169 pPrevThread = pCurrentThread;
173 /* Lets let somebody else remove an object now */
174 LeaveCriticalSection(&Thread_CritSect);
178 /* WIN32 statserv_closedown */
179 void statserv_closedown()
181 /* Shouldn't do anything if we are not initialized */
185 HANDLE *pThreadHandles = NULL;
187 /* We need to stop threads adding and removing while we */
188 /* start the closedown process */
189 EnterCriticalSection(&Thread_CritSect);
192 /* We have exclusive access to the thread stuff now */
193 /* Y didn't i use a semaphore - Oh well never mind */
194 ThreadList *pCurrentThread = pFirstThread;
196 /* Before we do anything else, we need to shutdown the listener */
197 if (pListener != NULL)
198 iochan_destroy(pListener);
200 for (; pCurrentThread != NULL; pCurrentThread = pCurrentThread->pNext)
202 /* Just destroy the IOCHAN, that should do the trick */
203 iochan_destroy(pCurrentThread->pIOChannel);
204 closesocket(pCurrentThread->pIOChannel->fd);
206 /* Keep a running count of our handles */
212 HANDLE *pCurrentHandle ;
214 /* Allocate the thread handle array */
215 pThreadHandles = (HANDLE *)malloc(sizeof(HANDLE) * iHandles);
216 pCurrentHandle = pThreadHandles;
218 for (pCurrentThread = pFirstThread;
219 pCurrentThread != NULL;
220 pCurrentThread = pCurrentThread->pNext, pCurrentHandle++)
222 /* Just the handle */
223 *pCurrentHandle = pCurrentThread->hThread;
227 /* We can now leave the critical section */
228 LeaveCriticalSection(&Thread_CritSect);
231 /* Now we can really do something */
234 logf (LOG_LOG, "waiting for %d to die", iHandles);
235 /* This will now wait, until all the threads close */
236 WaitForMultipleObjects(iHandles, pThreadHandles, TRUE, INFINITE);
238 /* Free the memory we allocated for the handle array */
239 free(pThreadHandles);
242 if (control_block.bend_stop)
243 (*control_block.bend_stop)(&control_block);
244 /* No longer require the critical section, since all threads are dead */
245 DeleteCriticalSection(&Thread_CritSect);
249 void __cdecl event_loop_thread (IOCHAN iochan)
251 event_loop (&iochan);
255 static void listener(IOCHAN h, int event)
257 COMSTACK line = (COMSTACK) iochan_getdata(h);
262 if (event == EVENT_INPUT)
264 if ((res = cs_listen(line, 0, 0)) < 0)
266 yaz_log(LOG_FATAL, "cs_listen failed");
271 yaz_log(LOG_DEBUG, "listen ok");
272 iochan_setevent(h, EVENT_OUTPUT);
273 iochan_setflags(h, EVENT_OUTPUT | EVENT_EXCEPT); /* set up for acpt */
275 else if (event == EVENT_OUTPUT)
277 COMSTACK new_line = cs_accept(line);
283 yaz_log(LOG_FATAL, "Accept failed.");
284 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT);
287 yaz_log(LOG_DEBUG, "Accept ok");
289 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session,
292 yaz_log(LOG_FATAL, "Failed to create iochan");
297 yaz_log(LOG_DEBUG, "Creating association");
298 if (!(newas = create_association(new_chan, new_line)))
300 yaz_log(LOG_FATAL, "Failed to create new assoc.");
304 newas->cs_get_mask = EVENT_INPUT;
305 newas->cs_put_mask = 0;
306 newas->cs_accept_mask = 0;
308 yaz_log(LOG_DEBUG, "Setting timeout %d", control_block.idle_timeout);
309 iochan_setdata(new_chan, newas);
310 iochan_settimeout(new_chan, 60);
312 /* Now what we need todo is create a new thread with this iochan as
314 newHandle = (HANDLE) _beginthread(event_loop_thread, 0, new_chan);
315 if (newHandle == (HANDLE) -1)
318 yaz_log(LOG_FATAL|LOG_ERRNO, "Failed to create new thread.");
322 /* We successfully created the thread, so add it to the list */
323 statserv_add(newHandle, new_chan);
325 yaz_log(LOG_DEBUG, "Created new thread, id = %ld iochan %p",(long) newHandle, new_chan);
326 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
330 yaz_log(LOG_FATAL, "Bad event on listener.");
336 int statserv_must_terminate(void)
343 static int term_flag = 0;
344 /* To save having an #ifdef in event_loop we need to
345 define this empty function
347 int statserv_must_terminate(void)
352 void statserv_remove(IOCHAN pIOChannel)
356 void statserv_closedown()
360 if (control_block.bend_stop)
361 (*control_block.bend_stop)(&control_block);
362 for (p = pListener; p; p = p->next)
368 void sigterm(int sig)
373 static void *new_session (void *vp);
374 static int no_sessions = 0;
377 static void listener(IOCHAN h, int event)
379 COMSTACK line = (COMSTACK) iochan_getdata(h);
381 static int child = 0;
384 if (event == EVENT_INPUT)
386 if (control_block.dynamic && !child)
393 yaz_log(LOG_FATAL|LOG_ERRNO, "pipe");
397 if ((res = fork()) < 0)
399 yaz_log(LOG_FATAL|LOG_ERRNO, "fork");
403 else if (res == 0) /* child */
410 for (pp = pListener; pp; pp = iochan_getnext(pp))
414 COMSTACK l = (COMSTACK)iochan_getdata(pp);
419 sprintf(nbuf, "%s(%d)", me, getpid());
420 yaz_log_init(control_block.loglevel, nbuf, 0);
421 /* ensure that bend_stop is not called when each child exits -
422 only for the main process ..
424 control_block.bend_stop = 0;
429 /* wait for child to take the call */
435 if ((res = read(hand[0], dummy, 1)) < 0 &&
436 yaz_errno() != EINTR)
438 yaz_log(LOG_FATAL|LOG_ERRNO, "handshake read");
444 yaz_log(LOG_DEBUG, "P: Child has taken the call");
449 if ((res = cs_listen_check(line, 0, 0, control_block.check_ip,
450 control_block.daemon_name)) < 0)
452 yaz_log(LOG_WARN|LOG_ERRNO, "cs_listen failed");
457 yaz_log(LOG_DEBUG, "listen ok");
458 iochan_setevent(h, EVENT_OUTPUT);
459 iochan_setflags(h, EVENT_OUTPUT | EVENT_EXCEPT); /* set up for acpt */
461 /* in dynamic mode, only the child ever comes down here */
462 else if (event == EVENT_OUTPUT)
464 COMSTACK new_line = cs_accept(line);
468 yaz_log(LOG_FATAL, "Accept failed.");
469 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
472 yaz_log(LOG_DEBUG, "accept ok");
473 if (control_block.dynamic)
476 /* close our half of the listener socket */
477 for (pp = pListener; pp; pp = iochan_getnext(pp))
479 COMSTACK l = (COMSTACK)iochan_getdata(pp);
484 yaz_log(LOG_DEBUG, "Releasing parent");
489 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
492 #if YAZ_POSIX_THREADS
493 if (control_block.threads)
495 pthread_t child_thread;
496 pthread_create (&child_thread, 0, new_session, new_line);
497 pthread_detach (child_thread);
500 new_session(new_line);
501 #elif YAZ_GNU_THREADS
502 if (control_block.threads)
507 attr = pth_attr_new ();
508 pth_attr_set (attr, PTH_ATTR_JOINABLE, FALSE);
509 pth_attr_set (attr, PTH_ATTR_STACK_SIZE, 32*1024);
510 pth_attr_set (attr, PTH_ATTR_NAME, "session");
511 yaz_log (LOG_LOG, "pth_spawn begin");
512 child_thread = pth_spawn (attr, new_session, new_line);
513 yaz_log (LOG_LOG, "pth_spawn finish");
514 pth_attr_destroy (attr);
517 new_session(new_line);
519 new_session(new_line);
522 else if (event == EVENT_TIMEOUT)
524 yaz_log(LOG_LOG, "Shutting down listener.");
529 yaz_log(LOG_FATAL, "Bad event on listener.");
534 static void *new_session (void *vp)
539 COMSTACK new_line = (COMSTACK) vp;
541 unsigned cs_get_mask, cs_accept_mask, mask =
542 ((new_line->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
543 ((new_line->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
547 cs_accept_mask = mask; /* accept didn't complete */
552 cs_accept_mask = 0; /* accept completed. */
553 cs_get_mask = mask = EVENT_INPUT;
556 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session, mask)))
558 yaz_log(LOG_FATAL, "Failed to create iochan");
561 if (!(newas = create_association(new_chan, new_line)))
563 yaz_log(LOG_FATAL, "Failed to create new assoc.");
566 newas->cs_accept_mask = cs_accept_mask;
567 newas->cs_get_mask = cs_get_mask;
569 iochan_setdata(new_chan, newas);
570 iochan_settimeout(new_chan, 60);
572 a = cs_addrstr(new_line);
576 yaz_log(LOG_LOG, "Starting session %d from %s",
577 no_sessions, a ? a : "[Unknown]");
578 if (max_sessions && no_sessions == max_sessions)
579 control_block.one_shot = 1;
580 if (control_block.threads)
582 event_loop(&new_chan);
586 new_chan->next = pListener;
587 pListener = new_chan;
595 static void inetd_connection(int what)
602 if ((line = cs_createbysocket(0, tcpip_type, 0, what)))
604 if ((chan = iochan_create(cs_fileno(line), ir_session, EVENT_INPUT)))
606 if ((assoc = create_association(chan, line)))
608 iochan_setdata(chan, assoc);
609 iochan_settimeout(chan, 60);
610 addr = cs_addrstr(line);
611 yaz_log(LOG_LOG, "Inetd association from %s",
612 addr ? addr : "[UNKNOWN]");
613 assoc->cs_get_mask = EVENT_INPUT;
617 yaz_log(LOG_FATAL, "Failed to create association structure");
619 chan->next = pListener;
624 yaz_log(LOG_FATAL, "Failed to create iochan");
629 yaz_log(LOG_ERRNO|LOG_FATAL, "Failed to create comstack on socket 0");
634 * Set up a listening endpoint, and give it to the event-handler.
636 static int add_listener(char *where, int what)
643 if (control_block.dynamic)
645 else if (control_block.threads)
650 yaz_log(LOG_LOG, "Adding %s %s listener on %s", mode,
651 what == PROTO_SR ? "SR" : "Z3950", where);
653 l = cs_create_host(where, 2, &ap);
656 yaz_log(LOG_FATAL|LOG_ERRNO, "Failed to listen on %s", where);
659 if (cs_bind(l, ap, CS_SERVER) < 0)
661 yaz_log(LOG_FATAL|LOG_ERRNO, "Failed to bind to %s", where);
665 if (!(lst = iochan_create(cs_fileno(l), listener, EVENT_INPUT |
668 yaz_log(LOG_FATAL|LOG_ERRNO, "Failed to create IOCHAN-type");
672 iochan_setdata(lst, l);
674 /* Ensure our listener chain is setup properly */
675 lst->next = pListener;
681 /* UNIX only (for windows we don't need to catch the signals) */
682 static void catchchld(int num)
684 while (waitpid(-1, 0, WNOHANG) > 0)
686 signal(SIGCHLD, catchchld);
690 statserv_options_block *statserv_getcontrol(void)
692 static statserv_options_block cb;
694 memcpy(&cb, &control_block, sizeof(cb));
698 void statserv_setcontrol(statserv_options_block *block)
700 memcpy(&control_block, block, sizeof(*block));
703 static void statserv_reset(void)
707 int statserv_start(int argc, char **argv)
712 /* We need to initialize the thread list */
713 ThreadList_Initialize();
718 if ((me = strrchr (argv[0], '\\')))
725 if (control_block.options_func(argc, argv))
728 if (control_block.bend_start)
729 (*control_block.bend_start)(&control_block);
731 yaz_log (LOG_LOG, "Starting server %s", me);
734 if (control_block.inetd)
735 inetd_connection(control_block.default_proto);
738 yaz_log (LOG_LOG, "Starting server %s pid=%d", me, getpid());
740 sigset_t sigs_to_block;
742 sigemptyset(&sigs_to_block);
743 sigaddset (&sigs_to_block, SIGTERM);
744 pthread_sigmask (SIG_BLOCK, &sigs_to_block, 0);
747 if (control_block.dynamic)
748 signal(SIGCHLD, catchchld);
750 signal (SIGPIPE, SIG_IGN);
751 signal (SIGTERM, sigterm);
752 if (*control_block.setuid)
756 if (!(pw = getpwnam(control_block.setuid)))
758 yaz_log(LOG_FATAL, "%s: Unknown user", control_block.setuid);
761 if (setuid(pw->pw_uid) < 0)
763 yaz_log(LOG_FATAL|LOG_ERRNO, "setuid");
771 if ((pListener == NULL) && *control_block.default_listen)
772 add_listener(control_block.default_listen,
773 control_block.default_proto);
775 if (pListener == NULL)
779 yaz_log(LOG_LOG, "Entering event loop.");
780 ret = event_loop(&pListener);
785 int check_options(int argc, char **argv)
790 while ((ret = options("1a:iszSTl:v:u:c:w:t:k:d:D:", argv, argc, &arg)) != -2)
795 if (add_listener(arg, control_block.default_proto))
796 return 1; /* failed to create listener */
799 control_block.one_shot = 1;
800 control_block.dynamic = 0;
803 control_block.default_proto = PROTO_Z3950;
806 fprintf (stderr, "%s: SR protocol no longer supported\n", me);
810 control_block.dynamic = 0;
813 #if YAZ_POSIX_THREADS
814 control_block.dynamic = 0;
815 control_block.threads = 1;
816 #elif YAZ_GNU_THREADS
817 control_block.dynamic = 0;
818 control_block.threads = 1;
820 fprintf(stderr, "%s: Threaded mode not available.\n", me);
825 strcpy(control_block.logfile, arg ? arg : "");
826 yaz_log_init(control_block.loglevel, me, control_block.logfile);
829 control_block.loglevel = yaz_log_mask_str(arg);
830 yaz_log_init(control_block.loglevel, me, control_block.logfile);
833 strcpy(control_block.apdufile, arg ? arg : "");
836 strcpy(control_block.setuid, arg ? arg : "");
839 strcpy(control_block.configname, arg ? arg : "");
842 strcpy(control_block.daemon_name, arg ? arg : "");
845 if (!arg || !(r = atoi(arg)))
847 fprintf(stderr, "%s: Specify positive timeout for -t.\n", me);
850 control_block.idle_timeout = r;
853 if (!arg || !(r = atoi(arg)))
855 fprintf(stderr, "%s: Specify positive size for -k.\n", me);
858 control_block.maxrecordsize = r * 1024;
861 control_block.inetd = 1;
871 max_sessions = atoi(arg);
874 fprintf(stderr, "Usage: %s [ -a <pdufile> -v <loglevel>"
875 " -l <logfile> -u <user> -c <config> -t <minutes>"
876 " -k <kilobytes> -d <daemon>"
877 " -ziST1 -w <directory> <listener-addr>... ]\n", me);
891 static Args ArgDetails;
893 /* name of the executable */
894 #define SZAPPNAME "server"
896 /* list of service dependencies - "dep1\0dep2\0\0" */
897 #define SZDEPENDENCIES ""
899 int statserv_main(int argc, char **argv,
900 bend_initresult *(*bend_init)(bend_initrequest *r),
901 void (*bend_close)(void *handle))
903 statserv_options_block *cb = statserv_getcontrol();
905 cb->bend_init = bend_init;
906 cb->bend_close = bend_close;
908 statserv_setcontrol(cb);
910 /* Lets setup the Arg structure */
911 ArgDetails.argc = argc;
912 ArgDetails.argv = argv;
914 /* Now setup the service with the service controller */
915 SetupService(argc, argv, &ArgDetails, SZAPPNAME,
916 cb->service_name, /* internal service name */
917 cb->service_display_name, /* displayed name */
922 int StartAppService(void *pHandle, int argc, char **argv)
924 /* Initializes the App */
928 void RunAppService(void *pHandle)
930 Args *pArgs = (Args *)pHandle;
932 /* Starts the app running */
933 statserv_start(pArgs->argc, pArgs->argv);
936 void StopAppService(void *pHandle)
939 statserv_closedown();
945 int statserv_main(int argc, char **argv,
946 bend_initresult *(*bend_init)(bend_initrequest *r),
947 void (*bend_close)(void *handle))
950 statserv_options_block *cb = statserv_getcontrol();
952 cb->bend_init = bend_init;
953 cb->bend_close = bend_close;
955 statserv_setcontrol(cb);
956 ret = statserv_start (argc, argv);
957 statserv_closedown ();