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.35 2006-03-22 13:50:46 mike Exp $
13 * \brief Implements GFS logic
27 #include <sys/types.h>
40 #include <libxml/parser.h>
41 #include <libxml/tree.h>
42 #include <libxml/xinclude.h>
55 #include <yaz/comstack.h>
56 #include <yaz/tcpip.h>
57 #include <yaz/options.h>
59 #include <yaz/xmosi.h>
64 #include <yaz/statserv.h>
66 static IOCHAN pListener = NULL;
68 static char gfs_root_dir[FILENAME_MAX+1];
69 static struct gfs_server *gfs_server_list = 0;
70 static struct gfs_listen *gfs_listen_list = 0;
71 static NMEM gfs_nmem = 0;
73 static char *me = "statserver"; /* log prefix */
74 static char *programname="statserver"; /* full program name */
76 DWORD current_control_tls;
77 static int init_control_tls = 0;
78 #elif YAZ_POSIX_THREADS
79 static pthread_key_t current_control_tls;
80 static int init_control_tls = 0;
82 static statserv_options_block *current_control_block = 0;
88 #define STAT_DEFAULT_LOG_LEVEL "none,fatal,warn,log,server,session,request"
89 /* the 'none' clears yaz' own default settings, including [log] */
91 int check_options(int argc, char **argv);
92 statserv_options_block control_block = {
94 0, /* threaded mode */
95 0, /* one shot (single session) */
97 "", /* diagnostic output to stderr */
98 "tcp:@:9999", /* default listener port */
99 PROTO_Z3950, /* default application protocol */
100 15, /* idle timeout (minutes) */
101 1024*1024, /* maximum PDU size (approx.) to allow */
102 "default-config", /* configuration name to pass to backend */
103 "", /* set user id */
104 0, /* bend_start handler */
105 0, /* bend_stop handler */
106 check_options, /* Default routine, for checking the run-time arguments */
109 0, /* default value for inet deamon */
110 0, /* handle (for service, etc) */
111 0, /* bend_init handle */
112 0, /* bend_close handle */
114 "Z39.50 Server", /* NT Service Name */
115 "Server", /* NT application Name */
116 "", /* NT Service Dependencies */
117 "Z39.50 Server", /* NT Service Display Name */
119 0, /* SOAP handlers */
121 0, /* background daemon */
122 "", /* SSL certificate filename */
123 "" /* XML config filename */
126 static int max_sessions = 0;
128 static int logbits_set = 0;
129 static int log_session = 0;
130 static int log_server = 0;
132 /** get_logbits sets global loglevel bits */
133 static void get_logbits(int force)
134 { /* needs to be called after parsing cmd-line args that can set loglevels!*/
135 if (force || !logbits_set)
138 log_session = yaz_log_module_level("session");
139 log_server = yaz_log_module_level("server");
144 static int add_listener(char *where, int listen_id);
147 static xmlDocPtr xml_config_doc = 0;
151 static xmlNodePtr xml_config_get_root()
156 ptr = xmlDocGetRootElement(xml_config_doc);
157 if (!ptr || ptr->type != XML_ELEMENT_NODE ||
158 strcmp((const char *) ptr->name, "yazgfs"))
160 yaz_log(YLOG_WARN, "Bad/missing root element for config %s",
161 control_block.xml_config);
171 static char *nmem_dup_xml_content(NMEM n, xmlNodePtr ptr)
175 int len = 1; /* start with 1, because of trailing 0 */
177 int first = 1; /* whitespace lead flag .. */
178 /* determine length */
179 for (p = ptr; p; p = p->next)
181 if (p->type == XML_TEXT_NODE)
182 len += xmlStrlen(p->content);
184 /* now allocate for the string */
185 str = nmem_malloc(n, len);
186 *str = '\0'; /* so we can use strcat */
187 for (p = ptr; p; p = p->next)
189 if (p->type == XML_TEXT_NODE)
194 while(*cp && isspace(*cp))
197 first = 0; /* reset if we got non-whitespace out */
199 strcat((char *)str, (const char *)cp); /* append */
202 /* remove trailing whitespace */
203 cp = strlen((const char *)str) + str;
204 while (cp != str && isspace(cp[-1]))
207 /* return resulting string */
212 static struct gfs_server * gfs_server_new()
214 struct gfs_server *n = nmem_malloc(gfs_nmem, sizeof(*n));
215 memcpy(&n->cb, &control_block, sizeof(control_block));
219 n->cql_transform = 0;
220 n->server_node_ptr = 0;
227 static struct gfs_listen * gfs_listen_new(const char *id,
230 struct gfs_listen *n = nmem_malloc(gfs_nmem, sizeof(*n));
232 n->id = nmem_strdup(gfs_nmem, id);
236 n->address = nmem_strdup(gfs_nmem, address);
240 static void gfs_server_chdir(struct gfs_server *gfs)
244 if (chdir(gfs_root_dir))
245 yaz_log(YLOG_WARN|YLOG_ERRNO, "chdir %s", gfs_root_dir);
249 if (chdir(gfs->directory))
250 yaz_log(YLOG_WARN|YLOG_ERRNO, "chdir %s",
255 int control_association(association *assoc, const char *host, int force_open)
257 char vhost[128], *cp;
260 strncpy(vhost, host, 127);
262 cp = strchr(vhost, ':');
267 assoc->cql_transform = 0;
268 assoc->server_node_ptr = 0;
270 assoc->stylesheet = 0;
271 if (control_block.xml_config[0])
273 struct gfs_server *gfs;
274 for (gfs = gfs_server_list; gfs; gfs = gfs->next)
276 int listen_match = 0;
278 if ( !gfs->host || (host && gfs->host && !strcmp(host, gfs->host)))
280 if (!gfs->listen_ref ||
281 gfs->listen_ref == assoc->client_chan->chan_id)
283 if (listen_match && host_match)
286 (assoc->last_control != &gfs->cb && assoc->backend))
288 statserv_setcontrol(assoc->last_control);
289 if (assoc->backend && assoc->init)
291 gfs_server_chdir(gfs);
292 (assoc->last_control->bend_close)(assoc->backend);
298 assoc->docpath = gfs->docpath;
299 assoc->stylesheet = gfs->stylesheet;
300 assoc->cql_transform = gfs->cql_transform;
301 assoc->server_node_ptr = gfs->server_node_ptr;
302 assoc->last_control = &gfs->cb;
303 statserv_setcontrol(&gfs->cb);
304 gfs_server_chdir(gfs);
305 yaz_log(YLOG_DEBUG, "server select: %s", gfs->cb.configname);
309 statserv_setcontrol(0);
310 assoc->last_control = 0;
311 yaz_log(YLOG_DEBUG, "server select: no match");
316 statserv_setcontrol(&control_block);
317 assoc->last_control = &control_block;
318 yaz_log(YLOG_DEBUG, "server select: config=%s", control_block.configname);
323 static void xml_config_read()
325 struct gfs_server **gfsp = &gfs_server_list;
326 struct gfs_listen **gfslp = &gfs_listen_list;
328 xmlNodePtr ptr = xml_config_get_root();
332 for (ptr = ptr->children; ptr; ptr = ptr->next)
334 struct _xmlAttr *attr;
335 if (ptr->type != XML_ELEMENT_NODE)
337 attr = ptr->properties;
338 if (!strcmp((const char *) ptr->name, "listen"))
341 <listen id="listenerid">tcp:@:9999</listen>
344 const char *address =
345 nmem_dup_xml_content(gfs_nmem, ptr->children);
346 for ( ; attr; attr = attr->next)
347 if (!xmlStrcmp(attr->name, BAD_CAST "id")
348 && attr->children && attr->children->type == XML_TEXT_NODE)
349 id = nmem_dup_xml_content(gfs_nmem, attr->children);
352 *gfslp = gfs_listen_new(id, address);
353 gfslp = &(*gfslp)->next;
354 *gfslp = 0; /* make listener list consistent for search */
357 else if (!strcmp((const char *) ptr->name, "server"))
359 xmlNodePtr ptr_server = ptr;
361 const char *listenref = 0;
364 for ( ; attr; attr = attr->next)
365 if (!xmlStrcmp(attr->name, BAD_CAST "listenref")
366 && attr->children && attr->children->type == XML_TEXT_NODE)
367 listenref = nmem_dup_xml_content(gfs_nmem, attr->children);
368 else if (!xmlStrcmp(attr->name, BAD_CAST "id")
370 && attr->children->type == XML_TEXT_NODE)
371 id = nmem_dup_xml_content(gfs_nmem, attr->children);
373 yaz_log(YLOG_WARN, "Unknown attribute '%s' for server",
375 *gfsp = gfs_server_new();
376 (*gfsp)->server_node_ptr = ptr_server;
380 struct gfs_listen *gl = gfs_listen_list;
381 for (id_no = 1; gl; gl = gl->next, id_no++)
382 if (gl->id && !strcmp(gl->id, listenref))
384 (*gfsp)->listen_ref = id_no;
388 yaz_log(YLOG_WARN, "Non-existent listenref '%s' in server "
389 "config element", listenref);
391 for (ptr = ptr_server->children; ptr; ptr = ptr->next)
393 if (ptr->type != XML_ELEMENT_NODE)
395 if (!strcmp((const char *) ptr->name, "host"))
397 (*gfsp)->host = nmem_dup_xml_content(gfs_nmem,
400 else if (!strcmp((const char *) ptr->name, "config"))
402 strcpy((*gfsp)->cb.configname,
403 nmem_dup_xml_content(gfs_nmem, ptr->children));
405 else if (!strcmp((const char *) ptr->name, "cql2rpn"))
407 (*gfsp)->cql_transform = cql_transform_open_fname(
408 nmem_dup_xml_content(gfs_nmem, ptr->children)
411 else if (!strcmp((const char *) ptr->name, "directory"))
414 nmem_dup_xml_content(gfs_nmem, ptr->children);
416 else if (!strcmp((const char *) ptr->name, "docpath"))
419 nmem_dup_xml_content(gfs_nmem, ptr->children);
421 else if (!strcmp((const char *) ptr->name, "stylesheet"))
423 char *s = nmem_dup_xml_content(gfs_nmem, ptr->children);
424 (*gfsp)->stylesheet =
425 nmem_malloc(gfs_nmem, strlen(s) + 2);
426 sprintf((*gfsp)->stylesheet, "/%s", s);
428 else if (!strcmp((const char *) ptr->name, "explain"))
430 ; /* being processed separately */
434 yaz_log(YLOG_FATAL, "Unknown element '%s' in config %s",
435 ptr->name, control_block.xml_config);
439 gfsp = &(*gfsp)->next;
446 static void xml_config_open()
448 if (!getcwd(gfs_root_dir, FILENAME_MAX))
450 yaz_log(YLOG_WARN|YLOG_ERRNO, "getcwd failed");
451 gfs_root_dir[0] = '\0';
454 init_control_tls = 1;
455 current_control_tls = TlsAlloc();
456 #elif YAZ_POSIX_THREADS
457 init_control_tls = 1;
458 pthread_key_create(¤t_control_tls, 0);
461 gfs_nmem = nmem_create();
463 if (control_block.xml_config[0] == '\0')
468 xml_config_doc = xmlParseFile(control_block.xml_config);
471 yaz_log(YLOG_FATAL, "Could not parse %s", control_block.xml_config);
476 int noSubstitutions = xmlXIncludeProcess(xml_config_doc);
477 if (noSubstitutions == -1)
479 yaz_log(YLOG_WARN, "XInclude processing failed for config %s",
480 control_block.xml_config);
489 static void xml_config_close()
494 xmlFreeDoc(xml_config_doc);
499 nmem_destroy(gfs_nmem);
501 if (init_control_tls)
502 TlsFree(current_control_tls);
503 #elif YAZ_POSIX_THREADS
504 if (init_control_tls)
505 pthread_key_delete(current_control_tls);
509 static void xml_config_add_listeners()
511 struct gfs_listen *gfs = gfs_listen_list;
514 for (id_no = 1; gfs; gfs = gfs->next, id_no++)
517 add_listener(gfs->address, id_no);
521 static void xml_config_bend_start()
523 if (control_block.xml_config[0])
525 struct gfs_server *gfs = gfs_server_list;
526 for (; gfs; gfs = gfs->next)
528 yaz_log(YLOG_DEBUG, "xml_config_bend_start config=%s",
530 statserv_setcontrol(&gfs->cb);
531 if (control_block.bend_start)
533 gfs_server_chdir(gfs);
534 (control_block.bend_start)(&gfs->cb);
540 yaz_log(YLOG_DEBUG, "xml_config_bend_start default config");
541 statserv_setcontrol(&control_block);
542 if (control_block.bend_start)
543 (*control_block.bend_start)(&control_block);
547 static void xml_config_bend_stop()
549 if (control_block.xml_config[0])
551 struct gfs_server *gfs = gfs_server_list;
552 for (; gfs; gfs = gfs->next)
554 yaz_log(YLOG_DEBUG, "xml_config_bend_stop config=%s",
556 statserv_setcontrol(&gfs->cb);
557 if (control_block.bend_stop)
558 (control_block.bend_stop)(&gfs->cb);
563 yaz_log(YLOG_DEBUG, "xml_config_bend_stop default config");
564 statserv_setcontrol(&control_block);
565 if (control_block.bend_stop)
566 (*control_block.bend_stop)(&control_block);
571 * handle incoming connect requests.
572 * The dynamic mode is a bit tricky mostly because we want to avoid
573 * doing all of the listening and accepting in the parent - it's
578 typedef struct _ThreadList ThreadList;
587 static ThreadList *pFirstThread;
588 static CRITICAL_SECTION Thread_CritSect;
589 static BOOL bInitialized = FALSE;
591 static void ThreadList_Initialize()
593 /* Initialize the critical Sections */
594 InitializeCriticalSection(&Thread_CritSect);
596 /* Set the first thraed */
599 /* we have been initialized */
603 static void statserv_add(HANDLE hThread, IOCHAN pIOChannel)
605 /* Only one thread can go through this section at a time */
606 EnterCriticalSection(&Thread_CritSect);
609 /* Lets create our new object */
610 ThreadList *pNewThread = (ThreadList *)malloc(sizeof(ThreadList));
611 pNewThread->hThread = hThread;
612 pNewThread->pIOChannel = pIOChannel;
613 pNewThread->pNext = pFirstThread;
614 pFirstThread = pNewThread;
616 /* Lets let somebody else create a new object now */
617 LeaveCriticalSection(&Thread_CritSect);
621 void statserv_remove(IOCHAN pIOChannel)
623 /* Only one thread can go through this section at a time */
624 EnterCriticalSection(&Thread_CritSect);
627 ThreadList *pCurrentThread = pFirstThread;
628 ThreadList *pNextThread;
629 ThreadList *pPrevThread =NULL;
631 /* Step through all the threads */
632 for (; pCurrentThread != NULL; pCurrentThread = pNextThread)
634 /* We only need to compare on the IO Channel */
635 if (pCurrentThread->pIOChannel == pIOChannel)
637 /* We have found the thread we want to delete */
638 /* First of all reset the next pointers */
639 if (pPrevThread == NULL)
640 pFirstThread = pCurrentThread->pNext;
642 pPrevThread->pNext = pCurrentThread->pNext;
644 /* All we need todo now is delete the memory */
645 free(pCurrentThread);
647 /* No need to look at any more threads */
652 /* We need to look at another thread */
653 pNextThread = pCurrentThread->pNext;
654 pPrevThread = pCurrentThread;
658 /* Lets let somebody else remove an object now */
659 LeaveCriticalSection(&Thread_CritSect);
663 /* WIN32 statserv_closedown */
664 void statserv_closedown()
666 /* Shouldn't do anything if we are not initialized */
670 HANDLE *pThreadHandles = NULL;
672 /* We need to stop threads adding and removing while we */
673 /* start the closedown process */
674 EnterCriticalSection(&Thread_CritSect);
677 /* We have exclusive access to the thread stuff now */
678 /* Y didn't i use a semaphore - Oh well never mind */
679 ThreadList *pCurrentThread = pFirstThread;
681 /* Before we do anything else, we need to shutdown the listener */
682 if (pListener != NULL)
683 iochan_destroy(pListener);
685 for (; pCurrentThread != NULL; pCurrentThread = pCurrentThread->pNext)
687 /* Just destroy the IOCHAN, that should do the trick */
688 iochan_destroy(pCurrentThread->pIOChannel);
689 closesocket(pCurrentThread->pIOChannel->fd);
691 /* Keep a running count of our handles */
697 HANDLE *pCurrentHandle ;
699 /* Allocate the thread handle array */
700 pThreadHandles = (HANDLE *)malloc(sizeof(HANDLE) * iHandles);
701 pCurrentHandle = pThreadHandles;
703 for (pCurrentThread = pFirstThread;
704 pCurrentThread != NULL;
705 pCurrentThread = pCurrentThread->pNext, pCurrentHandle++)
707 /* Just the handle */
708 *pCurrentHandle = pCurrentThread->hThread;
712 /* We can now leave the critical section */
713 LeaveCriticalSection(&Thread_CritSect);
716 /* Now we can really do something */
719 yaz_log(log_server, "waiting for %d to die", iHandles);
720 /* This will now wait, until all the threads close */
721 WaitForMultipleObjects(iHandles, pThreadHandles, TRUE, INFINITE);
723 /* Free the memory we allocated for the handle array */
724 free(pThreadHandles);
727 xml_config_bend_stop();
728 /* No longer require the critical section, since all threads are dead */
729 DeleteCriticalSection(&Thread_CritSect);
734 void __cdecl event_loop_thread (IOCHAN iochan)
736 event_loop (&iochan);
740 static void listener(IOCHAN h, int event)
742 COMSTACK line = (COMSTACK) iochan_getdata(h);
743 IOCHAN parent_chan = line->user;
748 if (event == EVENT_INPUT)
750 if ((res = cs_listen(line, 0, 0)) < 0)
752 yaz_log(YLOG_FATAL, "cs_listen failed");
757 yaz_log(YLOG_DEBUG, "listen ok");
758 iochan_setevent(h, EVENT_OUTPUT);
759 iochan_setflags(h, EVENT_OUTPUT | EVENT_EXCEPT); /* set up for acpt */
761 else if (event == EVENT_OUTPUT)
763 COMSTACK new_line = cs_accept(line);
769 yaz_log(YLOG_FATAL, "Accept failed.");
770 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT);
773 yaz_log(YLOG_DEBUG, "Accept ok");
775 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session,
776 EVENT_INPUT, parent_chan->chan_id)))
778 yaz_log(YLOG_FATAL, "Failed to create iochan");
783 yaz_log(YLOG_DEBUG, "Creating association");
784 if (!(newas = create_association(new_chan, new_line,
785 control_block.apdufile)))
787 yaz_log(YLOG_FATAL, "Failed to create new assoc.");
791 newas->cs_get_mask = EVENT_INPUT;
792 newas->cs_put_mask = 0;
793 newas->cs_accept_mask = 0;
795 yaz_log(YLOG_DEBUG, "Setting timeout %d", control_block.idle_timeout);
796 iochan_setdata(new_chan, newas);
797 iochan_settimeout(new_chan, 60);
799 /* Now what we need todo is create a new thread with this iochan as
801 newHandle = (HANDLE) _beginthread(event_loop_thread, 0, new_chan);
802 if (newHandle == (HANDLE) -1)
805 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create new thread.");
809 /* We successfully created the thread, so add it to the list */
810 statserv_add(newHandle, new_chan);
812 yaz_log(YLOG_DEBUG, "Created new thread, id = %ld iochan %p",(long) newHandle, new_chan);
813 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
817 yaz_log(YLOG_FATAL, "Bad event on listener.");
823 int statserv_must_terminate(void)
830 static int term_flag = 0;
831 /* To save having an #ifdef in event_loop we need to
832 define this empty function
834 int statserv_must_terminate(void)
839 void statserv_remove(IOCHAN pIOChannel)
843 void statserv_closedown()
847 xml_config_bend_stop();
848 for (p = pListener; p; p = p->next)
855 void sigterm(int sig)
860 static void *new_session (void *vp);
861 static int no_sessions = 0;
864 static void listener(IOCHAN h, int event)
866 COMSTACK line = (COMSTACK) iochan_getdata(h);
869 if (event == EVENT_INPUT)
872 if ((res = cs_listen_check(line, 0, 0, control_block.check_ip,
873 control_block.daemon_name)) < 0)
875 yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_listen failed");
880 yaz_log(YLOG_WARN, "cs_listen incomplete");
883 new_line = cs_accept(line);
886 yaz_log(YLOG_FATAL, "Accept failed.");
887 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
891 yaz_log(log_session, "Connect from %s", cs_addrstr(new_line));
894 if (control_block.dynamic)
896 if ((res = fork()) < 0)
898 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fork");
902 else if (res == 0) /* child */
907 for (pp = pListener; pp; pp = iochan_getnext(pp))
909 COMSTACK l = (COMSTACK)iochan_getdata(pp);
913 sprintf(nbuf, "%s(%d)", me, no_sessions);
914 yaz_log_init_prefix(nbuf);
915 /* ensure that bend_stop is not called when each child exits -
916 only for the main process .. */
917 control_block.bend_stop = 0;
926 if (control_block.threads)
928 #if YAZ_POSIX_THREADS
929 pthread_t child_thread;
930 pthread_create (&child_thread, 0, new_session, new_line);
931 pthread_detach (child_thread);
932 #elif YAZ_GNU_THREADS
936 attr = pth_attr_new ();
937 pth_attr_set (attr, PTH_ATTR_JOINABLE, FALSE);
938 pth_attr_set (attr, PTH_ATTR_STACK_SIZE, 32*1024);
939 pth_attr_set (attr, PTH_ATTR_NAME, "session");
940 yaz_log (YLOG_DEBUG, "pth_spawn begin");
941 child_thread = pth_spawn (attr, new_session, new_line);
942 yaz_log (YLOG_DEBUG, "pth_spawn finish");
943 pth_attr_destroy (attr);
945 new_session(new_line);
949 new_session(new_line);
951 else if (event == EVENT_TIMEOUT)
953 yaz_log(log_server, "Shutting down listener.");
958 yaz_log(YLOG_FATAL, "Bad event on listener.");
963 static void *new_session (void *vp)
968 COMSTACK new_line = (COMSTACK) vp;
969 IOCHAN parent_chan = new_line->user;
971 unsigned cs_get_mask, cs_accept_mask, mask =
972 ((new_line->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
973 ((new_line->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
977 cs_accept_mask = mask; /* accept didn't complete */
982 cs_accept_mask = 0; /* accept completed. */
983 cs_get_mask = mask = EVENT_INPUT;
986 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session, mask,
987 parent_chan->chan_id)))
989 yaz_log(YLOG_FATAL, "Failed to create iochan");
992 if (!(newas = create_association(new_chan, new_line,
993 control_block.apdufile)))
995 yaz_log(YLOG_FATAL, "Failed to create new assoc.");
998 newas->cs_accept_mask = cs_accept_mask;
999 newas->cs_get_mask = cs_get_mask;
1001 iochan_setdata(new_chan, newas);
1002 iochan_settimeout(new_chan, 60);
1004 a = cs_addrstr(new_line);
1008 yaz_log(log_session, "Starting session %d from %s (pid=%ld)",
1009 no_sessions, a ? a : "[Unknown]", (long) getpid());
1010 if (max_sessions && no_sessions >= max_sessions)
1011 control_block.one_shot = 1;
1012 if (control_block.threads)
1014 event_loop(&new_chan);
1018 new_chan->next = pListener;
1019 pListener = new_chan;
1027 static void inetd_connection(int what)
1034 if ((line = cs_createbysocket(0, tcpip_type, 0, what)))
1036 if ((chan = iochan_create(cs_fileno(line), ir_session, EVENT_INPUT,
1039 if ((assoc = create_association(chan, line,
1040 control_block.apdufile)))
1042 iochan_setdata(chan, assoc);
1043 iochan_settimeout(chan, 60);
1044 addr = cs_addrstr(line);
1045 yaz_log(log_session, "Inetd association from %s",
1046 addr ? addr : "[UNKNOWN]");
1047 assoc->cs_get_mask = EVENT_INPUT;
1051 yaz_log(YLOG_FATAL, "Failed to create association structure");
1053 chan->next = pListener;
1058 yaz_log(YLOG_FATAL, "Failed to create iochan");
1063 yaz_log(YLOG_ERRNO|YLOG_FATAL, "Failed to create comstack on socket 0");
1068 * Set up a listening endpoint, and give it to the event-handler.
1070 static int add_listener(char *where, int listen_id)
1077 if (control_block.dynamic)
1079 else if (control_block.threads)
1084 yaz_log(log_server, "Adding %s listener on %s id=%d", mode, where,
1087 l = cs_create_host(where, 2, &ap);
1090 yaz_log(YLOG_FATAL, "Failed to listen on %s", where);
1093 if (*control_block.cert_fname)
1094 cs_set_ssl_certificate_file(l, control_block.cert_fname);
1096 if (cs_bind(l, ap, CS_SERVER) < 0)
1098 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to bind to %s", where);
1102 if (!(lst = iochan_create(cs_fileno(l), listener, EVENT_INPUT |
1103 EVENT_EXCEPT, listen_id)))
1105 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create IOCHAN-type");
1109 iochan_setdata(lst, l); /* user-defined data for listener is COMSTACK */
1110 l->user = lst; /* user-defined data for COMSTACK is listener chan */
1112 /* Add listener to chain */
1113 lst->next = pListener;
1119 /* UNIX only (for windows we don't need to catch the signals) */
1120 static void catchchld(int num)
1122 while (waitpid(-1, 0, WNOHANG) > 0)
1124 signal(SIGCHLD, catchchld);
1128 statserv_options_block *statserv_getcontrol(void)
1131 if (init_control_tls)
1132 return (statserv_options_block *) TlsGetValue(current_control_tls);
1134 return &control_block;
1135 #elif YAZ_POSIX_THREADS
1136 if (init_control_tls)
1137 return pthread_getspecific(current_control_tls);
1139 return &control_block;
1141 if (current_control_block)
1142 return current_control_block;
1143 return &control_block;
1147 void statserv_setcontrol(statserv_options_block *block)
1149 chdir(gfs_root_dir);
1151 if (init_control_tls)
1152 TlsSetValue(current_control_tls, block);
1153 #elif YAZ_POSIX_THREADS
1154 if (init_control_tls)
1155 pthread_setspecific(current_control_tls, block);
1157 current_control_block = block;
1161 static void statserv_reset(void)
1165 int statserv_start(int argc, char **argv)
1169 /* We need to initialize the thread list */
1170 ThreadList_Initialize();
1180 if ((me = strrchr (argv[0], sep)))
1181 me++; /* get the basename */
1184 programname = argv[0];
1186 if (control_block.options_func(argc, argv))
1191 xml_config_bend_start();
1194 xml_config_add_listeners();
1196 yaz_log (log_server, "Starting server %s", me);
1197 if (!pListener && *control_block.default_listen)
1198 add_listener(control_block.default_listen, 0);
1201 if (control_block.inetd)
1202 inetd_connection(control_block.default_proto);
1206 if (control_block.background)
1208 /* create pipe so that parent waits until child has created
1212 yaz_log(YLOG_FATAL|YLOG_ERRNO, "pipe");
1226 int res = read(hand[0], dummy, 1);
1227 if (res < 0 && yaz_errno() != EINTR)
1229 yaz_log(YLOG_FATAL|YLOG_ERRNO, "read fork handshake");
1246 open("/dev/null", O_RDWR);
1249 xml_config_add_listeners();
1251 if (!pListener && *control_block.default_listen)
1252 add_listener(control_block.default_listen, 0);
1257 if (*control_block.pid_fname)
1259 FILE *f = fopen(control_block.pid_fname, "w");
1262 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Couldn't create %s",
1263 control_block.pid_fname);
1266 fprintf(f, "%ld", (long) getpid());
1270 if (control_block.background)
1274 yaz_log (log_server, "Starting server %s pid=%ld", programname,
1277 sigset_t sigs_to_block;
1279 sigemptyset(&sigs_to_block);
1280 sigaddset (&sigs_to_block, SIGTERM);
1281 pthread_sigmask (SIG_BLOCK, &sigs_to_block, 0);
1284 if (control_block.dynamic)
1285 signal(SIGCHLD, catchchld);
1287 signal (SIGPIPE, SIG_IGN);
1288 signal (SIGTERM, sigterm);
1289 if (*control_block.setuid)
1293 if (!(pw = getpwnam(control_block.setuid)))
1295 yaz_log(YLOG_FATAL, "%s: Unknown user", control_block.setuid);
1298 if (setuid(pw->pw_uid) < 0)
1300 yaz_log(YLOG_FATAL|YLOG_ERRNO, "setuid");
1306 if (pListener == NULL)
1308 yaz_log(YLOG_DEBUG, "Entering event loop.");
1309 return event_loop(&pListener);
1312 static void option_copy(char *dst, const char *src)
1314 strncpy(dst, src ? src : "", 127);
1318 int check_options(int argc, char **argv)
1323 if (getenv("YAZ_LOG") == 0) {
1325 * Set default log level. We want to avoid doing this if the
1326 * user has already explicitly specified a preferred default
1327 * log-level, hence the inelegant peek at the YAZ_LOG
1328 * environment variable that will subsequently be interpreted
1329 * by the YAZ logging module itself.
1331 yaz_log_init_level(yaz_log_mask_str(STAT_DEFAULT_LOG_LEVEL));
1335 while ((ret = options("1a:iszSTl:v:u:c:w:t:k:d:A:p:DC:f:m:",
1336 argv, argc, &arg)) != -2)
1341 if (add_listener(arg, 0))
1342 return 1; /* failed to create listener */
1345 control_block.one_shot = 1;
1346 control_block.dynamic = 0;
1349 control_block.default_proto = PROTO_Z3950;
1352 fprintf (stderr, "%s: SR protocol no longer supported\n", me);
1356 control_block.dynamic = 0;
1359 #if YAZ_POSIX_THREADS
1360 control_block.dynamic = 0;
1361 control_block.threads = 1;
1362 #elif YAZ_GNU_THREADS
1363 control_block.dynamic = 0;
1364 control_block.threads = 1;
1366 fprintf(stderr, "%s: Threaded mode not available.\n", me);
1371 option_copy(control_block.logfile, arg);
1372 yaz_log_init_file(control_block.logfile);
1376 fprintf(stderr, "%s: Specify time format for log file.\n", me);
1379 yaz_log_time_format(arg);
1382 int default_level = yaz_log_mask_str(STAT_DEFAULT_LOG_LEVEL);
1383 yaz_log_init_level(yaz_log_mask_str_x(arg, default_level));
1388 option_copy(control_block.apdufile, arg);
1391 option_copy(control_block.setuid, arg);
1394 option_copy(control_block.configname, arg);
1397 option_copy(control_block.cert_fname, arg);
1400 option_copy(control_block.daemon_name, arg);
1403 if (!arg || !(r = atoi(arg)))
1405 fprintf(stderr, "%s: Specify positive timeout for -t.\n", me);
1408 control_block.idle_timeout = r;
1411 if (!arg || !(r = atoi(arg)))
1413 fprintf(stderr, "%s: Specify positive size for -k.\n", me);
1416 control_block.maxrecordsize = r * 1024;
1419 control_block.inetd = 1;
1429 max_sessions = atoi(arg);
1432 option_copy(control_block.pid_fname, arg);
1436 option_copy(control_block.xml_config, arg);
1438 fprintf(stderr, "%s: Option -f unsupported since YAZ is compiled without Libxml2 support\n", me);
1443 control_block.background = 1;
1446 fprintf(stderr, "Usage: %s [ -a <pdufile> -v <loglevel>"
1447 " -l <logfile> -u <user> -c <config> -t <minutes>"
1448 " -k <kilobytes> -d <daemon> -p <pidfile> -C certfile"
1449 " -ziDST1 -m <time-format> -w <directory> <listener-addr>... ]\n", me);
1457 typedef struct _Args
1463 static Args ArgDetails;
1465 /* name of the executable */
1466 #define SZAPPNAME "server"
1468 /* list of service dependencies - "dep1\0dep2\0\0" */
1469 #define SZDEPENDENCIES ""
1471 int statserv_main(int argc, char **argv,
1472 bend_initresult *(*bend_init)(bend_initrequest *r),
1473 void (*bend_close)(void *handle))
1475 struct statserv_options_block *cb = &control_block;
1476 cb->bend_init = bend_init;
1477 cb->bend_close = bend_close;
1479 /* Lets setup the Arg structure */
1480 ArgDetails.argc = argc;
1481 ArgDetails.argv = argv;
1483 /* Now setup the service with the service controller */
1484 SetupService(argc, argv, &ArgDetails, SZAPPNAME,
1485 cb->service_name, /* internal service name */
1486 cb->service_display_name, /* displayed name */
1491 int StartAppService(void *pHandle, int argc, char **argv)
1493 /* Initializes the App */
1497 void RunAppService(void *pHandle)
1499 Args *pArgs = (Args *)pHandle;
1501 /* Starts the app running */
1502 statserv_start(pArgs->argc, pArgs->argv);
1505 void StopAppService(void *pHandle)
1508 statserv_closedown();
1514 int statserv_main(int argc, char **argv,
1515 bend_initresult *(*bend_init)(bend_initrequest *r),
1516 void (*bend_close)(void *handle))
1520 control_block.bend_init = bend_init;
1521 control_block.bend_close = bend_close;
1523 ret = statserv_start (argc, argv);
1524 statserv_closedown ();
1532 * indent-tabs-mode: nil
1534 * vim: shiftwidth=4 tabstop=8 expandtab