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.32 2005-08-22 20:34:21 adam Exp $
13 * \brief Implements GFS logic
26 #include <sys/types.h>
39 #include <libxml/parser.h>
40 #include <libxml/tree.h>
41 #include <libxml/xinclude.h>
54 #include <yaz/comstack.h>
55 #include <yaz/tcpip.h>
56 #include <yaz/options.h>
58 #include <yaz/xmosi.h>
63 #include <yaz/statserv.h>
65 static IOCHAN pListener = NULL;
67 static char gfs_root_dir[FILENAME_MAX+1];
68 static struct gfs_server *gfs_server_list = 0;
69 static struct gfs_listen *gfs_listen_list = 0;
70 static NMEM gfs_nmem = 0;
72 static char *me = "statserver"; /* log prefix */
73 static char *programname="statserver"; /* full program name */
75 DWORD current_control_tls;
76 static int init_control_tls = 0;
77 #elif YAZ_POSIX_THREADS
78 static pthread_key_t current_control_tls;
79 static int init_control_tls = 0;
81 static statserv_options_block *current_control_block = 0;
87 #define STAT_DEFAULT_LOG_LEVEL "none,fatal,warn,log,server,session,request"
88 /* the 'none' clears yaz' own default settings, including [log] */
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 YLOG_DEFAULT_LEVEL, /* log level */
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;
225 static struct gfs_listen * gfs_listen_new(const char *id,
228 struct gfs_listen *n = nmem_malloc(gfs_nmem, sizeof(*n));
230 n->id = nmem_strdup(gfs_nmem, id);
234 n->address = nmem_strdup(gfs_nmem, address);
238 static void gfs_server_chdir(struct gfs_server *gfs)
242 if (chdir(gfs_root_dir))
243 yaz_log(YLOG_WARN|YLOG_ERRNO, "chdir %s", gfs_root_dir);
247 if (chdir(gfs->directory))
248 yaz_log(YLOG_WARN|YLOG_ERRNO, "chdir %s",
253 int control_association(association *assoc, const char *host, int force_open)
255 char vhost[128], *cp;
258 strncpy(vhost, host, 127);
260 cp = strchr(vhost, ':');
265 if (control_block.xml_config[0])
267 struct gfs_server *gfs;
268 for (gfs = gfs_server_list; gfs; gfs = gfs->next)
270 int listen_match = 0;
272 if ( !gfs->host || (host && gfs->host && !strcmp(host, gfs->host)))
274 if (!gfs->listen_ref ||
275 gfs->listen_ref == assoc->client_chan->chan_id)
277 if (listen_match && host_match)
280 (assoc->last_control != &gfs->cb && assoc->backend))
282 statserv_setcontrol(assoc->last_control);
283 if (assoc->backend && assoc->init)
285 gfs_server_chdir(gfs);
286 (assoc->last_control->bend_close)(assoc->backend);
292 assoc->cql_transform = gfs->cql_transform;
293 assoc->server_node_ptr = gfs->server_node_ptr;
294 assoc->last_control = &gfs->cb;
295 statserv_setcontrol(&gfs->cb);
296 gfs_server_chdir(gfs);
297 yaz_log(YLOG_DEBUG, "server select: %s", gfs->cb.configname);
301 statserv_setcontrol(0);
302 assoc->last_control = 0;
303 assoc->cql_transform = 0;
304 assoc->server_node_ptr = 0;
305 yaz_log(YLOG_DEBUG, "server select: no match");
310 statserv_setcontrol(&control_block);
311 assoc->last_control = &control_block;
312 assoc->cql_transform = 0;
313 assoc->server_node_ptr = 0;
314 yaz_log(YLOG_DEBUG, "server select: config=%s", control_block.configname);
319 static void xml_config_read()
321 struct gfs_server **gfsp = &gfs_server_list;
322 struct gfs_listen **gfslp = &gfs_listen_list;
324 xmlNodePtr ptr = xml_config_get_root();
328 for (ptr = ptr->children; ptr; ptr = ptr->next)
330 struct _xmlAttr *attr;
331 if (ptr->type != XML_ELEMENT_NODE)
333 attr = ptr->properties;
334 if (!strcmp((const char *) ptr->name, "listen"))
337 <listen id="listenerid">tcp:@:9999</listen>
340 const char *address =
341 nmem_dup_xml_content(gfs_nmem, ptr->children);
342 for ( ; attr; attr = attr->next)
343 if (!xmlStrcmp(attr->name, BAD_CAST "id")
344 && attr->children && attr->children->type == XML_TEXT_NODE)
345 id = nmem_dup_xml_content(gfs_nmem, attr->children);
348 *gfslp = gfs_listen_new(id, address);
349 gfslp = &(*gfslp)->next;
350 *gfslp = 0; /* make listener list consistent for search */
353 else if (!strcmp((const char *) ptr->name, "server"))
355 xmlNodePtr ptr_server = ptr;
357 const char *listenref = 0;
360 for ( ; attr; attr = attr->next)
361 if (!xmlStrcmp(attr->name, BAD_CAST "listenref")
362 && attr->children && attr->children->type == XML_TEXT_NODE)
363 listenref = nmem_dup_xml_content(gfs_nmem, attr->children);
364 else if (!xmlStrcmp(attr->name, BAD_CAST "id")
366 && attr->children->type == XML_TEXT_NODE)
367 id = nmem_dup_xml_content(gfs_nmem, attr->children);
369 yaz_log(YLOG_WARN, "Unknown attribute '%s' for server",
371 *gfsp = gfs_server_new();
372 (*gfsp)->server_node_ptr = ptr_server;
376 struct gfs_listen *gl = gfs_listen_list;
377 for (id_no = 1; gl; gl = gl->next, id_no++)
378 if (gl->id && !strcmp(gl->id, listenref))
380 (*gfsp)->listen_ref = id_no;
384 yaz_log(YLOG_WARN, "Non-existent listenref '%s' in server "
385 "config element", listenref);
387 for (ptr = ptr_server->children; ptr; ptr = ptr->next)
389 if (ptr->type != XML_ELEMENT_NODE)
391 if (!strcmp((const char *) ptr->name, "host"))
393 (*gfsp)->host = nmem_dup_xml_content(gfs_nmem,
396 else if (!strcmp((const char *) ptr->name, "config"))
398 strcpy((*gfsp)->cb.configname,
399 nmem_dup_xml_content(gfs_nmem, ptr->children));
401 else if (!strcmp((const char *) ptr->name, "cql2rpn"))
403 (*gfsp)->cql_transform = cql_transform_open_fname(
404 nmem_dup_xml_content(gfs_nmem, ptr->children)
407 else if (!strcmp((const char *) ptr->name, "directory"))
410 nmem_dup_xml_content(gfs_nmem, ptr->children);
413 gfsp = &(*gfsp)->next;
420 static void xml_config_open()
422 if (!getcwd(gfs_root_dir, FILENAME_MAX))
424 yaz_log(YLOG_WARN|YLOG_ERRNO, "getcwd failed");
425 gfs_root_dir[0] = '\0';
428 init_control_tls = 1;
429 current_control_tls = TlsAlloc();
430 #elif YAZ_POSIX_THREADS
431 init_control_tls = 1;
432 pthread_key_create(¤t_control_tls, 0);
435 gfs_nmem = nmem_create();
437 if (control_block.xml_config[0] == '\0')
442 xml_config_doc = xmlParseFile(control_block.xml_config);
445 yaz_log(YLOG_FATAL, "Could not parse %s", control_block.xml_config);
450 int noSubstitutions = xmlXIncludeProcess(xml_config_doc);
451 if (noSubstitutions == -1)
453 yaz_log(YLOG_WARN, "XInclude processing failed for config %s",
454 control_block.xml_config);
463 static void xml_config_close()
468 xmlFreeDoc(xml_config_doc);
473 nmem_destroy(gfs_nmem);
475 if (init_control_tls)
476 TlsFree(current_control_tls);
477 #elif YAZ_POSIX_THREADS
478 if (init_control_tls)
479 pthread_key_delete(current_control_tls);
483 static void xml_config_add_listeners()
485 struct gfs_listen *gfs = gfs_listen_list;
488 for (id_no = 1; gfs; gfs = gfs->next, id_no++)
491 add_listener(gfs->address, id_no);
495 static void xml_config_bend_start()
497 if (control_block.xml_config[0])
499 struct gfs_server *gfs = gfs_server_list;
500 for (; gfs; gfs = gfs->next)
502 yaz_log(YLOG_DEBUG, "xml_config_bend_start config=%s",
504 statserv_setcontrol(&gfs->cb);
505 if (control_block.bend_start)
507 gfs_server_chdir(gfs);
508 (control_block.bend_start)(&gfs->cb);
514 yaz_log(YLOG_DEBUG, "xml_config_bend_start default config");
515 statserv_setcontrol(&control_block);
516 if (control_block.bend_start)
517 (*control_block.bend_start)(&control_block);
521 static void xml_config_bend_stop()
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_stop config=%s",
530 statserv_setcontrol(&gfs->cb);
531 if (control_block.bend_stop)
532 (control_block.bend_stop)(&gfs->cb);
537 yaz_log(YLOG_DEBUG, "xml_config_bend_stop default config");
538 statserv_setcontrol(&control_block);
539 if (control_block.bend_stop)
540 (*control_block.bend_stop)(&control_block);
545 * handle incoming connect requests.
546 * The dynamic mode is a bit tricky mostly because we want to avoid
547 * doing all of the listening and accepting in the parent - it's
552 typedef struct _ThreadList ThreadList;
561 static ThreadList *pFirstThread;
562 static CRITICAL_SECTION Thread_CritSect;
563 static BOOL bInitialized = FALSE;
565 static void ThreadList_Initialize()
567 /* Initialize the critical Sections */
568 InitializeCriticalSection(&Thread_CritSect);
570 /* Set the first thraed */
573 /* we have been initialized */
577 static void statserv_add(HANDLE hThread, IOCHAN pIOChannel)
579 /* Only one thread can go through this section at a time */
580 EnterCriticalSection(&Thread_CritSect);
583 /* Lets create our new object */
584 ThreadList *pNewThread = (ThreadList *)malloc(sizeof(ThreadList));
585 pNewThread->hThread = hThread;
586 pNewThread->pIOChannel = pIOChannel;
587 pNewThread->pNext = pFirstThread;
588 pFirstThread = pNewThread;
590 /* Lets let somebody else create a new object now */
591 LeaveCriticalSection(&Thread_CritSect);
595 void statserv_remove(IOCHAN pIOChannel)
597 /* Only one thread can go through this section at a time */
598 EnterCriticalSection(&Thread_CritSect);
601 ThreadList *pCurrentThread = pFirstThread;
602 ThreadList *pNextThread;
603 ThreadList *pPrevThread =NULL;
605 /* Step through all the threads */
606 for (; pCurrentThread != NULL; pCurrentThread = pNextThread)
608 /* We only need to compare on the IO Channel */
609 if (pCurrentThread->pIOChannel == pIOChannel)
611 /* We have found the thread we want to delete */
612 /* First of all reset the next pointers */
613 if (pPrevThread == NULL)
614 pFirstThread = pCurrentThread->pNext;
616 pPrevThread->pNext = pCurrentThread->pNext;
618 /* All we need todo now is delete the memory */
619 free(pCurrentThread);
621 /* No need to look at any more threads */
626 /* We need to look at another thread */
627 pNextThread = pCurrentThread->pNext;
628 pPrevThread = pCurrentThread;
632 /* Lets let somebody else remove an object now */
633 LeaveCriticalSection(&Thread_CritSect);
637 /* WIN32 statserv_closedown */
638 void statserv_closedown()
640 /* Shouldn't do anything if we are not initialized */
644 HANDLE *pThreadHandles = NULL;
646 /* We need to stop threads adding and removing while we */
647 /* start the closedown process */
648 EnterCriticalSection(&Thread_CritSect);
651 /* We have exclusive access to the thread stuff now */
652 /* Y didn't i use a semaphore - Oh well never mind */
653 ThreadList *pCurrentThread = pFirstThread;
655 /* Before we do anything else, we need to shutdown the listener */
656 if (pListener != NULL)
657 iochan_destroy(pListener);
659 for (; pCurrentThread != NULL; pCurrentThread = pCurrentThread->pNext)
661 /* Just destroy the IOCHAN, that should do the trick */
662 iochan_destroy(pCurrentThread->pIOChannel);
663 closesocket(pCurrentThread->pIOChannel->fd);
665 /* Keep a running count of our handles */
671 HANDLE *pCurrentHandle ;
673 /* Allocate the thread handle array */
674 pThreadHandles = (HANDLE *)malloc(sizeof(HANDLE) * iHandles);
675 pCurrentHandle = pThreadHandles;
677 for (pCurrentThread = pFirstThread;
678 pCurrentThread != NULL;
679 pCurrentThread = pCurrentThread->pNext, pCurrentHandle++)
681 /* Just the handle */
682 *pCurrentHandle = pCurrentThread->hThread;
686 /* We can now leave the critical section */
687 LeaveCriticalSection(&Thread_CritSect);
690 /* Now we can really do something */
693 yaz_log(log_server, "waiting for %d to die", iHandles);
694 /* This will now wait, until all the threads close */
695 WaitForMultipleObjects(iHandles, pThreadHandles, TRUE, INFINITE);
697 /* Free the memory we allocated for the handle array */
698 free(pThreadHandles);
701 xml_config_bend_stop();
702 /* No longer require the critical section, since all threads are dead */
703 DeleteCriticalSection(&Thread_CritSect);
708 void __cdecl event_loop_thread (IOCHAN iochan)
710 event_loop (&iochan);
714 static void listener(IOCHAN h, int event)
716 COMSTACK line = (COMSTACK) iochan_getdata(h);
717 IOCHAN parent_chan = line->user;
722 if (event == EVENT_INPUT)
724 if ((res = cs_listen(line, 0, 0)) < 0)
726 yaz_log(YLOG_FATAL, "cs_listen failed");
731 yaz_log(YLOG_DEBUG, "listen ok");
732 iochan_setevent(h, EVENT_OUTPUT);
733 iochan_setflags(h, EVENT_OUTPUT | EVENT_EXCEPT); /* set up for acpt */
735 else if (event == EVENT_OUTPUT)
737 COMSTACK new_line = cs_accept(line);
743 yaz_log(YLOG_FATAL, "Accept failed.");
744 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT);
747 yaz_log(YLOG_DEBUG, "Accept ok");
749 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session,
750 EVENT_INPUT, parent_chan->chan_id)))
752 yaz_log(YLOG_FATAL, "Failed to create iochan");
757 yaz_log(YLOG_DEBUG, "Creating association");
758 if (!(newas = create_association(new_chan, new_line,
759 control_block.apdufile)))
761 yaz_log(YLOG_FATAL, "Failed to create new assoc.");
765 newas->cs_get_mask = EVENT_INPUT;
766 newas->cs_put_mask = 0;
767 newas->cs_accept_mask = 0;
769 yaz_log(YLOG_DEBUG, "Setting timeout %d", control_block.idle_timeout);
770 iochan_setdata(new_chan, newas);
771 iochan_settimeout(new_chan, 60);
773 /* Now what we need todo is create a new thread with this iochan as
775 newHandle = (HANDLE) _beginthread(event_loop_thread, 0, new_chan);
776 if (newHandle == (HANDLE) -1)
779 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create new thread.");
783 /* We successfully created the thread, so add it to the list */
784 statserv_add(newHandle, new_chan);
786 yaz_log(YLOG_DEBUG, "Created new thread, id = %ld iochan %p",(long) newHandle, new_chan);
787 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
791 yaz_log(YLOG_FATAL, "Bad event on listener.");
797 int statserv_must_terminate(void)
804 static int term_flag = 0;
805 /* To save having an #ifdef in event_loop we need to
806 define this empty function
808 int statserv_must_terminate(void)
813 void statserv_remove(IOCHAN pIOChannel)
817 void statserv_closedown()
821 xml_config_bend_stop();
822 for (p = pListener; p; p = p->next)
829 void sigterm(int sig)
834 static void *new_session (void *vp);
835 static int no_sessions = 0;
838 static void listener(IOCHAN h, int event)
840 COMSTACK line = (COMSTACK) iochan_getdata(h);
843 if (event == EVENT_INPUT)
846 if ((res = cs_listen_check(line, 0, 0, control_block.check_ip,
847 control_block.daemon_name)) < 0)
849 yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_listen failed");
854 yaz_log(YLOG_WARN, "cs_listen incomplete");
857 new_line = cs_accept(line);
860 yaz_log(YLOG_FATAL, "Accept failed.");
861 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
865 yaz_log(log_session, "Connect from %s", cs_addrstr(new_line));
868 if (control_block.dynamic)
870 if ((res = fork()) < 0)
872 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fork");
876 else if (res == 0) /* child */
881 for (pp = pListener; pp; pp = iochan_getnext(pp))
883 COMSTACK l = (COMSTACK)iochan_getdata(pp);
887 sprintf(nbuf, "%s(%d)", me, no_sessions);
888 yaz_log_init(control_block.loglevel, nbuf, 0);
889 /* ensure that bend_stop is not called when each child exits -
890 only for the main process .. */
891 control_block.bend_stop = 0;
900 if (control_block.threads)
902 #if YAZ_POSIX_THREADS
903 pthread_t child_thread;
904 pthread_create (&child_thread, 0, new_session, new_line);
905 pthread_detach (child_thread);
906 #elif YAZ_GNU_THREADS
910 attr = pth_attr_new ();
911 pth_attr_set (attr, PTH_ATTR_JOINABLE, FALSE);
912 pth_attr_set (attr, PTH_ATTR_STACK_SIZE, 32*1024);
913 pth_attr_set (attr, PTH_ATTR_NAME, "session");
914 yaz_log (YLOG_DEBUG, "pth_spawn begin");
915 child_thread = pth_spawn (attr, new_session, new_line);
916 yaz_log (YLOG_DEBUG, "pth_spawn finish");
917 pth_attr_destroy (attr);
919 new_session(new_line);
923 new_session(new_line);
925 else if (event == EVENT_TIMEOUT)
927 yaz_log(log_server, "Shutting down listener.");
932 yaz_log(YLOG_FATAL, "Bad event on listener.");
937 static void *new_session (void *vp)
942 COMSTACK new_line = (COMSTACK) vp;
943 IOCHAN parent_chan = new_line->user;
945 unsigned cs_get_mask, cs_accept_mask, mask =
946 ((new_line->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
947 ((new_line->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
951 cs_accept_mask = mask; /* accept didn't complete */
956 cs_accept_mask = 0; /* accept completed. */
957 cs_get_mask = mask = EVENT_INPUT;
960 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session, mask,
961 parent_chan->chan_id)))
963 yaz_log(YLOG_FATAL, "Failed to create iochan");
966 if (!(newas = create_association(new_chan, new_line,
967 control_block.apdufile)))
969 yaz_log(YLOG_FATAL, "Failed to create new assoc.");
972 newas->cs_accept_mask = cs_accept_mask;
973 newas->cs_get_mask = cs_get_mask;
975 iochan_setdata(new_chan, newas);
976 iochan_settimeout(new_chan, 60);
978 a = cs_addrstr(new_line);
982 yaz_log(log_session, "Starting session %d from %s (pid=%ld)",
983 no_sessions, a ? a : "[Unknown]", (long) getpid());
984 if (max_sessions && no_sessions >= max_sessions)
985 control_block.one_shot = 1;
986 if (control_block.threads)
988 event_loop(&new_chan);
992 new_chan->next = pListener;
993 pListener = new_chan;
1001 static void inetd_connection(int what)
1008 if ((line = cs_createbysocket(0, tcpip_type, 0, what)))
1010 if ((chan = iochan_create(cs_fileno(line), ir_session, EVENT_INPUT,
1013 if ((assoc = create_association(chan, line,
1014 control_block.apdufile)))
1016 iochan_setdata(chan, assoc);
1017 iochan_settimeout(chan, 60);
1018 addr = cs_addrstr(line);
1019 yaz_log(log_session, "Inetd association from %s",
1020 addr ? addr : "[UNKNOWN]");
1021 assoc->cs_get_mask = EVENT_INPUT;
1025 yaz_log(YLOG_FATAL, "Failed to create association structure");
1027 chan->next = pListener;
1032 yaz_log(YLOG_FATAL, "Failed to create iochan");
1037 yaz_log(YLOG_ERRNO|YLOG_FATAL, "Failed to create comstack on socket 0");
1042 * Set up a listening endpoint, and give it to the event-handler.
1044 static int add_listener(char *where, int listen_id)
1051 if (control_block.dynamic)
1053 else if (control_block.threads)
1058 yaz_log(log_server, "Adding %s listener on %s id=%d", mode, where,
1061 l = cs_create_host(where, 2, &ap);
1064 yaz_log(YLOG_FATAL, "Failed to listen on %s", where);
1067 if (*control_block.cert_fname)
1068 cs_set_ssl_certificate_file(l, control_block.cert_fname);
1070 if (cs_bind(l, ap, CS_SERVER) < 0)
1072 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to bind to %s", where);
1076 if (!(lst = iochan_create(cs_fileno(l), listener, EVENT_INPUT |
1077 EVENT_EXCEPT, listen_id)))
1079 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create IOCHAN-type");
1083 iochan_setdata(lst, l); /* user-defined data for listener is COMSTACK */
1084 l->user = lst; /* user-defined data for COMSTACK is listener chan */
1086 /* Add listener to chain */
1087 lst->next = pListener;
1093 /* UNIX only (for windows we don't need to catch the signals) */
1094 static void catchchld(int num)
1096 while (waitpid(-1, 0, WNOHANG) > 0)
1098 signal(SIGCHLD, catchchld);
1102 statserv_options_block *statserv_getcontrol(void)
1105 if (init_control_tls)
1106 return (statserv_options_block *) TlsGetValue(current_control_tls);
1108 return &control_block;
1109 #elif YAZ_POSIX_THREADS
1110 if (init_control_tls)
1111 return pthread_getspecific(current_control_tls);
1113 return &control_block;
1115 if (current_control_block)
1116 return current_control_block;
1117 return &control_block;
1121 void statserv_setcontrol(statserv_options_block *block)
1123 chdir(gfs_root_dir);
1125 if (init_control_tls)
1126 TlsSetValue(current_control_tls, block);
1127 #elif YAZ_POSIX_THREADS
1128 if (init_control_tls)
1129 pthread_setspecific(current_control_tls, block);
1131 current_control_block = block;
1135 static void statserv_reset(void)
1139 int statserv_start(int argc, char **argv)
1143 /* We need to initialize the thread list */
1144 ThreadList_Initialize();
1154 if ((me = strrchr (argv[0], sep)))
1155 me++; /* get the basename */
1158 programname = argv[0];
1160 if (control_block.options_func(argc, argv))
1165 xml_config_bend_start();
1168 xml_config_add_listeners();
1170 yaz_log (log_server, "Starting server %s", me);
1171 if (!pListener && *control_block.default_listen)
1172 add_listener(control_block.default_listen, 0);
1175 if (control_block.inetd)
1176 inetd_connection(control_block.default_proto);
1180 if (control_block.background)
1182 /* create pipe so that parent waits until child has created
1186 yaz_log(YLOG_FATAL|YLOG_ERRNO, "pipe");
1200 int res = read(hand[0], dummy, 1);
1201 if (res < 0 && yaz_errno() != EINTR)
1203 yaz_log(YLOG_FATAL|YLOG_ERRNO, "read fork handshake");
1220 open("/dev/null", O_RDWR);
1223 xml_config_add_listeners();
1225 if (!pListener && *control_block.default_listen)
1226 add_listener(control_block.default_listen, 0);
1231 if (*control_block.pid_fname)
1233 FILE *f = fopen(control_block.pid_fname, "w");
1236 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Couldn't create %s",
1237 control_block.pid_fname);
1240 fprintf(f, "%ld", (long) getpid());
1244 if (control_block.background)
1248 yaz_log (log_server, "Starting server %s pid=%ld", programname,
1251 sigset_t sigs_to_block;
1253 sigemptyset(&sigs_to_block);
1254 sigaddset (&sigs_to_block, SIGTERM);
1255 pthread_sigmask (SIG_BLOCK, &sigs_to_block, 0);
1258 if (control_block.dynamic)
1259 signal(SIGCHLD, catchchld);
1261 signal (SIGPIPE, SIG_IGN);
1262 signal (SIGTERM, sigterm);
1263 if (*control_block.setuid)
1267 if (!(pw = getpwnam(control_block.setuid)))
1269 yaz_log(YLOG_FATAL, "%s: Unknown user", control_block.setuid);
1272 if (setuid(pw->pw_uid) < 0)
1274 yaz_log(YLOG_FATAL|YLOG_ERRNO, "setuid");
1280 if (pListener == NULL)
1282 yaz_log(YLOG_DEBUG, "Entering event loop.");
1283 return event_loop(&pListener);
1286 static void option_copy(char *dst, const char *src)
1288 strncpy(dst, src ? src : "", 127);
1292 int check_options(int argc, char **argv)
1297 /* set default log level */
1298 control_block.loglevel = yaz_log_mask_str(STAT_DEFAULT_LOG_LEVEL);
1299 yaz_log_init_level(control_block.loglevel);
1302 while ((ret = options("1a:iszSTl:v:u:c:w:t:k:d:A:p:DC:f:",
1303 argv, argc, &arg)) != -2)
1308 if (add_listener(arg, 0))
1309 return 1; /* failed to create listener */
1312 control_block.one_shot = 1;
1313 control_block.dynamic = 0;
1316 control_block.default_proto = PROTO_Z3950;
1319 fprintf (stderr, "%s: SR protocol no longer supported\n", me);
1323 control_block.dynamic = 0;
1326 #if YAZ_POSIX_THREADS
1327 control_block.dynamic = 0;
1328 control_block.threads = 1;
1329 #elif YAZ_GNU_THREADS
1330 control_block.dynamic = 0;
1331 control_block.threads = 1;
1333 fprintf(stderr, "%s: Threaded mode not available.\n", me);
1338 option_copy(control_block.logfile, arg);
1339 yaz_log_init(control_block.loglevel, me, control_block.logfile);
1342 control_block.loglevel =
1343 yaz_log_mask_str_x(arg,control_block.loglevel);
1344 yaz_log_init(control_block.loglevel, me, control_block.logfile);
1348 option_copy(control_block.apdufile, arg);
1351 option_copy(control_block.setuid, arg);
1354 option_copy(control_block.configname, arg);
1357 option_copy(control_block.cert_fname, arg);
1360 option_copy(control_block.daemon_name, arg);
1363 if (!arg || !(r = atoi(arg)))
1365 fprintf(stderr, "%s: Specify positive timeout for -t.\n", me);
1368 control_block.idle_timeout = r;
1371 if (!arg || !(r = atoi(arg)))
1373 fprintf(stderr, "%s: Specify positive size for -k.\n", me);
1376 control_block.maxrecordsize = r * 1024;
1379 control_block.inetd = 1;
1389 max_sessions = atoi(arg);
1392 option_copy(control_block.pid_fname, arg);
1396 option_copy(control_block.xml_config, arg);
1398 fprintf(stderr, "%s: Option -f unsupported since YAZ is compiled without Libxml2 support\n", me);
1403 control_block.background = 1;
1406 fprintf(stderr, "Usage: %s [ -a <pdufile> -v <loglevel>"
1407 " -l <logfile> -u <user> -c <config> -t <minutes>"
1408 " -k <kilobytes> -d <daemon> -p <pidfile> -C certfile"
1409 " -ziDST1 -w <directory> <listener-addr>... ]\n", me);
1417 typedef struct _Args
1423 static Args ArgDetails;
1425 /* name of the executable */
1426 #define SZAPPNAME "server"
1428 /* list of service dependencies - "dep1\0dep2\0\0" */
1429 #define SZDEPENDENCIES ""
1431 int statserv_main(int argc, char **argv,
1432 bend_initresult *(*bend_init)(bend_initrequest *r),
1433 void (*bend_close)(void *handle))
1435 struct statserv_options_block *cb = &control_block;
1436 cb->bend_init = bend_init;
1437 cb->bend_close = bend_close;
1439 /* Lets setup the Arg structure */
1440 ArgDetails.argc = argc;
1441 ArgDetails.argv = argv;
1443 /* Now setup the service with the service controller */
1444 SetupService(argc, argv, &ArgDetails, SZAPPNAME,
1445 cb->service_name, /* internal service name */
1446 cb->service_display_name, /* displayed name */
1451 int StartAppService(void *pHandle, int argc, char **argv)
1453 /* Initializes the App */
1457 void RunAppService(void *pHandle)
1459 Args *pArgs = (Args *)pHandle;
1461 /* Starts the app running */
1462 statserv_start(pArgs->argc, pArgs->argv);
1465 void StopAppService(void *pHandle)
1468 statserv_closedown();
1474 int statserv_main(int argc, char **argv,
1475 bend_initresult *(*bend_init)(bend_initrequest *r),
1476 void (*bend_close)(void *handle))
1480 control_block.bend_init = bend_init;
1481 control_block.bend_close = bend_close;
1483 ret = statserv_start (argc, argv);
1484 statserv_closedown ();
1492 * indent-tabs-mode: nil
1494 * vim: shiftwidth=4 tabstop=8 expandtab