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.38 2006-05-08 10:16:47 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 "none,fatal,warn,log,server,session,request"
89 /* the 'none' clears yaz' own default settings, including [log] */
91 int check_options(int argc, char **argv);
92 statserv_options_block control_block = {
94 0, /* threaded mode */
95 0, /* one shot (single session) */
96 0, /* __UNUSED_loglevel */
98 "", /* diagnostic output to stderr */
99 "tcp:@:9999", /* default listener port */
100 PROTO_Z3950, /* default application protocol */
101 15, /* idle timeout (minutes) */
102 1024*1024, /* maximum PDU size (approx.) to allow */
103 "default-config", /* configuration name to pass to backend */
104 "", /* set user id */
105 0, /* bend_start handler */
106 0, /* bend_stop handler */
107 check_options, /* Default routine, for checking the run-time arguments */
110 0, /* default value for inet deamon */
111 0, /* handle (for service, etc) */
112 0, /* bend_init handle */
113 0, /* bend_close handle */
115 "Z39.50 Server", /* NT Service Name */
116 "Server", /* NT application Name */
117 "", /* NT Service Dependencies */
118 "Z39.50 Server", /* NT Service Display Name */
120 0, /* SOAP handlers */
122 0, /* background daemon */
123 "", /* SSL certificate filename */
124 "" /* XML config filename */
127 static int max_sessions = 0;
129 static int logbits_set = 0;
130 static int log_session = 0;
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_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()
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 = 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()
215 struct gfs_server *n = nmem_malloc(gfs_nmem, sizeof(*n));
216 memcpy(&n->cb, &control_block, sizeof(control_block));
220 n->cql_transform = 0;
221 n->server_node_ptr = 0;
226 n->retrieval = yaz_retrieval_create();
231 static struct gfs_listen * gfs_listen_new(const char *id,
234 struct gfs_listen *n = nmem_malloc(gfs_nmem, sizeof(*n));
236 n->id = nmem_strdup(gfs_nmem, id);
240 n->address = nmem_strdup(gfs_nmem, address);
244 static void gfs_server_chdir(struct gfs_server *gfs)
248 if (chdir(gfs_root_dir))
249 yaz_log(YLOG_WARN|YLOG_ERRNO, "chdir %s", gfs_root_dir);
253 if (chdir(gfs->directory))
254 yaz_log(YLOG_WARN|YLOG_ERRNO, "chdir %s",
259 int control_association(association *assoc, const char *host, int force_open)
261 char vhost[128], *cp;
264 strncpy(vhost, host, 127);
266 cp = strchr(vhost, ':');
272 if (control_block.xml_config[0])
274 struct gfs_server *gfs;
275 for (gfs = gfs_server_list; gfs; gfs = gfs->next)
277 int listen_match = 0;
279 if ( !gfs->host || (host && gfs->host && !strcmp(host, gfs->host)))
281 if (!gfs->listen_ref ||
282 gfs->listen_ref == assoc->client_chan->chan_id)
284 if (listen_match && host_match)
287 (assoc->last_control != &gfs->cb && assoc->backend))
289 statserv_setcontrol(assoc->last_control);
290 if (assoc->backend && assoc->init)
292 gfs_server_chdir(gfs);
293 (assoc->last_control->bend_close)(assoc->backend);
300 assoc->last_control = &gfs->cb;
301 statserv_setcontrol(&gfs->cb);
302 gfs_server_chdir(gfs);
303 yaz_log(YLOG_DEBUG, "server select: %s", gfs->cb.configname);
307 statserv_setcontrol(0);
308 assoc->last_control = 0;
309 yaz_log(YLOG_DEBUG, "server select: no match");
314 statserv_setcontrol(&control_block);
315 assoc->last_control = &control_block;
316 yaz_log(YLOG_DEBUG, "server select: config=%s", control_block.configname);
321 static void xml_config_read()
323 struct gfs_server **gfsp = &gfs_server_list;
324 struct gfs_listen **gfslp = &gfs_listen_list;
326 xmlNodePtr ptr = xml_config_get_root();
330 for (ptr = ptr->children; ptr; ptr = ptr->next)
332 struct _xmlAttr *attr;
333 if (ptr->type != XML_ELEMENT_NODE)
335 attr = ptr->properties;
336 if (!strcmp((const char *) ptr->name, "listen"))
339 <listen id="listenerid">tcp:@:9999</listen>
342 const char *address =
343 nmem_dup_xml_content(gfs_nmem, ptr->children);
344 for ( ; attr; attr = attr->next)
345 if (!xmlStrcmp(attr->name, BAD_CAST "id")
346 && attr->children && attr->children->type == XML_TEXT_NODE)
347 id = nmem_dup_xml_content(gfs_nmem, attr->children);
350 *gfslp = gfs_listen_new(id, address);
351 gfslp = &(*gfslp)->next;
352 *gfslp = 0; /* make listener list consistent for search */
355 else if (!strcmp((const char *) ptr->name, "server"))
357 xmlNodePtr ptr_server = ptr;
359 const char *listenref = 0;
362 for ( ; attr; attr = attr->next)
363 if (!xmlStrcmp(attr->name, BAD_CAST "listenref")
364 && attr->children && attr->children->type == XML_TEXT_NODE)
365 listenref = nmem_dup_xml_content(gfs_nmem, attr->children);
366 else if (!xmlStrcmp(attr->name, BAD_CAST "id")
368 && attr->children->type == XML_TEXT_NODE)
369 id = nmem_dup_xml_content(gfs_nmem, attr->children);
371 yaz_log(YLOG_WARN, "Unknown attribute '%s' for server",
373 *gfsp = gfs_server_new();
374 (*gfsp)->server_node_ptr = ptr_server;
378 struct gfs_listen *gl = gfs_listen_list;
379 for (id_no = 1; gl; gl = gl->next, id_no++)
380 if (gl->id && !strcmp(gl->id, listenref))
382 (*gfsp)->listen_ref = id_no;
386 yaz_log(YLOG_WARN, "Non-existent listenref '%s' in server "
387 "config element", listenref);
389 for (ptr = ptr_server->children; ptr; ptr = ptr->next)
391 if (ptr->type != XML_ELEMENT_NODE)
393 if (!strcmp((const char *) ptr->name, "host"))
395 (*gfsp)->host = nmem_dup_xml_content(gfs_nmem,
398 else if (!strcmp((const char *) ptr->name, "config"))
400 strcpy((*gfsp)->cb.configname,
401 nmem_dup_xml_content(gfs_nmem, ptr->children));
403 else if (!strcmp((const char *) ptr->name, "cql2rpn"))
405 (*gfsp)->cql_transform = cql_transform_open_fname(
406 nmem_dup_xml_content(gfs_nmem, ptr->children)
409 else if (!strcmp((const char *) ptr->name, "directory"))
412 nmem_dup_xml_content(gfs_nmem, ptr->children);
414 else if (!strcmp((const char *) ptr->name, "docpath"))
417 nmem_dup_xml_content(gfs_nmem, ptr->children);
419 else if (!strcmp((const char *) ptr->name, "stylesheet"))
421 char *s = nmem_dup_xml_content(gfs_nmem, ptr->children);
422 (*gfsp)->stylesheet =
423 nmem_malloc(gfs_nmem, strlen(s) + 2);
424 sprintf((*gfsp)->stylesheet, "/%s", s);
426 else if (!strcmp((const char *) ptr->name, "explain"))
428 ; /* being processed separately */
430 else if (!strcmp((const char *) ptr->name, "retrievalinfo"))
432 if (yaz_retrieval_configure((*gfsp)->retrieval, ptr))
434 yaz_log(YLOG_FATAL, "%s in config %s",
435 yaz_retrieval_get_error((*gfsp)->retrieval),
436 control_block.xml_config);
442 yaz_log(YLOG_FATAL, "Unknown element '%s' in config %s",
443 ptr->name, control_block.xml_config);
447 gfsp = &(*gfsp)->next;
454 static void xml_config_open()
456 if (!getcwd(gfs_root_dir, FILENAME_MAX))
458 yaz_log(YLOG_WARN|YLOG_ERRNO, "getcwd failed");
459 gfs_root_dir[0] = '\0';
462 init_control_tls = 1;
463 current_control_tls = TlsAlloc();
464 #elif YAZ_POSIX_THREADS
465 init_control_tls = 1;
466 pthread_key_create(¤t_control_tls, 0);
469 gfs_nmem = nmem_create();
471 if (control_block.xml_config[0] == '\0')
476 xml_config_doc = xmlParseFile(control_block.xml_config);
479 yaz_log(YLOG_FATAL, "Could not parse %s", control_block.xml_config);
484 int noSubstitutions = xmlXIncludeProcess(xml_config_doc);
485 if (noSubstitutions == -1)
487 yaz_log(YLOG_WARN, "XInclude processing failed for config %s",
488 control_block.xml_config);
497 static void xml_config_close()
502 xmlFreeDoc(xml_config_doc);
507 nmem_destroy(gfs_nmem);
509 if (init_control_tls)
510 TlsFree(current_control_tls);
511 #elif YAZ_POSIX_THREADS
512 if (init_control_tls)
513 pthread_key_delete(current_control_tls);
517 static void xml_config_add_listeners()
519 struct gfs_listen *gfs = gfs_listen_list;
522 for (id_no = 1; gfs; gfs = gfs->next, id_no++)
525 add_listener(gfs->address, id_no);
529 static void xml_config_bend_start()
531 if (control_block.xml_config[0])
533 struct gfs_server *gfs = gfs_server_list;
534 for (; gfs; gfs = gfs->next)
536 yaz_log(YLOG_DEBUG, "xml_config_bend_start config=%s",
538 statserv_setcontrol(&gfs->cb);
539 if (control_block.bend_start)
541 gfs_server_chdir(gfs);
542 (control_block.bend_start)(&gfs->cb);
548 yaz_log(YLOG_DEBUG, "xml_config_bend_start default config");
549 statserv_setcontrol(&control_block);
550 if (control_block.bend_start)
551 (*control_block.bend_start)(&control_block);
555 static void xml_config_bend_stop()
557 if (control_block.xml_config[0])
559 struct gfs_server *gfs = gfs_server_list;
560 for (; gfs; gfs = gfs->next)
562 yaz_log(YLOG_DEBUG, "xml_config_bend_stop config=%s",
564 statserv_setcontrol(&gfs->cb);
565 if (control_block.bend_stop)
566 (control_block.bend_stop)(&gfs->cb);
571 yaz_log(YLOG_DEBUG, "xml_config_bend_stop default config");
572 statserv_setcontrol(&control_block);
573 if (control_block.bend_stop)
574 (*control_block.bend_stop)(&control_block);
579 * handle incoming connect requests.
580 * The dynamic mode is a bit tricky mostly because we want to avoid
581 * doing all of the listening and accepting in the parent - it's
586 typedef struct _ThreadList ThreadList;
595 static ThreadList *pFirstThread;
596 static CRITICAL_SECTION Thread_CritSect;
597 static BOOL bInitialized = FALSE;
599 static void ThreadList_Initialize()
601 /* Initialize the critical Sections */
602 InitializeCriticalSection(&Thread_CritSect);
604 /* Set the first thraed */
607 /* we have been initialized */
611 static void statserv_add(HANDLE hThread, IOCHAN pIOChannel)
613 /* Only one thread can go through this section at a time */
614 EnterCriticalSection(&Thread_CritSect);
617 /* Lets create our new object */
618 ThreadList *pNewThread = (ThreadList *)malloc(sizeof(ThreadList));
619 pNewThread->hThread = hThread;
620 pNewThread->pIOChannel = pIOChannel;
621 pNewThread->pNext = pFirstThread;
622 pFirstThread = pNewThread;
624 /* Lets let somebody else create a new object now */
625 LeaveCriticalSection(&Thread_CritSect);
629 void statserv_remove(IOCHAN pIOChannel)
631 /* Only one thread can go through this section at a time */
632 EnterCriticalSection(&Thread_CritSect);
635 ThreadList *pCurrentThread = pFirstThread;
636 ThreadList *pNextThread;
637 ThreadList *pPrevThread =NULL;
639 /* Step through all the threads */
640 for (; pCurrentThread != NULL; pCurrentThread = pNextThread)
642 /* We only need to compare on the IO Channel */
643 if (pCurrentThread->pIOChannel == pIOChannel)
645 /* We have found the thread we want to delete */
646 /* First of all reset the next pointers */
647 if (pPrevThread == NULL)
648 pFirstThread = pCurrentThread->pNext;
650 pPrevThread->pNext = pCurrentThread->pNext;
652 /* All we need todo now is delete the memory */
653 free(pCurrentThread);
655 /* No need to look at any more threads */
660 /* We need to look at another thread */
661 pNextThread = pCurrentThread->pNext;
662 pPrevThread = pCurrentThread;
666 /* Lets let somebody else remove an object now */
667 LeaveCriticalSection(&Thread_CritSect);
671 /* WIN32 statserv_closedown */
672 void statserv_closedown()
674 /* Shouldn't do anything if we are not initialized */
678 HANDLE *pThreadHandles = NULL;
680 /* We need to stop threads adding and removing while we */
681 /* start the closedown process */
682 EnterCriticalSection(&Thread_CritSect);
685 /* We have exclusive access to the thread stuff now */
686 /* Y didn't i use a semaphore - Oh well never mind */
687 ThreadList *pCurrentThread = pFirstThread;
689 /* Before we do anything else, we need to shutdown the listener */
690 if (pListener != NULL)
691 iochan_destroy(pListener);
693 for (; pCurrentThread != NULL; pCurrentThread = pCurrentThread->pNext)
695 /* Just destroy the IOCHAN, that should do the trick */
696 iochan_destroy(pCurrentThread->pIOChannel);
697 closesocket(pCurrentThread->pIOChannel->fd);
699 /* Keep a running count of our handles */
705 HANDLE *pCurrentHandle ;
707 /* Allocate the thread handle array */
708 pThreadHandles = (HANDLE *)malloc(sizeof(HANDLE) * iHandles);
709 pCurrentHandle = pThreadHandles;
711 for (pCurrentThread = pFirstThread;
712 pCurrentThread != NULL;
713 pCurrentThread = pCurrentThread->pNext, pCurrentHandle++)
715 /* Just the handle */
716 *pCurrentHandle = pCurrentThread->hThread;
720 /* We can now leave the critical section */
721 LeaveCriticalSection(&Thread_CritSect);
724 /* Now we can really do something */
727 yaz_log(log_server, "waiting for %d to die", iHandles);
728 /* This will now wait, until all the threads close */
729 WaitForMultipleObjects(iHandles, pThreadHandles, TRUE, INFINITE);
731 /* Free the memory we allocated for the handle array */
732 free(pThreadHandles);
735 xml_config_bend_stop();
736 /* No longer require the critical section, since all threads are dead */
737 DeleteCriticalSection(&Thread_CritSect);
742 void __cdecl event_loop_thread (IOCHAN iochan)
744 event_loop (&iochan);
748 static void listener(IOCHAN h, int event)
750 COMSTACK line = (COMSTACK) iochan_getdata(h);
751 IOCHAN parent_chan = line->user;
756 if (event == EVENT_INPUT)
758 if ((res = cs_listen(line, 0, 0)) < 0)
760 yaz_log(YLOG_FATAL, "cs_listen failed");
765 yaz_log(YLOG_DEBUG, "listen ok");
766 iochan_setevent(h, EVENT_OUTPUT);
767 iochan_setflags(h, EVENT_OUTPUT | EVENT_EXCEPT); /* set up for acpt */
769 else if (event == EVENT_OUTPUT)
771 COMSTACK new_line = cs_accept(line);
777 yaz_log(YLOG_FATAL, "Accept failed.");
778 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT);
781 yaz_log(YLOG_DEBUG, "Accept ok");
783 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session,
784 EVENT_INPUT, parent_chan->chan_id)))
786 yaz_log(YLOG_FATAL, "Failed to create iochan");
791 yaz_log(YLOG_DEBUG, "Creating association");
792 if (!(newas = create_association(new_chan, new_line,
793 control_block.apdufile)))
795 yaz_log(YLOG_FATAL, "Failed to create new assoc.");
799 newas->cs_get_mask = EVENT_INPUT;
800 newas->cs_put_mask = 0;
801 newas->cs_accept_mask = 0;
803 yaz_log(YLOG_DEBUG, "Setting timeout %d", control_block.idle_timeout);
804 iochan_setdata(new_chan, newas);
805 iochan_settimeout(new_chan, 60);
807 /* Now what we need todo is create a new thread with this iochan as
809 newHandle = (HANDLE) _beginthread(event_loop_thread, 0, new_chan);
810 if (newHandle == (HANDLE) -1)
813 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create new thread.");
817 /* We successfully created the thread, so add it to the list */
818 statserv_add(newHandle, new_chan);
820 yaz_log(YLOG_DEBUG, "Created new thread, id = %ld iochan %p",(long) newHandle, new_chan);
821 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
825 yaz_log(YLOG_FATAL, "Bad event on listener.");
831 int statserv_must_terminate(void)
838 static int term_flag = 0;
839 /* To save having an #ifdef in event_loop we need to
840 define this empty function
842 int statserv_must_terminate(void)
847 void statserv_remove(IOCHAN pIOChannel)
851 void statserv_closedown()
855 xml_config_bend_stop();
856 for (p = pListener; p; p = p->next)
863 void sigterm(int sig)
868 static void *new_session (void *vp);
869 static int no_sessions = 0;
872 static void listener(IOCHAN h, int event)
874 COMSTACK line = (COMSTACK) iochan_getdata(h);
877 if (event == EVENT_INPUT)
880 if ((res = cs_listen_check(line, 0, 0, control_block.check_ip,
881 control_block.daemon_name)) < 0)
883 yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_listen failed");
888 yaz_log(YLOG_WARN, "cs_listen incomplete");
891 new_line = cs_accept(line);
894 yaz_log(YLOG_FATAL, "Accept failed.");
895 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
899 yaz_log(log_session, "Connect from %s", cs_addrstr(new_line));
902 if (control_block.dynamic)
904 if ((res = fork()) < 0)
906 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fork");
910 else if (res == 0) /* child */
915 for (pp = pListener; pp; pp = iochan_getnext(pp))
917 COMSTACK l = (COMSTACK)iochan_getdata(pp);
921 sprintf(nbuf, "%s(%d)", me, no_sessions);
922 yaz_log_init_prefix(nbuf);
923 /* ensure that bend_stop is not called when each child exits -
924 only for the main process .. */
925 control_block.bend_stop = 0;
934 if (control_block.threads)
936 #if YAZ_POSIX_THREADS
937 pthread_t child_thread;
938 pthread_create (&child_thread, 0, new_session, new_line);
939 pthread_detach (child_thread);
940 #elif YAZ_GNU_THREADS
944 attr = pth_attr_new ();
945 pth_attr_set (attr, PTH_ATTR_JOINABLE, FALSE);
946 pth_attr_set (attr, PTH_ATTR_STACK_SIZE, 32*1024);
947 pth_attr_set (attr, PTH_ATTR_NAME, "session");
948 yaz_log (YLOG_DEBUG, "pth_spawn begin");
949 child_thread = pth_spawn (attr, new_session, new_line);
950 yaz_log (YLOG_DEBUG, "pth_spawn finish");
951 pth_attr_destroy (attr);
953 new_session(new_line);
957 new_session(new_line);
959 else if (event == EVENT_TIMEOUT)
961 yaz_log(log_server, "Shutting down listener.");
966 yaz_log(YLOG_FATAL, "Bad event on listener.");
971 static void *new_session (void *vp)
976 COMSTACK new_line = (COMSTACK) vp;
977 IOCHAN parent_chan = new_line->user;
979 unsigned cs_get_mask, cs_accept_mask, mask =
980 ((new_line->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
981 ((new_line->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
985 cs_accept_mask = mask; /* accept didn't complete */
990 cs_accept_mask = 0; /* accept completed. */
991 cs_get_mask = mask = EVENT_INPUT;
994 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session, mask,
995 parent_chan->chan_id)))
997 yaz_log(YLOG_FATAL, "Failed to create iochan");
1000 if (!(newas = create_association(new_chan, new_line,
1001 control_block.apdufile)))
1003 yaz_log(YLOG_FATAL, "Failed to create new assoc.");
1006 newas->cs_accept_mask = cs_accept_mask;
1007 newas->cs_get_mask = cs_get_mask;
1009 iochan_setdata(new_chan, newas);
1010 iochan_settimeout(new_chan, 60);
1012 a = cs_addrstr(new_line);
1016 yaz_log(log_session, "Starting session %d from %s (pid=%ld)",
1017 no_sessions, a ? a : "[Unknown]", (long) getpid());
1018 if (max_sessions && no_sessions >= max_sessions)
1019 control_block.one_shot = 1;
1020 if (control_block.threads)
1022 event_loop(&new_chan);
1026 new_chan->next = pListener;
1027 pListener = new_chan;
1035 static void inetd_connection(int what)
1042 if ((line = cs_createbysocket(0, tcpip_type, 0, what)))
1044 if ((chan = iochan_create(cs_fileno(line), ir_session, EVENT_INPUT,
1047 if ((assoc = create_association(chan, line,
1048 control_block.apdufile)))
1050 iochan_setdata(chan, assoc);
1051 iochan_settimeout(chan, 60);
1052 addr = cs_addrstr(line);
1053 yaz_log(log_session, "Inetd association from %s",
1054 addr ? addr : "[UNKNOWN]");
1055 assoc->cs_get_mask = EVENT_INPUT;
1059 yaz_log(YLOG_FATAL, "Failed to create association structure");
1061 chan->next = pListener;
1066 yaz_log(YLOG_FATAL, "Failed to create iochan");
1071 yaz_log(YLOG_ERRNO|YLOG_FATAL, "Failed to create comstack on socket 0");
1076 * Set up a listening endpoint, and give it to the event-handler.
1078 static int add_listener(char *where, int listen_id)
1085 if (control_block.dynamic)
1087 else if (control_block.threads)
1092 yaz_log(log_server, "Adding %s listener on %s id=%d", mode, where,
1095 l = cs_create_host(where, 2, &ap);
1098 yaz_log(YLOG_FATAL, "Failed to listen on %s", where);
1101 if (*control_block.cert_fname)
1102 cs_set_ssl_certificate_file(l, control_block.cert_fname);
1104 if (cs_bind(l, ap, CS_SERVER) < 0)
1106 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to bind to %s", where);
1110 if (!(lst = iochan_create(cs_fileno(l), listener, EVENT_INPUT |
1111 EVENT_EXCEPT, listen_id)))
1113 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create IOCHAN-type");
1117 iochan_setdata(lst, l); /* user-defined data for listener is COMSTACK */
1118 l->user = lst; /* user-defined data for COMSTACK is listener chan */
1120 /* Add listener to chain */
1121 lst->next = pListener;
1127 /* UNIX only (for windows we don't need to catch the signals) */
1128 static void catchchld(int num)
1130 while (waitpid(-1, 0, WNOHANG) > 0)
1132 signal(SIGCHLD, catchchld);
1136 statserv_options_block *statserv_getcontrol(void)
1139 if (init_control_tls)
1140 return (statserv_options_block *) TlsGetValue(current_control_tls);
1142 return &control_block;
1143 #elif YAZ_POSIX_THREADS
1144 if (init_control_tls)
1145 return pthread_getspecific(current_control_tls);
1147 return &control_block;
1149 if (current_control_block)
1150 return current_control_block;
1151 return &control_block;
1155 void statserv_setcontrol(statserv_options_block *block)
1157 chdir(gfs_root_dir);
1159 if (init_control_tls)
1160 TlsSetValue(current_control_tls, block);
1161 #elif YAZ_POSIX_THREADS
1162 if (init_control_tls)
1163 pthread_setspecific(current_control_tls, block);
1165 current_control_block = block;
1169 static void statserv_reset(void)
1173 int statserv_start(int argc, char **argv)
1177 /* We need to initialize the thread list */
1178 ThreadList_Initialize();
1188 if ((me = strrchr (argv[0], sep)))
1189 me++; /* get the basename */
1192 programname = argv[0];
1194 if (control_block.options_func(argc, argv))
1199 xml_config_bend_start();
1202 xml_config_add_listeners();
1204 yaz_log (log_server, "Starting server %s", me);
1205 if (!pListener && *control_block.default_listen)
1206 add_listener(control_block.default_listen, 0);
1209 if (control_block.inetd)
1210 inetd_connection(control_block.default_proto);
1214 if (control_block.background)
1216 /* create pipe so that parent waits until child has created
1220 yaz_log(YLOG_FATAL|YLOG_ERRNO, "pipe");
1234 int res = read(hand[0], dummy, 1);
1235 if (res < 0 && yaz_errno() != EINTR)
1237 yaz_log(YLOG_FATAL|YLOG_ERRNO, "read fork handshake");
1254 open("/dev/null", O_RDWR);
1257 xml_config_add_listeners();
1259 if (!pListener && *control_block.default_listen)
1260 add_listener(control_block.default_listen, 0);
1265 if (*control_block.pid_fname)
1267 FILE *f = fopen(control_block.pid_fname, "w");
1270 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Couldn't create %s",
1271 control_block.pid_fname);
1274 fprintf(f, "%ld", (long) getpid());
1278 if (control_block.background)
1282 yaz_log (log_server, "Starting server %s pid=%ld", programname,
1285 sigset_t sigs_to_block;
1287 sigemptyset(&sigs_to_block);
1288 sigaddset (&sigs_to_block, SIGTERM);
1289 pthread_sigmask (SIG_BLOCK, &sigs_to_block, 0);
1292 if (control_block.dynamic)
1293 signal(SIGCHLD, catchchld);
1295 signal (SIGPIPE, SIG_IGN);
1296 signal (SIGTERM, sigterm);
1297 if (*control_block.setuid)
1301 if (!(pw = getpwnam(control_block.setuid)))
1303 yaz_log(YLOG_FATAL, "%s: Unknown user", control_block.setuid);
1306 if (setuid(pw->pw_uid) < 0)
1308 yaz_log(YLOG_FATAL|YLOG_ERRNO, "setuid");
1314 if (pListener == NULL)
1316 yaz_log(YLOG_DEBUG, "Entering event loop.");
1317 return event_loop(&pListener);
1320 static void option_copy(char *dst, const char *src)
1322 strncpy(dst, src ? src : "", 127);
1326 int check_options(int argc, char **argv)
1331 if (getenv("YAZ_LOG") == 0) {
1333 * Set default log level. We want to avoid doing this if the
1334 * user has already explicitly specified a preferred default
1335 * log-level, hence the inelegant peek at the YAZ_LOG
1336 * environment variable that will subsequently be interpreted
1337 * by the YAZ logging module itself.
1339 yaz_log_init_level(yaz_log_mask_str(STAT_DEFAULT_LOG_LEVEL));
1343 while ((ret = options("1a:iszSTl:v:u:c:w:t:k:d:A:p:DC:f:m:",
1344 argv, argc, &arg)) != -2)
1349 if (add_listener(arg, 0))
1350 return 1; /* failed to create listener */
1353 control_block.one_shot = 1;
1354 control_block.dynamic = 0;
1357 control_block.default_proto = PROTO_Z3950;
1360 fprintf (stderr, "%s: SR protocol no longer supported\n", me);
1364 control_block.dynamic = 0;
1367 #if YAZ_POSIX_THREADS
1368 control_block.dynamic = 0;
1369 control_block.threads = 1;
1370 #elif YAZ_GNU_THREADS
1371 control_block.dynamic = 0;
1372 control_block.threads = 1;
1374 fprintf(stderr, "%s: Threaded mode not available.\n", me);
1379 option_copy(control_block.logfile, arg);
1380 yaz_log_init_file(control_block.logfile);
1384 fprintf(stderr, "%s: Specify time format for log file.\n", me);
1387 yaz_log_time_format(arg);
1390 int default_level = yaz_log_mask_str(STAT_DEFAULT_LOG_LEVEL);
1391 yaz_log_init_level(yaz_log_mask_str_x(arg, default_level));
1396 option_copy(control_block.apdufile, arg);
1399 option_copy(control_block.setuid, arg);
1402 option_copy(control_block.configname, arg);
1405 option_copy(control_block.cert_fname, arg);
1408 option_copy(control_block.daemon_name, arg);
1411 if (!arg || !(r = atoi(arg)))
1413 fprintf(stderr, "%s: Specify positive timeout for -t.\n", me);
1416 control_block.idle_timeout = r;
1419 if (!arg || !(r = atoi(arg)))
1421 fprintf(stderr, "%s: Specify positive size for -k.\n", me);
1424 control_block.maxrecordsize = r * 1024;
1427 control_block.inetd = 1;
1437 max_sessions = atoi(arg);
1440 option_copy(control_block.pid_fname, arg);
1444 option_copy(control_block.xml_config, arg);
1446 fprintf(stderr, "%s: Option -f unsupported since YAZ is compiled without Libxml2 support\n", me);
1451 control_block.background = 1;
1454 fprintf(stderr, "Usage: %s [ -a <pdufile> -v <loglevel>"
1455 " -l <logfile> -u <user> -c <config> -t <minutes>"
1456 " -k <kilobytes> -d <daemon> -p <pidfile> -C certfile"
1457 " -ziDST1 -m <time-format> -w <directory> <listener-addr>... ]\n", me);
1465 typedef struct _Args
1471 static Args ArgDetails;
1473 /* name of the executable */
1474 #define SZAPPNAME "server"
1476 /* list of service dependencies - "dep1\0dep2\0\0" */
1477 #define SZDEPENDENCIES ""
1479 int statserv_main(int argc, char **argv,
1480 bend_initresult *(*bend_init)(bend_initrequest *r),
1481 void (*bend_close)(void *handle))
1483 struct statserv_options_block *cb = &control_block;
1484 cb->bend_init = bend_init;
1485 cb->bend_close = bend_close;
1487 /* Lets setup the Arg structure */
1488 ArgDetails.argc = argc;
1489 ArgDetails.argv = argv;
1491 /* Now setup the service with the service controller */
1492 SetupService(argc, argv, &ArgDetails, SZAPPNAME,
1493 cb->service_name, /* internal service name */
1494 cb->service_display_name, /* displayed name */
1499 int StartAppService(void *pHandle, int argc, char **argv)
1501 /* Initializes the App */
1505 void RunAppService(void *pHandle)
1507 Args *pArgs = (Args *)pHandle;
1509 /* Starts the app running */
1510 statserv_start(pArgs->argc, pArgs->argv);
1513 void StopAppService(void *pHandle)
1516 statserv_closedown();
1522 int statserv_main(int argc, char **argv,
1523 bend_initresult *(*bend_init)(bend_initrequest *r),
1524 void (*bend_close)(void *handle))
1528 control_block.bend_init = bend_init;
1529 control_block.bend_close = bend_close;
1531 ret = statserv_start (argc, argv);
1532 statserv_closedown ();
1540 * indent-tabs-mode: nil
1542 * vim: shiftwidth=4 tabstop=8 expandtab