2 * Copyright (c) 1995-2004, Index Data
3 * See the file LICENSE for details.
5 * NT threaded server code by
6 * Chas Woodfield, Fretwell Downing Informatics.
8 * $Id: statserv.c,v 1.5 2004-01-18 02:28:42 adam Exp $
33 #include <yaz/comstack.h>
34 #include <yaz/tcpip.h>
35 #include <yaz/options.h>
37 #include <yaz/xmosi.h>
42 #include <yaz/statserv.h>
44 static IOCHAN pListener = NULL;
46 static char *me = "statserver";
50 int check_options(int argc, char **argv);
51 statserv_options_block control_block = {
53 0, /* threaded mode */
54 0, /* one shot (single session) */
55 LOG_DEFAULT_LEVEL, /* log level */
57 "", /* diagnostic output to stderr */
58 "tcp:@:9999", /* default listener port */
59 PROTO_Z3950, /* default application protocol */
60 15, /* idle timeout (minutes) */
61 1024*1024, /* maximum PDU size (approx.) to allow */
62 "default-config", /* configuration name to pass to backend */
64 0, /* bend_start handler */
65 0, /* bend_stop handler */
66 check_options, /* Default routine, for checking the run-time arguments */
69 0, /* default value for inet deamon */
70 0, /* handle (for service, etc) */
71 0, /* bend_init handle */
72 0, /* bend_close handle */
74 "Z39.50 Server", /* NT Service Name */
75 "Server", /* NT application Name */
76 "", /* NT Service Dependencies */
77 "Z39.50 Server", /* NT Service Display Name */
79 0, /* SOAP handlers */
81 0 /* background daemon */
84 static int max_sessions = 0;
87 * handle incoming connect requests.
88 * The dynamic mode is a bit tricky mostly because we want to avoid
89 * doing all of the listening and accepting in the parent - it's
94 typedef struct _ThreadList ThreadList;
103 static ThreadList *pFirstThread;
104 static CRITICAL_SECTION Thread_CritSect;
105 static BOOL bInitialized = FALSE;
107 static void ThreadList_Initialize()
109 /* Initialize the critical Sections */
110 InitializeCriticalSection(&Thread_CritSect);
112 /* Set the first thraed */
115 /* we have been initialized */
119 static void statserv_add(HANDLE hThread, IOCHAN pIOChannel)
121 /* Only one thread can go through this section at a time */
122 EnterCriticalSection(&Thread_CritSect);
125 /* Lets create our new object */
126 ThreadList *pNewThread = (ThreadList *)malloc(sizeof(ThreadList));
127 pNewThread->hThread = hThread;
128 pNewThread->pIOChannel = pIOChannel;
129 pNewThread->pNext = pFirstThread;
130 pFirstThread = pNewThread;
132 /* Lets let somebody else create a new object now */
133 LeaveCriticalSection(&Thread_CritSect);
137 void statserv_remove(IOCHAN pIOChannel)
139 /* Only one thread can go through this section at a time */
140 EnterCriticalSection(&Thread_CritSect);
143 ThreadList *pCurrentThread = pFirstThread;
144 ThreadList *pNextThread;
145 ThreadList *pPrevThread =NULL;
147 /* Step through alll the threads */
148 for (; pCurrentThread != NULL; pCurrentThread = pNextThread)
150 /* We only need to compare on the IO Channel */
151 if (pCurrentThread->pIOChannel == pIOChannel)
153 /* We have found the thread we want to delete */
154 /* First of all reset the next pointers */
155 if (pPrevThread == NULL)
156 pFirstThread = pCurrentThread->pNext;
158 pPrevThread->pNext = pCurrentThread->pNext;
160 /* All we need todo now is delete the memory */
161 free(pCurrentThread);
163 /* No need to look at any more threads */
168 /* We need to look at another thread */
169 pNextThread = pCurrentThread->pNext;
170 pPrevThread = pCurrentThread;
174 /* Lets let somebody else remove an object now */
175 LeaveCriticalSection(&Thread_CritSect);
179 /* WIN32 statserv_closedown */
180 void statserv_closedown()
182 /* Shouldn't do anything if we are not initialized */
186 HANDLE *pThreadHandles = NULL;
188 /* We need to stop threads adding and removing while we */
189 /* start the closedown process */
190 EnterCriticalSection(&Thread_CritSect);
193 /* We have exclusive access to the thread stuff now */
194 /* Y didn't i use a semaphore - Oh well never mind */
195 ThreadList *pCurrentThread = pFirstThread;
197 /* Before we do anything else, we need to shutdown the listener */
198 if (pListener != NULL)
199 iochan_destroy(pListener);
201 for (; pCurrentThread != NULL; pCurrentThread = pCurrentThread->pNext)
203 /* Just destroy the IOCHAN, that should do the trick */
204 iochan_destroy(pCurrentThread->pIOChannel);
205 closesocket(pCurrentThread->pIOChannel->fd);
207 /* Keep a running count of our handles */
213 HANDLE *pCurrentHandle ;
215 /* Allocate the thread handle array */
216 pThreadHandles = (HANDLE *)malloc(sizeof(HANDLE) * iHandles);
217 pCurrentHandle = pThreadHandles;
219 for (pCurrentThread = pFirstThread;
220 pCurrentThread != NULL;
221 pCurrentThread = pCurrentThread->pNext, pCurrentHandle++)
223 /* Just the handle */
224 *pCurrentHandle = pCurrentThread->hThread;
228 /* We can now leave the critical section */
229 LeaveCriticalSection(&Thread_CritSect);
232 /* Now we can really do something */
235 logf (LOG_LOG, "waiting for %d to die", iHandles);
236 /* This will now wait, until all the threads close */
237 WaitForMultipleObjects(iHandles, pThreadHandles, TRUE, INFINITE);
239 /* Free the memory we allocated for the handle array */
240 free(pThreadHandles);
243 if (control_block.bend_stop)
244 (*control_block.bend_stop)(&control_block);
245 /* No longer require the critical section, since all threads are dead */
246 DeleteCriticalSection(&Thread_CritSect);
250 void __cdecl event_loop_thread (IOCHAN iochan)
252 event_loop (&iochan);
256 static void listener(IOCHAN h, int event)
258 COMSTACK line = (COMSTACK) iochan_getdata(h);
263 if (event == EVENT_INPUT)
265 if ((res = cs_listen(line, 0, 0)) < 0)
267 yaz_log(LOG_FATAL, "cs_listen failed");
272 yaz_log(LOG_DEBUG, "listen ok");
273 iochan_setevent(h, EVENT_OUTPUT);
274 iochan_setflags(h, EVENT_OUTPUT | EVENT_EXCEPT); /* set up for acpt */
276 else if (event == EVENT_OUTPUT)
278 COMSTACK new_line = cs_accept(line);
284 yaz_log(LOG_FATAL, "Accept failed.");
285 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT);
288 yaz_log(LOG_DEBUG, "Accept ok");
290 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session,
293 yaz_log(LOG_FATAL, "Failed to create iochan");
298 yaz_log(LOG_DEBUG, "Creating association");
299 if (!(newas = create_association(new_chan, new_line)))
301 yaz_log(LOG_FATAL, "Failed to create new assoc.");
305 newas->cs_get_mask = EVENT_INPUT;
306 newas->cs_put_mask = 0;
307 newas->cs_accept_mask = 0;
309 yaz_log(LOG_DEBUG, "Setting timeout %d", control_block.idle_timeout);
310 iochan_setdata(new_chan, newas);
311 iochan_settimeout(new_chan, 60);
313 /* Now what we need todo is create a new thread with this iochan as
315 newHandle = (HANDLE) _beginthread(event_loop_thread, 0, new_chan);
316 if (newHandle == (HANDLE) -1)
319 yaz_log(LOG_FATAL|LOG_ERRNO, "Failed to create new thread.");
323 /* We successfully created the thread, so add it to the list */
324 statserv_add(newHandle, new_chan);
326 yaz_log(LOG_DEBUG, "Created new thread, id = %ld iochan %p",(long) newHandle, new_chan);
327 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
331 yaz_log(LOG_FATAL, "Bad event on listener.");
337 int statserv_must_terminate(void)
344 static int term_flag = 0;
345 /* To save having an #ifdef in event_loop we need to
346 define this empty function
348 int statserv_must_terminate(void)
353 void statserv_remove(IOCHAN pIOChannel)
357 void statserv_closedown()
361 if (control_block.bend_stop)
362 (*control_block.bend_stop)(&control_block);
363 for (p = pListener; p; p = p->next)
369 void sigterm(int sig)
374 static void *new_session (void *vp);
375 static int no_sessions = 0;
378 static void listener(IOCHAN h, int event)
380 COMSTACK line = (COMSTACK) iochan_getdata(h);
382 static int child = 0;
385 if (event == EVENT_INPUT)
387 if (control_block.dynamic && !child)
394 yaz_log(LOG_FATAL|LOG_ERRNO, "pipe");
398 if ((res = fork()) < 0)
400 yaz_log(LOG_FATAL|LOG_ERRNO, "fork");
404 else if (res == 0) /* child */
411 for (pp = pListener; pp; pp = iochan_getnext(pp))
415 COMSTACK l = (COMSTACK)iochan_getdata(pp);
420 sprintf(nbuf, "%s(%d)", me, getpid());
421 yaz_log_init(control_block.loglevel, nbuf, 0);
422 /* ensure that bend_stop is not called when each child exits -
423 only for the main process ..
425 control_block.bend_stop = 0;
430 /* wait for child to take the call */
436 if ((res = read(hand[0], dummy, 1)) < 0 &&
437 yaz_errno() != EINTR)
439 yaz_log(LOG_FATAL|LOG_ERRNO, "handshake read");
445 yaz_log(LOG_DEBUG, "P: Child has taken the call");
450 if ((res = cs_listen_check(line, 0, 0, control_block.check_ip,
451 control_block.daemon_name)) < 0)
453 yaz_log(LOG_WARN|LOG_ERRNO, "cs_listen failed");
458 yaz_log(LOG_DEBUG, "listen ok");
459 iochan_setevent(h, EVENT_OUTPUT);
460 iochan_setflags(h, EVENT_OUTPUT | EVENT_EXCEPT); /* set up for acpt */
462 /* in dynamic mode, only the child ever comes down here */
463 else if (event == EVENT_OUTPUT)
465 COMSTACK new_line = cs_accept(line);
469 yaz_log(LOG_FATAL, "Accept failed.");
470 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
473 yaz_log(LOG_DEBUG, "accept ok");
474 if (control_block.dynamic)
477 /* close our half of the listener socket */
478 for (pp = pListener; pp; pp = iochan_getnext(pp))
480 COMSTACK l = (COMSTACK)iochan_getdata(pp);
485 yaz_log(LOG_DEBUG, "Releasing parent");
490 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
493 #if YAZ_POSIX_THREADS
494 if (control_block.threads)
496 pthread_t child_thread;
497 pthread_create (&child_thread, 0, new_session, new_line);
498 pthread_detach (child_thread);
501 new_session(new_line);
502 #elif YAZ_GNU_THREADS
503 if (control_block.threads)
508 attr = pth_attr_new ();
509 pth_attr_set (attr, PTH_ATTR_JOINABLE, FALSE);
510 pth_attr_set (attr, PTH_ATTR_STACK_SIZE, 32*1024);
511 pth_attr_set (attr, PTH_ATTR_NAME, "session");
512 yaz_log (LOG_LOG, "pth_spawn begin");
513 child_thread = pth_spawn (attr, new_session, new_line);
514 yaz_log (LOG_LOG, "pth_spawn finish");
515 pth_attr_destroy (attr);
518 new_session(new_line);
520 new_session(new_line);
523 else if (event == EVENT_TIMEOUT)
525 yaz_log(LOG_LOG, "Shutting down listener.");
530 yaz_log(LOG_FATAL, "Bad event on listener.");
535 static void *new_session (void *vp)
540 COMSTACK new_line = (COMSTACK) vp;
542 unsigned cs_get_mask, cs_accept_mask, mask =
543 ((new_line->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
544 ((new_line->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
548 cs_accept_mask = mask; /* accept didn't complete */
553 cs_accept_mask = 0; /* accept completed. */
554 cs_get_mask = mask = EVENT_INPUT;
557 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session, mask)))
559 yaz_log(LOG_FATAL, "Failed to create iochan");
562 if (!(newas = create_association(new_chan, new_line)))
564 yaz_log(LOG_FATAL, "Failed to create new assoc.");
567 newas->cs_accept_mask = cs_accept_mask;
568 newas->cs_get_mask = cs_get_mask;
570 iochan_setdata(new_chan, newas);
571 iochan_settimeout(new_chan, 60);
573 a = cs_addrstr(new_line);
577 yaz_log(LOG_LOG, "Starting session %d from %s",
578 no_sessions, a ? a : "[Unknown]");
579 if (max_sessions && no_sessions == max_sessions)
580 control_block.one_shot = 1;
581 if (control_block.threads)
583 event_loop(&new_chan);
587 new_chan->next = pListener;
588 pListener = new_chan;
596 static void inetd_connection(int what)
603 if ((line = cs_createbysocket(0, tcpip_type, 0, what)))
605 if ((chan = iochan_create(cs_fileno(line), ir_session, EVENT_INPUT)))
607 if ((assoc = create_association(chan, line)))
609 iochan_setdata(chan, assoc);
610 iochan_settimeout(chan, 60);
611 addr = cs_addrstr(line);
612 yaz_log(LOG_LOG, "Inetd association from %s",
613 addr ? addr : "[UNKNOWN]");
614 assoc->cs_get_mask = EVENT_INPUT;
618 yaz_log(LOG_FATAL, "Failed to create association structure");
620 chan->next = pListener;
625 yaz_log(LOG_FATAL, "Failed to create iochan");
630 yaz_log(LOG_ERRNO|LOG_FATAL, "Failed to create comstack on socket 0");
635 * Set up a listening endpoint, and give it to the event-handler.
637 static int add_listener(char *where, int what)
644 if (control_block.dynamic)
646 else if (control_block.threads)
651 yaz_log(LOG_LOG, "Adding %s %s listener on %s", mode,
652 what == PROTO_SR ? "SR" : "Z3950", where);
654 l = cs_create_host(where, 2, &ap);
657 yaz_log(LOG_FATAL|LOG_ERRNO, "Failed to listen on %s", where);
660 if (cs_bind(l, ap, CS_SERVER) < 0)
662 yaz_log(LOG_FATAL|LOG_ERRNO, "Failed to bind to %s", where);
666 if (!(lst = iochan_create(cs_fileno(l), listener, EVENT_INPUT |
669 yaz_log(LOG_FATAL|LOG_ERRNO, "Failed to create IOCHAN-type");
673 iochan_setdata(lst, l);
675 /* Ensure our listener chain is setup properly */
676 lst->next = pListener;
682 /* UNIX only (for windows we don't need to catch the signals) */
683 static void catchchld(int num)
685 while (waitpid(-1, 0, WNOHANG) > 0)
687 signal(SIGCHLD, catchchld);
691 statserv_options_block *statserv_getcontrol(void)
693 static statserv_options_block cb;
695 memcpy(&cb, &control_block, sizeof(cb));
699 void statserv_setcontrol(statserv_options_block *block)
701 memcpy(&control_block, block, sizeof(*block));
704 static void statserv_reset(void)
708 int statserv_start(int argc, char **argv)
713 /* We need to initialize the thread list */
714 ThreadList_Initialize();
719 if ((me = strrchr (argv[0], '\\')))
726 if (control_block.options_func(argc, argv))
729 if (control_block.bend_start)
730 (*control_block.bend_start)(&control_block);
732 yaz_log (LOG_LOG, "Starting server %s", me);
733 if (!pListener && *control_block.default_listen)
734 add_listener(control_block.default_listen,
735 control_block.default_proto);
741 if (control_block.inetd)
742 inetd_connection(control_block.default_proto);
745 if (control_block.background)
763 open("/dev/null",O_RDWR);
766 if (!pListener && *control_block.default_listen)
767 add_listener(control_block.default_listen,
768 control_block.default_proto);
773 if (*control_block.pid_fname)
775 FILE *f = fopen(control_block.pid_fname, "w");
778 yaz_log(LOG_FATAL|LOG_ERRNO, "Couldn't create %s",
779 control_block.pid_fname);
782 fprintf(f, "%ld", (long) getpid());
786 yaz_log (LOG_LOG, "Starting server %s pid=%d", me, getpid());
788 sigset_t sigs_to_block;
790 sigemptyset(&sigs_to_block);
791 sigaddset (&sigs_to_block, SIGTERM);
792 pthread_sigmask (SIG_BLOCK, &sigs_to_block, 0);
795 if (control_block.dynamic)
796 signal(SIGCHLD, catchchld);
798 signal (SIGPIPE, SIG_IGN);
799 signal (SIGTERM, sigterm);
800 if (*control_block.setuid)
804 if (!(pw = getpwnam(control_block.setuid)))
806 yaz_log(LOG_FATAL, "%s: Unknown user", control_block.setuid);
809 if (setuid(pw->pw_uid) < 0)
811 yaz_log(LOG_FATAL|LOG_ERRNO, "setuid");
817 if ((pListener == NULL) && *control_block.default_listen)
818 add_listener(control_block.default_listen,
819 control_block.default_proto);
821 if (pListener == NULL)
825 yaz_log(LOG_LOG, "Entering event loop.");
826 ret = event_loop(&pListener);
831 int check_options(int argc, char **argv)
836 while ((ret = options("1a:iszSTl:v:u:c:w:t:k:d:A:p:D", argv, argc, &arg)) != -2)
841 if (add_listener(arg, control_block.default_proto))
842 return 1; /* failed to create listener */
845 control_block.one_shot = 1;
846 control_block.dynamic = 0;
849 control_block.default_proto = PROTO_Z3950;
852 fprintf (stderr, "%s: SR protocol no longer supported\n", me);
856 control_block.dynamic = 0;
859 #if YAZ_POSIX_THREADS
860 control_block.dynamic = 0;
861 control_block.threads = 1;
862 #elif YAZ_GNU_THREADS
863 control_block.dynamic = 0;
864 control_block.threads = 1;
866 fprintf(stderr, "%s: Threaded mode not available.\n", me);
871 strcpy(control_block.logfile, arg ? arg : "");
872 yaz_log_init(control_block.loglevel, me, control_block.logfile);
875 control_block.loglevel = yaz_log_mask_str(arg);
876 yaz_log_init(control_block.loglevel, me, control_block.logfile);
879 strcpy(control_block.apdufile, arg ? arg : "");
882 strcpy(control_block.setuid, arg ? arg : "");
885 strcpy(control_block.configname, arg ? arg : "");
888 strcpy(control_block.daemon_name, arg ? arg : "");
891 if (!arg || !(r = atoi(arg)))
893 fprintf(stderr, "%s: Specify positive timeout for -t.\n", me);
896 control_block.idle_timeout = r;
899 if (!arg || !(r = atoi(arg)))
901 fprintf(stderr, "%s: Specify positive size for -k.\n", me);
904 control_block.maxrecordsize = r * 1024;
907 control_block.inetd = 1;
917 max_sessions = atoi(arg);
920 if (strlen(arg) >= sizeof(control_block.pid_fname))
922 yaz_log(LOG_FATAL, "pid fname too long");
925 strcpy(control_block.pid_fname, arg);
928 control_block.background = 1;
931 fprintf(stderr, "Usage: %s [ -a <pdufile> -v <loglevel>"
932 " -l <logfile> -u <user> -c <config> -t <minutes>"
933 " -k <kilobytes> -d <daemon> -p <pidfile>"
934 " -ziDST1 -w <directory> <listener-addr>... ]\n", me);
948 static Args ArgDetails;
950 /* name of the executable */
951 #define SZAPPNAME "server"
953 /* list of service dependencies - "dep1\0dep2\0\0" */
954 #define SZDEPENDENCIES ""
956 int statserv_main(int argc, char **argv,
957 bend_initresult *(*bend_init)(bend_initrequest *r),
958 void (*bend_close)(void *handle))
960 statserv_options_block *cb = statserv_getcontrol();
962 cb->bend_init = bend_init;
963 cb->bend_close = bend_close;
965 statserv_setcontrol(cb);
967 /* Lets setup the Arg structure */
968 ArgDetails.argc = argc;
969 ArgDetails.argv = argv;
971 /* Now setup the service with the service controller */
972 SetupService(argc, argv, &ArgDetails, SZAPPNAME,
973 cb->service_name, /* internal service name */
974 cb->service_display_name, /* displayed name */
979 int StartAppService(void *pHandle, int argc, char **argv)
981 /* Initializes the App */
985 void RunAppService(void *pHandle)
987 Args *pArgs = (Args *)pHandle;
989 /* Starts the app running */
990 statserv_start(pArgs->argc, pArgs->argv);
993 void StopAppService(void *pHandle)
996 statserv_closedown();
1002 int statserv_main(int argc, char **argv,
1003 bend_initresult *(*bend_init)(bend_initrequest *r),
1004 void (*bend_close)(void *handle))
1007 statserv_options_block *cb = statserv_getcontrol();
1009 cb->bend_init = bend_init;
1010 cb->bend_close = bend_close;
1012 statserv_setcontrol(cb);
1013 ret = statserv_start (argc, argv);
1014 statserv_closedown ();