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.30 2005-05-08 07:13:57 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 += strlen(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(str, cp); /* append */
202 /* remove trailing whitespace */
203 cp = strlen(str) + str;
204 while ((char*) 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 (!strcmp(attr->name, "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 (!strcmp(attr->name, "listenref") && attr->children &&
362 attr->children->type == XML_TEXT_NODE)
363 listenref = nmem_dup_xml_content(gfs_nmem, attr->children);
364 else if (!strcmp(attr->name, "id") && attr->children &&
365 attr->children->type == XML_TEXT_NODE)
366 id = nmem_dup_xml_content(gfs_nmem, attr->children);
368 yaz_log(YLOG_WARN, "Unknown attribute '%s' for server",
370 *gfsp = gfs_server_new();
371 (*gfsp)->server_node_ptr = ptr_server;
375 struct gfs_listen *gl = gfs_listen_list;
376 for (id_no = 1; gl; gl = gl->next, id_no++)
377 if (gl->id && !strcmp(gl->id, listenref))
379 (*gfsp)->listen_ref = id_no;
383 yaz_log(YLOG_WARN, "Non-existent listenref '%s' in server "
384 "config element", listenref);
386 for (ptr = ptr_server->children; ptr; ptr = ptr->next)
388 if (ptr->type != XML_ELEMENT_NODE)
390 if (!strcmp((const char *) ptr->name, "host"))
392 (*gfsp)->host = nmem_dup_xml_content(gfs_nmem,
395 else if (!strcmp((const char *) ptr->name, "config"))
397 strcpy((*gfsp)->cb.configname,
398 nmem_dup_xml_content(gfs_nmem, ptr->children));
400 else if (!strcmp((const char *) ptr->name, "cql2rpn"))
402 (*gfsp)->cql_transform = cql_transform_open_fname(
403 nmem_dup_xml_content(gfs_nmem, ptr->children)
406 else if (!strcmp((const char *) ptr->name, "directory"))
409 nmem_dup_xml_content(gfs_nmem, ptr->children);
412 gfsp = &(*gfsp)->next;
419 static void xml_config_open()
421 if (!getcwd(gfs_root_dir, FILENAME_MAX))
423 yaz_log(YLOG_WARN|YLOG_ERRNO, "getcwd failed");
424 gfs_root_dir[0] = '\0';
427 init_control_tls = 1;
428 current_control_tls = TlsAlloc();
429 #elif YAZ_POSIX_THREADS
430 init_control_tls = 1;
431 pthread_key_create(¤t_control_tls, 0);
434 gfs_nmem = nmem_create();
436 if (control_block.xml_config[0] == '\0')
441 xml_config_doc = xmlParseFile(control_block.xml_config);
444 yaz_log(YLOG_FATAL, "Could not parse %s", control_block.xml_config);
449 int noSubstitutions = xmlXIncludeProcess(xml_config_doc);
450 if (noSubstitutions == -1)
452 yaz_log(YLOG_WARN, "XInclude processing failed for config %s",
453 control_block.xml_config);
462 static void xml_config_close()
467 xmlFreeDoc(xml_config_doc);
472 nmem_destroy(gfs_nmem);
474 if (init_control_tls)
475 TlsFree(current_control_tls);
476 #elif YAZ_POSIX_THREADS
477 if (init_control_tls)
478 pthread_key_delete(current_control_tls);
482 static void xml_config_add_listeners()
484 struct gfs_listen *gfs = gfs_listen_list;
487 for (id_no = 1; gfs; gfs = gfs->next, id_no++)
490 add_listener(gfs->address, id_no);
494 static void xml_config_bend_start()
496 if (control_block.xml_config[0])
498 struct gfs_server *gfs = gfs_server_list;
499 for (; gfs; gfs = gfs->next)
501 yaz_log(YLOG_DEBUG, "xml_config_bend_start config=%s",
503 statserv_setcontrol(&gfs->cb);
504 if (control_block.bend_start)
506 gfs_server_chdir(gfs);
507 (control_block.bend_start)(&gfs->cb);
513 yaz_log(YLOG_DEBUG, "xml_config_bend_start default config");
514 statserv_setcontrol(&control_block);
515 if (control_block.bend_start)
516 (*control_block.bend_start)(&control_block);
520 static void xml_config_bend_stop()
522 if (control_block.xml_config[0])
524 struct gfs_server *gfs = gfs_server_list;
525 for (; gfs; gfs = gfs->next)
527 yaz_log(YLOG_DEBUG, "xml_config_bend_stop config=%s",
529 statserv_setcontrol(&gfs->cb);
530 if (control_block.bend_stop)
531 (control_block.bend_stop)(&gfs->cb);
536 yaz_log(YLOG_DEBUG, "xml_config_bend_stop default config");
537 statserv_setcontrol(&control_block);
538 if (control_block.bend_stop)
539 (*control_block.bend_stop)(&control_block);
544 * handle incoming connect requests.
545 * The dynamic mode is a bit tricky mostly because we want to avoid
546 * doing all of the listening and accepting in the parent - it's
551 typedef struct _ThreadList ThreadList;
560 static ThreadList *pFirstThread;
561 static CRITICAL_SECTION Thread_CritSect;
562 static BOOL bInitialized = FALSE;
564 static void ThreadList_Initialize()
566 /* Initialize the critical Sections */
567 InitializeCriticalSection(&Thread_CritSect);
569 /* Set the first thraed */
572 /* we have been initialized */
576 static void statserv_add(HANDLE hThread, IOCHAN pIOChannel)
578 /* Only one thread can go through this section at a time */
579 EnterCriticalSection(&Thread_CritSect);
582 /* Lets create our new object */
583 ThreadList *pNewThread = (ThreadList *)malloc(sizeof(ThreadList));
584 pNewThread->hThread = hThread;
585 pNewThread->pIOChannel = pIOChannel;
586 pNewThread->pNext = pFirstThread;
587 pFirstThread = pNewThread;
589 /* Lets let somebody else create a new object now */
590 LeaveCriticalSection(&Thread_CritSect);
594 void statserv_remove(IOCHAN pIOChannel)
596 /* Only one thread can go through this section at a time */
597 EnterCriticalSection(&Thread_CritSect);
600 ThreadList *pCurrentThread = pFirstThread;
601 ThreadList *pNextThread;
602 ThreadList *pPrevThread =NULL;
604 /* Step through all the threads */
605 for (; pCurrentThread != NULL; pCurrentThread = pNextThread)
607 /* We only need to compare on the IO Channel */
608 if (pCurrentThread->pIOChannel == pIOChannel)
610 /* We have found the thread we want to delete */
611 /* First of all reset the next pointers */
612 if (pPrevThread == NULL)
613 pFirstThread = pCurrentThread->pNext;
615 pPrevThread->pNext = pCurrentThread->pNext;
617 /* All we need todo now is delete the memory */
618 free(pCurrentThread);
620 /* No need to look at any more threads */
625 /* We need to look at another thread */
626 pNextThread = pCurrentThread->pNext;
627 pPrevThread = pCurrentThread;
631 /* Lets let somebody else remove an object now */
632 LeaveCriticalSection(&Thread_CritSect);
636 /* WIN32 statserv_closedown */
637 void statserv_closedown()
639 /* Shouldn't do anything if we are not initialized */
643 HANDLE *pThreadHandles = NULL;
645 /* We need to stop threads adding and removing while we */
646 /* start the closedown process */
647 EnterCriticalSection(&Thread_CritSect);
650 /* We have exclusive access to the thread stuff now */
651 /* Y didn't i use a semaphore - Oh well never mind */
652 ThreadList *pCurrentThread = pFirstThread;
654 /* Before we do anything else, we need to shutdown the listener */
655 if (pListener != NULL)
656 iochan_destroy(pListener);
658 for (; pCurrentThread != NULL; pCurrentThread = pCurrentThread->pNext)
660 /* Just destroy the IOCHAN, that should do the trick */
661 iochan_destroy(pCurrentThread->pIOChannel);
662 closesocket(pCurrentThread->pIOChannel->fd);
664 /* Keep a running count of our handles */
670 HANDLE *pCurrentHandle ;
672 /* Allocate the thread handle array */
673 pThreadHandles = (HANDLE *)malloc(sizeof(HANDLE) * iHandles);
674 pCurrentHandle = pThreadHandles;
676 for (pCurrentThread = pFirstThread;
677 pCurrentThread != NULL;
678 pCurrentThread = pCurrentThread->pNext, pCurrentHandle++)
680 /* Just the handle */
681 *pCurrentHandle = pCurrentThread->hThread;
685 /* We can now leave the critical section */
686 LeaveCriticalSection(&Thread_CritSect);
689 /* Now we can really do something */
692 yaz_log(log_server, "waiting for %d to die", iHandles);
693 /* This will now wait, until all the threads close */
694 WaitForMultipleObjects(iHandles, pThreadHandles, TRUE, INFINITE);
696 /* Free the memory we allocated for the handle array */
697 free(pThreadHandles);
700 xml_config_bend_stop();
701 /* No longer require the critical section, since all threads are dead */
702 DeleteCriticalSection(&Thread_CritSect);
707 void __cdecl event_loop_thread (IOCHAN iochan)
709 event_loop (&iochan);
713 static void listener(IOCHAN h, int event)
715 COMSTACK line = (COMSTACK) iochan_getdata(h);
716 IOCHAN parent_chan = line->user;
721 if (event == EVENT_INPUT)
723 if ((res = cs_listen(line, 0, 0)) < 0)
725 yaz_log(YLOG_FATAL, "cs_listen failed");
730 yaz_log(YLOG_DEBUG, "listen ok");
731 iochan_setevent(h, EVENT_OUTPUT);
732 iochan_setflags(h, EVENT_OUTPUT | EVENT_EXCEPT); /* set up for acpt */
734 else if (event == EVENT_OUTPUT)
736 COMSTACK new_line = cs_accept(line);
742 yaz_log(YLOG_FATAL, "Accept failed.");
743 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT);
746 yaz_log(YLOG_DEBUG, "Accept ok");
748 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session,
749 EVENT_INPUT, parent_chan->chan_id)))
751 yaz_log(YLOG_FATAL, "Failed to create iochan");
756 yaz_log(YLOG_DEBUG, "Creating association");
757 if (!(newas = create_association(new_chan, new_line,
758 control_block.apdufile)))
760 yaz_log(YLOG_FATAL, "Failed to create new assoc.");
764 newas->cs_get_mask = EVENT_INPUT;
765 newas->cs_put_mask = 0;
766 newas->cs_accept_mask = 0;
768 yaz_log(YLOG_DEBUG, "Setting timeout %d", control_block.idle_timeout);
769 iochan_setdata(new_chan, newas);
770 iochan_settimeout(new_chan, 60);
772 /* Now what we need todo is create a new thread with this iochan as
774 newHandle = (HANDLE) _beginthread(event_loop_thread, 0, new_chan);
775 if (newHandle == (HANDLE) -1)
778 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create new thread.");
782 /* We successfully created the thread, so add it to the list */
783 statserv_add(newHandle, new_chan);
785 yaz_log(YLOG_DEBUG, "Created new thread, id = %ld iochan %p",(long) newHandle, new_chan);
786 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
790 yaz_log(YLOG_FATAL, "Bad event on listener.");
796 int statserv_must_terminate(void)
803 static int term_flag = 0;
804 /* To save having an #ifdef in event_loop we need to
805 define this empty function
807 int statserv_must_terminate(void)
812 void statserv_remove(IOCHAN pIOChannel)
816 void statserv_closedown()
820 xml_config_bend_stop();
821 for (p = pListener; p; p = p->next)
828 void sigterm(int sig)
833 static void *new_session (void *vp);
834 static int no_sessions = 0;
837 static void listener(IOCHAN h, int event)
839 COMSTACK line = (COMSTACK) iochan_getdata(h);
842 if (event == EVENT_INPUT)
845 if ((res = cs_listen_check(line, 0, 0, control_block.check_ip,
846 control_block.daemon_name)) < 0)
848 yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_listen failed");
853 yaz_log(YLOG_WARN, "cs_listen incomplete");
856 new_line = cs_accept(line);
859 yaz_log(YLOG_FATAL, "Accept failed.");
860 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
864 yaz_log(log_session, "Connect from %s", cs_addrstr(new_line));
867 if (control_block.dynamic)
869 if ((res = fork()) < 0)
871 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fork");
875 else if (res == 0) /* child */
880 for (pp = pListener; pp; pp = iochan_getnext(pp))
882 COMSTACK l = (COMSTACK)iochan_getdata(pp);
886 sprintf(nbuf, "%s(%d)", me, no_sessions);
887 yaz_log_init(control_block.loglevel, nbuf, 0);
888 /* ensure that bend_stop is not called when each child exits -
889 only for the main process .. */
890 control_block.bend_stop = 0;
899 if (control_block.threads)
901 #if YAZ_POSIX_THREADS
902 pthread_t child_thread;
903 pthread_create (&child_thread, 0, new_session, new_line);
904 pthread_detach (child_thread);
905 #elif YAZ_GNU_THREADS
909 attr = pth_attr_new ();
910 pth_attr_set (attr, PTH_ATTR_JOINABLE, FALSE);
911 pth_attr_set (attr, PTH_ATTR_STACK_SIZE, 32*1024);
912 pth_attr_set (attr, PTH_ATTR_NAME, "session");
913 yaz_log (YLOG_DEBUG, "pth_spawn begin");
914 child_thread = pth_spawn (attr, new_session, new_line);
915 yaz_log (YLOG_DEBUG, "pth_spawn finish");
916 pth_attr_destroy (attr);
918 new_session(new_line);
922 new_session(new_line);
924 else if (event == EVENT_TIMEOUT)
926 yaz_log(log_server, "Shutting down listener.");
931 yaz_log(YLOG_FATAL, "Bad event on listener.");
936 static void *new_session (void *vp)
941 COMSTACK new_line = (COMSTACK) vp;
942 IOCHAN parent_chan = new_line->user;
944 unsigned cs_get_mask, cs_accept_mask, mask =
945 ((new_line->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
946 ((new_line->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
950 cs_accept_mask = mask; /* accept didn't complete */
955 cs_accept_mask = 0; /* accept completed. */
956 cs_get_mask = mask = EVENT_INPUT;
959 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session, mask,
960 parent_chan->chan_id)))
962 yaz_log(YLOG_FATAL, "Failed to create iochan");
965 if (!(newas = create_association(new_chan, new_line,
966 control_block.apdufile)))
968 yaz_log(YLOG_FATAL, "Failed to create new assoc.");
971 newas->cs_accept_mask = cs_accept_mask;
972 newas->cs_get_mask = cs_get_mask;
974 iochan_setdata(new_chan, newas);
975 iochan_settimeout(new_chan, 60);
977 a = cs_addrstr(new_line);
981 yaz_log(log_session, "Starting session %d from %s (pid=%ld)",
982 no_sessions, a ? a : "[Unknown]", (long) getpid());
983 if (max_sessions && no_sessions >= max_sessions)
984 control_block.one_shot = 1;
985 if (control_block.threads)
987 event_loop(&new_chan);
991 new_chan->next = pListener;
992 pListener = new_chan;
1000 static void inetd_connection(int what)
1007 if ((line = cs_createbysocket(0, tcpip_type, 0, what)))
1009 if ((chan = iochan_create(cs_fileno(line), ir_session, EVENT_INPUT,
1012 if ((assoc = create_association(chan, line,
1013 control_block.apdufile)))
1015 iochan_setdata(chan, assoc);
1016 iochan_settimeout(chan, 60);
1017 addr = cs_addrstr(line);
1018 yaz_log(log_session, "Inetd association from %s",
1019 addr ? addr : "[UNKNOWN]");
1020 assoc->cs_get_mask = EVENT_INPUT;
1024 yaz_log(YLOG_FATAL, "Failed to create association structure");
1026 chan->next = pListener;
1031 yaz_log(YLOG_FATAL, "Failed to create iochan");
1036 yaz_log(YLOG_ERRNO|YLOG_FATAL, "Failed to create comstack on socket 0");
1041 * Set up a listening endpoint, and give it to the event-handler.
1043 static int add_listener(char *where, int listen_id)
1050 if (control_block.dynamic)
1052 else if (control_block.threads)
1057 yaz_log(log_server, "Adding %s listener on %s id=%d", mode, where,
1060 l = cs_create_host(where, 2, &ap);
1063 yaz_log(YLOG_FATAL, "Failed to listen on %s", where);
1066 if (*control_block.cert_fname)
1067 cs_set_ssl_certificate_file(l, control_block.cert_fname);
1069 if (cs_bind(l, ap, CS_SERVER) < 0)
1071 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to bind to %s", where);
1075 if (!(lst = iochan_create(cs_fileno(l), listener, EVENT_INPUT |
1076 EVENT_EXCEPT, listen_id)))
1078 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create IOCHAN-type");
1082 iochan_setdata(lst, l); /* user-defined data for listener is COMSTACK */
1083 l->user = lst; /* user-defined data for COMSTACK is listener chan */
1085 /* Add listener to chain */
1086 lst->next = pListener;
1092 /* UNIX only (for windows we don't need to catch the signals) */
1093 static void catchchld(int num)
1095 while (waitpid(-1, 0, WNOHANG) > 0)
1097 signal(SIGCHLD, catchchld);
1101 statserv_options_block *statserv_getcontrol(void)
1104 if (init_control_tls)
1105 return (statserv_options_block *) TlsGetValue(current_control_tls);
1107 return &control_block;
1108 #elif YAZ_POSIX_THREADS
1109 if (init_control_tls)
1110 return pthread_getspecific(current_control_tls);
1112 return &control_block;
1114 if (current_control_block)
1115 return current_control_block;
1116 return &control_block;
1120 void statserv_setcontrol(statserv_options_block *block)
1122 chdir(gfs_root_dir);
1124 if (init_control_tls)
1125 TlsSetValue(current_control_tls, block);
1126 #elif YAZ_POSIX_THREADS
1127 if (init_control_tls)
1128 pthread_setspecific(current_control_tls, block);
1130 current_control_block = block;
1134 static void statserv_reset(void)
1138 int statserv_start(int argc, char **argv)
1142 /* We need to initialize the thread list */
1143 ThreadList_Initialize();
1153 if ((me = strrchr (argv[0], sep)))
1154 me++; /* get the basename */
1157 programname = argv[0];
1159 if (control_block.options_func(argc, argv))
1164 xml_config_bend_start();
1167 xml_config_add_listeners();
1169 yaz_log (log_server, "Starting server %s", me);
1170 if (!pListener && *control_block.default_listen)
1171 add_listener(control_block.default_listen, 0);
1174 if (control_block.inetd)
1175 inetd_connection(control_block.default_proto);
1179 if (control_block.background)
1181 /* create pipe so that parent waits until child has created
1185 yaz_log(YLOG_FATAL|YLOG_ERRNO, "pipe");
1199 int res = read(hand[0], dummy, 1);
1200 if (res < 0 && yaz_errno() != EINTR)
1202 yaz_log(YLOG_FATAL|YLOG_ERRNO, "read fork handshake");
1219 open("/dev/null", O_RDWR);
1222 xml_config_add_listeners();
1224 if (!pListener && *control_block.default_listen)
1225 add_listener(control_block.default_listen, 0);
1230 if (*control_block.pid_fname)
1232 FILE *f = fopen(control_block.pid_fname, "w");
1235 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Couldn't create %s",
1236 control_block.pid_fname);
1239 fprintf(f, "%ld", (long) getpid());
1243 if (control_block.background)
1247 yaz_log (log_server, "Starting server %s pid=%ld", programname,
1250 sigset_t sigs_to_block;
1252 sigemptyset(&sigs_to_block);
1253 sigaddset (&sigs_to_block, SIGTERM);
1254 pthread_sigmask (SIG_BLOCK, &sigs_to_block, 0);
1257 if (control_block.dynamic)
1258 signal(SIGCHLD, catchchld);
1260 signal (SIGPIPE, SIG_IGN);
1261 signal (SIGTERM, sigterm);
1262 if (*control_block.setuid)
1266 if (!(pw = getpwnam(control_block.setuid)))
1268 yaz_log(YLOG_FATAL, "%s: Unknown user", control_block.setuid);
1271 if (setuid(pw->pw_uid) < 0)
1273 yaz_log(YLOG_FATAL|YLOG_ERRNO, "setuid");
1279 if (pListener == NULL)
1281 yaz_log(YLOG_DEBUG, "Entering event loop.");
1282 return event_loop(&pListener);
1285 static void option_copy(char *dst, const char *src)
1287 strncpy(dst, src ? src : "", 127);
1291 int check_options(int argc, char **argv)
1296 /* set default log level */
1297 control_block.loglevel = yaz_log_mask_str(STAT_DEFAULT_LOG_LEVEL);
1298 yaz_log_init_level(control_block.loglevel);
1301 while ((ret = options("1a:iszSTl:v:u:c:w:t:k:d:A:p:DC:f:",
1302 argv, argc, &arg)) != -2)
1307 if (add_listener(arg, 0))
1308 return 1; /* failed to create listener */
1311 control_block.one_shot = 1;
1312 control_block.dynamic = 0;
1315 control_block.default_proto = PROTO_Z3950;
1318 fprintf (stderr, "%s: SR protocol no longer supported\n", me);
1322 control_block.dynamic = 0;
1325 #if YAZ_POSIX_THREADS
1326 control_block.dynamic = 0;
1327 control_block.threads = 1;
1328 #elif YAZ_GNU_THREADS
1329 control_block.dynamic = 0;
1330 control_block.threads = 1;
1332 fprintf(stderr, "%s: Threaded mode not available.\n", me);
1337 option_copy(control_block.logfile, arg);
1338 yaz_log_init(control_block.loglevel, me, control_block.logfile);
1341 control_block.loglevel =
1342 yaz_log_mask_str_x(arg,control_block.loglevel);
1343 yaz_log_init(control_block.loglevel, me, control_block.logfile);
1347 option_copy(control_block.apdufile, arg);
1350 option_copy(control_block.setuid, arg);
1353 option_copy(control_block.configname, arg);
1356 option_copy(control_block.cert_fname, arg);
1359 option_copy(control_block.daemon_name, arg);
1362 if (!arg || !(r = atoi(arg)))
1364 fprintf(stderr, "%s: Specify positive timeout for -t.\n", me);
1367 control_block.idle_timeout = r;
1370 if (!arg || !(r = atoi(arg)))
1372 fprintf(stderr, "%s: Specify positive size for -k.\n", me);
1375 control_block.maxrecordsize = r * 1024;
1378 control_block.inetd = 1;
1388 max_sessions = atoi(arg);
1391 option_copy(control_block.pid_fname, arg);
1395 option_copy(control_block.xml_config, arg);
1397 fprintf(stderr, "%s: Option -f unsupported since YAZ is compiled without Libxml2 support\n", me);
1402 control_block.background = 1;
1405 fprintf(stderr, "Usage: %s [ -a <pdufile> -v <loglevel>"
1406 " -l <logfile> -u <user> -c <config> -t <minutes>"
1407 " -k <kilobytes> -d <daemon> -p <pidfile> -C certfile"
1408 " -ziDST1 -w <directory> <listener-addr>... ]\n", me);
1416 typedef struct _Args
1422 static Args ArgDetails;
1424 /* name of the executable */
1425 #define SZAPPNAME "server"
1427 /* list of service dependencies - "dep1\0dep2\0\0" */
1428 #define SZDEPENDENCIES ""
1430 int statserv_main(int argc, char **argv,
1431 bend_initresult *(*bend_init)(bend_initrequest *r),
1432 void (*bend_close)(void *handle))
1434 struct statserv_options_block *cb = &control_block;
1435 cb->bend_init = bend_init;
1436 cb->bend_close = bend_close;
1438 /* Lets setup the Arg structure */
1439 ArgDetails.argc = argc;
1440 ArgDetails.argv = argv;
1442 /* Now setup the service with the service controller */
1443 SetupService(argc, argv, &ArgDetails, SZAPPNAME,
1444 cb->service_name, /* internal service name */
1445 cb->service_display_name, /* displayed name */
1450 int StartAppService(void *pHandle, int argc, char **argv)
1452 /* Initializes the App */
1456 void RunAppService(void *pHandle)
1458 Args *pArgs = (Args *)pHandle;
1460 /* Starts the app running */
1461 statserv_start(pArgs->argc, pArgs->argv);
1464 void StopAppService(void *pHandle)
1467 statserv_closedown();
1473 int statserv_main(int argc, char **argv,
1474 bend_initresult *(*bend_init)(bend_initrequest *r),
1475 void (*bend_close)(void *handle))
1479 control_block.bend_init = bend_init;
1480 control_block.bend_close = bend_close;
1482 ret = statserv_start (argc, argv);
1483 statserv_closedown ();