2 * Copyright (c) 1995-2004, 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.4 2004-01-17 01:20:13 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 */
80 0, /* SOAP handlers */
82 0 /* background daemon */
85 static int max_sessions = 0;
88 * handle incoming connect requests.
89 * The dynamic mode is a bit tricky mostly because we want to avoid
90 * doing all of the listening and accepting in the parent - it's
95 typedef struct _ThreadList ThreadList;
104 static ThreadList *pFirstThread;
105 static CRITICAL_SECTION Thread_CritSect;
106 static BOOL bInitialized = FALSE;
108 static void ThreadList_Initialize()
110 /* Initialize the critical Sections */
111 InitializeCriticalSection(&Thread_CritSect);
113 /* Set the first thraed */
116 /* we have been initialized */
120 static void statserv_add(HANDLE hThread, IOCHAN pIOChannel)
122 /* Only one thread can go through this section at a time */
123 EnterCriticalSection(&Thread_CritSect);
126 /* Lets create our new object */
127 ThreadList *pNewThread = (ThreadList *)malloc(sizeof(ThreadList));
128 pNewThread->hThread = hThread;
129 pNewThread->pIOChannel = pIOChannel;
130 pNewThread->pNext = pFirstThread;
131 pFirstThread = pNewThread;
133 /* Lets let somebody else create a new object now */
134 LeaveCriticalSection(&Thread_CritSect);
138 void statserv_remove(IOCHAN pIOChannel)
140 /* Only one thread can go through this section at a time */
141 EnterCriticalSection(&Thread_CritSect);
144 ThreadList *pCurrentThread = pFirstThread;
145 ThreadList *pNextThread;
146 ThreadList *pPrevThread =NULL;
148 /* Step through alll the threads */
149 for (; pCurrentThread != NULL; pCurrentThread = pNextThread)
151 /* We only need to compare on the IO Channel */
152 if (pCurrentThread->pIOChannel == pIOChannel)
154 /* We have found the thread we want to delete */
155 /* First of all reset the next pointers */
156 if (pPrevThread == NULL)
157 pFirstThread = pCurrentThread->pNext;
159 pPrevThread->pNext = pCurrentThread->pNext;
161 /* All we need todo now is delete the memory */
162 free(pCurrentThread);
164 /* No need to look at any more threads */
169 /* We need to look at another thread */
170 pNextThread = pCurrentThread->pNext;
171 pPrevThread = pCurrentThread;
175 /* Lets let somebody else remove an object now */
176 LeaveCriticalSection(&Thread_CritSect);
180 /* WIN32 statserv_closedown */
181 void statserv_closedown()
183 /* Shouldn't do anything if we are not initialized */
187 HANDLE *pThreadHandles = NULL;
189 /* We need to stop threads adding and removing while we */
190 /* start the closedown process */
191 EnterCriticalSection(&Thread_CritSect);
194 /* We have exclusive access to the thread stuff now */
195 /* Y didn't i use a semaphore - Oh well never mind */
196 ThreadList *pCurrentThread = pFirstThread;
198 /* Before we do anything else, we need to shutdown the listener */
199 if (pListener != NULL)
200 iochan_destroy(pListener);
202 for (; pCurrentThread != NULL; pCurrentThread = pCurrentThread->pNext)
204 /* Just destroy the IOCHAN, that should do the trick */
205 iochan_destroy(pCurrentThread->pIOChannel);
206 closesocket(pCurrentThread->pIOChannel->fd);
208 /* Keep a running count of our handles */
214 HANDLE *pCurrentHandle ;
216 /* Allocate the thread handle array */
217 pThreadHandles = (HANDLE *)malloc(sizeof(HANDLE) * iHandles);
218 pCurrentHandle = pThreadHandles;
220 for (pCurrentThread = pFirstThread;
221 pCurrentThread != NULL;
222 pCurrentThread = pCurrentThread->pNext, pCurrentHandle++)
224 /* Just the handle */
225 *pCurrentHandle = pCurrentThread->hThread;
229 /* We can now leave the critical section */
230 LeaveCriticalSection(&Thread_CritSect);
233 /* Now we can really do something */
236 logf (LOG_LOG, "waiting for %d to die", iHandles);
237 /* This will now wait, until all the threads close */
238 WaitForMultipleObjects(iHandles, pThreadHandles, TRUE, INFINITE);
240 /* Free the memory we allocated for the handle array */
241 free(pThreadHandles);
244 if (control_block.bend_stop)
245 (*control_block.bend_stop)(&control_block);
246 /* No longer require the critical section, since all threads are dead */
247 DeleteCriticalSection(&Thread_CritSect);
251 void __cdecl event_loop_thread (IOCHAN iochan)
253 event_loop (&iochan);
257 static void listener(IOCHAN h, int event)
259 COMSTACK line = (COMSTACK) iochan_getdata(h);
264 if (event == EVENT_INPUT)
266 if ((res = cs_listen(line, 0, 0)) < 0)
268 yaz_log(LOG_FATAL, "cs_listen failed");
273 yaz_log(LOG_DEBUG, "listen ok");
274 iochan_setevent(h, EVENT_OUTPUT);
275 iochan_setflags(h, EVENT_OUTPUT | EVENT_EXCEPT); /* set up for acpt */
277 else if (event == EVENT_OUTPUT)
279 COMSTACK new_line = cs_accept(line);
285 yaz_log(LOG_FATAL, "Accept failed.");
286 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT);
289 yaz_log(LOG_DEBUG, "Accept ok");
291 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session,
294 yaz_log(LOG_FATAL, "Failed to create iochan");
299 yaz_log(LOG_DEBUG, "Creating association");
300 if (!(newas = create_association(new_chan, new_line)))
302 yaz_log(LOG_FATAL, "Failed to create new assoc.");
306 newas->cs_get_mask = EVENT_INPUT;
307 newas->cs_put_mask = 0;
308 newas->cs_accept_mask = 0;
310 yaz_log(LOG_DEBUG, "Setting timeout %d", control_block.idle_timeout);
311 iochan_setdata(new_chan, newas);
312 iochan_settimeout(new_chan, 60);
314 /* Now what we need todo is create a new thread with this iochan as
316 newHandle = (HANDLE) _beginthread(event_loop_thread, 0, new_chan);
317 if (newHandle == (HANDLE) -1)
320 yaz_log(LOG_FATAL|LOG_ERRNO, "Failed to create new thread.");
324 /* We successfully created the thread, so add it to the list */
325 statserv_add(newHandle, new_chan);
327 yaz_log(LOG_DEBUG, "Created new thread, id = %ld iochan %p",(long) newHandle, new_chan);
328 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
332 yaz_log(LOG_FATAL, "Bad event on listener.");
338 int statserv_must_terminate(void)
345 static int term_flag = 0;
346 /* To save having an #ifdef in event_loop we need to
347 define this empty function
349 int statserv_must_terminate(void)
354 void statserv_remove(IOCHAN pIOChannel)
358 void statserv_closedown()
362 if (control_block.bend_stop)
363 (*control_block.bend_stop)(&control_block);
364 for (p = pListener; p; p = p->next)
370 void sigterm(int sig)
375 static void *new_session (void *vp);
376 static int no_sessions = 0;
379 static void listener(IOCHAN h, int event)
381 COMSTACK line = (COMSTACK) iochan_getdata(h);
383 static int child = 0;
386 if (event == EVENT_INPUT)
388 if (control_block.dynamic && !child)
395 yaz_log(LOG_FATAL|LOG_ERRNO, "pipe");
399 if ((res = fork()) < 0)
401 yaz_log(LOG_FATAL|LOG_ERRNO, "fork");
405 else if (res == 0) /* child */
412 for (pp = pListener; pp; pp = iochan_getnext(pp))
416 COMSTACK l = (COMSTACK)iochan_getdata(pp);
421 sprintf(nbuf, "%s(%d)", me, getpid());
422 yaz_log_init(control_block.loglevel, nbuf, 0);
423 /* ensure that bend_stop is not called when each child exits -
424 only for the main process ..
426 control_block.bend_stop = 0;
431 /* wait for child to take the call */
437 if ((res = read(hand[0], dummy, 1)) < 0 &&
438 yaz_errno() != EINTR)
440 yaz_log(LOG_FATAL|LOG_ERRNO, "handshake read");
446 yaz_log(LOG_DEBUG, "P: Child has taken the call");
451 if ((res = cs_listen_check(line, 0, 0, control_block.check_ip,
452 control_block.daemon_name)) < 0)
454 yaz_log(LOG_WARN|LOG_ERRNO, "cs_listen failed");
459 yaz_log(LOG_DEBUG, "listen ok");
460 iochan_setevent(h, EVENT_OUTPUT);
461 iochan_setflags(h, EVENT_OUTPUT | EVENT_EXCEPT); /* set up for acpt */
463 /* in dynamic mode, only the child ever comes down here */
464 else if (event == EVENT_OUTPUT)
466 COMSTACK new_line = cs_accept(line);
470 yaz_log(LOG_FATAL, "Accept failed.");
471 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
474 yaz_log(LOG_DEBUG, "accept ok");
475 if (control_block.dynamic)
478 /* close our half of the listener socket */
479 for (pp = pListener; pp; pp = iochan_getnext(pp))
481 COMSTACK l = (COMSTACK)iochan_getdata(pp);
486 yaz_log(LOG_DEBUG, "Releasing parent");
491 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
494 #if YAZ_POSIX_THREADS
495 if (control_block.threads)
497 pthread_t child_thread;
498 pthread_create (&child_thread, 0, new_session, new_line);
499 pthread_detach (child_thread);
502 new_session(new_line);
503 #elif YAZ_GNU_THREADS
504 if (control_block.threads)
509 attr = pth_attr_new ();
510 pth_attr_set (attr, PTH_ATTR_JOINABLE, FALSE);
511 pth_attr_set (attr, PTH_ATTR_STACK_SIZE, 32*1024);
512 pth_attr_set (attr, PTH_ATTR_NAME, "session");
513 yaz_log (LOG_LOG, "pth_spawn begin");
514 child_thread = pth_spawn (attr, new_session, new_line);
515 yaz_log (LOG_LOG, "pth_spawn finish");
516 pth_attr_destroy (attr);
519 new_session(new_line);
521 new_session(new_line);
524 else if (event == EVENT_TIMEOUT)
526 yaz_log(LOG_LOG, "Shutting down listener.");
531 yaz_log(LOG_FATAL, "Bad event on listener.");
536 static void *new_session (void *vp)
541 COMSTACK new_line = (COMSTACK) vp;
543 unsigned cs_get_mask, cs_accept_mask, mask =
544 ((new_line->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
545 ((new_line->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
549 cs_accept_mask = mask; /* accept didn't complete */
554 cs_accept_mask = 0; /* accept completed. */
555 cs_get_mask = mask = EVENT_INPUT;
558 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session, mask)))
560 yaz_log(LOG_FATAL, "Failed to create iochan");
563 if (!(newas = create_association(new_chan, new_line)))
565 yaz_log(LOG_FATAL, "Failed to create new assoc.");
568 newas->cs_accept_mask = cs_accept_mask;
569 newas->cs_get_mask = cs_get_mask;
571 iochan_setdata(new_chan, newas);
572 iochan_settimeout(new_chan, 60);
574 a = cs_addrstr(new_line);
578 yaz_log(LOG_LOG, "Starting session %d from %s",
579 no_sessions, a ? a : "[Unknown]");
580 if (max_sessions && no_sessions == max_sessions)
581 control_block.one_shot = 1;
582 if (control_block.threads)
584 event_loop(&new_chan);
588 new_chan->next = pListener;
589 pListener = new_chan;
597 static void inetd_connection(int what)
604 if ((line = cs_createbysocket(0, tcpip_type, 0, what)))
606 if ((chan = iochan_create(cs_fileno(line), ir_session, EVENT_INPUT)))
608 if ((assoc = create_association(chan, line)))
610 iochan_setdata(chan, assoc);
611 iochan_settimeout(chan, 60);
612 addr = cs_addrstr(line);
613 yaz_log(LOG_LOG, "Inetd association from %s",
614 addr ? addr : "[UNKNOWN]");
615 assoc->cs_get_mask = EVENT_INPUT;
619 yaz_log(LOG_FATAL, "Failed to create association structure");
621 chan->next = pListener;
626 yaz_log(LOG_FATAL, "Failed to create iochan");
631 yaz_log(LOG_ERRNO|LOG_FATAL, "Failed to create comstack on socket 0");
636 * Set up a listening endpoint, and give it to the event-handler.
638 static int add_listener(char *where, int what)
645 if (control_block.dynamic)
647 else if (control_block.threads)
652 yaz_log(LOG_LOG, "Adding %s %s listener on %s", mode,
653 what == PROTO_SR ? "SR" : "Z3950", where);
655 l = cs_create_host(where, 2, &ap);
658 yaz_log(LOG_FATAL|LOG_ERRNO, "Failed to listen on %s", where);
661 if (cs_bind(l, ap, CS_SERVER) < 0)
663 yaz_log(LOG_FATAL|LOG_ERRNO, "Failed to bind to %s", where);
667 if (!(lst = iochan_create(cs_fileno(l), listener, EVENT_INPUT |
670 yaz_log(LOG_FATAL|LOG_ERRNO, "Failed to create IOCHAN-type");
674 iochan_setdata(lst, l);
676 /* Ensure our listener chain is setup properly */
677 lst->next = pListener;
683 /* UNIX only (for windows we don't need to catch the signals) */
684 static void catchchld(int num)
686 while (waitpid(-1, 0, WNOHANG) > 0)
688 signal(SIGCHLD, catchchld);
692 statserv_options_block *statserv_getcontrol(void)
694 static statserv_options_block cb;
696 memcpy(&cb, &control_block, sizeof(cb));
700 void statserv_setcontrol(statserv_options_block *block)
702 memcpy(&control_block, block, sizeof(*block));
705 static void statserv_reset(void)
709 int statserv_start(int argc, char **argv)
714 /* We need to initialize the thread list */
715 ThreadList_Initialize();
720 if ((me = strrchr (argv[0], '\\')))
727 if (control_block.options_func(argc, argv))
730 if (control_block.bend_start)
731 (*control_block.bend_start)(&control_block);
733 yaz_log (LOG_LOG, "Starting server %s", me);
734 if (!pListener && *control_block.default_listen)
735 add_listener(control_block.default_listen,
736 control_block.default_proto);
742 if (control_block.inetd)
743 inetd_connection(control_block.default_proto);
746 if (!pListener && *control_block.default_listen)
747 add_listener(control_block.default_listen,
748 control_block.default_proto);
753 if (*control_block.pid_fname)
755 FILE *f = fopen(control_block.pid_fname, "w");
758 yaz_log(LOG_FATAL|LOG_ERRNO, "Couldn't create %s",
759 control_block.pid_fname);
762 fprintf(f, "%ld", (long) getpid());
766 yaz_log (LOG_LOG, "Starting server %s pid=%d", me, getpid());
768 sigset_t sigs_to_block;
770 sigemptyset(&sigs_to_block);
771 sigaddset (&sigs_to_block, SIGTERM);
772 pthread_sigmask (SIG_BLOCK, &sigs_to_block, 0);
775 if (control_block.dynamic)
776 signal(SIGCHLD, catchchld);
778 signal (SIGPIPE, SIG_IGN);
779 signal (SIGTERM, sigterm);
780 if (*control_block.setuid)
784 if (!(pw = getpwnam(control_block.setuid)))
786 yaz_log(LOG_FATAL, "%s: Unknown user", control_block.setuid);
789 if (setuid(pw->pw_uid) < 0)
791 yaz_log(LOG_FATAL|LOG_ERRNO, "setuid");
795 if (!control_block.inetd && control_block.background)
813 open("/dev/null",O_RDWR);
818 if ((pListener == NULL) && *control_block.default_listen)
819 add_listener(control_block.default_listen,
820 control_block.default_proto);
822 if (pListener == NULL)
826 yaz_log(LOG_LOG, "Entering event loop.");
827 ret = event_loop(&pListener);
832 int check_options(int argc, char **argv)
837 while ((ret = options("1a:iszSTl:v:u:c:w:t:k:d:A:p:D", argv, argc, &arg)) != -2)
842 if (add_listener(arg, control_block.default_proto))
843 return 1; /* failed to create listener */
846 control_block.one_shot = 1;
847 control_block.dynamic = 0;
850 control_block.default_proto = PROTO_Z3950;
853 fprintf (stderr, "%s: SR protocol no longer supported\n", me);
857 control_block.dynamic = 0;
860 #if YAZ_POSIX_THREADS
861 control_block.dynamic = 0;
862 control_block.threads = 1;
863 #elif YAZ_GNU_THREADS
864 control_block.dynamic = 0;
865 control_block.threads = 1;
867 fprintf(stderr, "%s: Threaded mode not available.\n", me);
872 strcpy(control_block.logfile, arg ? arg : "");
873 yaz_log_init(control_block.loglevel, me, control_block.logfile);
876 control_block.loglevel = yaz_log_mask_str(arg);
877 yaz_log_init(control_block.loglevel, me, control_block.logfile);
880 strcpy(control_block.apdufile, arg ? arg : "");
883 strcpy(control_block.setuid, arg ? arg : "");
886 strcpy(control_block.configname, arg ? arg : "");
889 strcpy(control_block.daemon_name, arg ? arg : "");
892 if (!arg || !(r = atoi(arg)))
894 fprintf(stderr, "%s: Specify positive timeout for -t.\n", me);
897 control_block.idle_timeout = r;
900 if (!arg || !(r = atoi(arg)))
902 fprintf(stderr, "%s: Specify positive size for -k.\n", me);
905 control_block.maxrecordsize = r * 1024;
908 control_block.inetd = 1;
918 max_sessions = atoi(arg);
921 if (strlen(arg) >= sizeof(control_block.pid_fname))
923 yaz_log(LOG_FATAL, "pid fname too long");
926 strcpy(control_block.pid_fname, arg);
929 control_block.background = 1;
932 fprintf(stderr, "Usage: %s [ -a <pdufile> -v <loglevel>"
933 " -l <logfile> -u <user> -c <config> -t <minutes>"
934 " -k <kilobytes> -d <daemon> -p <pidfile>"
935 " -ziDST1 -w <directory> <listener-addr>... ]\n", me);
949 static Args ArgDetails;
951 /* name of the executable */
952 #define SZAPPNAME "server"
954 /* list of service dependencies - "dep1\0dep2\0\0" */
955 #define SZDEPENDENCIES ""
957 int statserv_main(int argc, char **argv,
958 bend_initresult *(*bend_init)(bend_initrequest *r),
959 void (*bend_close)(void *handle))
961 statserv_options_block *cb = statserv_getcontrol();
963 cb->bend_init = bend_init;
964 cb->bend_close = bend_close;
966 statserv_setcontrol(cb);
968 /* Lets setup the Arg structure */
969 ArgDetails.argc = argc;
970 ArgDetails.argv = argv;
972 /* Now setup the service with the service controller */
973 SetupService(argc, argv, &ArgDetails, SZAPPNAME,
974 cb->service_name, /* internal service name */
975 cb->service_display_name, /* displayed name */
980 int StartAppService(void *pHandle, int argc, char **argv)
982 /* Initializes the App */
986 void RunAppService(void *pHandle)
988 Args *pArgs = (Args *)pHandle;
990 /* Starts the app running */
991 statserv_start(pArgs->argc, pArgs->argv);
994 void StopAppService(void *pHandle)
997 statserv_closedown();
1003 int statserv_main(int argc, char **argv,
1004 bend_initresult *(*bend_init)(bend_initrequest *r),
1005 void (*bend_close)(void *handle))
1008 statserv_options_block *cb = statserv_getcontrol();
1010 cb->bend_init = bend_init;
1011 cb->bend_close = bend_close;
1013 statserv_setcontrol(cb);
1014 ret = statserv_start (argc, argv);
1015 statserv_closedown ();