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.10 2004-11-02 11:37:21 heikki Exp $
13 * \brief Implements GFS logic
38 #include <yaz/comstack.h>
39 #include <yaz/tcpip.h>
40 #include <yaz/options.h>
42 #include <yaz/xmosi.h>
47 #include <yaz/statserv.h>
49 static IOCHAN pListener = NULL;
51 static char *me = "statserver";
55 int check_options(int argc, char **argv);
56 statserv_options_block control_block = {
58 0, /* threaded mode */
59 0, /* one shot (single session) */
60 LOG_DEFAULT_LEVEL, /* log level */
62 "", /* diagnostic output to stderr */
63 "tcp:@:9999", /* default listener port */
64 PROTO_Z3950, /* default application protocol */
65 15, /* idle timeout (minutes) */
66 1024*1024, /* maximum PDU size (approx.) to allow */
67 "default-config", /* configuration name to pass to backend */
69 0, /* bend_start handler */
70 0, /* bend_stop handler */
71 check_options, /* Default routine, for checking the run-time arguments */
74 0, /* default value for inet deamon */
75 0, /* handle (for service, etc) */
76 0, /* bend_init handle */
77 0, /* bend_close handle */
79 "Z39.50 Server", /* NT Service Name */
80 "Server", /* NT application Name */
81 "", /* NT Service Dependencies */
82 "Z39.50 Server", /* NT Service Display Name */
84 0, /* SOAP handlers */
86 0, /* background daemon */
87 "" /* SSL certificate filename */
90 static int max_sessions = 0;
93 * handle incoming connect requests.
94 * The dynamic mode is a bit tricky mostly because we want to avoid
95 * doing all of the listening and accepting in the parent - it's
100 typedef struct _ThreadList ThreadList;
109 static ThreadList *pFirstThread;
110 static CRITICAL_SECTION Thread_CritSect;
111 static BOOL bInitialized = FALSE;
113 static void ThreadList_Initialize()
115 /* Initialize the critical Sections */
116 InitializeCriticalSection(&Thread_CritSect);
118 /* Set the first thraed */
121 /* we have been initialized */
125 static void statserv_add(HANDLE hThread, IOCHAN pIOChannel)
127 /* Only one thread can go through this section at a time */
128 EnterCriticalSection(&Thread_CritSect);
131 /* Lets create our new object */
132 ThreadList *pNewThread = (ThreadList *)malloc(sizeof(ThreadList));
133 pNewThread->hThread = hThread;
134 pNewThread->pIOChannel = pIOChannel;
135 pNewThread->pNext = pFirstThread;
136 pFirstThread = pNewThread;
138 /* Lets let somebody else create a new object now */
139 LeaveCriticalSection(&Thread_CritSect);
143 void statserv_remove(IOCHAN pIOChannel)
145 /* Only one thread can go through this section at a time */
146 EnterCriticalSection(&Thread_CritSect);
149 ThreadList *pCurrentThread = pFirstThread;
150 ThreadList *pNextThread;
151 ThreadList *pPrevThread =NULL;
153 /* Step through alll the threads */
154 for (; pCurrentThread != NULL; pCurrentThread = pNextThread)
156 /* We only need to compare on the IO Channel */
157 if (pCurrentThread->pIOChannel == pIOChannel)
159 /* We have found the thread we want to delete */
160 /* First of all reset the next pointers */
161 if (pPrevThread == NULL)
162 pFirstThread = pCurrentThread->pNext;
164 pPrevThread->pNext = pCurrentThread->pNext;
166 /* All we need todo now is delete the memory */
167 free(pCurrentThread);
169 /* No need to look at any more threads */
174 /* We need to look at another thread */
175 pNextThread = pCurrentThread->pNext;
176 pPrevThread = pCurrentThread;
180 /* Lets let somebody else remove an object now */
181 LeaveCriticalSection(&Thread_CritSect);
185 /* WIN32 statserv_closedown */
186 void statserv_closedown()
188 /* Shouldn't do anything if we are not initialized */
192 HANDLE *pThreadHandles = NULL;
194 /* We need to stop threads adding and removing while we */
195 /* start the closedown process */
196 EnterCriticalSection(&Thread_CritSect);
199 /* We have exclusive access to the thread stuff now */
200 /* Y didn't i use a semaphore - Oh well never mind */
201 ThreadList *pCurrentThread = pFirstThread;
203 /* Before we do anything else, we need to shutdown the listener */
204 if (pListener != NULL)
205 iochan_destroy(pListener);
207 for (; pCurrentThread != NULL; pCurrentThread = pCurrentThread->pNext)
209 /* Just destroy the IOCHAN, that should do the trick */
210 iochan_destroy(pCurrentThread->pIOChannel);
211 closesocket(pCurrentThread->pIOChannel->fd);
213 /* Keep a running count of our handles */
219 HANDLE *pCurrentHandle ;
221 /* Allocate the thread handle array */
222 pThreadHandles = (HANDLE *)malloc(sizeof(HANDLE) * iHandles);
223 pCurrentHandle = pThreadHandles;
225 for (pCurrentThread = pFirstThread;
226 pCurrentThread != NULL;
227 pCurrentThread = pCurrentThread->pNext, pCurrentHandle++)
229 /* Just the handle */
230 *pCurrentHandle = pCurrentThread->hThread;
234 /* We can now leave the critical section */
235 LeaveCriticalSection(&Thread_CritSect);
238 /* Now we can really do something */
241 logf (LOG_LOG, "waiting for %d to die", iHandles);
242 /* This will now wait, until all the threads close */
243 WaitForMultipleObjects(iHandles, pThreadHandles, TRUE, INFINITE);
245 /* Free the memory we allocated for the handle array */
246 free(pThreadHandles);
249 if (control_block.bend_stop)
250 (*control_block.bend_stop)(&control_block);
251 /* No longer require the critical section, since all threads are dead */
252 DeleteCriticalSection(&Thread_CritSect);
256 void __cdecl event_loop_thread (IOCHAN iochan)
258 event_loop (&iochan);
262 static void listener(IOCHAN h, int event)
264 COMSTACK line = (COMSTACK) iochan_getdata(h);
269 if (event == EVENT_INPUT)
271 if ((res = cs_listen(line, 0, 0)) < 0)
273 yaz_log(LOG_FATAL, "cs_listen failed");
278 yaz_log(LOG_DEBUG, "listen ok");
279 iochan_setevent(h, EVENT_OUTPUT);
280 iochan_setflags(h, EVENT_OUTPUT | EVENT_EXCEPT); /* set up for acpt */
282 else if (event == EVENT_OUTPUT)
284 COMSTACK new_line = cs_accept(line);
290 yaz_log(LOG_FATAL, "Accept failed.");
291 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT);
294 yaz_log(LOG_DEBUG, "Accept ok");
296 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session,
299 yaz_log(LOG_FATAL, "Failed to create iochan");
304 yaz_log(LOG_DEBUG, "Creating association");
305 if (!(newas = create_association(new_chan, new_line)))
307 yaz_log(LOG_FATAL, "Failed to create new assoc.");
311 newas->cs_get_mask = EVENT_INPUT;
312 newas->cs_put_mask = 0;
313 newas->cs_accept_mask = 0;
315 yaz_log(LOG_DEBUG, "Setting timeout %d", control_block.idle_timeout);
316 iochan_setdata(new_chan, newas);
317 iochan_settimeout(new_chan, 60);
319 /* Now what we need todo is create a new thread with this iochan as
321 newHandle = (HANDLE) _beginthread(event_loop_thread, 0, new_chan);
322 if (newHandle == (HANDLE) -1)
325 yaz_log(LOG_FATAL|LOG_ERRNO, "Failed to create new thread.");
329 /* We successfully created the thread, so add it to the list */
330 statserv_add(newHandle, new_chan);
332 yaz_log(LOG_DEBUG, "Created new thread, id = %ld iochan %p",(long) newHandle, new_chan);
333 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
337 yaz_log(LOG_FATAL, "Bad event on listener.");
343 int statserv_must_terminate(void)
350 static int term_flag = 0;
351 /* To save having an #ifdef in event_loop we need to
352 define this empty function
354 int statserv_must_terminate(void)
359 void statserv_remove(IOCHAN pIOChannel)
363 void statserv_closedown()
367 if (control_block.bend_stop)
368 (*control_block.bend_stop)(&control_block);
369 for (p = pListener; p; p = p->next)
375 void sigterm(int sig)
380 static void *new_session (void *vp);
381 static int no_sessions = 0;
384 static void listener(IOCHAN h, int event)
386 COMSTACK line = (COMSTACK) iochan_getdata(h);
388 static int child = 0;
391 if (event == EVENT_INPUT)
393 if (control_block.dynamic && !child)
400 yaz_log(LOG_FATAL|LOG_ERRNO, "pipe");
404 if ((res = fork()) < 0)
406 yaz_log(LOG_FATAL|LOG_ERRNO, "fork");
410 else if (res == 0) /* child */
417 for (pp = pListener; pp; pp = iochan_getnext(pp))
421 COMSTACK l = (COMSTACK)iochan_getdata(pp);
426 sprintf(nbuf, "%s(%d)", me, getpid());
427 yaz_log_init(control_block.loglevel, nbuf, 0);
428 /* ensure that bend_stop is not called when each child exits -
429 only for the main process .. */
430 control_block.bend_stop = 0;
435 /* wait for child to take the call */
441 if ((res = read(hand[0], dummy, 1)) < 0 &&
442 yaz_errno() != EINTR)
444 yaz_log(LOG_FATAL|LOG_ERRNO, "handshake read");
450 yaz_log(LOG_DEBUG, "P: Child has taken the call");
455 if ((res = cs_listen_check(line, 0, 0, control_block.check_ip,
456 control_block.daemon_name)) < 0)
458 yaz_log(LOG_WARN|LOG_ERRNO, "cs_listen failed");
463 yaz_log(LOG_DEBUG, "listen ok");
464 iochan_setevent(h, EVENT_OUTPUT);
465 iochan_setflags(h, EVENT_OUTPUT | EVENT_EXCEPT); /* set up for acpt */
467 /* in dynamic mode, only the child ever comes down here */
468 else if (event == EVENT_OUTPUT)
470 COMSTACK new_line = cs_accept(line);
474 yaz_log(LOG_FATAL, "Accept failed.");
475 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
478 yaz_log(LOG_DEBUG, "accept ok");
479 if (control_block.dynamic)
482 /* close our half of the listener socket */
483 for (pp = pListener; pp; pp = iochan_getnext(pp))
485 COMSTACK l = (COMSTACK)iochan_getdata(pp);
490 yaz_log(LOG_DEBUG, "Releasing parent");
495 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
498 #if YAZ_POSIX_THREADS
499 if (control_block.threads)
501 pthread_t child_thread;
502 pthread_create (&child_thread, 0, new_session, new_line);
503 pthread_detach (child_thread);
506 new_session(new_line);
507 #elif YAZ_GNU_THREADS
508 if (control_block.threads)
513 attr = pth_attr_new ();
514 pth_attr_set (attr, PTH_ATTR_JOINABLE, FALSE);
515 pth_attr_set (attr, PTH_ATTR_STACK_SIZE, 32*1024);
516 pth_attr_set (attr, PTH_ATTR_NAME, "session");
517 yaz_log (LOG_LOG, "pth_spawn begin");
518 child_thread = pth_spawn (attr, new_session, new_line);
519 yaz_log (LOG_LOG, "pth_spawn finish");
520 pth_attr_destroy (attr);
523 new_session(new_line);
525 new_session(new_line);
528 else if (event == EVENT_TIMEOUT)
530 yaz_log(LOG_LOG, "Shutting down listener.");
535 yaz_log(LOG_FATAL, "Bad event on listener.");
540 static void *new_session (void *vp)
545 COMSTACK new_line = (COMSTACK) vp;
547 unsigned cs_get_mask, cs_accept_mask, mask =
548 ((new_line->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
549 ((new_line->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
553 cs_accept_mask = mask; /* accept didn't complete */
558 cs_accept_mask = 0; /* accept completed. */
559 cs_get_mask = mask = EVENT_INPUT;
562 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session, mask)))
564 yaz_log(LOG_FATAL, "Failed to create iochan");
567 if (!(newas = create_association(new_chan, new_line)))
569 yaz_log(LOG_FATAL, "Failed to create new assoc.");
572 newas->cs_accept_mask = cs_accept_mask;
573 newas->cs_get_mask = cs_get_mask;
575 iochan_setdata(new_chan, newas);
576 iochan_settimeout(new_chan, 60);
578 a = cs_addrstr(new_line);
582 yaz_log(LOG_LOG, "Starting session %d from %s",
583 no_sessions, a ? a : "[Unknown]");
584 if (max_sessions && no_sessions == max_sessions)
585 control_block.one_shot = 1;
586 if (control_block.threads)
588 event_loop(&new_chan);
592 new_chan->next = pListener;
593 pListener = new_chan;
601 static void inetd_connection(int what)
608 if ((line = cs_createbysocket(0, tcpip_type, 0, what)))
610 if ((chan = iochan_create(cs_fileno(line), ir_session, EVENT_INPUT)))
612 if ((assoc = create_association(chan, line)))
614 iochan_setdata(chan, assoc);
615 iochan_settimeout(chan, 60);
616 addr = cs_addrstr(line);
617 yaz_log(LOG_LOG, "Inetd association from %s",
618 addr ? addr : "[UNKNOWN]");
619 assoc->cs_get_mask = EVENT_INPUT;
623 yaz_log(LOG_FATAL, "Failed to create association structure");
625 chan->next = pListener;
630 yaz_log(LOG_FATAL, "Failed to create iochan");
635 yaz_log(LOG_ERRNO|LOG_FATAL, "Failed to create comstack on socket 0");
640 * Set up a listening endpoint, and give it to the event-handler.
642 static int add_listener(char *where, int what)
649 if (control_block.dynamic)
651 else if (control_block.threads)
656 yaz_log(LOG_LOG, "Adding %s %s listener on %s", mode,
657 what == PROTO_SR ? "SR" : "Z3950", where);
659 l = cs_create_host(where, 2, &ap);
662 yaz_log(LOG_FATAL, "Failed to listen on %s", where);
665 if (*control_block.cert_fname)
666 cs_set_ssl_certificate_file(l, control_block.cert_fname);
668 if (cs_bind(l, ap, CS_SERVER) < 0)
670 yaz_log(LOG_FATAL|LOG_ERRNO, "Failed to bind to %s", where);
674 if (!(lst = iochan_create(cs_fileno(l), listener, EVENT_INPUT |
677 yaz_log(LOG_FATAL|LOG_ERRNO, "Failed to create IOCHAN-type");
681 iochan_setdata(lst, l);
683 /* Ensure our listener chain is setup properly */
684 lst->next = pListener;
690 /* UNIX only (for windows we don't need to catch the signals) */
691 static void catchchld(int num)
693 while (waitpid(-1, 0, WNOHANG) > 0)
695 signal(SIGCHLD, catchchld);
699 statserv_options_block *statserv_getcontrol(void)
701 static statserv_options_block cb;
703 memcpy(&cb, &control_block, sizeof(cb));
707 void statserv_setcontrol(statserv_options_block *block)
709 memcpy(&control_block, block, sizeof(*block));
712 static void statserv_reset(void)
716 int statserv_start(int argc, char **argv)
721 /* We need to initialize the thread list */
722 ThreadList_Initialize();
727 if ((me = strrchr (argv[0], '\\')))
734 if (control_block.options_func(argc, argv))
737 if (control_block.bend_start)
738 (*control_block.bend_start)(&control_block);
740 yaz_log (LOG_LOG, "Starting server %s", me);
741 if (!pListener && *control_block.default_listen)
742 add_listener(control_block.default_listen,
743 control_block.default_proto);
749 if (control_block.inetd)
750 inetd_connection(control_block.default_proto);
753 if (control_block.background)
771 open("/dev/null",O_RDWR);
774 if (!pListener && *control_block.default_listen)
775 add_listener(control_block.default_listen,
776 control_block.default_proto);
781 if (*control_block.pid_fname)
783 FILE *f = fopen(control_block.pid_fname, "w");
786 yaz_log(LOG_FATAL|LOG_ERRNO, "Couldn't create %s",
787 control_block.pid_fname);
790 fprintf(f, "%ld", (long) getpid());
794 yaz_log (LOG_LOG, "Starting server %s pid=%d", me, getpid());
796 sigset_t sigs_to_block;
798 sigemptyset(&sigs_to_block);
799 sigaddset (&sigs_to_block, SIGTERM);
800 pthread_sigmask (SIG_BLOCK, &sigs_to_block, 0);
803 if (control_block.dynamic)
804 signal(SIGCHLD, catchchld);
806 signal (SIGPIPE, SIG_IGN);
807 signal (SIGTERM, sigterm);
808 if (*control_block.setuid)
812 if (!(pw = getpwnam(control_block.setuid)))
814 yaz_log(LOG_FATAL, "%s: Unknown user", control_block.setuid);
817 if (setuid(pw->pw_uid) < 0)
819 yaz_log(LOG_FATAL|LOG_ERRNO, "setuid");
825 if ((pListener == NULL) && *control_block.default_listen)
826 add_listener(control_block.default_listen,
827 control_block.default_proto);
829 if (pListener == NULL)
833 yaz_log(LOG_LOG, "Entering event loop.");
834 ret = event_loop(&pListener);
839 int check_options(int argc, char **argv)
844 while ((ret = options("1a:iszSTl:v:u:c:w:t:k:d:A:p:DC:",
845 argv, argc, &arg)) != -2)
850 if (add_listener(arg, control_block.default_proto))
851 return 1; /* failed to create listener */
854 control_block.one_shot = 1;
855 control_block.dynamic = 0;
858 control_block.default_proto = PROTO_Z3950;
861 fprintf (stderr, "%s: SR protocol no longer supported\n", me);
865 control_block.dynamic = 0;
868 #if YAZ_POSIX_THREADS
869 control_block.dynamic = 0;
870 control_block.threads = 1;
871 #elif YAZ_GNU_THREADS
872 control_block.dynamic = 0;
873 control_block.threads = 1;
875 fprintf(stderr, "%s: Threaded mode not available.\n", me);
880 strcpy(control_block.logfile, arg ? arg : "");
881 yaz_log_init(control_block.loglevel, me, control_block.logfile);
884 control_block.loglevel = yaz_log_mask_str(arg);
885 yaz_log_init(control_block.loglevel, me, control_block.logfile);
888 strcpy(control_block.apdufile, arg ? arg : "");
891 strcpy(control_block.setuid, arg ? arg : "");
894 strcpy(control_block.configname, arg ? arg : "");
897 strcpy(control_block.cert_fname, arg ? arg : "");
900 strcpy(control_block.daemon_name, arg ? arg : "");
903 if (!arg || !(r = atoi(arg)))
905 fprintf(stderr, "%s: Specify positive timeout for -t.\n", me);
908 control_block.idle_timeout = r;
911 if (!arg || !(r = atoi(arg)))
913 fprintf(stderr, "%s: Specify positive size for -k.\n", me);
916 control_block.maxrecordsize = r * 1024;
919 control_block.inetd = 1;
929 max_sessions = atoi(arg);
932 if (strlen(arg) >= sizeof(control_block.pid_fname))
934 yaz_log(LOG_FATAL, "pid fname too long");
937 strcpy(control_block.pid_fname, arg);
940 control_block.background = 1;
943 fprintf(stderr, "Usage: %s [ -a <pdufile> -v <loglevel>"
944 " -l <logfile> -u <user> -c <config> -t <minutes>"
945 " -k <kilobytes> -d <daemon> -p <pidfile> -C certfile"
946 " -ziDST1 -w <directory> <listener-addr>... ]\n", me);
960 static Args ArgDetails;
962 /* name of the executable */
963 #define SZAPPNAME "server"
965 /* list of service dependencies - "dep1\0dep2\0\0" */
966 #define SZDEPENDENCIES ""
968 int statserv_main(int argc, char **argv,
969 bend_initresult *(*bend_init)(bend_initrequest *r),
970 void (*bend_close)(void *handle))
972 statserv_options_block *cb = statserv_getcontrol();
974 cb->bend_init = bend_init;
975 cb->bend_close = bend_close;
977 statserv_setcontrol(cb);
979 /* Lets setup the Arg structure */
980 ArgDetails.argc = argc;
981 ArgDetails.argv = argv;
983 /* Now setup the service with the service controller */
984 SetupService(argc, argv, &ArgDetails, SZAPPNAME,
985 cb->service_name, /* internal service name */
986 cb->service_display_name, /* displayed name */
991 int StartAppService(void *pHandle, int argc, char **argv)
993 /* Initializes the App */
997 void RunAppService(void *pHandle)
999 Args *pArgs = (Args *)pHandle;
1001 /* Starts the app running */
1002 statserv_start(pArgs->argc, pArgs->argv);
1005 void StopAppService(void *pHandle)
1008 statserv_closedown();
1014 int statserv_main(int argc, char **argv,
1015 bend_initresult *(*bend_init)(bend_initrequest *r),
1016 void (*bend_close)(void *handle))
1019 statserv_options_block *cb = statserv_getcontrol();
1021 cb->bend_init = bend_init;
1022 cb->bend_close = bend_close;
1024 statserv_setcontrol(cb);
1025 ret = statserv_start (argc, argv);
1026 statserv_closedown ();