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.7 2004-04-30 19:10:35 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 */
82 "" /* SSL certificate filename */
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, "Failed to listen on %s", where);
661 if (*control_block.cert_fname)
662 cs_set_ssl_certf(l, control_block.cert_fname);
664 if (cs_bind(l, ap, CS_SERVER) < 0)
666 yaz_log(LOG_FATAL|LOG_ERRNO, "Failed to bind to %s", where);
670 if (!(lst = iochan_create(cs_fileno(l), listener, EVENT_INPUT |
673 yaz_log(LOG_FATAL|LOG_ERRNO, "Failed to create IOCHAN-type");
677 iochan_setdata(lst, l);
679 /* Ensure our listener chain is setup properly */
680 lst->next = pListener;
686 /* UNIX only (for windows we don't need to catch the signals) */
687 static void catchchld(int num)
689 while (waitpid(-1, 0, WNOHANG) > 0)
691 signal(SIGCHLD, catchchld);
695 statserv_options_block *statserv_getcontrol(void)
697 static statserv_options_block cb;
699 memcpy(&cb, &control_block, sizeof(cb));
703 void statserv_setcontrol(statserv_options_block *block)
705 memcpy(&control_block, block, sizeof(*block));
708 static void statserv_reset(void)
712 int statserv_start(int argc, char **argv)
717 /* We need to initialize the thread list */
718 ThreadList_Initialize();
723 if ((me = strrchr (argv[0], '\\')))
730 if (control_block.options_func(argc, argv))
733 if (control_block.bend_start)
734 (*control_block.bend_start)(&control_block);
736 yaz_log (LOG_LOG, "Starting server %s", me);
737 if (!pListener && *control_block.default_listen)
738 add_listener(control_block.default_listen,
739 control_block.default_proto);
745 if (control_block.inetd)
746 inetd_connection(control_block.default_proto);
749 if (control_block.background)
767 open("/dev/null",O_RDWR);
770 if (!pListener && *control_block.default_listen)
771 add_listener(control_block.default_listen,
772 control_block.default_proto);
777 if (*control_block.pid_fname)
779 FILE *f = fopen(control_block.pid_fname, "w");
782 yaz_log(LOG_FATAL|LOG_ERRNO, "Couldn't create %s",
783 control_block.pid_fname);
786 fprintf(f, "%ld", (long) getpid());
790 yaz_log (LOG_LOG, "Starting server %s pid=%d", me, getpid());
792 sigset_t sigs_to_block;
794 sigemptyset(&sigs_to_block);
795 sigaddset (&sigs_to_block, SIGTERM);
796 pthread_sigmask (SIG_BLOCK, &sigs_to_block, 0);
799 if (control_block.dynamic)
800 signal(SIGCHLD, catchchld);
802 signal (SIGPIPE, SIG_IGN);
803 signal (SIGTERM, sigterm);
804 if (*control_block.setuid)
808 if (!(pw = getpwnam(control_block.setuid)))
810 yaz_log(LOG_FATAL, "%s: Unknown user", control_block.setuid);
813 if (setuid(pw->pw_uid) < 0)
815 yaz_log(LOG_FATAL|LOG_ERRNO, "setuid");
821 if ((pListener == NULL) && *control_block.default_listen)
822 add_listener(control_block.default_listen,
823 control_block.default_proto);
825 if (pListener == NULL)
829 yaz_log(LOG_LOG, "Entering event loop.");
830 ret = event_loop(&pListener);
835 int check_options(int argc, char **argv)
840 while ((ret = options("1a:iszSTl:v:u:c:w:t:k:d:A:p:DC:",
841 argv, argc, &arg)) != -2)
846 if (add_listener(arg, control_block.default_proto))
847 return 1; /* failed to create listener */
850 control_block.one_shot = 1;
851 control_block.dynamic = 0;
854 control_block.default_proto = PROTO_Z3950;
857 fprintf (stderr, "%s: SR protocol no longer supported\n", me);
861 control_block.dynamic = 0;
864 #if YAZ_POSIX_THREADS
865 control_block.dynamic = 0;
866 control_block.threads = 1;
867 #elif YAZ_GNU_THREADS
868 control_block.dynamic = 0;
869 control_block.threads = 1;
871 fprintf(stderr, "%s: Threaded mode not available.\n", me);
876 strcpy(control_block.logfile, arg ? arg : "");
877 yaz_log_init(control_block.loglevel, me, control_block.logfile);
880 control_block.loglevel = yaz_log_mask_str(arg);
881 yaz_log_init(control_block.loglevel, me, control_block.logfile);
884 strcpy(control_block.apdufile, arg ? arg : "");
887 strcpy(control_block.setuid, arg ? arg : "");
890 strcpy(control_block.configname, arg ? arg : "");
893 strcpy(control_block.cert_fname, arg ? arg : "");
896 strcpy(control_block.daemon_name, arg ? arg : "");
899 if (!arg || !(r = atoi(arg)))
901 fprintf(stderr, "%s: Specify positive timeout for -t.\n", me);
904 control_block.idle_timeout = r;
907 if (!arg || !(r = atoi(arg)))
909 fprintf(stderr, "%s: Specify positive size for -k.\n", me);
912 control_block.maxrecordsize = r * 1024;
915 control_block.inetd = 1;
925 max_sessions = atoi(arg);
928 if (strlen(arg) >= sizeof(control_block.pid_fname))
930 yaz_log(LOG_FATAL, "pid fname too long");
933 strcpy(control_block.pid_fname, arg);
936 control_block.background = 1;
939 fprintf(stderr, "Usage: %s [ -a <pdufile> -v <loglevel>"
940 " -l <logfile> -u <user> -c <config> -t <minutes>"
941 " -k <kilobytes> -d <daemon> -p <pidfile> -C certfile"
942 " -ziDST1 -w <directory> <listener-addr>... ]\n", me);
956 static Args ArgDetails;
958 /* name of the executable */
959 #define SZAPPNAME "server"
961 /* list of service dependencies - "dep1\0dep2\0\0" */
962 #define SZDEPENDENCIES ""
964 int statserv_main(int argc, char **argv,
965 bend_initresult *(*bend_init)(bend_initrequest *r),
966 void (*bend_close)(void *handle))
968 statserv_options_block *cb = statserv_getcontrol();
970 cb->bend_init = bend_init;
971 cb->bend_close = bend_close;
973 statserv_setcontrol(cb);
975 /* Lets setup the Arg structure */
976 ArgDetails.argc = argc;
977 ArgDetails.argv = argv;
979 /* Now setup the service with the service controller */
980 SetupService(argc, argv, &ArgDetails, SZAPPNAME,
981 cb->service_name, /* internal service name */
982 cb->service_display_name, /* displayed name */
987 int StartAppService(void *pHandle, int argc, char **argv)
989 /* Initializes the App */
993 void RunAppService(void *pHandle)
995 Args *pArgs = (Args *)pHandle;
997 /* Starts the app running */
998 statserv_start(pArgs->argc, pArgs->argv);
1001 void StopAppService(void *pHandle)
1004 statserv_closedown();
1010 int statserv_main(int argc, char **argv,
1011 bend_initresult *(*bend_init)(bend_initrequest *r),
1012 void (*bend_close)(void *handle))
1015 statserv_options_block *cb = statserv_getcontrol();
1017 cb->bend_init = bend_init;
1018 cb->bend_close = bend_close;
1020 statserv_setcontrol(cb);
1021 ret = statserv_start (argc, argv);
1022 statserv_closedown ();