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.96 2003-02-23 14:26:58 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;
373 static int max_sessions = 0;
376 static void listener(IOCHAN h, int event)
378 COMSTACK line = (COMSTACK) iochan_getdata(h);
380 static int child = 0;
383 if (event == EVENT_INPUT)
385 if (control_block.dynamic && !child)
392 yaz_log(LOG_FATAL|LOG_ERRNO, "pipe");
396 if ((res = fork()) < 0)
398 yaz_log(LOG_FATAL|LOG_ERRNO, "fork");
402 else if (res == 0) /* child */
409 for (pp = pListener; pp; pp = iochan_getnext(pp))
413 COMSTACK l = (COMSTACK)iochan_getdata(pp);
418 sprintf(nbuf, "%s(%d)", me, getpid());
419 yaz_log_init(control_block.loglevel, nbuf, 0);
420 /* ensure that bend_stop is not called when each child exits -
421 only for the main process ..
423 control_block.bend_stop = 0;
428 /* wait for child to take the call */
434 if ((res = read(hand[0], dummy, 1)) < 0 &&
435 yaz_errno() != EINTR)
437 yaz_log(LOG_FATAL|LOG_ERRNO, "handshake read");
443 yaz_log(LOG_DEBUG, "P: Child has taken the call");
448 if ((res = cs_listen_check(line, 0, 0, control_block.check_ip,
449 control_block.daemon_name)) < 0)
451 yaz_log(LOG_WARN|LOG_ERRNO, "cs_listen failed");
456 yaz_log(LOG_DEBUG, "listen ok");
457 iochan_setevent(h, EVENT_OUTPUT);
458 iochan_setflags(h, EVENT_OUTPUT | EVENT_EXCEPT); /* set up for acpt */
460 /* in dynamic mode, only the child ever comes down here */
461 else if (event == EVENT_OUTPUT)
463 COMSTACK new_line = cs_accept(line);
467 yaz_log(LOG_FATAL, "Accept failed.");
468 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
471 yaz_log(LOG_DEBUG, "accept ok");
472 if (control_block.dynamic)
475 /* close our half of the listener socket */
476 for (pp = pListener; pp; pp = iochan_getnext(pp))
478 COMSTACK l = (COMSTACK)iochan_getdata(pp);
483 yaz_log(LOG_DEBUG, "Releasing parent");
488 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
491 #if YAZ_POSIX_THREADS
492 if (control_block.threads)
494 pthread_t child_thread;
495 pthread_create (&child_thread, 0, new_session, new_line);
496 pthread_detach (child_thread);
499 new_session(new_line);
500 #elif YAZ_GNU_THREADS
501 if (control_block.threads)
506 attr = pth_attr_new ();
507 pth_attr_set (attr, PTH_ATTR_JOINABLE, FALSE);
508 pth_attr_set (attr, PTH_ATTR_STACK_SIZE, 32*1024);
509 pth_attr_set (attr, PTH_ATTR_NAME, "session");
510 yaz_log (LOG_LOG, "pth_spawn begin");
511 child_thread = pth_spawn (attr, new_session, new_line);
512 yaz_log (LOG_LOG, "pth_spawn finish");
513 pth_attr_destroy (attr);
516 new_session(new_line);
518 new_session(new_line);
521 else if (event == EVENT_TIMEOUT)
523 yaz_log(LOG_LOG, "Shutting down listener.");
528 yaz_log(LOG_FATAL, "Bad event on listener.");
533 static void *new_session (void *vp)
538 COMSTACK new_line = (COMSTACK) vp;
540 unsigned cs_get_mask, cs_accept_mask, mask =
541 ((new_line->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
542 ((new_line->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
546 cs_accept_mask = mask; /* accept didn't complete */
551 cs_accept_mask = 0; /* accept completed. */
552 cs_get_mask = mask = EVENT_INPUT;
555 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session, mask)))
557 yaz_log(LOG_FATAL, "Failed to create iochan");
560 if (!(newas = create_association(new_chan, new_line)))
562 yaz_log(LOG_FATAL, "Failed to create new assoc.");
565 newas->cs_accept_mask = cs_accept_mask;
566 newas->cs_get_mask = cs_get_mask;
568 iochan_setdata(new_chan, newas);
569 iochan_settimeout(new_chan, 60);
571 a = cs_addrstr(new_line);
575 yaz_log(LOG_LOG, "Starting session %d from %s",
576 no_sessions, a ? a : "[Unknown]");
577 if (max_sessions && no_sessions == max_sessions)
578 control_block.one_shot = 1;
579 if (control_block.threads)
581 event_loop(&new_chan);
585 new_chan->next = pListener;
586 pListener = new_chan;
594 static void inetd_connection(int what)
601 if ((line = cs_createbysocket(0, tcpip_type, 0, what)))
603 if ((chan = iochan_create(cs_fileno(line), ir_session, EVENT_INPUT)))
605 if ((assoc = create_association(chan, line)))
607 iochan_setdata(chan, assoc);
608 iochan_settimeout(chan, 60);
609 addr = cs_addrstr(line);
610 yaz_log(LOG_LOG, "Inetd association from %s",
611 addr ? addr : "[UNKNOWN]");
612 assoc->cs_get_mask = EVENT_INPUT;
616 yaz_log(LOG_FATAL, "Failed to create association structure");
618 chan->next = pListener;
623 yaz_log(LOG_FATAL, "Failed to create iochan");
628 yaz_log(LOG_ERRNO|LOG_FATAL, "Failed to create comstack on socket 0");
633 * Set up a listening endpoint, and give it to the event-handler.
635 static int add_listener(char *where, int what)
642 if (control_block.dynamic)
644 else if (control_block.threads)
649 yaz_log(LOG_LOG, "Adding %s %s listener on %s", mode,
650 what == PROTO_SR ? "SR" : "Z3950", where);
652 l = cs_create_host(where, 0, &ap);
655 yaz_log(LOG_FATAL|LOG_ERRNO, "Failed to listen on %s", where);
658 if (cs_bind(l, ap, CS_SERVER) < 0)
660 yaz_log(LOG_FATAL|LOG_ERRNO, "Failed to bind to %s",
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> <listender-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 ();