2 * Copyright (C) 1995-2006, 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.40 2006-07-07 13:02:21 marc 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) */
96 0, /* __UNUSED_loglevel */
98 "", /* diagnostic output to stderr */
99 "tcp:@:9999", /* default listener port */
100 PROTO_Z3950, /* default application protocol */
101 15, /* idle timeout (minutes) */
102 1024*1024, /* maximum PDU size (approx.) to allow */
103 "default-config", /* configuration name to pass to backend */
104 "", /* set user id */
105 0, /* bend_start handler */
106 0, /* bend_stop handler */
107 check_options, /* Default routine, for checking the run-time arguments */
110 0, /* default value for inet deamon */
111 0, /* handle (for service, etc) */
112 0, /* bend_init handle */
113 0, /* bend_close handle */
115 "Z39.50 Server", /* NT Service Name */
116 "Server", /* NT application Name */
117 "", /* NT Service Dependencies */
118 "Z39.50 Server", /* NT Service Display Name */
120 0, /* SOAP handlers */
122 0, /* background daemon */
123 "", /* SSL certificate filename */
124 "" /* XML config filename */
127 static int max_sessions = 0;
129 static int logbits_set = 0;
130 static int log_session = 0; /* one-line logs for session */
131 static int log_sessiondetail = 0; /* more detailed stuff */
132 static int log_server = 0;
134 /** get_logbits sets global loglevel bits */
135 static void get_logbits(int force)
136 { /* needs to be called after parsing cmd-line args that can set loglevels!*/
137 if (force || !logbits_set)
140 log_session = yaz_log_module_level("session");
141 log_sessiondetail = yaz_log_module_level("sessiondetail");
142 log_server = yaz_log_module_level("server");
147 static int add_listener(char *where, int listen_id);
150 static xmlDocPtr xml_config_doc = 0;
154 static xmlNodePtr xml_config_get_root()
159 ptr = xmlDocGetRootElement(xml_config_doc);
160 if (!ptr || ptr->type != XML_ELEMENT_NODE ||
161 strcmp((const char *) ptr->name, "yazgfs"))
163 yaz_log(YLOG_WARN, "Bad/missing root element for config %s",
164 control_block.xml_config);
174 static char *nmem_dup_xml_content(NMEM n, xmlNodePtr ptr)
178 int len = 1; /* start with 1, because of trailing 0 */
180 int first = 1; /* whitespace lead flag .. */
181 /* determine length */
182 for (p = ptr; p; p = p->next)
184 if (p->type == XML_TEXT_NODE)
185 len += xmlStrlen(p->content);
187 /* now allocate for the string */
188 str = nmem_malloc(n, len);
189 *str = '\0'; /* so we can use strcat */
190 for (p = ptr; p; p = p->next)
192 if (p->type == XML_TEXT_NODE)
197 while(*cp && isspace(*cp))
200 first = 0; /* reset if we got non-whitespace out */
202 strcat((char *)str, (const char *)cp); /* append */
205 /* remove trailing whitespace */
206 cp = strlen((const char *)str) + str;
207 while (cp != str && isspace(cp[-1]))
210 /* return resulting string */
215 static struct gfs_server * gfs_server_new()
217 struct gfs_server *n = nmem_malloc(gfs_nmem, sizeof(*n));
218 memcpy(&n->cb, &control_block, sizeof(control_block));
222 n->cql_transform = 0;
223 n->server_node_ptr = 0;
228 n->retrieval = yaz_retrieval_create();
233 static struct gfs_listen * gfs_listen_new(const char *id,
236 struct gfs_listen *n = nmem_malloc(gfs_nmem, sizeof(*n));
238 n->id = nmem_strdup(gfs_nmem, id);
242 n->address = nmem_strdup(gfs_nmem, address);
246 static void gfs_server_chdir(struct gfs_server *gfs)
250 if (chdir(gfs_root_dir))
251 yaz_log(YLOG_WARN|YLOG_ERRNO, "chdir %s", gfs_root_dir);
255 if (chdir(gfs->directory))
256 yaz_log(YLOG_WARN|YLOG_ERRNO, "chdir %s",
261 int control_association(association *assoc, const char *host, int force_open)
263 char vhost[128], *cp;
266 strncpy(vhost, host, 127);
268 cp = strchr(vhost, ':');
274 if (control_block.xml_config[0])
276 struct gfs_server *gfs;
277 for (gfs = gfs_server_list; gfs; gfs = gfs->next)
279 int listen_match = 0;
281 if ( !gfs->host || (host && gfs->host && !strcmp(host, gfs->host)))
283 if (!gfs->listen_ref ||
284 gfs->listen_ref == assoc->client_chan->chan_id)
286 if (listen_match && host_match)
289 (assoc->last_control != &gfs->cb && assoc->backend))
291 statserv_setcontrol(assoc->last_control);
292 if (assoc->backend && assoc->init)
294 gfs_server_chdir(gfs);
295 (assoc->last_control->bend_close)(assoc->backend);
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 */
432 else if (!strcmp((const char *) ptr->name, "retrievalinfo"))
434 if (yaz_retrieval_configure((*gfsp)->retrieval, ptr))
436 yaz_log(YLOG_FATAL, "%s in config %s",
437 yaz_retrieval_get_error((*gfsp)->retrieval),
438 control_block.xml_config);
444 yaz_log(YLOG_FATAL, "Unknown element '%s' in config %s",
445 ptr->name, control_block.xml_config);
449 gfsp = &(*gfsp)->next;
456 static void xml_config_open()
458 if (!getcwd(gfs_root_dir, FILENAME_MAX))
460 yaz_log(YLOG_WARN|YLOG_ERRNO, "getcwd failed");
461 gfs_root_dir[0] = '\0';
464 init_control_tls = 1;
465 current_control_tls = TlsAlloc();
466 #elif YAZ_POSIX_THREADS
467 init_control_tls = 1;
468 pthread_key_create(¤t_control_tls, 0);
471 gfs_nmem = nmem_create();
473 if (control_block.xml_config[0] == '\0')
478 xml_config_doc = xmlParseFile(control_block.xml_config);
481 yaz_log(YLOG_FATAL, "Could not parse %s", control_block.xml_config);
486 int noSubstitutions = xmlXIncludeProcess(xml_config_doc);
487 if (noSubstitutions == -1)
489 yaz_log(YLOG_WARN, "XInclude processing failed for config %s",
490 control_block.xml_config);
499 static void xml_config_close()
504 xmlFreeDoc(xml_config_doc);
509 nmem_destroy(gfs_nmem);
511 if (init_control_tls)
512 TlsFree(current_control_tls);
513 #elif YAZ_POSIX_THREADS
514 if (init_control_tls)
515 pthread_key_delete(current_control_tls);
519 static void xml_config_add_listeners()
521 struct gfs_listen *gfs = gfs_listen_list;
524 for (id_no = 1; gfs; gfs = gfs->next, id_no++)
527 add_listener(gfs->address, id_no);
531 static void xml_config_bend_start()
533 if (control_block.xml_config[0])
535 struct gfs_server *gfs = gfs_server_list;
536 for (; gfs; gfs = gfs->next)
538 yaz_log(YLOG_DEBUG, "xml_config_bend_start config=%s",
540 statserv_setcontrol(&gfs->cb);
541 if (control_block.bend_start)
543 gfs_server_chdir(gfs);
544 (control_block.bend_start)(&gfs->cb);
550 yaz_log(YLOG_DEBUG, "xml_config_bend_start default config");
551 statserv_setcontrol(&control_block);
552 if (control_block.bend_start)
553 (*control_block.bend_start)(&control_block);
557 static void xml_config_bend_stop()
559 if (control_block.xml_config[0])
561 struct gfs_server *gfs = gfs_server_list;
562 for (; gfs; gfs = gfs->next)
564 yaz_log(YLOG_DEBUG, "xml_config_bend_stop config=%s",
566 statserv_setcontrol(&gfs->cb);
567 if (control_block.bend_stop)
568 (control_block.bend_stop)(&gfs->cb);
573 yaz_log(YLOG_DEBUG, "xml_config_bend_stop default config");
574 statserv_setcontrol(&control_block);
575 if (control_block.bend_stop)
576 (*control_block.bend_stop)(&control_block);
581 * handle incoming connect requests.
582 * The dynamic mode is a bit tricky mostly because we want to avoid
583 * doing all of the listening and accepting in the parent - it's
588 typedef struct _ThreadList ThreadList;
597 static ThreadList *pFirstThread;
598 static CRITICAL_SECTION Thread_CritSect;
599 static BOOL bInitialized = FALSE;
601 static void ThreadList_Initialize()
603 /* Initialize the critical Sections */
604 InitializeCriticalSection(&Thread_CritSect);
606 /* Set the first thraed */
609 /* we have been initialized */
613 static void statserv_add(HANDLE hThread, IOCHAN pIOChannel)
615 /* Only one thread can go through this section at a time */
616 EnterCriticalSection(&Thread_CritSect);
619 /* Lets create our new object */
620 ThreadList *pNewThread = (ThreadList *)malloc(sizeof(ThreadList));
621 pNewThread->hThread = hThread;
622 pNewThread->pIOChannel = pIOChannel;
623 pNewThread->pNext = pFirstThread;
624 pFirstThread = pNewThread;
626 /* Lets let somebody else create a new object now */
627 LeaveCriticalSection(&Thread_CritSect);
631 void statserv_remove(IOCHAN pIOChannel)
633 /* Only one thread can go through this section at a time */
634 EnterCriticalSection(&Thread_CritSect);
637 ThreadList *pCurrentThread = pFirstThread;
638 ThreadList *pNextThread;
639 ThreadList *pPrevThread =NULL;
641 /* Step through all the threads */
642 for (; pCurrentThread != NULL; pCurrentThread = pNextThread)
644 /* We only need to compare on the IO Channel */
645 if (pCurrentThread->pIOChannel == pIOChannel)
647 /* We have found the thread we want to delete */
648 /* First of all reset the next pointers */
649 if (pPrevThread == NULL)
650 pFirstThread = pCurrentThread->pNext;
652 pPrevThread->pNext = pCurrentThread->pNext;
654 /* All we need todo now is delete the memory */
655 free(pCurrentThread);
657 /* No need to look at any more threads */
662 /* We need to look at another thread */
663 pNextThread = pCurrentThread->pNext;
664 pPrevThread = pCurrentThread;
668 /* Lets let somebody else remove an object now */
669 LeaveCriticalSection(&Thread_CritSect);
673 /* WIN32 statserv_closedown */
674 void statserv_closedown()
676 /* Shouldn't do anything if we are not initialized */
680 HANDLE *pThreadHandles = NULL;
682 /* We need to stop threads adding and removing while we */
683 /* start the closedown process */
684 EnterCriticalSection(&Thread_CritSect);
687 /* We have exclusive access to the thread stuff now */
688 /* Y didn't i use a semaphore - Oh well never mind */
689 ThreadList *pCurrentThread = pFirstThread;
691 /* Before we do anything else, we need to shutdown the listener */
692 if (pListener != NULL)
693 iochan_destroy(pListener);
695 for (; pCurrentThread != NULL; pCurrentThread = pCurrentThread->pNext)
697 /* Just destroy the IOCHAN, that should do the trick */
698 iochan_destroy(pCurrentThread->pIOChannel);
699 closesocket(pCurrentThread->pIOChannel->fd);
701 /* Keep a running count of our handles */
707 HANDLE *pCurrentHandle ;
709 /* Allocate the thread handle array */
710 pThreadHandles = (HANDLE *)malloc(sizeof(HANDLE) * iHandles);
711 pCurrentHandle = pThreadHandles;
713 for (pCurrentThread = pFirstThread;
714 pCurrentThread != NULL;
715 pCurrentThread = pCurrentThread->pNext, pCurrentHandle++)
717 /* Just the handle */
718 *pCurrentHandle = pCurrentThread->hThread;
722 /* We can now leave the critical section */
723 LeaveCriticalSection(&Thread_CritSect);
726 /* Now we can really do something */
729 yaz_log(log_server, "waiting for %d to die", iHandles);
730 /* This will now wait, until all the threads close */
731 WaitForMultipleObjects(iHandles, pThreadHandles, TRUE, INFINITE);
733 /* Free the memory we allocated for the handle array */
734 free(pThreadHandles);
737 xml_config_bend_stop();
738 /* No longer require the critical section, since all threads are dead */
739 DeleteCriticalSection(&Thread_CritSect);
744 void __cdecl event_loop_thread (IOCHAN iochan)
746 event_loop (&iochan);
750 static void listener(IOCHAN h, int event)
752 COMSTACK line = (COMSTACK) iochan_getdata(h);
753 IOCHAN parent_chan = line->user;
758 if (event == EVENT_INPUT)
760 if ((res = cs_listen(line, 0, 0)) < 0)
762 yaz_log(YLOG_FATAL, "cs_listen failed");
767 yaz_log(YLOG_DEBUG, "listen ok");
768 iochan_setevent(h, EVENT_OUTPUT);
769 iochan_setflags(h, EVENT_OUTPUT | EVENT_EXCEPT); /* set up for acpt */
771 else if (event == EVENT_OUTPUT)
773 COMSTACK new_line = cs_accept(line);
779 yaz_log(YLOG_FATAL, "Accept failed.");
780 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT);
783 yaz_log(YLOG_DEBUG, "Accept ok");
785 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session,
786 EVENT_INPUT, parent_chan->chan_id)))
788 yaz_log(YLOG_FATAL, "Failed to create iochan");
793 yaz_log(YLOG_DEBUG, "Creating association");
794 if (!(newas = create_association(new_chan, new_line,
795 control_block.apdufile)))
797 yaz_log(YLOG_FATAL, "Failed to create new assoc.");
801 newas->cs_get_mask = EVENT_INPUT;
802 newas->cs_put_mask = 0;
803 newas->cs_accept_mask = 0;
805 yaz_log(YLOG_DEBUG, "Setting timeout %d", control_block.idle_timeout);
806 iochan_setdata(new_chan, newas);
807 iochan_settimeout(new_chan, 60);
809 /* Now what we need todo is create a new thread with this iochan as
811 newHandle = (HANDLE) _beginthread(event_loop_thread, 0, new_chan);
812 if (newHandle == (HANDLE) -1)
815 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create new thread.");
819 /* We successfully created the thread, so add it to the list */
820 statserv_add(newHandle, new_chan);
822 yaz_log(YLOG_DEBUG, "Created new thread, id = %ld iochan %p",(long) newHandle, new_chan);
823 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
827 yaz_log(YLOG_FATAL, "Bad event on listener.");
833 int statserv_must_terminate(void)
840 static int term_flag = 0;
841 /* To save having an #ifdef in event_loop we need to
842 define this empty function
844 int statserv_must_terminate(void)
849 void statserv_remove(IOCHAN pIOChannel)
853 void statserv_closedown()
857 xml_config_bend_stop();
858 for (p = pListener; p; p = p->next)
865 void sigterm(int sig)
870 static void *new_session (void *vp);
871 static int no_sessions = 0;
874 static void listener(IOCHAN h, int event)
876 COMSTACK line = (COMSTACK) iochan_getdata(h);
879 if (event == EVENT_INPUT)
882 if ((res = cs_listen_check(line, 0, 0, control_block.check_ip,
883 control_block.daemon_name)) < 0)
885 yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_listen failed");
890 yaz_log(YLOG_WARN, "cs_listen incomplete");
893 new_line = cs_accept(line);
896 yaz_log(YLOG_FATAL, "Accept failed.");
897 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
901 yaz_log(log_sessiondetail, "Connect from %s", cs_addrstr(new_line));
904 if (control_block.dynamic)
906 if ((res = fork()) < 0)
908 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fork");
912 else if (res == 0) /* child */
917 for (pp = pListener; pp; pp = iochan_getnext(pp))
919 COMSTACK l = (COMSTACK)iochan_getdata(pp);
923 sprintf(nbuf, "%s(%d)", me, no_sessions);
924 yaz_log_init_prefix(nbuf);
925 /* ensure that bend_stop is not called when each child exits -
926 only for the main process .. */
927 control_block.bend_stop = 0;
936 if (control_block.threads)
938 #if YAZ_POSIX_THREADS
939 pthread_t child_thread;
940 pthread_create (&child_thread, 0, new_session, new_line);
941 pthread_detach (child_thread);
942 #elif YAZ_GNU_THREADS
946 attr = pth_attr_new ();
947 pth_attr_set (attr, PTH_ATTR_JOINABLE, FALSE);
948 pth_attr_set (attr, PTH_ATTR_STACK_SIZE, 32*1024);
949 pth_attr_set (attr, PTH_ATTR_NAME, "session");
950 yaz_log (YLOG_DEBUG, "pth_spawn begin");
951 child_thread = pth_spawn (attr, new_session, new_line);
952 yaz_log (YLOG_DEBUG, "pth_spawn finish");
953 pth_attr_destroy (attr);
955 new_session(new_line);
959 new_session(new_line);
961 else if (event == EVENT_TIMEOUT)
963 yaz_log(log_server, "Shutting down listener.");
968 yaz_log(YLOG_FATAL, "Bad event on listener.");
973 static void *new_session (void *vp)
978 COMSTACK new_line = (COMSTACK) vp;
979 IOCHAN parent_chan = new_line->user;
981 unsigned cs_get_mask, cs_accept_mask, mask =
982 ((new_line->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
983 ((new_line->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
987 cs_accept_mask = mask; /* accept didn't complete */
992 cs_accept_mask = 0; /* accept completed. */
993 cs_get_mask = mask = EVENT_INPUT;
996 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session, mask,
997 parent_chan->chan_id)))
999 yaz_log(YLOG_FATAL, "Failed to create iochan");
1002 if (!(newas = create_association(new_chan, new_line,
1003 control_block.apdufile)))
1005 yaz_log(YLOG_FATAL, "Failed to create new assoc.");
1008 newas->cs_accept_mask = cs_accept_mask;
1009 newas->cs_get_mask = cs_get_mask;
1011 iochan_setdata(new_chan, newas);
1012 iochan_settimeout(new_chan, 60);
1014 a = cs_addrstr(new_line);
1018 yaz_log(log_session, "Session - OK %d %s %ld",
1019 no_sessions, a ? a : "[Unknown]", (long) getpid());
1020 if (max_sessions && no_sessions >= max_sessions)
1021 control_block.one_shot = 1;
1022 if (control_block.threads)
1024 event_loop(&new_chan);
1028 new_chan->next = pListener;
1029 pListener = new_chan;
1037 static void inetd_connection(int what)
1044 if ((line = cs_createbysocket(0, tcpip_type, 0, what)))
1046 if ((chan = iochan_create(cs_fileno(line), ir_session, EVENT_INPUT,
1049 if ((assoc = create_association(chan, line,
1050 control_block.apdufile)))
1052 iochan_setdata(chan, assoc);
1053 iochan_settimeout(chan, 60);
1054 addr = cs_addrstr(line);
1055 yaz_log(log_sessiondetail, "Inetd association from %s",
1056 addr ? addr : "[UNKNOWN]");
1057 assoc->cs_get_mask = EVENT_INPUT;
1061 yaz_log(YLOG_FATAL, "Failed to create association structure");
1063 chan->next = pListener;
1068 yaz_log(YLOG_FATAL, "Failed to create iochan");
1073 yaz_log(YLOG_ERRNO|YLOG_FATAL, "Failed to create comstack on socket 0");
1078 * Set up a listening endpoint, and give it to the event-handler.
1080 static int add_listener(char *where, int listen_id)
1087 if (control_block.dynamic)
1089 else if (control_block.threads)
1094 yaz_log(log_server, "Adding %s listener on %s id=%d", mode, where,
1097 l = cs_create_host(where, 2, &ap);
1100 yaz_log(YLOG_FATAL, "Failed to listen on %s", where);
1103 if (*control_block.cert_fname)
1104 cs_set_ssl_certificate_file(l, control_block.cert_fname);
1106 if (cs_bind(l, ap, CS_SERVER) < 0)
1108 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to bind to %s", where);
1112 if (!(lst = iochan_create(cs_fileno(l), listener, EVENT_INPUT |
1113 EVENT_EXCEPT, listen_id)))
1115 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create IOCHAN-type");
1119 iochan_setdata(lst, l); /* user-defined data for listener is COMSTACK */
1120 l->user = lst; /* user-defined data for COMSTACK is listener chan */
1122 /* Add listener to chain */
1123 lst->next = pListener;
1129 /* UNIX only (for windows we don't need to catch the signals) */
1130 static void catchchld(int num)
1132 while (waitpid(-1, 0, WNOHANG) > 0)
1134 signal(SIGCHLD, catchchld);
1138 statserv_options_block *statserv_getcontrol(void)
1141 if (init_control_tls)
1142 return (statserv_options_block *) TlsGetValue(current_control_tls);
1144 return &control_block;
1145 #elif YAZ_POSIX_THREADS
1146 if (init_control_tls)
1147 return pthread_getspecific(current_control_tls);
1149 return &control_block;
1151 if (current_control_block)
1152 return current_control_block;
1153 return &control_block;
1157 void statserv_setcontrol(statserv_options_block *block)
1159 chdir(gfs_root_dir);
1161 if (init_control_tls)
1162 TlsSetValue(current_control_tls, block);
1163 #elif YAZ_POSIX_THREADS
1164 if (init_control_tls)
1165 pthread_setspecific(current_control_tls, block);
1167 current_control_block = block;
1171 static void statserv_reset(void)
1175 int statserv_start(int argc, char **argv)
1179 /* We need to initialize the thread list */
1180 ThreadList_Initialize();
1190 if ((me = strrchr (argv[0], sep)))
1191 me++; /* get the basename */
1194 programname = argv[0];
1196 if (control_block.options_func(argc, argv))
1201 xml_config_bend_start();
1204 xml_config_add_listeners();
1206 yaz_log (log_server, "Starting server %s", me);
1207 if (!pListener && *control_block.default_listen)
1208 add_listener(control_block.default_listen, 0);
1211 if (control_block.inetd)
1212 inetd_connection(control_block.default_proto);
1216 if (control_block.background)
1218 /* create pipe so that parent waits until child has created
1222 yaz_log(YLOG_FATAL|YLOG_ERRNO, "pipe");
1236 int res = read(hand[0], dummy, 1);
1237 if (res < 0 && yaz_errno() != EINTR)
1239 yaz_log(YLOG_FATAL|YLOG_ERRNO, "read fork handshake");
1256 open("/dev/null", O_RDWR);
1259 xml_config_add_listeners();
1261 if (!pListener && *control_block.default_listen)
1262 add_listener(control_block.default_listen, 0);
1267 if (*control_block.pid_fname)
1269 FILE *f = fopen(control_block.pid_fname, "w");
1272 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Couldn't create %s",
1273 control_block.pid_fname);
1276 fprintf(f, "%ld", (long) getpid());
1280 if (control_block.background)
1284 yaz_log (log_server, "Starting server %s pid=%ld", programname,
1287 sigset_t sigs_to_block;
1289 sigemptyset(&sigs_to_block);
1290 sigaddset (&sigs_to_block, SIGTERM);
1291 pthread_sigmask (SIG_BLOCK, &sigs_to_block, 0);
1294 if (control_block.dynamic)
1295 signal(SIGCHLD, catchchld);
1297 signal (SIGPIPE, SIG_IGN);
1298 signal (SIGTERM, sigterm);
1299 if (*control_block.setuid)
1303 if (!(pw = getpwnam(control_block.setuid)))
1305 yaz_log(YLOG_FATAL, "%s: Unknown user", control_block.setuid);
1308 if (setuid(pw->pw_uid) < 0)
1310 yaz_log(YLOG_FATAL|YLOG_ERRNO, "setuid");
1316 if (pListener == NULL)
1318 yaz_log(YLOG_DEBUG, "Entering event loop.");
1319 return event_loop(&pListener);
1322 static void option_copy(char *dst, const char *src)
1324 strncpy(dst, src ? src : "", 127);
1328 int check_options(int argc, char **argv)
1333 if (getenv("YAZ_LOG") == 0) {
1335 * Set default log level. We want to avoid doing this if the
1336 * user has already explicitly specified a preferred default
1337 * log-level, hence the inelegant peek at the YAZ_LOG
1338 * environment variable that will subsequently be interpreted
1339 * by the YAZ logging module itself.
1341 yaz_log_init_level(yaz_log_mask_str(STAT_DEFAULT_LOG_LEVEL));
1345 while ((ret = options("1a:iszSTl:v:u:c:w:t:k:d:A:p:DC:f:m:",
1346 argv, argc, &arg)) != -2)
1351 if (add_listener(arg, 0))
1352 return 1; /* failed to create listener */
1355 control_block.one_shot = 1;
1356 control_block.dynamic = 0;
1359 control_block.default_proto = PROTO_Z3950;
1362 fprintf (stderr, "%s: SR protocol no longer supported\n", me);
1366 control_block.dynamic = 0;
1369 #if YAZ_POSIX_THREADS
1370 control_block.dynamic = 0;
1371 control_block.threads = 1;
1372 #elif YAZ_GNU_THREADS
1373 control_block.dynamic = 0;
1374 control_block.threads = 1;
1376 fprintf(stderr, "%s: Threaded mode not available.\n", me);
1381 option_copy(control_block.logfile, arg);
1382 yaz_log_init_file(control_block.logfile);
1386 fprintf(stderr, "%s: Specify time format for log file.\n", me);
1389 yaz_log_time_format(arg);
1392 int default_level = yaz_log_mask_str(STAT_DEFAULT_LOG_LEVEL);
1393 yaz_log_init_level(yaz_log_mask_str_x(arg, default_level));
1398 option_copy(control_block.apdufile, arg);
1401 option_copy(control_block.setuid, arg);
1404 option_copy(control_block.configname, arg);
1407 option_copy(control_block.cert_fname, arg);
1410 option_copy(control_block.daemon_name, arg);
1413 if (!arg || !(r = atoi(arg)))
1415 fprintf(stderr, "%s: Specify positive timeout for -t.\n", me);
1418 control_block.idle_timeout = r;
1421 if (!arg || !(r = atoi(arg)))
1423 fprintf(stderr, "%s: Specify positive size for -k.\n", me);
1426 control_block.maxrecordsize = r * 1024;
1429 control_block.inetd = 1;
1439 max_sessions = atoi(arg);
1442 option_copy(control_block.pid_fname, arg);
1446 option_copy(control_block.xml_config, arg);
1448 fprintf(stderr, "%s: Option -f unsupported since YAZ is compiled without Libxml2 support\n", me);
1453 control_block.background = 1;
1456 fprintf(stderr, "Usage: %s [ -a <pdufile> -v <loglevel>"
1457 " -l <logfile> -u <user> -c <config> -t <minutes>"
1458 " -k <kilobytes> -d <daemon> -p <pidfile> -C certfile"
1459 " -ziDST1 -m <time-format> -w <directory> <listener-addr>... ]\n", me);
1467 typedef struct _Args
1473 static Args ArgDetails;
1475 /* name of the executable */
1476 #define SZAPPNAME "server"
1478 /* list of service dependencies - "dep1\0dep2\0\0" */
1479 #define SZDEPENDENCIES ""
1481 int statserv_main(int argc, char **argv,
1482 bend_initresult *(*bend_init)(bend_initrequest *r),
1483 void (*bend_close)(void *handle))
1485 struct statserv_options_block *cb = &control_block;
1486 cb->bend_init = bend_init;
1487 cb->bend_close = bend_close;
1489 /* Lets setup the Arg structure */
1490 ArgDetails.argc = argc;
1491 ArgDetails.argv = argv;
1493 /* Now setup the service with the service controller */
1494 SetupService(argc, argv, &ArgDetails, SZAPPNAME,
1495 cb->service_name, /* internal service name */
1496 cb->service_display_name, /* displayed name */
1501 int StartAppService(void *pHandle, int argc, char **argv)
1503 /* Initializes the App */
1507 void RunAppService(void *pHandle)
1509 Args *pArgs = (Args *)pHandle;
1511 /* Starts the app running */
1512 statserv_start(pArgs->argc, pArgs->argv);
1515 void StopAppService(void *pHandle)
1518 statserv_closedown();
1524 int statserv_main(int argc, char **argv,
1525 bend_initresult *(*bend_init)(bend_initrequest *r),
1526 void (*bend_close)(void *handle))
1530 control_block.bend_init = bend_init;
1531 control_block.bend_close = bend_close;
1533 ret = statserv_start (argc, argv);
1534 statserv_closedown ();
1542 * indent-tabs-mode: nil
1544 * vim: shiftwidth=4 tabstop=8 expandtab