2 * Copyright (c) 1995-2002, 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.82 2002-05-17 12:48:29 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 60, /* 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 * handle incoming connect requests.
84 * The dynamic mode is a bit tricky mostly because we want to avoid
85 * doing all of the listening and accepting in the parent - it's
90 typedef struct _ThreadList ThreadList;
99 static ThreadList *pFirstThread;
100 static CRITICAL_SECTION Thread_CritSect;
101 static BOOL bInitialized = FALSE;
103 static void ThreadList_Initialize()
105 /* Initialize the critical Sections */
106 InitializeCriticalSection(&Thread_CritSect);
108 /* Set the first thraed */
111 /* we have been initialized */
115 static void statserv_add(HANDLE hThread, IOCHAN pIOChannel)
117 /* Only one thread can go through this section at a time */
118 EnterCriticalSection(&Thread_CritSect);
121 /* Lets create our new object */
122 ThreadList *pNewThread = (ThreadList *)malloc(sizeof(ThreadList));
123 pNewThread->hThread = hThread;
124 pNewThread->pIOChannel = pIOChannel;
125 pNewThread->pNext = pFirstThread;
126 pFirstThread = pNewThread;
128 /* Lets let somebody else create a new object now */
129 LeaveCriticalSection(&Thread_CritSect);
133 void statserv_remove(IOCHAN pIOChannel)
135 /* Only one thread can go through this section at a time */
136 EnterCriticalSection(&Thread_CritSect);
139 ThreadList *pCurrentThread = pFirstThread;
140 ThreadList *pNextThread;
141 ThreadList *pPrevThread =NULL;
143 /* Step through alll the threads */
144 for (; pCurrentThread != NULL; pCurrentThread = pNextThread)
146 /* We only need to compare on the IO Channel */
147 if (pCurrentThread->pIOChannel == pIOChannel)
149 /* We have found the thread we want to delete */
150 /* First of all reset the next pointers */
151 if (pPrevThread == NULL)
152 pFirstThread = pCurrentThread->pNext;
154 pPrevThread->pNext = pCurrentThread->pNext;
156 /* All we need todo now is delete the memory */
157 free(pCurrentThread);
159 /* No need to look at any more threads */
164 /* We need to look at another thread */
165 pNextThread = pCurrentThread->pNext;
166 pPrevThread = pCurrentThread;
170 /* Lets let somebody else remove an object now */
171 LeaveCriticalSection(&Thread_CritSect);
175 /* WIN32 statserv_closedown */
176 void statserv_closedown()
178 /* Shouldn't do anything if we are not initialized */
182 HANDLE *pThreadHandles = NULL;
184 /* We need to stop threads adding and removing while we */
185 /* start the closedown process */
186 EnterCriticalSection(&Thread_CritSect);
189 /* We have exclusive access to the thread stuff now */
190 /* Y didn't i use a semaphore - Oh well never mind */
191 ThreadList *pCurrentThread = pFirstThread;
193 /* Before we do anything else, we need to shutdown the listener */
194 if (pListener != NULL)
195 iochan_destroy(pListener);
197 for (; pCurrentThread != NULL; pCurrentThread = pCurrentThread->pNext)
199 /* Just destroy the IOCHAN, that should do the trick */
200 iochan_destroy(pCurrentThread->pIOChannel);
201 closesocket(pCurrentThread->pIOChannel->fd);
203 /* Keep a running count of our handles */
209 HANDLE *pCurrentHandle ;
211 /* Allocate the thread handle array */
212 pThreadHandles = (HANDLE *)malloc(sizeof(HANDLE) * iHandles);
213 pCurrentHandle = pThreadHandles;
215 for (pCurrentThread = pFirstThread;
216 pCurrentThread != NULL;
217 pCurrentThread = pCurrentThread->pNext, pCurrentHandle++)
219 /* Just the handle */
220 *pCurrentHandle = pCurrentThread->hThread;
224 /* We can now leave the critical section */
225 LeaveCriticalSection(&Thread_CritSect);
228 /* Now we can really do something */
231 logf (LOG_LOG, "waiting for %d to die", iHandles);
232 /* This will now wait, until all the threads close */
233 WaitForMultipleObjects(iHandles, pThreadHandles, TRUE, INFINITE);
235 /* Free the memory we allocated for the handle array */
236 free(pThreadHandles);
239 if (control_block.bend_stop)
240 (*control_block.bend_stop)(&control_block);
241 /* No longer require the critical section, since all threads are dead */
242 DeleteCriticalSection(&Thread_CritSect);
246 void __cdecl event_loop_thread (IOCHAN iochan)
248 event_loop (&iochan);
252 static void listener(IOCHAN h, int event)
254 COMSTACK line = (COMSTACK) iochan_getdata(h);
259 if (event == EVENT_INPUT)
261 if ((res = cs_listen(line, 0, 0)) < 0)
263 yaz_log(LOG_FATAL, "cs_listen failed");
268 yaz_log(LOG_DEBUG, "listen ok");
269 iochan_setevent(h, EVENT_OUTPUT);
270 iochan_setflags(h, EVENT_OUTPUT | EVENT_EXCEPT); /* set up for acpt */
272 else if (event == EVENT_OUTPUT)
274 COMSTACK new_line = cs_accept(line);
280 yaz_log(LOG_FATAL, "Accept failed.");
281 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT);
284 yaz_log(LOG_DEBUG, "Accept ok");
286 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session,
289 yaz_log(LOG_FATAL, "Failed to create iochan");
294 yaz_log(LOG_DEBUG, "Creating association");
295 if (!(newas = create_association(new_chan, new_line)))
297 yaz_log(LOG_FATAL, "Failed to create new assoc.");
301 newas->cs_get_mask = EVENT_INPUT;
302 newas->cs_put_mask = 0;
303 newas->cs_accept_mask = 0;
305 yaz_log(LOG_DEBUG, "Setting timeout %d", control_block.idle_timeout);
306 iochan_setdata(new_chan, newas);
307 iochan_settimeout(new_chan, control_block.idle_timeout * 60);
309 /* Now what we need todo is create a new thread with this iochan as
311 newHandle = (HANDLE) _beginthread(event_loop_thread, 0, new_chan);
312 if (newHandle == (HANDLE) -1)
315 yaz_log(LOG_FATAL|LOG_ERRNO, "Failed to create new thread.");
319 /* We successfully created the thread, so add it to the list */
320 statserv_add(newHandle, new_chan);
322 yaz_log(LOG_DEBUG, "Created new thread, id = %ld iochan %p",(long) newHandle, new_chan);
323 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
327 yaz_log(LOG_FATAL, "Bad event on listener.");
335 /* To save having an #ifdef in event_loop we need to define this empty function */
336 void statserv_remove(IOCHAN pIOChannel)
340 void statserv_closedown()
344 if (control_block.bend_stop)
345 (*control_block.bend_stop)(&control_block);
347 for (p = pListener; p; p = p->next)
351 void sigterm(int sig)
353 statserv_closedown();
357 static void *new_session (void *vp);
358 static int no_sessions = 0;
361 static void listener(IOCHAN h, int event)
363 COMSTACK line = (COMSTACK) iochan_getdata(h);
365 static int child = 0;
368 if (event == EVENT_INPUT)
370 if (control_block.dynamic && !child)
377 yaz_log(LOG_FATAL|LOG_ERRNO, "pipe");
381 if ((res = fork()) < 0)
383 yaz_log(LOG_FATAL|LOG_ERRNO, "fork");
387 else if (res == 0) /* child */
394 for (pp = pListener; pp; pp = iochan_getnext(pp))
398 COMSTACK l = (COMSTACK)iochan_getdata(pp);
403 sprintf(nbuf, "%s(%d)", me, getpid());
404 yaz_log_init(control_block.loglevel, nbuf, 0);
409 /* wait for child to take the call */
415 if ((res = read(hand[0], dummy, 1)) < 0 && errno != EINTR)
417 yaz_log(LOG_FATAL|LOG_ERRNO, "handshake read");
423 yaz_log(LOG_DEBUG, "P: Child has taken the call");
428 if ((res = cs_listen_check(line, 0, 0, control_block.check_ip,
429 control_block.daemon_name)) < 0)
431 yaz_log(LOG_WARN, "cs_listen failed");
436 yaz_log(LOG_DEBUG, "listen ok");
437 iochan_setevent(h, EVENT_OUTPUT);
438 iochan_setflags(h, EVENT_OUTPUT | EVENT_EXCEPT); /* set up for acpt */
440 /* in dynamic mode, only the child ever comes down here */
441 else if (event == EVENT_OUTPUT)
443 COMSTACK new_line = cs_accept(line);
447 yaz_log(LOG_FATAL, "Accept failed.");
448 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
451 yaz_log(LOG_DEBUG, "accept ok");
452 if (control_block.dynamic)
455 /* close our half of the listener socket */
456 for (pp = pListener; pp; pp = iochan_getnext(pp))
458 COMSTACK l = (COMSTACK)iochan_getdata(pp);
463 yaz_log(LOG_DEBUG, "Releasing parent");
468 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
471 #if YAZ_POSIX_THREADS
472 if (control_block.threads)
474 pthread_t child_thread;
475 pthread_create (&child_thread, 0, new_session, new_line);
476 pthread_detach (child_thread);
479 new_session(new_line);
480 #elif YAZ_GNU_THREADS
481 if (control_block.threads)
486 attr = pth_attr_new ();
487 pth_attr_set (attr, PTH_ATTR_JOINABLE, FALSE);
488 pth_attr_set (attr, PTH_ATTR_STACK_SIZE, 32*1024);
489 pth_attr_set (attr, PTH_ATTR_NAME, "session");
490 yaz_log (LOG_LOG, "pth_spawn begin");
491 child_thread = pth_spawn (attr, new_session, new_line);
492 yaz_log (LOG_LOG, "pth_spawn finish");
493 pth_attr_destroy (attr);
496 new_session(new_line);
498 new_session(new_line);
503 yaz_log(LOG_FATAL, "Bad event on listener.");
509 static void *new_session (void *vp)
514 COMSTACK new_line = (COMSTACK) vp;
516 unsigned cs_get_mask, cs_accept_mask, mask =
517 ((new_line->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
518 ((new_line->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
522 cs_accept_mask = mask; /* accept didn't complete */
527 cs_accept_mask = 0; /* accept completed. */
528 cs_get_mask = mask = EVENT_INPUT;
531 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session, mask)))
533 yaz_log(LOG_FATAL, "Failed to create iochan");
536 if (!(newas = create_association(new_chan, new_line)))
538 yaz_log(LOG_FATAL, "Failed to create new assoc.");
541 newas->cs_accept_mask = cs_accept_mask;
542 newas->cs_get_mask = cs_get_mask;
544 iochan_setdata(new_chan, newas);
545 iochan_settimeout(new_chan, control_block.idle_timeout * 60);
546 a = cs_addrstr(new_line);
547 yaz_log(LOG_LOG, "Starting session %d from %s",
548 no_sessions, a ? a : "[Unknown]");
549 if (control_block.threads)
551 event_loop(&new_chan);
555 new_chan->next = pListener;
556 pListener = new_chan;
563 static void inetd_connection(int what)
570 if ((line = cs_createbysocket(0, tcpip_type, 0, what)))
572 if ((chan = iochan_create(cs_fileno(line), ir_session, EVENT_INPUT)))
574 if ((assoc = create_association(chan, line)))
576 iochan_setdata(chan, assoc);
577 iochan_settimeout(chan, control_block.idle_timeout * 60);
578 addr = cs_addrstr(line);
579 yaz_log(LOG_LOG, "Inetd association from %s",
580 addr ? addr : "[UNKNOWN]");
581 assoc->cs_get_mask = EVENT_INPUT;
585 yaz_log(LOG_FATAL, "Failed to create association structure");
587 chan->next = pListener;
592 yaz_log(LOG_FATAL, "Failed to create iochan");
597 yaz_log(LOG_ERRNO|LOG_FATAL, "Failed to create comstack on socket 0");
602 * Set up a listening endpoint, and give it to the event-handler.
604 static int add_listener(char *where, int what)
611 if (control_block.dynamic)
613 else if (control_block.threads)
618 yaz_log(LOG_LOG, "Adding %s %s listener on %s", mode,
619 what == PROTO_SR ? "SR" : "Z3950", where);
621 l = cs_create_host(where, 0, &ap);
624 yaz_log(LOG_FATAL|LOG_ERRNO, "Failed to listen on %s", where);
627 if (cs_bind(l, ap, CS_SERVER) < 0)
629 yaz_log(LOG_FATAL|LOG_ERRNO, "Failed to bind to %s", where);
633 if (!(lst = iochan_create(cs_fileno(l), listener, EVENT_INPUT |
636 yaz_log(LOG_FATAL|LOG_ERRNO, "Failed to create IOCHAN-type");
640 iochan_setdata(lst, l);
642 /* Ensure our listener chain is setup properly */
643 lst->next = pListener;
649 /* For windows we don't need to catch the signals */
650 static void catchchld(int num)
652 while (waitpid(-1, 0, WNOHANG) > 0)
654 signal(SIGCHLD, catchchld);
658 statserv_options_block *statserv_getcontrol(void)
660 static statserv_options_block cb;
662 memcpy(&cb, &control_block, sizeof(cb));
666 void statserv_setcontrol(statserv_options_block *block)
668 memcpy(&control_block, block, sizeof(*block));
671 int statserv_start(int argc, char **argv)
676 /* We need to initialize the thread list */
677 ThreadList_Initialize();
681 if ((me = strrchr (argv[0], '\\')))
688 if (control_block.options_func(argc, argv))
691 if (control_block.bend_start)
692 (*control_block.bend_start)(&control_block);
694 logf (LOG_LOG, "Starting server %s", me);
696 if (control_block.inetd)
697 inetd_connection(control_block.default_proto);
700 logf (LOG_LOG, "Starting server %s pid=%d", me, getpid());
702 sigset_t sigs_to_block;
704 sigemptyset(&sigs_to_block);
705 sigaddset (&sigs_to_block, SIGTERM);
706 pthread_sigmask (SIG_BLOCK, &sigs_to_block, 0);
709 if (control_block.dynamic)
710 signal(SIGCHLD, catchchld);
712 signal (SIGPIPE, SIG_IGN);
713 signal (SIGTERM, sigterm);
714 if (*control_block.setuid)
718 if (!(pw = getpwnam(control_block.setuid)))
720 yaz_log(LOG_FATAL, "%s: Unknown user", control_block.setuid);
723 if (setuid(pw->pw_uid) < 0)
725 yaz_log(LOG_FATAL|LOG_ERRNO, "setuid");
731 if ((pListener == NULL) && *control_block.default_listen)
732 add_listener(control_block.default_listen,
733 control_block.default_proto);
735 if (pListener == NULL)
739 yaz_log(LOG_LOG, "Entering event loop.");
740 ret = event_loop(&pListener);
745 int check_options(int argc, char **argv)
750 while ((ret = options("1a:iszSTl:v:u:c:w:t:k:d:", argv, argc, &arg)) != -2)
755 if (add_listener(arg, control_block.default_proto))
756 return 1; /* failed to create listener */
759 control_block.one_shot = 1;
760 control_block.dynamic = 0;
763 control_block.default_proto = PROTO_Z3950;
766 fprintf (stderr, "%s: SR protocol no longer supported\n", me);
770 control_block.dynamic = 0;
773 #if YAZ_POSIX_THREADS
774 control_block.dynamic = 0;
775 control_block.threads = 1;
776 #elif YAZ_GNU_THREADS
777 control_block.dynamic = 0;
778 control_block.threads = 1;
780 fprintf(stderr, "%s: Threaded mode not available.\n", me);
785 strcpy(control_block.logfile, arg ? arg : "");
786 yaz_log_init(control_block.loglevel, me, control_block.logfile);
789 control_block.loglevel = yaz_log_mask_str(arg);
790 yaz_log_init(control_block.loglevel, me, control_block.logfile);
793 strcpy(control_block.apdufile, arg ? arg : "");
796 strcpy(control_block.setuid, arg ? arg : "");
799 strcpy(control_block.configname, arg ? arg : "");
802 strcpy(control_block.daemon_name, arg ? arg : "");
805 if (!arg || !(r = atoi(arg)))
807 fprintf(stderr, "%s: Specify positive timeout for -t.\n", me);
810 control_block.idle_timeout = r;
813 if (!arg || !(r = atoi(arg)))
815 fprintf(stderr, "%s: Specify positive size for -k.\n", me);
818 control_block.maxrecordsize = r * 1024;
821 control_block.inetd = 1;
831 fprintf(stderr, "Usage: %s [ -a <pdufile> -v <loglevel>"
832 " -l <logfile> -u <user> -c <config> -t <minutes>"
833 " -k <kilobytes> -d <daemon>"
834 " -ziST -w <directory> <listender-addr>... ]\n", me);
848 static Args ArgDetails;
850 /* name of the executable */
851 #define SZAPPNAME "server"
853 /* list of service dependencies - "dep1\0dep2\0\0" */
854 #define SZDEPENDENCIES ""
856 int statserv_main(int argc, char **argv,
857 bend_initresult *(*bend_init)(bend_initrequest *r),
858 void (*bend_close)(void *handle))
860 statserv_options_block *cb = statserv_getcontrol();
862 cb->bend_init = bend_init;
863 cb->bend_close = bend_close;
865 statserv_setcontrol(cb);
867 /* Lets setup the Arg structure */
868 ArgDetails.argc = argc;
869 ArgDetails.argv = argv;
871 /* Now setup the service with the service controller */
872 SetupService(argc, argv, &ArgDetails, SZAPPNAME,
873 cb->service_name, /* internal service name */
874 cb->service_name, /* displayed name of the service */
879 int StartAppService(void *pHandle, int argc, char **argv)
881 /* Initializes the App */
885 void RunAppService(void *pHandle)
887 Args *pArgs = (Args *)pHandle;
889 /* Starts the app running */
890 statserv_start(pArgs->argc, pArgs->argv);
893 void StopAppService(void *pHandle)
896 statserv_closedown();
899 int statserv_main(int argc, char **argv,
900 bend_initresult *(*bend_init)(bend_initrequest *r),
901 void (*bend_close)(void *handle))
904 statserv_options_block *cb = statserv_getcontrol();
906 cb->bend_init = bend_init;
907 cb->bend_close = bend_close;
909 statserv_setcontrol(cb);
910 ret = statserv_start (argc, argv);
911 statserv_closedown ();