2 * Copyright (C) 1995-2005, Index Data ApS
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.26 2005-03-08 11:07:50 adam Exp $
13 * \brief Implements GFS logic
26 #include <sys/types.h>
39 #include <libxml/parser.h>
40 #include <libxml/tree.h>
53 #include <yaz/comstack.h>
54 #include <yaz/tcpip.h>
55 #include <yaz/options.h>
57 #include <yaz/xmosi.h>
62 #include <yaz/statserv.h>
64 static IOCHAN pListener = NULL;
66 static struct gfs_server *gfs_server_list = 0;
67 static struct gfs_listen *gfs_listen_list = 0;
68 static NMEM gfs_nmem = 0;
70 static char *me = "statserver"; /* log prefix */
71 static char *programname="statserver"; /* full program name */
73 DWORD current_control_tls;
74 static int init_control_tls = 0;
75 #elif YAZ_POSIX_THREADS
76 static pthread_key_t current_control_tls;
77 static int init_control_tls = 0;
79 static statserv_options_block *current_control_block = 0;
85 #define STAT_DEFAULT_LOG_LEVEL "none,fatal,warn,log,server,session,request"
86 /* the 'none' clears yaz' own default settings, including [log] */
88 int check_options(int argc, char **argv);
89 statserv_options_block control_block = {
91 0, /* threaded mode */
92 0, /* one shot (single session) */
93 YLOG_DEFAULT_LEVEL, /* log level */
95 "", /* diagnostic output to stderr */
96 "tcp:@:9999", /* default listener port */
97 PROTO_Z3950, /* default application protocol */
98 15, /* idle timeout (minutes) */
99 1024*1024, /* maximum PDU size (approx.) to allow */
100 "default-config", /* configuration name to pass to backend */
101 "", /* set user id */
102 0, /* bend_start handler */
103 0, /* bend_stop handler */
104 check_options, /* Default routine, for checking the run-time arguments */
107 0, /* default value for inet deamon */
108 0, /* handle (for service, etc) */
109 0, /* bend_init handle */
110 0, /* bend_close handle */
112 "Z39.50 Server", /* NT Service Name */
113 "Server", /* NT application Name */
114 "", /* NT Service Dependencies */
115 "Z39.50 Server", /* NT Service Display Name */
117 0, /* SOAP handlers */
119 0, /* background daemon */
120 "", /* SSL certificate filename */
121 "" /* XML config filename */
124 static int max_sessions = 0;
126 static int logbits_set = 0;
127 static int log_session = 0;
128 static int log_server = 0;
130 /** get_logbits sets global loglevel bits */
131 static void get_logbits(int force)
132 { /* needs to be called after parsing cmd-line args that can set loglevels!*/
133 if (force || !logbits_set)
136 log_session = yaz_log_module_level("session");
137 log_server = yaz_log_module_level("server");
142 static int add_listener(char *where, int listen_id);
145 static xmlDocPtr xml_config_doc = 0;
149 static xmlNodePtr xml_config_get_root()
154 ptr = xmlDocGetRootElement(xml_config_doc);
155 if (!ptr || ptr->type != XML_ELEMENT_NODE ||
156 strcmp((const char *) ptr->name, "yazgfs"))
158 yaz_log(YLOG_WARN, "Bad/missing root element for config %s",
159 control_block.xml_config);
169 static char *nmem_dup_xml_content(NMEM n, xmlNodePtr ptr)
173 int len = 1; /* start with 1, because of trailing 0 */
175 int first = 1; /* whitespace lead flag .. */
176 /* determine length */
177 for (p = ptr; p; p = p->next)
179 if (p->type == XML_TEXT_NODE)
180 len += strlen(p->content);
182 /* now allocate for the string */
183 str = nmem_malloc(n, len);
184 *str = '\0'; /* so we can use strcat */
185 for (p = ptr; p; p = p->next)
187 if (p->type == XML_TEXT_NODE)
192 while(*cp && isspace(*cp))
195 first = 0; /* reset if we got non-whitespace out */
197 strcat(str, cp); /* append */
200 /* remove trailing whitespace */
201 cp = strlen(str) + str;
202 while ((char*) cp != str && isspace(cp[-1]))
205 /* return resulting string */
210 static struct gfs_server * gfs_server_new()
212 struct gfs_server *n = nmem_malloc(gfs_nmem, sizeof(*n));
213 memcpy(&n->cb, &control_block, sizeof(control_block));
217 n->cql_transform = 0;
218 n->server_node_ptr = 0;
223 static struct gfs_listen * gfs_listen_new(const char *id,
226 struct gfs_listen *n = nmem_malloc(gfs_nmem, sizeof(*n));
228 n->id = nmem_strdup(gfs_nmem, id);
232 n->address = nmem_strdup(gfs_nmem, address);
236 int control_association(association *assoc, const char *host, int force_open)
238 char vhost[128], *cp;
241 strncpy(vhost, host, 127);
243 cp = strchr(vhost, ':');
248 if (control_block.xml_config[0])
250 struct gfs_server *gfs;
251 for (gfs = gfs_server_list; gfs; gfs = gfs->next)
253 int listen_match = 0;
255 if ( !gfs->host || (host && gfs->host && !strcmp(host, gfs->host)))
257 if (!gfs->listen_ref ||
258 gfs->listen_ref == assoc->client_chan->chan_id)
260 if (listen_match && host_match)
263 (assoc->last_control != &gfs->cb && assoc->backend))
265 statserv_setcontrol(assoc->last_control);
266 if (assoc->backend && assoc->init)
267 (assoc->last_control->bend_close)(assoc->backend);
273 if (chdir(gfs->directory))
274 yaz_log(YLOG_WARN|YLOG_ERRNO, "chdir %s",
278 assoc->cql_transform = gfs->cql_transform;
279 assoc->server_node_ptr = gfs->server_node_ptr;
280 assoc->last_control = &gfs->cb;
281 statserv_setcontrol(&gfs->cb);
282 yaz_log(YLOG_DEBUG, "server select: %s", gfs->cb.configname);
286 statserv_setcontrol(0);
287 assoc->last_control = 0;
288 assoc->cql_transform = 0;
289 assoc->server_node_ptr = 0;
290 yaz_log(YLOG_DEBUG, "server select: no match");
295 statserv_setcontrol(&control_block);
296 assoc->last_control = &control_block;
297 assoc->cql_transform = 0;
298 assoc->server_node_ptr = 0;
299 yaz_log(YLOG_DEBUG, "server select: config=%s", control_block.configname);
304 static void xml_config_read()
306 struct gfs_server **gfsp = &gfs_server_list;
307 struct gfs_listen **gfslp = &gfs_listen_list;
309 xmlNodePtr ptr = xml_config_get_root();
313 for (ptr = ptr->children; ptr; ptr = ptr->next)
315 struct _xmlAttr *attr;
316 if (ptr->type != XML_ELEMENT_NODE)
318 attr = ptr->properties;
319 if (!strcmp((const char *) ptr->name, "listen"))
322 <listen id="listenerid">tcp:@:9999</listen>
325 const char *address =
326 nmem_dup_xml_content(gfs_nmem, ptr->children);
327 for ( ; attr; attr = attr->next)
328 if (!strcmp(attr->name, "id")
329 && attr->children && attr->children->type == XML_TEXT_NODE)
330 id = nmem_dup_xml_content(gfs_nmem, attr->children);
333 *gfslp = gfs_listen_new(id, address);
334 gfslp = &(*gfslp)->next;
335 *gfslp = 0; /* make listener list consistent for search */
338 else if (!strcmp((const char *) ptr->name, "server"))
340 xmlNodePtr ptr_server = ptr;
342 const char *listenref = 0;
345 for ( ; attr; attr = attr->next)
346 if (!strcmp(attr->name, "listenref") && attr->children &&
347 attr->children->type == XML_TEXT_NODE)
348 listenref = nmem_dup_xml_content(gfs_nmem, attr->children);
349 else if (!strcmp(attr->name, "id") && attr->children &&
350 attr->children->type == XML_TEXT_NODE)
351 id = nmem_dup_xml_content(gfs_nmem, attr->children);
353 yaz_log(YLOG_WARN, "Unknown attribute '%s' for server",
355 *gfsp = gfs_server_new();
356 (*gfsp)->server_node_ptr = ptr_server;
360 struct gfs_listen *gl = gfs_listen_list;
361 for (id_no = 1; gl; gl = gl->next, id_no++)
362 if (gl->id && !strcmp(gl->id, listenref))
364 (*gfsp)->listen_ref = id_no;
368 yaz_log(YLOG_WARN, "Non-existent listenref '%s' in server "
369 "config element", listenref);
371 for (ptr = ptr_server->children; ptr; ptr = ptr->next)
373 if (ptr->type != XML_ELEMENT_NODE)
375 if (!strcmp((const char *) ptr->name, "host"))
377 (*gfsp)->host = nmem_dup_xml_content(gfs_nmem,
380 else if (!strcmp((const char *) ptr->name, "config"))
382 strcpy((*gfsp)->cb.configname,
383 nmem_dup_xml_content(gfs_nmem, ptr->children));
385 else if (!strcmp((const char *) ptr->name, "cql2rpn"))
387 (*gfsp)->cql_transform = cql_transform_open_fname(
388 nmem_dup_xml_content(gfs_nmem, ptr->children)
391 else if (!strcmp((const char *) ptr->name, "directory"))
394 nmem_dup_xml_content(gfs_nmem, ptr->children);
397 gfsp = &(*gfsp)->next;
404 static void xml_config_open()
407 init_control_tls = 1;
408 current_control_tls = TlsAlloc();
409 #elif YAZ_POSIX_THREADS
410 init_control_tls = 1;
411 pthread_key_create(¤t_control_tls, 0);
414 gfs_nmem = nmem_create();
416 if (control_block.xml_config[0] == '\0')
421 xml_config_doc = xmlParseFile(control_block.xml_config);
424 yaz_log(YLOG_WARN, "Could not parse %s", control_block.xml_config);
432 static void xml_config_close()
437 xmlFreeDoc(xml_config_doc);
442 nmem_destroy(gfs_nmem);
444 if (init_control_tls)
445 TlsFree(current_control_tls);
446 #elif YAZ_POSIX_THREADS
447 if (init_control_tls)
448 pthread_key_delete(current_control_tls);
452 static void xml_config_add_listeners()
454 struct gfs_listen *gfs = gfs_listen_list;
457 for (id_no = 1; gfs; gfs = gfs->next, id_no++)
460 add_listener(gfs->address, id_no);
464 static void xml_config_bend_start()
466 if (control_block.xml_config[0])
468 struct gfs_server *gfs = gfs_server_list;
469 for (; gfs; gfs = gfs->next)
471 yaz_log(YLOG_DEBUG, "xml_config_bend_start config=%s",
473 statserv_setcontrol(&gfs->cb);
474 if (control_block.bend_start)
475 (control_block.bend_start)(&gfs->cb);
480 yaz_log(YLOG_DEBUG, "xml_config_bend_start default config");
481 statserv_setcontrol(&control_block);
482 if (control_block.bend_start)
483 (*control_block.bend_start)(&control_block);
488 static void xml_config_bend_stop()
490 if (control_block.xml_config[0])
492 struct gfs_server *gfs = gfs_server_list;
493 for (; gfs; gfs = gfs->next)
495 yaz_log(YLOG_DEBUG, "xml_config_bend_stop config=%s",
497 statserv_setcontrol(&gfs->cb);
498 if (control_block.bend_stop)
499 (control_block.bend_stop)(&gfs->cb);
504 yaz_log(YLOG_DEBUG, "xml_config_bend_stop default config");
505 statserv_setcontrol(&control_block);
506 if (control_block.bend_stop)
507 (*control_block.bend_stop)(&control_block);
512 * handle incoming connect requests.
513 * The dynamic mode is a bit tricky mostly because we want to avoid
514 * doing all of the listening and accepting in the parent - it's
519 typedef struct _ThreadList ThreadList;
528 static ThreadList *pFirstThread;
529 static CRITICAL_SECTION Thread_CritSect;
530 static BOOL bInitialized = FALSE;
532 static void ThreadList_Initialize()
534 /* Initialize the critical Sections */
535 InitializeCriticalSection(&Thread_CritSect);
537 /* Set the first thraed */
540 /* we have been initialized */
544 static void statserv_add(HANDLE hThread, IOCHAN pIOChannel)
546 /* Only one thread can go through this section at a time */
547 EnterCriticalSection(&Thread_CritSect);
550 /* Lets create our new object */
551 ThreadList *pNewThread = (ThreadList *)malloc(sizeof(ThreadList));
552 pNewThread->hThread = hThread;
553 pNewThread->pIOChannel = pIOChannel;
554 pNewThread->pNext = pFirstThread;
555 pFirstThread = pNewThread;
557 /* Lets let somebody else create a new object now */
558 LeaveCriticalSection(&Thread_CritSect);
562 void statserv_remove(IOCHAN pIOChannel)
564 /* Only one thread can go through this section at a time */
565 EnterCriticalSection(&Thread_CritSect);
568 ThreadList *pCurrentThread = pFirstThread;
569 ThreadList *pNextThread;
570 ThreadList *pPrevThread =NULL;
572 /* Step through all the threads */
573 for (; pCurrentThread != NULL; pCurrentThread = pNextThread)
575 /* We only need to compare on the IO Channel */
576 if (pCurrentThread->pIOChannel == pIOChannel)
578 /* We have found the thread we want to delete */
579 /* First of all reset the next pointers */
580 if (pPrevThread == NULL)
581 pFirstThread = pCurrentThread->pNext;
583 pPrevThread->pNext = pCurrentThread->pNext;
585 /* All we need todo now is delete the memory */
586 free(pCurrentThread);
588 /* No need to look at any more threads */
593 /* We need to look at another thread */
594 pNextThread = pCurrentThread->pNext;
595 pPrevThread = pCurrentThread;
599 /* Lets let somebody else remove an object now */
600 LeaveCriticalSection(&Thread_CritSect);
604 /* WIN32 statserv_closedown */
605 void statserv_closedown()
607 /* Shouldn't do anything if we are not initialized */
611 HANDLE *pThreadHandles = NULL;
613 /* We need to stop threads adding and removing while we */
614 /* start the closedown process */
615 EnterCriticalSection(&Thread_CritSect);
618 /* We have exclusive access to the thread stuff now */
619 /* Y didn't i use a semaphore - Oh well never mind */
620 ThreadList *pCurrentThread = pFirstThread;
622 /* Before we do anything else, we need to shutdown the listener */
623 if (pListener != NULL)
624 iochan_destroy(pListener);
626 for (; pCurrentThread != NULL; pCurrentThread = pCurrentThread->pNext)
628 /* Just destroy the IOCHAN, that should do the trick */
629 iochan_destroy(pCurrentThread->pIOChannel);
630 closesocket(pCurrentThread->pIOChannel->fd);
632 /* Keep a running count of our handles */
638 HANDLE *pCurrentHandle ;
640 /* Allocate the thread handle array */
641 pThreadHandles = (HANDLE *)malloc(sizeof(HANDLE) * iHandles);
642 pCurrentHandle = pThreadHandles;
644 for (pCurrentThread = pFirstThread;
645 pCurrentThread != NULL;
646 pCurrentThread = pCurrentThread->pNext, pCurrentHandle++)
648 /* Just the handle */
649 *pCurrentHandle = pCurrentThread->hThread;
653 /* We can now leave the critical section */
654 LeaveCriticalSection(&Thread_CritSect);
657 /* Now we can really do something */
660 yaz_log(log_server, "waiting for %d to die", iHandles);
661 /* This will now wait, until all the threads close */
662 WaitForMultipleObjects(iHandles, pThreadHandles, TRUE, INFINITE);
664 /* Free the memory we allocated for the handle array */
665 free(pThreadHandles);
668 xml_config_bend_stop();
669 /* No longer require the critical section, since all threads are dead */
670 DeleteCriticalSection(&Thread_CritSect);
675 void __cdecl event_loop_thread (IOCHAN iochan)
677 event_loop (&iochan);
681 static void listener(IOCHAN h, int event)
683 COMSTACK line = (COMSTACK) iochan_getdata(h);
684 IOCHAN parent_chan = line->user;
689 if (event == EVENT_INPUT)
691 if ((res = cs_listen(line, 0, 0)) < 0)
693 yaz_log(YLOG_FATAL, "cs_listen failed");
698 yaz_log(YLOG_DEBUG, "listen ok");
699 iochan_setevent(h, EVENT_OUTPUT);
700 iochan_setflags(h, EVENT_OUTPUT | EVENT_EXCEPT); /* set up for acpt */
702 else if (event == EVENT_OUTPUT)
704 COMSTACK new_line = cs_accept(line);
710 yaz_log(YLOG_FATAL, "Accept failed.");
711 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT);
714 yaz_log(YLOG_DEBUG, "Accept ok");
716 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session,
717 EVENT_INPUT, parent_chan->chan_id)))
719 yaz_log(YLOG_FATAL, "Failed to create iochan");
724 yaz_log(YLOG_DEBUG, "Creating association");
725 if (!(newas = create_association(new_chan, new_line,
726 control_block.apdufile)))
728 yaz_log(YLOG_FATAL, "Failed to create new assoc.");
732 newas->cs_get_mask = EVENT_INPUT;
733 newas->cs_put_mask = 0;
734 newas->cs_accept_mask = 0;
736 yaz_log(YLOG_DEBUG, "Setting timeout %d", control_block.idle_timeout);
737 iochan_setdata(new_chan, newas);
738 iochan_settimeout(new_chan, 60);
740 /* Now what we need todo is create a new thread with this iochan as
742 newHandle = (HANDLE) _beginthread(event_loop_thread, 0, new_chan);
743 if (newHandle == (HANDLE) -1)
746 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create new thread.");
750 /* We successfully created the thread, so add it to the list */
751 statserv_add(newHandle, new_chan);
753 yaz_log(YLOG_DEBUG, "Created new thread, id = %ld iochan %p",(long) newHandle, new_chan);
754 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
758 yaz_log(YLOG_FATAL, "Bad event on listener.");
764 int statserv_must_terminate(void)
771 static int term_flag = 0;
772 /* To save having an #ifdef in event_loop we need to
773 define this empty function
775 int statserv_must_terminate(void)
780 void statserv_remove(IOCHAN pIOChannel)
784 void statserv_closedown()
788 xml_config_bend_stop();
789 for (p = pListener; p; p = p->next)
796 void sigterm(int sig)
801 static void *new_session (void *vp);
802 static int no_sessions = 0;
805 static void listener(IOCHAN h, int event)
807 COMSTACK line = (COMSTACK) iochan_getdata(h);
810 if (event == EVENT_INPUT)
813 if ((res = cs_listen_check(line, 0, 0, control_block.check_ip,
814 control_block.daemon_name)) < 0)
816 yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_listen failed");
821 yaz_log(YLOG_WARN, "cs_listen incomplete");
824 new_line = cs_accept(line);
827 yaz_log(YLOG_FATAL, "Accept failed.");
828 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
832 yaz_log(log_session, "Connect from %s", cs_addrstr(new_line));
835 if (control_block.dynamic)
837 if ((res = fork()) < 0)
839 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fork");
843 else if (res == 0) /* child */
848 for (pp = pListener; pp; pp = iochan_getnext(pp))
850 COMSTACK l = (COMSTACK)iochan_getdata(pp);
854 sprintf(nbuf, "%s(%d)", me, no_sessions);
855 yaz_log_init(control_block.loglevel, nbuf, 0);
856 /* ensure that bend_stop is not called when each child exits -
857 only for the main process .. */
858 control_block.bend_stop = 0;
867 if (control_block.threads)
869 #if YAZ_POSIX_THREADS
870 pthread_t child_thread;
871 pthread_create (&child_thread, 0, new_session, new_line);
872 pthread_detach (child_thread);
873 #elif YAZ_GNU_THREADS
877 attr = pth_attr_new ();
878 pth_attr_set (attr, PTH_ATTR_JOINABLE, FALSE);
879 pth_attr_set (attr, PTH_ATTR_STACK_SIZE, 32*1024);
880 pth_attr_set (attr, PTH_ATTR_NAME, "session");
881 yaz_log (YLOG_DEBUG, "pth_spawn begin");
882 child_thread = pth_spawn (attr, new_session, new_line);
883 yaz_log (YLOG_DEBUG, "pth_spawn finish");
884 pth_attr_destroy (attr);
886 new_session(new_line);
890 new_session(new_line);
892 else if (event == EVENT_TIMEOUT)
894 yaz_log(log_server, "Shutting down listener.");
899 yaz_log(YLOG_FATAL, "Bad event on listener.");
904 static void *new_session (void *vp)
909 COMSTACK new_line = (COMSTACK) vp;
910 IOCHAN parent_chan = new_line->user;
912 unsigned cs_get_mask, cs_accept_mask, mask =
913 ((new_line->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
914 ((new_line->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
918 cs_accept_mask = mask; /* accept didn't complete */
923 cs_accept_mask = 0; /* accept completed. */
924 cs_get_mask = mask = EVENT_INPUT;
927 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session, mask,
928 parent_chan->chan_id)))
930 yaz_log(YLOG_FATAL, "Failed to create iochan");
933 if (!(newas = create_association(new_chan, new_line,
934 control_block.apdufile)))
936 yaz_log(YLOG_FATAL, "Failed to create new assoc.");
939 newas->cs_accept_mask = cs_accept_mask;
940 newas->cs_get_mask = cs_get_mask;
942 iochan_setdata(new_chan, newas);
943 iochan_settimeout(new_chan, 60);
945 a = cs_addrstr(new_line);
949 yaz_log(log_session, "Starting session %d from %s (pid=%ld)",
950 no_sessions, a ? a : "[Unknown]", (long) getpid());
951 if (max_sessions && no_sessions >= max_sessions)
952 control_block.one_shot = 1;
953 if (control_block.threads)
955 event_loop(&new_chan);
959 new_chan->next = pListener;
960 pListener = new_chan;
968 static void inetd_connection(int what)
975 if ((line = cs_createbysocket(0, tcpip_type, 0, what)))
977 if ((chan = iochan_create(cs_fileno(line), ir_session, EVENT_INPUT,
980 if ((assoc = create_association(chan, line,
981 control_block.apdufile)))
983 iochan_setdata(chan, assoc);
984 iochan_settimeout(chan, 60);
985 addr = cs_addrstr(line);
986 yaz_log(log_session, "Inetd association from %s",
987 addr ? addr : "[UNKNOWN]");
988 assoc->cs_get_mask = EVENT_INPUT;
992 yaz_log(YLOG_FATAL, "Failed to create association structure");
994 chan->next = pListener;
999 yaz_log(YLOG_FATAL, "Failed to create iochan");
1004 yaz_log(YLOG_ERRNO|YLOG_FATAL, "Failed to create comstack on socket 0");
1009 * Set up a listening endpoint, and give it to the event-handler.
1011 static int add_listener(char *where, int listen_id)
1018 if (control_block.dynamic)
1020 else if (control_block.threads)
1025 yaz_log(log_server, "Adding %s listener on %s id=%d", mode, where,
1028 l = cs_create_host(where, 2, &ap);
1031 yaz_log(YLOG_FATAL, "Failed to listen on %s", where);
1034 if (*control_block.cert_fname)
1035 cs_set_ssl_certificate_file(l, control_block.cert_fname);
1037 if (cs_bind(l, ap, CS_SERVER) < 0)
1039 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to bind to %s", where);
1043 if (!(lst = iochan_create(cs_fileno(l), listener, EVENT_INPUT |
1044 EVENT_EXCEPT, listen_id)))
1046 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create IOCHAN-type");
1050 iochan_setdata(lst, l); /* user-defined data for listener is COMSTACK */
1051 l->user = lst; /* user-defined data for COMSTACK is listener chan */
1053 /* Add listener to chain */
1054 lst->next = pListener;
1060 /* UNIX only (for windows we don't need to catch the signals) */
1061 static void catchchld(int num)
1063 while (waitpid(-1, 0, WNOHANG) > 0)
1065 signal(SIGCHLD, catchchld);
1069 statserv_options_block *statserv_getcontrol(void)
1072 if (init_control_tls)
1073 return (statserv_options_block *) TlsGetValue(current_control_tls);
1075 return &control_block;
1076 #elif YAZ_POSIX_THREADS
1077 if (init_control_tls)
1078 return pthread_getspecific(current_control_tls);
1080 return &control_block;
1082 if (current_control_block)
1083 return current_control_block;
1084 return &control_block;
1088 void statserv_setcontrol(statserv_options_block *block)
1091 if (init_control_tls)
1092 TlsSetValue(current_control_tls, block);
1093 #elif YAZ_POSIX_THREADS
1094 if (init_control_tls)
1095 pthread_setspecific(current_control_tls, block);
1097 current_control_block = block;
1101 static void statserv_reset(void)
1105 int statserv_start(int argc, char **argv)
1109 /* We need to initialize the thread list */
1110 ThreadList_Initialize();
1120 if ((me = strrchr (argv[0], sep)))
1121 me++; /* get the basename */
1124 programname = argv[0];
1126 if (control_block.options_func(argc, argv))
1131 xml_config_bend_start();
1134 xml_config_add_listeners();
1136 yaz_log (log_server, "Starting server %s", me);
1137 if (!pListener && *control_block.default_listen)
1138 add_listener(control_block.default_listen, 0);
1141 if (control_block.inetd)
1142 inetd_connection(control_block.default_proto);
1146 if (control_block.background)
1148 /* create pipe so that parent waits until child has created
1152 yaz_log(YLOG_FATAL|YLOG_ERRNO, "pipe");
1166 int res = read(hand[0], dummy, 1);
1167 if (res < 0 && yaz_errno() != EINTR)
1169 yaz_log(YLOG_FATAL|YLOG_ERRNO, "read fork handshake");
1186 open("/dev/null", O_RDWR);
1189 xml_config_add_listeners();
1191 if (!pListener && *control_block.default_listen)
1192 add_listener(control_block.default_listen, 0);
1197 if (*control_block.pid_fname)
1199 FILE *f = fopen(control_block.pid_fname, "w");
1202 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Couldn't create %s",
1203 control_block.pid_fname);
1206 fprintf(f, "%ld", (long) getpid());
1210 if (control_block.background)
1214 yaz_log (log_server, "Starting server %s pid=%ld", programname,
1217 sigset_t sigs_to_block;
1219 sigemptyset(&sigs_to_block);
1220 sigaddset (&sigs_to_block, SIGTERM);
1221 pthread_sigmask (SIG_BLOCK, &sigs_to_block, 0);
1224 if (control_block.dynamic)
1225 signal(SIGCHLD, catchchld);
1227 signal (SIGPIPE, SIG_IGN);
1228 signal (SIGTERM, sigterm);
1229 if (*control_block.setuid)
1233 if (!(pw = getpwnam(control_block.setuid)))
1235 yaz_log(YLOG_FATAL, "%s: Unknown user", control_block.setuid);
1238 if (setuid(pw->pw_uid) < 0)
1240 yaz_log(YLOG_FATAL|YLOG_ERRNO, "setuid");
1246 if (pListener == NULL)
1248 yaz_log(YLOG_DEBUG, "Entering event loop.");
1249 return event_loop(&pListener);
1252 static void option_copy(char *dst, const char *src)
1254 strncpy(dst, src ? src : "", 127);
1258 int check_options(int argc, char **argv)
1263 /* set default log level */
1264 control_block.loglevel = yaz_log_mask_str(STAT_DEFAULT_LOG_LEVEL);
1265 yaz_log_init_level(control_block.loglevel);
1267 while ((ret = options("1a:iszSTl:v:u:c:w:t:k:d:A:p:DC:f:",
1268 argv, argc, &arg)) != -2)
1273 if (add_listener(arg, 0))
1274 return 1; /* failed to create listener */
1277 control_block.one_shot = 1;
1278 control_block.dynamic = 0;
1281 control_block.default_proto = PROTO_Z3950;
1284 fprintf (stderr, "%s: SR protocol no longer supported\n", me);
1288 control_block.dynamic = 0;
1291 #if YAZ_POSIX_THREADS
1292 control_block.dynamic = 0;
1293 control_block.threads = 1;
1294 #elif YAZ_GNU_THREADS
1295 control_block.dynamic = 0;
1296 control_block.threads = 1;
1298 fprintf(stderr, "%s: Threaded mode not available.\n", me);
1303 option_copy(control_block.logfile, arg);
1304 yaz_log_init(control_block.loglevel, me, control_block.logfile);
1307 control_block.loglevel =
1308 yaz_log_mask_str_x(arg,control_block.loglevel);
1309 yaz_log_init(control_block.loglevel, me, control_block.logfile);
1312 option_copy(control_block.apdufile, arg);
1315 option_copy(control_block.setuid, arg);
1318 option_copy(control_block.configname, arg);
1321 option_copy(control_block.cert_fname, arg);
1324 option_copy(control_block.daemon_name, arg);
1327 if (!arg || !(r = atoi(arg)))
1329 fprintf(stderr, "%s: Specify positive timeout for -t.\n", me);
1332 control_block.idle_timeout = r;
1335 if (!arg || !(r = atoi(arg)))
1337 fprintf(stderr, "%s: Specify positive size for -k.\n", me);
1340 control_block.maxrecordsize = r * 1024;
1343 control_block.inetd = 1;
1353 max_sessions = atoi(arg);
1356 option_copy(control_block.pid_fname, arg);
1360 option_copy(control_block.xml_config, arg);
1362 fprintf(stderr, "%s: Option -f unsupported since YAZ is compiled without Libxml2 support\n", me);
1367 control_block.background = 1;
1370 fprintf(stderr, "Usage: %s [ -a <pdufile> -v <loglevel>"
1371 " -l <logfile> -u <user> -c <config> -t <minutes>"
1372 " -k <kilobytes> -d <daemon> -p <pidfile> -C certfile"
1373 " -ziDST1 -w <directory> <listener-addr>... ]\n", me);
1382 typedef struct _Args
1388 static Args ArgDetails;
1390 /* name of the executable */
1391 #define SZAPPNAME "server"
1393 /* list of service dependencies - "dep1\0dep2\0\0" */
1394 #define SZDEPENDENCIES ""
1396 int statserv_main(int argc, char **argv,
1397 bend_initresult *(*bend_init)(bend_initrequest *r),
1398 void (*bend_close)(void *handle))
1400 struct statserv_options_block *cb = &control_block;
1401 cb->bend_init = bend_init;
1402 cb->bend_close = bend_close;
1404 /* Lets setup the Arg structure */
1405 ArgDetails.argc = argc;
1406 ArgDetails.argv = argv;
1408 /* Now setup the service with the service controller */
1409 SetupService(argc, argv, &ArgDetails, SZAPPNAME,
1410 cb->service_name, /* internal service name */
1411 cb->service_display_name, /* displayed name */
1416 int StartAppService(void *pHandle, int argc, char **argv)
1418 /* Initializes the App */
1422 void RunAppService(void *pHandle)
1424 Args *pArgs = (Args *)pHandle;
1426 /* Starts the app running */
1427 statserv_start(pArgs->argc, pArgs->argv);
1430 void StopAppService(void *pHandle)
1433 statserv_closedown();
1439 int statserv_main(int argc, char **argv,
1440 bend_initresult *(*bend_init)(bend_initrequest *r),
1441 void (*bend_close)(void *handle))
1445 control_block.bend_init = bend_init;
1446 control_block.bend_close = bend_close;
1448 ret = statserv_start (argc, argv);
1449 statserv_closedown ();