2 * Copyright (C) 1995-2007, 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.51 2007-11-12 08:41:56 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) */
96 "", /* diagnostic output to stderr */
97 "tcp:@:9999", /* default listener port */
98 PROTO_Z3950, /* default application protocol */
99 15, /* idle timeout (minutes) */
100 1024*1024, /* maximum PDU size (approx.) to allow */
101 "default-config", /* configuration name to pass to backend */
102 "", /* set user id */
103 0, /* bend_start handler */
104 0, /* bend_stop handler */
105 check_options, /* Default routine, for checking the run-time arguments */
108 0, /* default value for inet deamon */
109 0, /* handle (for service, etc) */
110 0, /* bend_init handle */
111 0, /* bend_close handle */
113 "Z39.50 Server", /* NT Service Name */
114 "Server", /* NT application Name */
115 "", /* NT Service Dependencies */
116 "Z39.50 Server", /* NT Service Display Name */
118 0, /* SOAP handlers */
120 0, /* background daemon */
121 "", /* SSL certificate filename */
122 "" /* XML config filename */
125 static int max_sessions = 0;
127 static int logbits_set = 0;
128 static int log_session = 0; /* one-line logs for session */
129 static int log_sessiondetail = 0; /* more detailed stuff */
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_sessiondetail = yaz_log_module_level("sessiondetail");
140 log_server = yaz_log_module_level("server");
145 static int add_listener(char *where, int listen_id);
148 static xmlDocPtr xml_config_doc = 0;
152 static xmlNodePtr xml_config_get_root(void)
157 ptr = xmlDocGetRootElement(xml_config_doc);
158 if (!ptr || ptr->type != XML_ELEMENT_NODE ||
159 strcmp((const char *) ptr->name, "yazgfs"))
161 yaz_log(YLOG_WARN, "Bad/missing root element for config %s",
162 control_block.xml_config);
172 static char *nmem_dup_xml_content(NMEM n, xmlNodePtr ptr)
176 int len = 1; /* start with 1, because of trailing 0 */
178 int first = 1; /* whitespace lead flag .. */
179 /* determine length */
180 for (p = ptr; p; p = p->next)
182 if (p->type == XML_TEXT_NODE)
183 len += xmlStrlen(p->content);
185 /* now allocate for the string */
186 str = (unsigned char *) nmem_malloc(n, len);
187 *str = '\0'; /* so we can use strcat */
188 for (p = ptr; p; p = p->next)
190 if (p->type == XML_TEXT_NODE)
195 while(*cp && isspace(*cp))
198 first = 0; /* reset if we got non-whitespace out */
200 strcat((char *)str, (const char *)cp); /* append */
203 /* remove trailing whitespace */
204 cp = strlen((const char *)str) + str;
205 while (cp != str && isspace(cp[-1]))
208 /* return resulting string */
213 static struct gfs_server * gfs_server_new(void)
215 struct gfs_server *n = (struct gfs_server *)
216 nmem_malloc(gfs_nmem, sizeof(*n));
217 memcpy(&n->cb, &control_block, sizeof(control_block));
221 n->cql_transform = 0;
222 n->ccl_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 = (struct gfs_listen *)
237 nmem_malloc(gfs_nmem, sizeof(*n));
239 n->id = nmem_strdup(gfs_nmem, id);
243 n->address = nmem_strdup(gfs_nmem, address);
247 static void gfs_server_chdir(struct gfs_server *gfs)
251 if (chdir(gfs_root_dir))
252 yaz_log(YLOG_WARN|YLOG_ERRNO, "chdir %s", gfs_root_dir);
256 if (chdir(gfs->directory))
257 yaz_log(YLOG_WARN|YLOG_ERRNO, "chdir %s",
262 int control_association(association *assoc, const char *host, int force_open)
264 char vhost[128], *cp;
267 strncpy(vhost, host, 127);
269 cp = strchr(vhost, ':');
275 if (control_block.xml_config[0])
277 struct gfs_server *gfs;
278 for (gfs = gfs_server_list; gfs; gfs = gfs->next)
280 int listen_match = 0;
282 if ( !gfs->host || (host && gfs->host && !strcmp(host, gfs->host)))
284 if (!gfs->listen_ref ||
285 gfs->listen_ref == assoc->client_chan->chan_id)
287 if (listen_match && host_match)
290 (assoc->last_control != &gfs->cb && assoc->backend))
292 statserv_setcontrol(assoc->last_control);
293 if (assoc->backend && assoc->init)
295 gfs_server_chdir(gfs);
296 (assoc->last_control->bend_close)(assoc->backend);
303 assoc->last_control = &gfs->cb;
304 statserv_setcontrol(&gfs->cb);
306 gfs_server_chdir(gfs);
312 statserv_setcontrol(0);
313 assoc->last_control = 0;
319 statserv_setcontrol(&control_block);
320 assoc->last_control = &control_block;
322 yaz_log(YLOG_DEBUG, "server select: config=%s",
323 assoc->last_control->configname);
325 assoc->maximumRecordSize = assoc->last_control->maxrecordsize;
326 assoc->preferredMessageSize = assoc->last_control->maxrecordsize;
327 cs_set_max_recv_bytes(assoc->client_link, assoc->maximumRecordSize);
331 static void xml_config_read(void)
333 struct gfs_server **gfsp = &gfs_server_list;
334 struct gfs_listen **gfslp = &gfs_listen_list;
336 xmlNodePtr ptr = xml_config_get_root();
340 for (ptr = ptr->children; ptr; ptr = ptr->next)
342 struct _xmlAttr *attr;
343 if (ptr->type != XML_ELEMENT_NODE)
345 attr = ptr->properties;
346 if (!strcmp((const char *) ptr->name, "listen"))
349 <listen id="listenerid">tcp:@:9999</listen>
352 const char *address =
353 nmem_dup_xml_content(gfs_nmem, ptr->children);
354 for ( ; attr; attr = attr->next)
355 if (!xmlStrcmp(attr->name, BAD_CAST "id")
356 && attr->children && attr->children->type == XML_TEXT_NODE)
357 id = nmem_dup_xml_content(gfs_nmem, attr->children);
360 *gfslp = gfs_listen_new(id, address);
361 gfslp = &(*gfslp)->next;
362 *gfslp = 0; /* make listener list consistent for search */
365 else if (!strcmp((const char *) ptr->name, "server"))
367 xmlNodePtr ptr_server = ptr;
369 const char *listenref = 0;
371 struct gfs_server *gfs;
373 for ( ; attr; attr = attr->next)
374 if (!xmlStrcmp(attr->name, BAD_CAST "listenref")
375 && attr->children && attr->children->type == XML_TEXT_NODE)
376 listenref = nmem_dup_xml_content(gfs_nmem, attr->children);
377 else if (!xmlStrcmp(attr->name, BAD_CAST "id")
379 && attr->children->type == XML_TEXT_NODE)
380 id = nmem_dup_xml_content(gfs_nmem, attr->children);
382 yaz_log(YLOG_WARN, "Unknown attribute '%s' for server",
384 gfs = *gfsp = gfs_server_new();
385 gfs->server_node_ptr = ptr_server;
389 struct gfs_listen *gl = gfs_listen_list;
390 for (id_no = 1; gl; gl = gl->next, id_no++)
391 if (gl->id && !strcmp(gl->id, listenref))
393 gfs->listen_ref = id_no;
397 yaz_log(YLOG_WARN, "Non-existent listenref '%s' in server "
398 "config element", listenref);
400 for (ptr = ptr_server->children; ptr; ptr = ptr->next)
402 if (ptr->type != XML_ELEMENT_NODE)
404 if (!strcmp((const char *) ptr->name, "host"))
406 gfs->host = nmem_dup_xml_content(gfs_nmem,
409 else if (!strcmp((const char *) ptr->name, "config"))
411 strcpy(gfs->cb.configname,
412 nmem_dup_xml_content(gfs_nmem, ptr->children));
414 else if (!strcmp((const char *) ptr->name, "cql2rpn"))
416 gfs->cql_transform = cql_transform_open_fname(
417 nmem_dup_xml_content(gfs_nmem, ptr->children)
420 else if (!strcmp((const char *) ptr->name, "ccl2rpn"))
425 name = nmem_dup_xml_content(gfs_nmem, ptr->children);
426 if ((f = fopen(name, "r")) == 0) {
427 yaz_log(YLOG_FATAL, "can't open CCL file '%s'", name);
430 gfs->ccl_transform = ccl_qual_mk();
431 ccl_qual_file (gfs->ccl_transform, f);
434 else if (!strcmp((const char *) ptr->name, "directory"))
437 nmem_dup_xml_content(gfs_nmem, ptr->children);
439 else if (!strcmp((const char *) ptr->name, "docpath"))
442 nmem_dup_xml_content(gfs_nmem, ptr->children);
444 else if (!strcmp((const char *) ptr->name, "maximumrecordsize"))
446 gfs->cb.maxrecordsize = atoi(
447 nmem_dup_xml_content(gfs_nmem, ptr->children));
449 else if (!strcmp((const char *) ptr->name, "stylesheet"))
451 char *s = nmem_dup_xml_content(gfs_nmem, ptr->children);
452 gfs->stylesheet = (char *)
453 nmem_malloc(gfs_nmem, strlen(s) + 2);
454 sprintf(gfs->stylesheet, "/%s", s);
456 else if (!strcmp((const char *) ptr->name, "explain"))
458 ; /* being processed separately */
460 else if (!strcmp((const char *) ptr->name, "retrievalinfo"))
462 if (yaz_retrieval_configure(gfs->retrieval, ptr))
464 yaz_log(YLOG_FATAL, "%s in config %s",
465 yaz_retrieval_get_error(gfs->retrieval),
466 control_block.xml_config);
472 yaz_log(YLOG_FATAL, "Unknown element '%s' in config %s",
473 ptr->name, control_block.xml_config);
477 gfsp = &(*gfsp)->next;
484 static void xml_config_open(void)
486 if (!getcwd(gfs_root_dir, FILENAME_MAX))
488 yaz_log(YLOG_WARN|YLOG_ERRNO, "getcwd failed");
489 gfs_root_dir[0] = '\0';
492 init_control_tls = 1;
493 current_control_tls = TlsAlloc();
494 #elif YAZ_POSIX_THREADS
495 init_control_tls = 1;
496 pthread_key_create(¤t_control_tls, 0);
499 gfs_nmem = nmem_create();
501 if (control_block.xml_config[0] == '\0')
506 xml_config_doc = xmlParseFile(control_block.xml_config);
509 yaz_log(YLOG_FATAL, "Could not parse %s", control_block.xml_config);
514 int noSubstitutions = xmlXIncludeProcess(xml_config_doc);
515 if (noSubstitutions == -1)
517 yaz_log(YLOG_WARN, "XInclude processing failed for config %s",
518 control_block.xml_config);
527 static void xml_config_close(void)
532 xmlFreeDoc(xml_config_doc);
537 nmem_destroy(gfs_nmem);
539 if (init_control_tls)
540 TlsFree(current_control_tls);
541 #elif YAZ_POSIX_THREADS
542 if (init_control_tls)
543 pthread_key_delete(current_control_tls);
547 static void xml_config_add_listeners(void)
549 struct gfs_listen *gfs = gfs_listen_list;
552 for (id_no = 1; gfs; gfs = gfs->next, id_no++)
555 add_listener(gfs->address, id_no);
559 static void xml_config_bend_start(void)
561 if (control_block.xml_config[0])
563 struct gfs_server *gfs = gfs_server_list;
564 for (; gfs; gfs = gfs->next)
566 yaz_log(YLOG_DEBUG, "xml_config_bend_start config=%s",
568 statserv_setcontrol(&gfs->cb);
569 if (control_block.bend_start)
571 gfs_server_chdir(gfs);
572 (control_block.bend_start)(&gfs->cb);
578 yaz_log(YLOG_DEBUG, "xml_config_bend_start default config");
579 statserv_setcontrol(&control_block);
580 if (control_block.bend_start)
581 (*control_block.bend_start)(&control_block);
585 static void xml_config_bend_stop(void)
587 if (control_block.xml_config[0])
589 struct gfs_server *gfs = gfs_server_list;
590 for (; gfs; gfs = gfs->next)
592 yaz_log(YLOG_DEBUG, "xml_config_bend_stop config=%s",
594 statserv_setcontrol(&gfs->cb);
595 if (control_block.bend_stop)
596 (control_block.bend_stop)(&gfs->cb);
601 yaz_log(YLOG_DEBUG, "xml_config_bend_stop default config");
602 statserv_setcontrol(&control_block);
603 if (control_block.bend_stop)
604 (*control_block.bend_stop)(&control_block);
609 * handle incoming connect requests.
610 * The dynamic mode is a bit tricky mostly because we want to avoid
611 * doing all of the listening and accepting in the parent - it's
616 typedef struct _ThreadList ThreadList;
625 static ThreadList *pFirstThread;
626 static CRITICAL_SECTION Thread_CritSect;
627 static BOOL bInitialized = FALSE;
629 static void ThreadList_Initialize()
631 /* Initialize the critical Sections */
632 InitializeCriticalSection(&Thread_CritSect);
634 /* Set the first thraed */
637 /* we have been initialized */
641 static void statserv_add(HANDLE hThread, IOCHAN pIOChannel)
643 /* Only one thread can go through this section at a time */
644 EnterCriticalSection(&Thread_CritSect);
647 /* Lets create our new object */
648 ThreadList *pNewThread = (ThreadList *)malloc(sizeof(ThreadList));
649 pNewThread->hThread = hThread;
650 pNewThread->pIOChannel = pIOChannel;
651 pNewThread->pNext = pFirstThread;
652 pFirstThread = pNewThread;
654 /* Lets let somebody else create a new object now */
655 LeaveCriticalSection(&Thread_CritSect);
659 void statserv_remove(IOCHAN pIOChannel)
661 /* Only one thread can go through this section at a time */
662 EnterCriticalSection(&Thread_CritSect);
665 ThreadList *pCurrentThread = pFirstThread;
666 ThreadList *pNextThread;
667 ThreadList *pPrevThread =NULL;
669 /* Step through all the threads */
670 for (; pCurrentThread != NULL; pCurrentThread = pNextThread)
672 /* We only need to compare on the IO Channel */
673 if (pCurrentThread->pIOChannel == pIOChannel)
675 /* We have found the thread we want to delete */
676 /* First of all reset the next pointers */
677 if (pPrevThread == NULL)
678 pFirstThread = pCurrentThread->pNext;
680 pPrevThread->pNext = pCurrentThread->pNext;
682 /* All we need todo now is delete the memory */
683 free(pCurrentThread);
685 /* No need to look at any more threads */
690 /* We need to look at another thread */
691 pNextThread = pCurrentThread->pNext;
692 pPrevThread = pCurrentThread;
696 /* Lets let somebody else remove an object now */
697 LeaveCriticalSection(&Thread_CritSect);
701 /* WIN32 statserv_closedown */
702 void statserv_closedown()
704 /* Shouldn't do anything if we are not initialized */
708 HANDLE *pThreadHandles = NULL;
710 /* We need to stop threads adding and removing while we */
711 /* start the closedown process */
712 EnterCriticalSection(&Thread_CritSect);
715 /* We have exclusive access to the thread stuff now */
716 /* Y didn't i use a semaphore - Oh well never mind */
717 ThreadList *pCurrentThread = pFirstThread;
719 /* Before we do anything else, we need to shutdown the listener */
720 if (pListener != NULL)
721 iochan_destroy(pListener);
723 for (; pCurrentThread != NULL; pCurrentThread = pCurrentThread->pNext)
725 /* Just destroy the IOCHAN, that should do the trick */
726 iochan_destroy(pCurrentThread->pIOChannel);
727 closesocket(pCurrentThread->pIOChannel->fd);
729 /* Keep a running count of our handles */
735 HANDLE *pCurrentHandle ;
737 /* Allocate the thread handle array */
738 pThreadHandles = (HANDLE *)malloc(sizeof(HANDLE) * iHandles);
739 pCurrentHandle = pThreadHandles;
741 for (pCurrentThread = pFirstThread;
742 pCurrentThread != NULL;
743 pCurrentThread = pCurrentThread->pNext, pCurrentHandle++)
745 /* Just the handle */
746 *pCurrentHandle = pCurrentThread->hThread;
750 /* We can now leave the critical section */
751 LeaveCriticalSection(&Thread_CritSect);
754 /* Now we can really do something */
757 yaz_log(log_server, "waiting for %d to die", iHandles);
758 /* This will now wait, until all the threads close */
759 WaitForMultipleObjects(iHandles, pThreadHandles, TRUE, INFINITE);
761 /* Free the memory we allocated for the handle array */
762 free(pThreadHandles);
765 xml_config_bend_stop();
766 /* No longer require the critical section, since all threads are dead */
767 DeleteCriticalSection(&Thread_CritSect);
772 void __cdecl event_loop_thread (IOCHAN iochan)
774 event_loop (&iochan);
778 static void listener(IOCHAN h, int event)
780 COMSTACK line = (COMSTACK) iochan_getdata(h);
781 IOCHAN parent_chan = line->user;
786 if (event == EVENT_INPUT)
791 if ((res = cs_listen(line, 0, 0)) < 0)
793 yaz_log(YLOG_FATAL|YLOG_ERRNO, "cs_listen failed");
797 return; /* incomplete */
798 yaz_log(YLOG_DEBUG, "listen ok");
799 new_line = cs_accept(line);
802 yaz_log(YLOG_FATAL, "Accept failed.");
805 yaz_log(YLOG_DEBUG, "Accept ok");
807 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session,
808 EVENT_INPUT, parent_chan->chan_id)))
810 yaz_log(YLOG_FATAL, "Failed to create iochan");
815 yaz_log(YLOG_DEBUG, "Creating association");
816 if (!(newas = create_association(new_chan, new_line,
817 control_block.apdufile)))
819 yaz_log(YLOG_FATAL, "Failed to create new assoc.");
823 newas->cs_get_mask = EVENT_INPUT;
824 newas->cs_put_mask = 0;
825 newas->cs_accept_mask = 0;
827 yaz_log(YLOG_DEBUG, "Setting timeout %d", control_block.idle_timeout);
828 iochan_setdata(new_chan, newas);
829 iochan_settimeout(new_chan, 60);
831 /* Now what we need todo is create a new thread with this iochan as
833 newHandle = (HANDLE) _beginthread(event_loop_thread, 0, new_chan);
834 if (newHandle == (HANDLE) -1)
837 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create new thread.");
841 /* We successfully created the thread, so add it to the list */
842 statserv_add(newHandle, new_chan);
844 yaz_log(YLOG_DEBUG, "Created new thread, id = %ld iochan %p",(long) newHandle, new_chan);
845 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
849 yaz_log(YLOG_FATAL, "Bad event on listener.");
855 int statserv_must_terminate(void)
862 static int term_flag = 0;
863 /* To save having an #ifdef in event_loop we need to
864 define this empty function
866 int statserv_must_terminate(void)
871 void statserv_remove(IOCHAN pIOChannel)
875 void statserv_closedown()
879 xml_config_bend_stop();
880 for (p = pListener; p; p = p->next)
887 void sigterm(int sig)
892 static void *new_session (void *vp);
893 static int no_sessions = 0;
896 static void listener(IOCHAN h, int event)
898 COMSTACK line = (COMSTACK) iochan_getdata(h);
901 if (event == EVENT_INPUT)
904 if ((res = cs_listen_check(line, 0, 0, control_block.check_ip,
905 control_block.daemon_name)) < 0)
907 yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_listen failed");
912 yaz_log(YLOG_WARN, "cs_listen incomplete");
915 new_line = cs_accept(line);
918 yaz_log(YLOG_FATAL, "Accept failed.");
919 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
923 yaz_log(log_sessiondetail, "Connect from %s", cs_addrstr(new_line));
926 if (control_block.dynamic)
928 if ((res = fork()) < 0)
930 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fork");
934 else if (res == 0) /* child */
939 for (pp = pListener; pp; pp = iochan_getnext(pp))
941 COMSTACK l = (COMSTACK)iochan_getdata(pp);
945 sprintf(nbuf, "%s(%d)", me, no_sessions);
946 yaz_log_init_prefix(nbuf);
947 /* ensure that bend_stop is not called when each child exits -
948 only for the main process .. */
949 control_block.bend_stop = 0;
958 if (control_block.threads)
960 #if YAZ_POSIX_THREADS
961 pthread_t child_thread;
962 pthread_create (&child_thread, 0, new_session, new_line);
963 pthread_detach (child_thread);
964 #elif YAZ_GNU_THREADS
968 attr = pth_attr_new ();
969 pth_attr_set (attr, PTH_ATTR_JOINABLE, FALSE);
970 pth_attr_set (attr, PTH_ATTR_STACK_SIZE, 32*1024);
971 pth_attr_set (attr, PTH_ATTR_NAME, "session");
972 yaz_log (YLOG_DEBUG, "pth_spawn begin");
973 child_thread = pth_spawn (attr, new_session, new_line);
974 yaz_log (YLOG_DEBUG, "pth_spawn finish");
975 pth_attr_destroy (attr);
977 new_session(new_line);
981 new_session(new_line);
983 else if (event == EVENT_TIMEOUT)
985 yaz_log(log_server, "Shutting down listener.");
990 yaz_log(YLOG_FATAL, "Bad event on listener.");
995 static void *new_session (void *vp)
1000 COMSTACK new_line = (COMSTACK) vp;
1001 IOCHAN parent_chan = (IOCHAN) new_line->user;
1003 unsigned cs_get_mask, cs_accept_mask, mask =
1004 ((new_line->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
1005 ((new_line->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
1009 cs_accept_mask = mask; /* accept didn't complete */
1014 cs_accept_mask = 0; /* accept completed. */
1015 cs_get_mask = mask = EVENT_INPUT;
1018 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session, mask,
1019 parent_chan->chan_id)))
1021 yaz_log(YLOG_FATAL, "Failed to create iochan");
1024 if (!(newas = create_association(new_chan, new_line,
1025 control_block.apdufile)))
1027 yaz_log(YLOG_FATAL, "Failed to create new assoc.");
1030 newas->cs_accept_mask = cs_accept_mask;
1031 newas->cs_get_mask = cs_get_mask;
1033 iochan_setdata(new_chan, newas);
1034 iochan_settimeout(new_chan, 60);
1036 a = cs_addrstr(new_line);
1040 yaz_log(log_session, "Session - OK %d %s %ld",
1041 no_sessions, a ? a : "[Unknown]", (long) getpid());
1042 if (max_sessions && no_sessions >= max_sessions)
1043 control_block.one_shot = 1;
1044 if (control_block.threads)
1046 iochan_event_loop(&new_chan);
1050 new_chan->next = pListener;
1051 pListener = new_chan;
1059 static void inetd_connection(int what)
1066 if ((line = cs_createbysocket(0, tcpip_type, 0, what)))
1068 if ((chan = iochan_create(cs_fileno(line), ir_session, EVENT_INPUT,
1071 if ((assoc = create_association(chan, line,
1072 control_block.apdufile)))
1074 iochan_setdata(chan, assoc);
1075 iochan_settimeout(chan, 60);
1076 addr = cs_addrstr(line);
1077 yaz_log(log_sessiondetail, "Inetd association from %s",
1078 addr ? addr : "[UNKNOWN]");
1079 assoc->cs_get_mask = EVENT_INPUT;
1083 yaz_log(YLOG_FATAL, "Failed to create association structure");
1085 chan->next = pListener;
1090 yaz_log(YLOG_FATAL, "Failed to create iochan");
1095 yaz_log(YLOG_ERRNO|YLOG_FATAL, "Failed to create comstack on socket 0");
1100 * Set up a listening endpoint, and give it to the event-handler.
1102 static int add_listener(char *where, int listen_id)
1109 if (control_block.dynamic)
1111 else if (control_block.threads)
1116 yaz_log(log_server, "Adding %s listener on %s id=%d", mode, where,
1119 l = cs_create_host(where, 2, &ap);
1122 yaz_log(YLOG_FATAL, "Failed to listen on %s", where);
1125 if (*control_block.cert_fname)
1126 cs_set_ssl_certificate_file(l, control_block.cert_fname);
1128 if (cs_bind(l, ap, CS_SERVER) < 0)
1130 if (cs_errno(l) == CSYSERR)
1131 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to bind to %s", where);
1133 yaz_log(YLOG_FATAL, "Failed to bind to %s: %s", where,
1138 if (!(lst = iochan_create(cs_fileno(l), listener, EVENT_INPUT |
1139 EVENT_EXCEPT, listen_id)))
1141 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create IOCHAN-type");
1145 iochan_setdata(lst, l); /* user-defined data for listener is COMSTACK */
1146 l->user = lst; /* user-defined data for COMSTACK is listener chan */
1148 /* Add listener to chain */
1149 lst->next = pListener;
1155 /* UNIX only (for windows we don't need to catch the signals) */
1156 static void catchchld(int num)
1158 while (waitpid(-1, 0, WNOHANG) > 0)
1160 signal(SIGCHLD, catchchld);
1164 statserv_options_block *statserv_getcontrol(void)
1167 if (init_control_tls)
1168 return (statserv_options_block *) TlsGetValue(current_control_tls);
1170 return &control_block;
1171 #elif YAZ_POSIX_THREADS
1172 if (init_control_tls)
1173 return (statserv_options_block *)
1174 pthread_getspecific(current_control_tls);
1176 return &control_block;
1178 if (current_control_block)
1179 return current_control_block;
1180 return &control_block;
1184 void statserv_setcontrol(statserv_options_block *block)
1186 chdir(gfs_root_dir);
1188 if (init_control_tls)
1189 TlsSetValue(current_control_tls, block);
1190 #elif YAZ_POSIX_THREADS
1191 if (init_control_tls)
1192 pthread_setspecific(current_control_tls, block);
1194 current_control_block = block;
1198 static void statserv_reset(void)
1202 int statserv_start(int argc, char **argv)
1206 /* We need to initialize the thread list */
1207 ThreadList_Initialize();
1217 if ((me = strrchr (argv[0], sep)))
1218 me++; /* get the basename */
1221 programname = argv[0];
1223 if (control_block.options_func(argc, argv))
1228 xml_config_bend_start();
1231 xml_config_add_listeners();
1233 yaz_log (log_server, "Starting server %s", me);
1234 if (!pListener && *control_block.default_listen)
1235 add_listener(control_block.default_listen, 0);
1238 if (control_block.inetd)
1239 inetd_connection(control_block.default_proto);
1243 if (control_block.background)
1245 /* create pipe so that parent waits until child has created
1249 yaz_log(YLOG_FATAL|YLOG_ERRNO, "pipe");
1263 int res = read(hand[0], dummy, 1);
1264 if (res < 0 && yaz_errno() != EINTR)
1266 yaz_log(YLOG_FATAL|YLOG_ERRNO, "read fork handshake");
1283 open("/dev/null", O_RDWR);
1286 xml_config_add_listeners();
1288 if (!pListener && *control_block.default_listen)
1289 add_listener(control_block.default_listen, 0);
1294 if (*control_block.pid_fname)
1296 FILE *f = fopen(control_block.pid_fname, "w");
1299 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Couldn't create %s",
1300 control_block.pid_fname);
1303 fprintf(f, "%ld", (long) getpid());
1307 if (control_block.background)
1311 yaz_log (log_server, "Starting server %s pid=%ld", programname,
1314 sigset_t sigs_to_block;
1316 sigemptyset(&sigs_to_block);
1317 sigaddset (&sigs_to_block, SIGTERM);
1318 pthread_sigmask (SIG_BLOCK, &sigs_to_block, 0);
1321 if (control_block.dynamic)
1322 signal(SIGCHLD, catchchld);
1324 signal (SIGPIPE, SIG_IGN);
1325 signal (SIGTERM, sigterm);
1326 if (*control_block.setuid)
1330 if (!(pw = getpwnam(control_block.setuid)))
1332 yaz_log(YLOG_FATAL, "%s: Unknown user", control_block.setuid);
1335 if (setuid(pw->pw_uid) < 0)
1337 yaz_log(YLOG_FATAL|YLOG_ERRNO, "setuid");
1343 if (pListener == NULL)
1345 yaz_log(YLOG_DEBUG, "Entering event loop.");
1346 return iochan_event_loop(&pListener);
1349 static void option_copy(char *dst, const char *src)
1351 strncpy(dst, src ? src : "", 127);
1355 int check_options(int argc, char **argv)
1360 yaz_log_init_level(yaz_log_mask_str(STAT_DEFAULT_LOG_LEVEL));
1363 while ((ret = options("1a:iszSTl:v:u:c:w:t:k:d:A:p:DC:f:m:r:",
1364 argv, argc, &arg)) != -2)
1369 if (add_listener(arg, 0))
1370 return 1; /* failed to create listener */
1373 control_block.one_shot = 1;
1374 control_block.dynamic = 0;
1377 control_block.default_proto = PROTO_Z3950;
1380 fprintf (stderr, "%s: SR protocol no longer supported\n", me);
1384 control_block.dynamic = 0;
1387 #if YAZ_POSIX_THREADS
1388 control_block.dynamic = 0;
1389 control_block.threads = 1;
1390 #elif YAZ_GNU_THREADS
1391 control_block.dynamic = 0;
1392 control_block.threads = 1;
1394 fprintf(stderr, "%s: Threaded mode not available.\n", me);
1399 option_copy(control_block.logfile, arg);
1400 yaz_log_init_file(control_block.logfile);
1404 fprintf(stderr, "%s: Specify time format for log file.\n", me);
1407 yaz_log_time_format(arg);
1410 yaz_log_init_level(yaz_log_mask_str(arg));
1414 option_copy(control_block.apdufile, arg);
1417 option_copy(control_block.setuid, arg);
1420 option_copy(control_block.configname, arg);
1423 option_copy(control_block.cert_fname, arg);
1426 option_copy(control_block.daemon_name, arg);
1429 if (!arg || !(r = atoi(arg)))
1431 fprintf(stderr, "%s: Specify positive timeout for -t.\n", me);
1434 control_block.idle_timeout = r;
1437 if (!arg || !(r = atoi(arg)))
1439 fprintf(stderr, "%s: Specify positive size for -k.\n", me);
1442 control_block.maxrecordsize = r * 1024;
1445 control_block.inetd = 1;
1455 max_sessions = atoi(arg);
1458 option_copy(control_block.pid_fname, arg);
1462 option_copy(control_block.xml_config, arg);
1464 fprintf(stderr, "%s: Option -f unsupported since YAZ is compiled without Libxml2 support\n", me);
1469 control_block.background = 1;
1472 if (!arg || !(r = atoi(arg)))
1474 fprintf(stderr, "%s: Specify positive size for -r.\n", me);
1477 yaz_log_init_max_size(r * 1024);
1480 fprintf(stderr, "Usage: %s [ -a <pdufile> -v <loglevel>"
1481 " -l <logfile> -u <user> -c <config> -t <minutes>"
1482 " -k <kilobytes> -d <daemon> -p <pidfile> -C certfile"
1483 " -ziDST1 -m <time-format> -w <directory> <listener-addr>... ]\n", me);
1491 typedef struct _Args
1497 static Args ArgDetails;
1499 /* name of the executable */
1500 #define SZAPPNAME "server"
1502 /* list of service dependencies - "dep1\0dep2\0\0" */
1503 #define SZDEPENDENCIES ""
1505 int statserv_main(int argc, char **argv,
1506 bend_initresult *(*bend_init)(bend_initrequest *r),
1507 void (*bend_close)(void *handle))
1509 struct statserv_options_block *cb = &control_block;
1510 cb->bend_init = bend_init;
1511 cb->bend_close = bend_close;
1513 /* Lets setup the Arg structure */
1514 ArgDetails.argc = argc;
1515 ArgDetails.argv = argv;
1517 /* Now setup the service with the service controller */
1518 SetupService(argc, argv, &ArgDetails, SZAPPNAME,
1519 cb->service_name, /* internal service name */
1520 cb->service_display_name, /* displayed name */
1525 int StartAppService(void *pHandle, int argc, char **argv)
1527 /* Initializes the App */
1531 void RunAppService(void *pHandle)
1533 Args *pArgs = (Args *)pHandle;
1535 /* Starts the app running */
1536 statserv_start(pArgs->argc, pArgs->argv);
1539 void StopAppService(void *pHandle)
1542 statserv_closedown();
1548 int statserv_main(int argc, char **argv,
1549 bend_initresult *(*bend_init)(bend_initrequest *r),
1550 void (*bend_close)(void *handle))
1554 control_block.bend_init = bend_init;
1555 control_block.bend_close = bend_close;
1557 ret = statserv_start (argc, argv);
1558 statserv_closedown ();
1566 * indent-tabs-mode: nil
1568 * vim: shiftwidth=4 tabstop=8 expandtab