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.45 2006-10-09 11:21:37 adam 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 "server,session,request"
90 int check_options(int argc, char **argv);
91 statserv_options_block control_block = {
93 0, /* threaded mode */
94 0, /* one shot (single session) */
95 0, /* __UNUSED_loglevel */
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; /* one-line logs for session */
130 static int log_sessiondetail = 0; /* more detailed stuff */
131 static int log_server = 0;
133 /** get_logbits sets global loglevel bits */
134 static void get_logbits(int force)
135 { /* needs to be called after parsing cmd-line args that can set loglevels!*/
136 if (force || !logbits_set)
139 log_session = yaz_log_module_level("session");
140 log_sessiondetail = yaz_log_module_level("sessiondetail");
141 log_server = yaz_log_module_level("server");
146 static int add_listener(char *where, int listen_id);
149 static xmlDocPtr xml_config_doc = 0;
153 static xmlNodePtr xml_config_get_root(void)
158 ptr = xmlDocGetRootElement(xml_config_doc);
159 if (!ptr || ptr->type != XML_ELEMENT_NODE ||
160 strcmp((const char *) ptr->name, "yazgfs"))
162 yaz_log(YLOG_WARN, "Bad/missing root element for config %s",
163 control_block.xml_config);
173 static char *nmem_dup_xml_content(NMEM n, xmlNodePtr ptr)
177 int len = 1; /* start with 1, because of trailing 0 */
179 int first = 1; /* whitespace lead flag .. */
180 /* determine length */
181 for (p = ptr; p; p = p->next)
183 if (p->type == XML_TEXT_NODE)
184 len += xmlStrlen(p->content);
186 /* now allocate for the string */
187 str = nmem_malloc(n, len);
188 *str = '\0'; /* so we can use strcat */
189 for (p = ptr; p; p = p->next)
191 if (p->type == XML_TEXT_NODE)
196 while(*cp && isspace(*cp))
199 first = 0; /* reset if we got non-whitespace out */
201 strcat((char *)str, (const char *)cp); /* append */
204 /* remove trailing whitespace */
205 cp = strlen((const char *)str) + str;
206 while (cp != str && isspace(cp[-1]))
209 /* return resulting string */
214 static struct gfs_server * gfs_server_new(void)
216 struct gfs_server *n = nmem_malloc(gfs_nmem, sizeof(*n));
217 memcpy(&n->cb, &control_block, sizeof(control_block));
221 n->cql_transform = 0;
222 n->server_node_ptr = 0;
227 n->retrieval = yaz_retrieval_create();
232 static struct gfs_listen * gfs_listen_new(const char *id,
235 struct gfs_listen *n = nmem_malloc(gfs_nmem, sizeof(*n));
237 n->id = nmem_strdup(gfs_nmem, id);
241 n->address = nmem_strdup(gfs_nmem, address);
245 static void gfs_server_chdir(struct gfs_server *gfs)
249 if (chdir(gfs_root_dir))
250 yaz_log(YLOG_WARN|YLOG_ERRNO, "chdir %s", gfs_root_dir);
254 if (chdir(gfs->directory))
255 yaz_log(YLOG_WARN|YLOG_ERRNO, "chdir %s",
260 int control_association(association *assoc, const char *host, int force_open)
262 char vhost[128], *cp;
265 strncpy(vhost, host, 127);
267 cp = strchr(vhost, ':');
273 if (control_block.xml_config[0])
275 struct gfs_server *gfs;
276 for (gfs = gfs_server_list; gfs; gfs = gfs->next)
278 int listen_match = 0;
280 if ( !gfs->host || (host && gfs->host && !strcmp(host, gfs->host)))
282 if (!gfs->listen_ref ||
283 gfs->listen_ref == assoc->client_chan->chan_id)
285 if (listen_match && host_match)
288 (assoc->last_control != &gfs->cb && assoc->backend))
290 statserv_setcontrol(assoc->last_control);
291 if (assoc->backend && assoc->init)
293 gfs_server_chdir(gfs);
294 (assoc->last_control->bend_close)(assoc->backend);
301 assoc->last_control = &gfs->cb;
302 statserv_setcontrol(&gfs->cb);
304 gfs_server_chdir(gfs);
310 statserv_setcontrol(0);
311 assoc->last_control = 0;
317 statserv_setcontrol(&control_block);
318 assoc->last_control = &control_block;
320 yaz_log(YLOG_DEBUG, "server select: config=%s",
321 assoc->last_control->configname);
323 assoc->maximumRecordSize = assoc->last_control->maxrecordsize;
324 assoc->preferredMessageSize = assoc->last_control->maxrecordsize;
325 cs_set_max_recv_bytes(assoc->client_link, assoc->maximumRecordSize);
329 static void xml_config_read(void)
331 struct gfs_server **gfsp = &gfs_server_list;
332 struct gfs_listen **gfslp = &gfs_listen_list;
334 xmlNodePtr ptr = xml_config_get_root();
338 for (ptr = ptr->children; ptr; ptr = ptr->next)
340 struct _xmlAttr *attr;
341 if (ptr->type != XML_ELEMENT_NODE)
343 attr = ptr->properties;
344 if (!strcmp((const char *) ptr->name, "listen"))
347 <listen id="listenerid">tcp:@:9999</listen>
350 const char *address =
351 nmem_dup_xml_content(gfs_nmem, ptr->children);
352 for ( ; attr; attr = attr->next)
353 if (!xmlStrcmp(attr->name, BAD_CAST "id")
354 && attr->children && attr->children->type == XML_TEXT_NODE)
355 id = nmem_dup_xml_content(gfs_nmem, attr->children);
358 *gfslp = gfs_listen_new(id, address);
359 gfslp = &(*gfslp)->next;
360 *gfslp = 0; /* make listener list consistent for search */
363 else if (!strcmp((const char *) ptr->name, "server"))
365 xmlNodePtr ptr_server = ptr;
367 const char *listenref = 0;
369 struct gfs_server *gfs;
371 for ( ; attr; attr = attr->next)
372 if (!xmlStrcmp(attr->name, BAD_CAST "listenref")
373 && attr->children && attr->children->type == XML_TEXT_NODE)
374 listenref = nmem_dup_xml_content(gfs_nmem, attr->children);
375 else if (!xmlStrcmp(attr->name, BAD_CAST "id")
377 && attr->children->type == XML_TEXT_NODE)
378 id = nmem_dup_xml_content(gfs_nmem, attr->children);
380 yaz_log(YLOG_WARN, "Unknown attribute '%s' for server",
382 gfs = *gfsp = gfs_server_new();
383 gfs->server_node_ptr = ptr_server;
387 struct gfs_listen *gl = gfs_listen_list;
388 for (id_no = 1; gl; gl = gl->next, id_no++)
389 if (gl->id && !strcmp(gl->id, listenref))
391 gfs->listen_ref = id_no;
395 yaz_log(YLOG_WARN, "Non-existent listenref '%s' in server "
396 "config element", listenref);
398 for (ptr = ptr_server->children; ptr; ptr = ptr->next)
400 if (ptr->type != XML_ELEMENT_NODE)
402 if (!strcmp((const char *) ptr->name, "host"))
404 gfs->host = nmem_dup_xml_content(gfs_nmem,
407 else if (!strcmp((const char *) ptr->name, "config"))
409 strcpy(gfs->cb.configname,
410 nmem_dup_xml_content(gfs_nmem, ptr->children));
412 else if (!strcmp((const char *) ptr->name, "cql2rpn"))
414 gfs->cql_transform = cql_transform_open_fname(
415 nmem_dup_xml_content(gfs_nmem, ptr->children)
418 else if (!strcmp((const char *) ptr->name, "directory"))
421 nmem_dup_xml_content(gfs_nmem, ptr->children);
423 else if (!strcmp((const char *) ptr->name, "docpath"))
426 nmem_dup_xml_content(gfs_nmem, ptr->children);
428 else if (!strcmp((const char *) ptr->name, "maximumrecordsize"))
430 gfs->cb.maxrecordsize = atoi(
431 nmem_dup_xml_content(gfs_nmem, ptr->children));
433 else if (!strcmp((const char *) ptr->name, "stylesheet"))
435 char *s = nmem_dup_xml_content(gfs_nmem, ptr->children);
437 nmem_malloc(gfs_nmem, strlen(s) + 2);
438 sprintf(gfs->stylesheet, "/%s", s);
440 else if (!strcmp((const char *) ptr->name, "explain"))
442 ; /* being processed separately */
444 else if (!strcmp((const char *) ptr->name, "retrievalinfo"))
446 if (yaz_retrieval_configure(gfs->retrieval, ptr))
448 yaz_log(YLOG_FATAL, "%s in config %s",
449 yaz_retrieval_get_error(gfs->retrieval),
450 control_block.xml_config);
456 yaz_log(YLOG_FATAL, "Unknown element '%s' in config %s",
457 ptr->name, control_block.xml_config);
461 gfsp = &(*gfsp)->next;
468 static void xml_config_open(void)
470 if (!getcwd(gfs_root_dir, FILENAME_MAX))
472 yaz_log(YLOG_WARN|YLOG_ERRNO, "getcwd failed");
473 gfs_root_dir[0] = '\0';
476 init_control_tls = 1;
477 current_control_tls = TlsAlloc();
478 #elif YAZ_POSIX_THREADS
479 init_control_tls = 1;
480 pthread_key_create(¤t_control_tls, 0);
483 gfs_nmem = nmem_create();
485 if (control_block.xml_config[0] == '\0')
490 xml_config_doc = xmlParseFile(control_block.xml_config);
493 yaz_log(YLOG_FATAL, "Could not parse %s", control_block.xml_config);
498 int noSubstitutions = xmlXIncludeProcess(xml_config_doc);
499 if (noSubstitutions == -1)
501 yaz_log(YLOG_WARN, "XInclude processing failed for config %s",
502 control_block.xml_config);
511 static void xml_config_close(void)
516 xmlFreeDoc(xml_config_doc);
521 nmem_destroy(gfs_nmem);
523 if (init_control_tls)
524 TlsFree(current_control_tls);
525 #elif YAZ_POSIX_THREADS
526 if (init_control_tls)
527 pthread_key_delete(current_control_tls);
531 static void xml_config_add_listeners(void)
533 struct gfs_listen *gfs = gfs_listen_list;
536 for (id_no = 1; gfs; gfs = gfs->next, id_no++)
539 add_listener(gfs->address, id_no);
543 static void xml_config_bend_start(void)
545 if (control_block.xml_config[0])
547 struct gfs_server *gfs = gfs_server_list;
548 for (; gfs; gfs = gfs->next)
550 yaz_log(YLOG_DEBUG, "xml_config_bend_start config=%s",
552 statserv_setcontrol(&gfs->cb);
553 if (control_block.bend_start)
555 gfs_server_chdir(gfs);
556 (control_block.bend_start)(&gfs->cb);
562 yaz_log(YLOG_DEBUG, "xml_config_bend_start default config");
563 statserv_setcontrol(&control_block);
564 if (control_block.bend_start)
565 (*control_block.bend_start)(&control_block);
569 static void xml_config_bend_stop(void)
571 if (control_block.xml_config[0])
573 struct gfs_server *gfs = gfs_server_list;
574 for (; gfs; gfs = gfs->next)
576 yaz_log(YLOG_DEBUG, "xml_config_bend_stop config=%s",
578 statserv_setcontrol(&gfs->cb);
579 if (control_block.bend_stop)
580 (control_block.bend_stop)(&gfs->cb);
585 yaz_log(YLOG_DEBUG, "xml_config_bend_stop default config");
586 statserv_setcontrol(&control_block);
587 if (control_block.bend_stop)
588 (*control_block.bend_stop)(&control_block);
593 * handle incoming connect requests.
594 * The dynamic mode is a bit tricky mostly because we want to avoid
595 * doing all of the listening and accepting in the parent - it's
600 typedef struct _ThreadList ThreadList;
609 static ThreadList *pFirstThread;
610 static CRITICAL_SECTION Thread_CritSect;
611 static BOOL bInitialized = FALSE;
613 static void ThreadList_Initialize()
615 /* Initialize the critical Sections */
616 InitializeCriticalSection(&Thread_CritSect);
618 /* Set the first thraed */
621 /* we have been initialized */
625 static void statserv_add(HANDLE hThread, IOCHAN pIOChannel)
627 /* Only one thread can go through this section at a time */
628 EnterCriticalSection(&Thread_CritSect);
631 /* Lets create our new object */
632 ThreadList *pNewThread = (ThreadList *)malloc(sizeof(ThreadList));
633 pNewThread->hThread = hThread;
634 pNewThread->pIOChannel = pIOChannel;
635 pNewThread->pNext = pFirstThread;
636 pFirstThread = pNewThread;
638 /* Lets let somebody else create a new object now */
639 LeaveCriticalSection(&Thread_CritSect);
643 void statserv_remove(IOCHAN pIOChannel)
645 /* Only one thread can go through this section at a time */
646 EnterCriticalSection(&Thread_CritSect);
649 ThreadList *pCurrentThread = pFirstThread;
650 ThreadList *pNextThread;
651 ThreadList *pPrevThread =NULL;
653 /* Step through all the threads */
654 for (; pCurrentThread != NULL; pCurrentThread = pNextThread)
656 /* We only need to compare on the IO Channel */
657 if (pCurrentThread->pIOChannel == pIOChannel)
659 /* We have found the thread we want to delete */
660 /* First of all reset the next pointers */
661 if (pPrevThread == NULL)
662 pFirstThread = pCurrentThread->pNext;
664 pPrevThread->pNext = pCurrentThread->pNext;
666 /* All we need todo now is delete the memory */
667 free(pCurrentThread);
669 /* No need to look at any more threads */
674 /* We need to look at another thread */
675 pNextThread = pCurrentThread->pNext;
676 pPrevThread = pCurrentThread;
680 /* Lets let somebody else remove an object now */
681 LeaveCriticalSection(&Thread_CritSect);
685 /* WIN32 statserv_closedown */
686 void statserv_closedown()
688 /* Shouldn't do anything if we are not initialized */
692 HANDLE *pThreadHandles = NULL;
694 /* We need to stop threads adding and removing while we */
695 /* start the closedown process */
696 EnterCriticalSection(&Thread_CritSect);
699 /* We have exclusive access to the thread stuff now */
700 /* Y didn't i use a semaphore - Oh well never mind */
701 ThreadList *pCurrentThread = pFirstThread;
703 /* Before we do anything else, we need to shutdown the listener */
704 if (pListener != NULL)
705 iochan_destroy(pListener);
707 for (; pCurrentThread != NULL; pCurrentThread = pCurrentThread->pNext)
709 /* Just destroy the IOCHAN, that should do the trick */
710 iochan_destroy(pCurrentThread->pIOChannel);
711 closesocket(pCurrentThread->pIOChannel->fd);
713 /* Keep a running count of our handles */
719 HANDLE *pCurrentHandle ;
721 /* Allocate the thread handle array */
722 pThreadHandles = (HANDLE *)malloc(sizeof(HANDLE) * iHandles);
723 pCurrentHandle = pThreadHandles;
725 for (pCurrentThread = pFirstThread;
726 pCurrentThread != NULL;
727 pCurrentThread = pCurrentThread->pNext, pCurrentHandle++)
729 /* Just the handle */
730 *pCurrentHandle = pCurrentThread->hThread;
734 /* We can now leave the critical section */
735 LeaveCriticalSection(&Thread_CritSect);
738 /* Now we can really do something */
741 yaz_log(log_server, "waiting for %d to die", iHandles);
742 /* This will now wait, until all the threads close */
743 WaitForMultipleObjects(iHandles, pThreadHandles, TRUE, INFINITE);
745 /* Free the memory we allocated for the handle array */
746 free(pThreadHandles);
749 xml_config_bend_stop();
750 /* No longer require the critical section, since all threads are dead */
751 DeleteCriticalSection(&Thread_CritSect);
756 void __cdecl event_loop_thread (IOCHAN iochan)
758 event_loop (&iochan);
762 static void listener(IOCHAN h, int event)
764 COMSTACK line = (COMSTACK) iochan_getdata(h);
765 IOCHAN parent_chan = line->user;
770 if (event == EVENT_INPUT)
775 if ((res = cs_listen(line, 0, 0)) < 0)
777 yaz_log(YLOG_FATAL|YLOG_ERRNO, "cs_listen failed");
781 return; /* incomplete */
782 yaz_log(YLOG_DEBUG, "listen ok");
783 new_line = cs_accept(line);
786 yaz_log(YLOG_FATAL, "Accept failed.");
789 yaz_log(YLOG_DEBUG, "Accept ok");
791 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session,
792 EVENT_INPUT, parent_chan->chan_id)))
794 yaz_log(YLOG_FATAL, "Failed to create iochan");
799 yaz_log(YLOG_DEBUG, "Creating association");
800 if (!(newas = create_association(new_chan, new_line,
801 control_block.apdufile)))
803 yaz_log(YLOG_FATAL, "Failed to create new assoc.");
807 newas->cs_get_mask = EVENT_INPUT;
808 newas->cs_put_mask = 0;
809 newas->cs_accept_mask = 0;
811 yaz_log(YLOG_DEBUG, "Setting timeout %d", control_block.idle_timeout);
812 iochan_setdata(new_chan, newas);
813 iochan_settimeout(new_chan, 60);
815 /* Now what we need todo is create a new thread with this iochan as
817 newHandle = (HANDLE) _beginthread(event_loop_thread, 0, new_chan);
818 if (newHandle == (HANDLE) -1)
821 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create new thread.");
825 /* We successfully created the thread, so add it to the list */
826 statserv_add(newHandle, new_chan);
828 yaz_log(YLOG_DEBUG, "Created new thread, id = %ld iochan %p",(long) newHandle, new_chan);
829 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
833 yaz_log(YLOG_FATAL, "Bad event on listener.");
839 int statserv_must_terminate(void)
846 static int term_flag = 0;
847 /* To save having an #ifdef in event_loop we need to
848 define this empty function
850 int statserv_must_terminate(void)
855 void statserv_remove(IOCHAN pIOChannel)
859 void statserv_closedown()
863 xml_config_bend_stop();
864 for (p = pListener; p; p = p->next)
871 void sigterm(int sig)
876 static void *new_session (void *vp);
877 static int no_sessions = 0;
880 static void listener(IOCHAN h, int event)
882 COMSTACK line = (COMSTACK) iochan_getdata(h);
885 if (event == EVENT_INPUT)
888 if ((res = cs_listen_check(line, 0, 0, control_block.check_ip,
889 control_block.daemon_name)) < 0)
891 yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_listen failed");
896 yaz_log(YLOG_WARN, "cs_listen incomplete");
899 new_line = cs_accept(line);
902 yaz_log(YLOG_FATAL, "Accept failed.");
903 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
907 yaz_log(log_sessiondetail, "Connect from %s", cs_addrstr(new_line));
910 if (control_block.dynamic)
912 if ((res = fork()) < 0)
914 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fork");
918 else if (res == 0) /* child */
923 for (pp = pListener; pp; pp = iochan_getnext(pp))
925 COMSTACK l = (COMSTACK)iochan_getdata(pp);
929 sprintf(nbuf, "%s(%d)", me, no_sessions);
930 yaz_log_init_prefix(nbuf);
931 /* ensure that bend_stop is not called when each child exits -
932 only for the main process .. */
933 control_block.bend_stop = 0;
942 if (control_block.threads)
944 #if YAZ_POSIX_THREADS
945 pthread_t child_thread;
946 pthread_create (&child_thread, 0, new_session, new_line);
947 pthread_detach (child_thread);
948 #elif YAZ_GNU_THREADS
952 attr = pth_attr_new ();
953 pth_attr_set (attr, PTH_ATTR_JOINABLE, FALSE);
954 pth_attr_set (attr, PTH_ATTR_STACK_SIZE, 32*1024);
955 pth_attr_set (attr, PTH_ATTR_NAME, "session");
956 yaz_log (YLOG_DEBUG, "pth_spawn begin");
957 child_thread = pth_spawn (attr, new_session, new_line);
958 yaz_log (YLOG_DEBUG, "pth_spawn finish");
959 pth_attr_destroy (attr);
961 new_session(new_line);
965 new_session(new_line);
967 else if (event == EVENT_TIMEOUT)
969 yaz_log(log_server, "Shutting down listener.");
974 yaz_log(YLOG_FATAL, "Bad event on listener.");
979 static void *new_session (void *vp)
984 COMSTACK new_line = (COMSTACK) vp;
985 IOCHAN parent_chan = new_line->user;
987 unsigned cs_get_mask, cs_accept_mask, mask =
988 ((new_line->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
989 ((new_line->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
993 cs_accept_mask = mask; /* accept didn't complete */
998 cs_accept_mask = 0; /* accept completed. */
999 cs_get_mask = mask = EVENT_INPUT;
1002 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session, mask,
1003 parent_chan->chan_id)))
1005 yaz_log(YLOG_FATAL, "Failed to create iochan");
1008 if (!(newas = create_association(new_chan, new_line,
1009 control_block.apdufile)))
1011 yaz_log(YLOG_FATAL, "Failed to create new assoc.");
1014 newas->cs_accept_mask = cs_accept_mask;
1015 newas->cs_get_mask = cs_get_mask;
1017 iochan_setdata(new_chan, newas);
1018 iochan_settimeout(new_chan, 60);
1020 a = cs_addrstr(new_line);
1024 yaz_log(log_session, "Session - OK %d %s %ld",
1025 no_sessions, a ? a : "[Unknown]", (long) getpid());
1026 if (max_sessions && no_sessions >= max_sessions)
1027 control_block.one_shot = 1;
1028 if (control_block.threads)
1030 event_loop(&new_chan);
1034 new_chan->next = pListener;
1035 pListener = new_chan;
1043 static void inetd_connection(int what)
1050 if ((line = cs_createbysocket(0, tcpip_type, 0, what)))
1052 if ((chan = iochan_create(cs_fileno(line), ir_session, EVENT_INPUT,
1055 if ((assoc = create_association(chan, line,
1056 control_block.apdufile)))
1058 iochan_setdata(chan, assoc);
1059 iochan_settimeout(chan, 60);
1060 addr = cs_addrstr(line);
1061 yaz_log(log_sessiondetail, "Inetd association from %s",
1062 addr ? addr : "[UNKNOWN]");
1063 assoc->cs_get_mask = EVENT_INPUT;
1067 yaz_log(YLOG_FATAL, "Failed to create association structure");
1069 chan->next = pListener;
1074 yaz_log(YLOG_FATAL, "Failed to create iochan");
1079 yaz_log(YLOG_ERRNO|YLOG_FATAL, "Failed to create comstack on socket 0");
1084 * Set up a listening endpoint, and give it to the event-handler.
1086 static int add_listener(char *where, int listen_id)
1093 if (control_block.dynamic)
1095 else if (control_block.threads)
1100 yaz_log(log_server, "Adding %s listener on %s id=%d", mode, where,
1103 l = cs_create_host(where, 2, &ap);
1106 yaz_log(YLOG_FATAL, "Failed to listen on %s", where);
1109 if (*control_block.cert_fname)
1110 cs_set_ssl_certificate_file(l, control_block.cert_fname);
1112 if (cs_bind(l, ap, CS_SERVER) < 0)
1114 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to bind to %s", where);
1118 if (!(lst = iochan_create(cs_fileno(l), listener, EVENT_INPUT |
1119 EVENT_EXCEPT, listen_id)))
1121 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create IOCHAN-type");
1125 iochan_setdata(lst, l); /* user-defined data for listener is COMSTACK */
1126 l->user = lst; /* user-defined data for COMSTACK is listener chan */
1128 /* Add listener to chain */
1129 lst->next = pListener;
1135 /* UNIX only (for windows we don't need to catch the signals) */
1136 static void catchchld(int num)
1138 while (waitpid(-1, 0, WNOHANG) > 0)
1140 signal(SIGCHLD, catchchld);
1144 statserv_options_block *statserv_getcontrol(void)
1147 if (init_control_tls)
1148 return (statserv_options_block *) TlsGetValue(current_control_tls);
1150 return &control_block;
1151 #elif YAZ_POSIX_THREADS
1152 if (init_control_tls)
1153 return pthread_getspecific(current_control_tls);
1155 return &control_block;
1157 if (current_control_block)
1158 return current_control_block;
1159 return &control_block;
1163 void statserv_setcontrol(statserv_options_block *block)
1165 chdir(gfs_root_dir);
1167 if (init_control_tls)
1168 TlsSetValue(current_control_tls, block);
1169 #elif YAZ_POSIX_THREADS
1170 if (init_control_tls)
1171 pthread_setspecific(current_control_tls, block);
1173 current_control_block = block;
1177 static void statserv_reset(void)
1181 int statserv_start(int argc, char **argv)
1185 /* We need to initialize the thread list */
1186 ThreadList_Initialize();
1196 if ((me = strrchr (argv[0], sep)))
1197 me++; /* get the basename */
1200 programname = argv[0];
1202 if (control_block.options_func(argc, argv))
1207 xml_config_bend_start();
1210 xml_config_add_listeners();
1212 yaz_log (log_server, "Starting server %s", me);
1213 if (!pListener && *control_block.default_listen)
1214 add_listener(control_block.default_listen, 0);
1217 if (control_block.inetd)
1218 inetd_connection(control_block.default_proto);
1222 if (control_block.background)
1224 /* create pipe so that parent waits until child has created
1228 yaz_log(YLOG_FATAL|YLOG_ERRNO, "pipe");
1242 int res = read(hand[0], dummy, 1);
1243 if (res < 0 && yaz_errno() != EINTR)
1245 yaz_log(YLOG_FATAL|YLOG_ERRNO, "read fork handshake");
1262 open("/dev/null", O_RDWR);
1265 xml_config_add_listeners();
1267 if (!pListener && *control_block.default_listen)
1268 add_listener(control_block.default_listen, 0);
1273 if (*control_block.pid_fname)
1275 FILE *f = fopen(control_block.pid_fname, "w");
1278 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Couldn't create %s",
1279 control_block.pid_fname);
1282 fprintf(f, "%ld", (long) getpid());
1286 if (control_block.background)
1290 yaz_log (log_server, "Starting server %s pid=%ld", programname,
1293 sigset_t sigs_to_block;
1295 sigemptyset(&sigs_to_block);
1296 sigaddset (&sigs_to_block, SIGTERM);
1297 pthread_sigmask (SIG_BLOCK, &sigs_to_block, 0);
1300 if (control_block.dynamic)
1301 signal(SIGCHLD, catchchld);
1303 signal (SIGPIPE, SIG_IGN);
1304 signal (SIGTERM, sigterm);
1305 if (*control_block.setuid)
1309 if (!(pw = getpwnam(control_block.setuid)))
1311 yaz_log(YLOG_FATAL, "%s: Unknown user", control_block.setuid);
1314 if (setuid(pw->pw_uid) < 0)
1316 yaz_log(YLOG_FATAL|YLOG_ERRNO, "setuid");
1322 if (pListener == NULL)
1324 yaz_log(YLOG_DEBUG, "Entering event loop.");
1325 return event_loop(&pListener);
1328 static void option_copy(char *dst, const char *src)
1330 strncpy(dst, src ? src : "", 127);
1334 int check_options(int argc, char **argv)
1339 yaz_log_init_level(yaz_log_mask_str(STAT_DEFAULT_LOG_LEVEL));
1342 while ((ret = options("1a:iszSTl:v:u:c:w:t:k:d:A:p:DC:f:m:r:",
1343 argv, argc, &arg)) != -2)
1348 if (add_listener(arg, 0))
1349 return 1; /* failed to create listener */
1352 control_block.one_shot = 1;
1353 control_block.dynamic = 0;
1356 control_block.default_proto = PROTO_Z3950;
1359 fprintf (stderr, "%s: SR protocol no longer supported\n", me);
1363 control_block.dynamic = 0;
1366 #if YAZ_POSIX_THREADS
1367 control_block.dynamic = 0;
1368 control_block.threads = 1;
1369 #elif YAZ_GNU_THREADS
1370 control_block.dynamic = 0;
1371 control_block.threads = 1;
1373 fprintf(stderr, "%s: Threaded mode not available.\n", me);
1378 option_copy(control_block.logfile, arg);
1379 yaz_log_init_file(control_block.logfile);
1383 fprintf(stderr, "%s: Specify time format for log file.\n", me);
1386 yaz_log_time_format(arg);
1389 yaz_log_init_level(yaz_log_mask_str(arg));
1393 option_copy(control_block.apdufile, arg);
1396 option_copy(control_block.setuid, arg);
1399 option_copy(control_block.configname, arg);
1402 option_copy(control_block.cert_fname, arg);
1405 option_copy(control_block.daemon_name, arg);
1408 if (!arg || !(r = atoi(arg)))
1410 fprintf(stderr, "%s: Specify positive timeout for -t.\n", me);
1413 control_block.idle_timeout = r;
1416 if (!arg || !(r = atoi(arg)))
1418 fprintf(stderr, "%s: Specify positive size for -k.\n", me);
1421 control_block.maxrecordsize = r * 1024;
1424 control_block.inetd = 1;
1434 max_sessions = atoi(arg);
1437 option_copy(control_block.pid_fname, arg);
1441 option_copy(control_block.xml_config, arg);
1443 fprintf(stderr, "%s: Option -f unsupported since YAZ is compiled without Libxml2 support\n", me);
1448 control_block.background = 1;
1451 if (!arg || !(r = atoi(arg)))
1453 fprintf(stderr, "%s: Specify positive size for -r.\n", me);
1456 yaz_log_init_max_size(r * 1024);
1459 fprintf(stderr, "Usage: %s [ -a <pdufile> -v <loglevel>"
1460 " -l <logfile> -u <user> -c <config> -t <minutes>"
1461 " -k <kilobytes> -d <daemon> -p <pidfile> -C certfile"
1462 " -ziDST1 -m <time-format> -w <directory> <listener-addr>... ]\n", me);
1470 typedef struct _Args
1476 static Args ArgDetails;
1478 /* name of the executable */
1479 #define SZAPPNAME "server"
1481 /* list of service dependencies - "dep1\0dep2\0\0" */
1482 #define SZDEPENDENCIES ""
1484 int statserv_main(int argc, char **argv,
1485 bend_initresult *(*bend_init)(bend_initrequest *r),
1486 void (*bend_close)(void *handle))
1488 struct statserv_options_block *cb = &control_block;
1489 cb->bend_init = bend_init;
1490 cb->bend_close = bend_close;
1492 /* Lets setup the Arg structure */
1493 ArgDetails.argc = argc;
1494 ArgDetails.argv = argv;
1496 /* Now setup the service with the service controller */
1497 SetupService(argc, argv, &ArgDetails, SZAPPNAME,
1498 cb->service_name, /* internal service name */
1499 cb->service_display_name, /* displayed name */
1504 int StartAppService(void *pHandle, int argc, char **argv)
1506 /* Initializes the App */
1510 void RunAppService(void *pHandle)
1512 Args *pArgs = (Args *)pHandle;
1514 /* Starts the app running */
1515 statserv_start(pArgs->argc, pArgs->argv);
1518 void StopAppService(void *pHandle)
1521 statserv_closedown();
1527 int statserv_main(int argc, char **argv,
1528 bend_initresult *(*bend_init)(bend_initrequest *r),
1529 void (*bend_close)(void *handle))
1533 control_block.bend_init = bend_init;
1534 control_block.bend_close = bend_close;
1536 ret = statserv_start (argc, argv);
1537 statserv_closedown ();
1545 * indent-tabs-mode: nil
1547 * vim: shiftwidth=4 tabstop=8 expandtab