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.36 2006-03-22 17:58:32 mike 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;
228 static struct gfs_listen * gfs_listen_new(const char *id,
231 struct gfs_listen *n = nmem_malloc(gfs_nmem, sizeof(*n));
233 n->id = nmem_strdup(gfs_nmem, id);
237 n->address = nmem_strdup(gfs_nmem, address);
241 static void gfs_server_chdir(struct gfs_server *gfs)
245 if (chdir(gfs_root_dir))
246 yaz_log(YLOG_WARN|YLOG_ERRNO, "chdir %s", gfs_root_dir);
250 if (chdir(gfs->directory))
251 yaz_log(YLOG_WARN|YLOG_ERRNO, "chdir %s",
256 int control_association(association *assoc, const char *host, int force_open)
258 char vhost[128], *cp;
261 strncpy(vhost, host, 127);
263 cp = strchr(vhost, ':');
268 assoc->cql_transform = 0;
269 assoc->server_node_ptr = 0;
271 assoc->stylesheet = 0;
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);
299 assoc->docpath = gfs->docpath;
300 assoc->stylesheet = gfs->stylesheet;
301 assoc->cql_transform = gfs->cql_transform;
302 assoc->server_node_ptr = gfs->server_node_ptr;
303 assoc->last_control = &gfs->cb;
304 statserv_setcontrol(&gfs->cb);
305 gfs_server_chdir(gfs);
306 yaz_log(YLOG_DEBUG, "server select: %s", gfs->cb.configname);
310 statserv_setcontrol(0);
311 assoc->last_control = 0;
312 yaz_log(YLOG_DEBUG, "server select: no match");
317 statserv_setcontrol(&control_block);
318 assoc->last_control = &control_block;
319 yaz_log(YLOG_DEBUG, "server select: config=%s", control_block.configname);
324 static void xml_config_read()
326 struct gfs_server **gfsp = &gfs_server_list;
327 struct gfs_listen **gfslp = &gfs_listen_list;
329 xmlNodePtr ptr = xml_config_get_root();
333 for (ptr = ptr->children; ptr; ptr = ptr->next)
335 struct _xmlAttr *attr;
336 if (ptr->type != XML_ELEMENT_NODE)
338 attr = ptr->properties;
339 if (!strcmp((const char *) ptr->name, "listen"))
342 <listen id="listenerid">tcp:@:9999</listen>
345 const char *address =
346 nmem_dup_xml_content(gfs_nmem, ptr->children);
347 for ( ; attr; attr = attr->next)
348 if (!xmlStrcmp(attr->name, BAD_CAST "id")
349 && attr->children && attr->children->type == XML_TEXT_NODE)
350 id = nmem_dup_xml_content(gfs_nmem, attr->children);
353 *gfslp = gfs_listen_new(id, address);
354 gfslp = &(*gfslp)->next;
355 *gfslp = 0; /* make listener list consistent for search */
358 else if (!strcmp((const char *) ptr->name, "server"))
360 xmlNodePtr ptr_server = ptr;
362 const char *listenref = 0;
365 for ( ; attr; attr = attr->next)
366 if (!xmlStrcmp(attr->name, BAD_CAST "listenref")
367 && attr->children && attr->children->type == XML_TEXT_NODE)
368 listenref = nmem_dup_xml_content(gfs_nmem, attr->children);
369 else if (!xmlStrcmp(attr->name, BAD_CAST "id")
371 && attr->children->type == XML_TEXT_NODE)
372 id = nmem_dup_xml_content(gfs_nmem, attr->children);
374 yaz_log(YLOG_WARN, "Unknown attribute '%s' for server",
376 *gfsp = gfs_server_new();
377 (*gfsp)->server_node_ptr = ptr_server;
381 struct gfs_listen *gl = gfs_listen_list;
382 for (id_no = 1; gl; gl = gl->next, id_no++)
383 if (gl->id && !strcmp(gl->id, listenref))
385 (*gfsp)->listen_ref = id_no;
389 yaz_log(YLOG_WARN, "Non-existent listenref '%s' in server "
390 "config element", listenref);
392 for (ptr = ptr_server->children; ptr; ptr = ptr->next)
394 if (ptr->type != XML_ELEMENT_NODE)
396 if (!strcmp((const char *) ptr->name, "host"))
398 (*gfsp)->host = nmem_dup_xml_content(gfs_nmem,
401 else if (!strcmp((const char *) ptr->name, "config"))
403 strcpy((*gfsp)->cb.configname,
404 nmem_dup_xml_content(gfs_nmem, ptr->children));
406 else if (!strcmp((const char *) ptr->name, "cql2rpn"))
408 (*gfsp)->cql_transform = cql_transform_open_fname(
409 nmem_dup_xml_content(gfs_nmem, ptr->children)
412 else if (!strcmp((const char *) ptr->name, "directory"))
415 nmem_dup_xml_content(gfs_nmem, ptr->children);
417 else if (!strcmp((const char *) ptr->name, "docpath"))
420 nmem_dup_xml_content(gfs_nmem, ptr->children);
422 else if (!strcmp((const char *) ptr->name, "stylesheet"))
424 char *s = nmem_dup_xml_content(gfs_nmem, ptr->children);
425 (*gfsp)->stylesheet =
426 nmem_malloc(gfs_nmem, strlen(s) + 2);
427 sprintf((*gfsp)->stylesheet, "/%s", s);
429 else if (!strcmp((const char *) ptr->name, "explain"))
431 ; /* being processed separately */
435 yaz_log(YLOG_FATAL, "Unknown element '%s' in config %s",
436 ptr->name, control_block.xml_config);
440 gfsp = &(*gfsp)->next;
447 static void xml_config_open()
449 if (!getcwd(gfs_root_dir, FILENAME_MAX))
451 yaz_log(YLOG_WARN|YLOG_ERRNO, "getcwd failed");
452 gfs_root_dir[0] = '\0';
455 init_control_tls = 1;
456 current_control_tls = TlsAlloc();
457 #elif YAZ_POSIX_THREADS
458 init_control_tls = 1;
459 pthread_key_create(¤t_control_tls, 0);
462 gfs_nmem = nmem_create();
464 if (control_block.xml_config[0] == '\0')
469 xml_config_doc = xmlParseFile(control_block.xml_config);
472 yaz_log(YLOG_FATAL, "Could not parse %s", control_block.xml_config);
477 int noSubstitutions = xmlXIncludeProcess(xml_config_doc);
478 if (noSubstitutions == -1)
480 yaz_log(YLOG_WARN, "XInclude processing failed for config %s",
481 control_block.xml_config);
490 static void xml_config_close()
495 xmlFreeDoc(xml_config_doc);
500 nmem_destroy(gfs_nmem);
502 if (init_control_tls)
503 TlsFree(current_control_tls);
504 #elif YAZ_POSIX_THREADS
505 if (init_control_tls)
506 pthread_key_delete(current_control_tls);
510 static void xml_config_add_listeners()
512 struct gfs_listen *gfs = gfs_listen_list;
515 for (id_no = 1; gfs; gfs = gfs->next, id_no++)
518 add_listener(gfs->address, id_no);
522 static void xml_config_bend_start()
524 if (control_block.xml_config[0])
526 struct gfs_server *gfs = gfs_server_list;
527 for (; gfs; gfs = gfs->next)
529 yaz_log(YLOG_DEBUG, "xml_config_bend_start config=%s",
531 statserv_setcontrol(&gfs->cb);
532 if (control_block.bend_start)
534 gfs_server_chdir(gfs);
535 (control_block.bend_start)(&gfs->cb);
541 yaz_log(YLOG_DEBUG, "xml_config_bend_start default config");
542 statserv_setcontrol(&control_block);
543 if (control_block.bend_start)
544 (*control_block.bend_start)(&control_block);
548 static void xml_config_bend_stop()
550 if (control_block.xml_config[0])
552 struct gfs_server *gfs = gfs_server_list;
553 for (; gfs; gfs = gfs->next)
555 yaz_log(YLOG_DEBUG, "xml_config_bend_stop config=%s",
557 statserv_setcontrol(&gfs->cb);
558 if (control_block.bend_stop)
559 (control_block.bend_stop)(&gfs->cb);
564 yaz_log(YLOG_DEBUG, "xml_config_bend_stop default config");
565 statserv_setcontrol(&control_block);
566 if (control_block.bend_stop)
567 (*control_block.bend_stop)(&control_block);
572 * handle incoming connect requests.
573 * The dynamic mode is a bit tricky mostly because we want to avoid
574 * doing all of the listening and accepting in the parent - it's
579 typedef struct _ThreadList ThreadList;
588 static ThreadList *pFirstThread;
589 static CRITICAL_SECTION Thread_CritSect;
590 static BOOL bInitialized = FALSE;
592 static void ThreadList_Initialize()
594 /* Initialize the critical Sections */
595 InitializeCriticalSection(&Thread_CritSect);
597 /* Set the first thraed */
600 /* we have been initialized */
604 static void statserv_add(HANDLE hThread, IOCHAN pIOChannel)
606 /* Only one thread can go through this section at a time */
607 EnterCriticalSection(&Thread_CritSect);
610 /* Lets create our new object */
611 ThreadList *pNewThread = (ThreadList *)malloc(sizeof(ThreadList));
612 pNewThread->hThread = hThread;
613 pNewThread->pIOChannel = pIOChannel;
614 pNewThread->pNext = pFirstThread;
615 pFirstThread = pNewThread;
617 /* Lets let somebody else create a new object now */
618 LeaveCriticalSection(&Thread_CritSect);
622 void statserv_remove(IOCHAN pIOChannel)
624 /* Only one thread can go through this section at a time */
625 EnterCriticalSection(&Thread_CritSect);
628 ThreadList *pCurrentThread = pFirstThread;
629 ThreadList *pNextThread;
630 ThreadList *pPrevThread =NULL;
632 /* Step through all the threads */
633 for (; pCurrentThread != NULL; pCurrentThread = pNextThread)
635 /* We only need to compare on the IO Channel */
636 if (pCurrentThread->pIOChannel == pIOChannel)
638 /* We have found the thread we want to delete */
639 /* First of all reset the next pointers */
640 if (pPrevThread == NULL)
641 pFirstThread = pCurrentThread->pNext;
643 pPrevThread->pNext = pCurrentThread->pNext;
645 /* All we need todo now is delete the memory */
646 free(pCurrentThread);
648 /* No need to look at any more threads */
653 /* We need to look at another thread */
654 pNextThread = pCurrentThread->pNext;
655 pPrevThread = pCurrentThread;
659 /* Lets let somebody else remove an object now */
660 LeaveCriticalSection(&Thread_CritSect);
664 /* WIN32 statserv_closedown */
665 void statserv_closedown()
667 /* Shouldn't do anything if we are not initialized */
671 HANDLE *pThreadHandles = NULL;
673 /* We need to stop threads adding and removing while we */
674 /* start the closedown process */
675 EnterCriticalSection(&Thread_CritSect);
678 /* We have exclusive access to the thread stuff now */
679 /* Y didn't i use a semaphore - Oh well never mind */
680 ThreadList *pCurrentThread = pFirstThread;
682 /* Before we do anything else, we need to shutdown the listener */
683 if (pListener != NULL)
684 iochan_destroy(pListener);
686 for (; pCurrentThread != NULL; pCurrentThread = pCurrentThread->pNext)
688 /* Just destroy the IOCHAN, that should do the trick */
689 iochan_destroy(pCurrentThread->pIOChannel);
690 closesocket(pCurrentThread->pIOChannel->fd);
692 /* Keep a running count of our handles */
698 HANDLE *pCurrentHandle ;
700 /* Allocate the thread handle array */
701 pThreadHandles = (HANDLE *)malloc(sizeof(HANDLE) * iHandles);
702 pCurrentHandle = pThreadHandles;
704 for (pCurrentThread = pFirstThread;
705 pCurrentThread != NULL;
706 pCurrentThread = pCurrentThread->pNext, pCurrentHandle++)
708 /* Just the handle */
709 *pCurrentHandle = pCurrentThread->hThread;
713 /* We can now leave the critical section */
714 LeaveCriticalSection(&Thread_CritSect);
717 /* Now we can really do something */
720 yaz_log(log_server, "waiting for %d to die", iHandles);
721 /* This will now wait, until all the threads close */
722 WaitForMultipleObjects(iHandles, pThreadHandles, TRUE, INFINITE);
724 /* Free the memory we allocated for the handle array */
725 free(pThreadHandles);
728 xml_config_bend_stop();
729 /* No longer require the critical section, since all threads are dead */
730 DeleteCriticalSection(&Thread_CritSect);
735 void __cdecl event_loop_thread (IOCHAN iochan)
737 event_loop (&iochan);
741 static void listener(IOCHAN h, int event)
743 COMSTACK line = (COMSTACK) iochan_getdata(h);
744 IOCHAN parent_chan = line->user;
749 if (event == EVENT_INPUT)
751 if ((res = cs_listen(line, 0, 0)) < 0)
753 yaz_log(YLOG_FATAL, "cs_listen failed");
758 yaz_log(YLOG_DEBUG, "listen ok");
759 iochan_setevent(h, EVENT_OUTPUT);
760 iochan_setflags(h, EVENT_OUTPUT | EVENT_EXCEPT); /* set up for acpt */
762 else if (event == EVENT_OUTPUT)
764 COMSTACK new_line = cs_accept(line);
770 yaz_log(YLOG_FATAL, "Accept failed.");
771 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT);
774 yaz_log(YLOG_DEBUG, "Accept ok");
776 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session,
777 EVENT_INPUT, parent_chan->chan_id)))
779 yaz_log(YLOG_FATAL, "Failed to create iochan");
784 yaz_log(YLOG_DEBUG, "Creating association");
785 if (!(newas = create_association(new_chan, new_line,
786 control_block.apdufile)))
788 yaz_log(YLOG_FATAL, "Failed to create new assoc.");
792 newas->cs_get_mask = EVENT_INPUT;
793 newas->cs_put_mask = 0;
794 newas->cs_accept_mask = 0;
796 yaz_log(YLOG_DEBUG, "Setting timeout %d", control_block.idle_timeout);
797 iochan_setdata(new_chan, newas);
798 iochan_settimeout(new_chan, 60);
800 /* Now what we need todo is create a new thread with this iochan as
802 newHandle = (HANDLE) _beginthread(event_loop_thread, 0, new_chan);
803 if (newHandle == (HANDLE) -1)
806 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create new thread.");
810 /* We successfully created the thread, so add it to the list */
811 statserv_add(newHandle, new_chan);
813 yaz_log(YLOG_DEBUG, "Created new thread, id = %ld iochan %p",(long) newHandle, new_chan);
814 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
818 yaz_log(YLOG_FATAL, "Bad event on listener.");
824 int statserv_must_terminate(void)
831 static int term_flag = 0;
832 /* To save having an #ifdef in event_loop we need to
833 define this empty function
835 int statserv_must_terminate(void)
840 void statserv_remove(IOCHAN pIOChannel)
844 void statserv_closedown()
848 xml_config_bend_stop();
849 for (p = pListener; p; p = p->next)
856 void sigterm(int sig)
861 static void *new_session (void *vp);
862 static int no_sessions = 0;
865 static void listener(IOCHAN h, int event)
867 COMSTACK line = (COMSTACK) iochan_getdata(h);
870 if (event == EVENT_INPUT)
873 if ((res = cs_listen_check(line, 0, 0, control_block.check_ip,
874 control_block.daemon_name)) < 0)
876 yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_listen failed");
881 yaz_log(YLOG_WARN, "cs_listen incomplete");
884 new_line = cs_accept(line);
887 yaz_log(YLOG_FATAL, "Accept failed.");
888 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
892 yaz_log(log_session, "Connect from %s", cs_addrstr(new_line));
895 if (control_block.dynamic)
897 if ((res = fork()) < 0)
899 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fork");
903 else if (res == 0) /* child */
908 for (pp = pListener; pp; pp = iochan_getnext(pp))
910 COMSTACK l = (COMSTACK)iochan_getdata(pp);
914 sprintf(nbuf, "%s(%d)", me, no_sessions);
915 yaz_log_init_prefix(nbuf);
916 /* ensure that bend_stop is not called when each child exits -
917 only for the main process .. */
918 control_block.bend_stop = 0;
927 if (control_block.threads)
929 #if YAZ_POSIX_THREADS
930 pthread_t child_thread;
931 pthread_create (&child_thread, 0, new_session, new_line);
932 pthread_detach (child_thread);
933 #elif YAZ_GNU_THREADS
937 attr = pth_attr_new ();
938 pth_attr_set (attr, PTH_ATTR_JOINABLE, FALSE);
939 pth_attr_set (attr, PTH_ATTR_STACK_SIZE, 32*1024);
940 pth_attr_set (attr, PTH_ATTR_NAME, "session");
941 yaz_log (YLOG_DEBUG, "pth_spawn begin");
942 child_thread = pth_spawn (attr, new_session, new_line);
943 yaz_log (YLOG_DEBUG, "pth_spawn finish");
944 pth_attr_destroy (attr);
946 new_session(new_line);
950 new_session(new_line);
952 else if (event == EVENT_TIMEOUT)
954 yaz_log(log_server, "Shutting down listener.");
959 yaz_log(YLOG_FATAL, "Bad event on listener.");
964 static void *new_session (void *vp)
969 COMSTACK new_line = (COMSTACK) vp;
970 IOCHAN parent_chan = new_line->user;
972 unsigned cs_get_mask, cs_accept_mask, mask =
973 ((new_line->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
974 ((new_line->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
978 cs_accept_mask = mask; /* accept didn't complete */
983 cs_accept_mask = 0; /* accept completed. */
984 cs_get_mask = mask = EVENT_INPUT;
987 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session, mask,
988 parent_chan->chan_id)))
990 yaz_log(YLOG_FATAL, "Failed to create iochan");
993 if (!(newas = create_association(new_chan, new_line,
994 control_block.apdufile)))
996 yaz_log(YLOG_FATAL, "Failed to create new assoc.");
999 newas->cs_accept_mask = cs_accept_mask;
1000 newas->cs_get_mask = cs_get_mask;
1002 iochan_setdata(new_chan, newas);
1003 iochan_settimeout(new_chan, 60);
1005 a = cs_addrstr(new_line);
1009 yaz_log(log_session, "Starting session %d from %s (pid=%ld)",
1010 no_sessions, a ? a : "[Unknown]", (long) getpid());
1011 if (max_sessions && no_sessions >= max_sessions)
1012 control_block.one_shot = 1;
1013 if (control_block.threads)
1015 event_loop(&new_chan);
1019 new_chan->next = pListener;
1020 pListener = new_chan;
1028 static void inetd_connection(int what)
1035 if ((line = cs_createbysocket(0, tcpip_type, 0, what)))
1037 if ((chan = iochan_create(cs_fileno(line), ir_session, EVENT_INPUT,
1040 if ((assoc = create_association(chan, line,
1041 control_block.apdufile)))
1043 iochan_setdata(chan, assoc);
1044 iochan_settimeout(chan, 60);
1045 addr = cs_addrstr(line);
1046 yaz_log(log_session, "Inetd association from %s",
1047 addr ? addr : "[UNKNOWN]");
1048 assoc->cs_get_mask = EVENT_INPUT;
1052 yaz_log(YLOG_FATAL, "Failed to create association structure");
1054 chan->next = pListener;
1059 yaz_log(YLOG_FATAL, "Failed to create iochan");
1064 yaz_log(YLOG_ERRNO|YLOG_FATAL, "Failed to create comstack on socket 0");
1069 * Set up a listening endpoint, and give it to the event-handler.
1071 static int add_listener(char *where, int listen_id)
1078 if (control_block.dynamic)
1080 else if (control_block.threads)
1085 yaz_log(log_server, "Adding %s listener on %s id=%d", mode, where,
1088 l = cs_create_host(where, 2, &ap);
1091 yaz_log(YLOG_FATAL, "Failed to listen on %s", where);
1094 if (*control_block.cert_fname)
1095 cs_set_ssl_certificate_file(l, control_block.cert_fname);
1097 if (cs_bind(l, ap, CS_SERVER) < 0)
1099 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to bind to %s", where);
1103 if (!(lst = iochan_create(cs_fileno(l), listener, EVENT_INPUT |
1104 EVENT_EXCEPT, listen_id)))
1106 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create IOCHAN-type");
1110 iochan_setdata(lst, l); /* user-defined data for listener is COMSTACK */
1111 l->user = lst; /* user-defined data for COMSTACK is listener chan */
1113 /* Add listener to chain */
1114 lst->next = pListener;
1120 /* UNIX only (for windows we don't need to catch the signals) */
1121 static void catchchld(int num)
1123 while (waitpid(-1, 0, WNOHANG) > 0)
1125 signal(SIGCHLD, catchchld);
1129 statserv_options_block *statserv_getcontrol(void)
1132 if (init_control_tls)
1133 return (statserv_options_block *) TlsGetValue(current_control_tls);
1135 return &control_block;
1136 #elif YAZ_POSIX_THREADS
1137 if (init_control_tls)
1138 return pthread_getspecific(current_control_tls);
1140 return &control_block;
1142 if (current_control_block)
1143 return current_control_block;
1144 return &control_block;
1148 void statserv_setcontrol(statserv_options_block *block)
1150 chdir(gfs_root_dir);
1152 if (init_control_tls)
1153 TlsSetValue(current_control_tls, block);
1154 #elif YAZ_POSIX_THREADS
1155 if (init_control_tls)
1156 pthread_setspecific(current_control_tls, block);
1158 current_control_block = block;
1162 static void statserv_reset(void)
1166 int statserv_start(int argc, char **argv)
1170 /* We need to initialize the thread list */
1171 ThreadList_Initialize();
1181 if ((me = strrchr (argv[0], sep)))
1182 me++; /* get the basename */
1185 programname = argv[0];
1187 if (control_block.options_func(argc, argv))
1192 xml_config_bend_start();
1195 xml_config_add_listeners();
1197 yaz_log (log_server, "Starting server %s", me);
1198 if (!pListener && *control_block.default_listen)
1199 add_listener(control_block.default_listen, 0);
1202 if (control_block.inetd)
1203 inetd_connection(control_block.default_proto);
1207 if (control_block.background)
1209 /* create pipe so that parent waits until child has created
1213 yaz_log(YLOG_FATAL|YLOG_ERRNO, "pipe");
1227 int res = read(hand[0], dummy, 1);
1228 if (res < 0 && yaz_errno() != EINTR)
1230 yaz_log(YLOG_FATAL|YLOG_ERRNO, "read fork handshake");
1247 open("/dev/null", O_RDWR);
1250 xml_config_add_listeners();
1252 if (!pListener && *control_block.default_listen)
1253 add_listener(control_block.default_listen, 0);
1258 if (*control_block.pid_fname)
1260 FILE *f = fopen(control_block.pid_fname, "w");
1263 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Couldn't create %s",
1264 control_block.pid_fname);
1267 fprintf(f, "%ld", (long) getpid());
1271 if (control_block.background)
1275 yaz_log (log_server, "Starting server %s pid=%ld", programname,
1278 sigset_t sigs_to_block;
1280 sigemptyset(&sigs_to_block);
1281 sigaddset (&sigs_to_block, SIGTERM);
1282 pthread_sigmask (SIG_BLOCK, &sigs_to_block, 0);
1285 if (control_block.dynamic)
1286 signal(SIGCHLD, catchchld);
1288 signal (SIGPIPE, SIG_IGN);
1289 signal (SIGTERM, sigterm);
1290 if (*control_block.setuid)
1294 if (!(pw = getpwnam(control_block.setuid)))
1296 yaz_log(YLOG_FATAL, "%s: Unknown user", control_block.setuid);
1299 if (setuid(pw->pw_uid) < 0)
1301 yaz_log(YLOG_FATAL|YLOG_ERRNO, "setuid");
1307 if (pListener == NULL)
1309 yaz_log(YLOG_DEBUG, "Entering event loop.");
1310 return event_loop(&pListener);
1313 static void option_copy(char *dst, const char *src)
1315 strncpy(dst, src ? src : "", 127);
1319 int check_options(int argc, char **argv)
1324 if (getenv("YAZ_LOG") == 0) {
1326 * Set default log level. We want to avoid doing this if the
1327 * user has already explicitly specified a preferred default
1328 * log-level, hence the inelegant peek at the YAZ_LOG
1329 * environment variable that will subsequently be interpreted
1330 * by the YAZ logging module itself.
1332 yaz_log_init_level(yaz_log_mask_str(STAT_DEFAULT_LOG_LEVEL));
1336 while ((ret = options("1a:iszSTl:v:u:c:w:t:k:d:A:p:DC:f:m:",
1337 argv, argc, &arg)) != -2)
1342 if (add_listener(arg, 0))
1343 return 1; /* failed to create listener */
1346 control_block.one_shot = 1;
1347 control_block.dynamic = 0;
1350 control_block.default_proto = PROTO_Z3950;
1353 fprintf (stderr, "%s: SR protocol no longer supported\n", me);
1357 control_block.dynamic = 0;
1360 #if YAZ_POSIX_THREADS
1361 control_block.dynamic = 0;
1362 control_block.threads = 1;
1363 #elif YAZ_GNU_THREADS
1364 control_block.dynamic = 0;
1365 control_block.threads = 1;
1367 fprintf(stderr, "%s: Threaded mode not available.\n", me);
1372 option_copy(control_block.logfile, arg);
1373 yaz_log_init_file(control_block.logfile);
1377 fprintf(stderr, "%s: Specify time format for log file.\n", me);
1380 yaz_log_time_format(arg);
1383 int default_level = yaz_log_mask_str(STAT_DEFAULT_LOG_LEVEL);
1384 yaz_log_init_level(yaz_log_mask_str_x(arg, default_level));
1389 option_copy(control_block.apdufile, arg);
1392 option_copy(control_block.setuid, arg);
1395 option_copy(control_block.configname, arg);
1398 option_copy(control_block.cert_fname, arg);
1401 option_copy(control_block.daemon_name, arg);
1404 if (!arg || !(r = atoi(arg)))
1406 fprintf(stderr, "%s: Specify positive timeout for -t.\n", me);
1409 control_block.idle_timeout = r;
1412 if (!arg || !(r = atoi(arg)))
1414 fprintf(stderr, "%s: Specify positive size for -k.\n", me);
1417 control_block.maxrecordsize = r * 1024;
1420 control_block.inetd = 1;
1430 max_sessions = atoi(arg);
1433 option_copy(control_block.pid_fname, arg);
1437 option_copy(control_block.xml_config, arg);
1439 fprintf(stderr, "%s: Option -f unsupported since YAZ is compiled without Libxml2 support\n", me);
1444 control_block.background = 1;
1447 fprintf(stderr, "Usage: %s [ -a <pdufile> -v <loglevel>"
1448 " -l <logfile> -u <user> -c <config> -t <minutes>"
1449 " -k <kilobytes> -d <daemon> -p <pidfile> -C certfile"
1450 " -ziDST1 -m <time-format> -w <directory> <listener-addr>... ]\n", me);
1458 typedef struct _Args
1464 static Args ArgDetails;
1466 /* name of the executable */
1467 #define SZAPPNAME "server"
1469 /* list of service dependencies - "dep1\0dep2\0\0" */
1470 #define SZDEPENDENCIES ""
1472 int statserv_main(int argc, char **argv,
1473 bend_initresult *(*bend_init)(bend_initrequest *r),
1474 void (*bend_close)(void *handle))
1476 struct statserv_options_block *cb = &control_block;
1477 cb->bend_init = bend_init;
1478 cb->bend_close = bend_close;
1480 /* Lets setup the Arg structure */
1481 ArgDetails.argc = argc;
1482 ArgDetails.argv = argv;
1484 /* Now setup the service with the service controller */
1485 SetupService(argc, argv, &ArgDetails, SZAPPNAME,
1486 cb->service_name, /* internal service name */
1487 cb->service_display_name, /* displayed name */
1492 int StartAppService(void *pHandle, int argc, char **argv)
1494 /* Initializes the App */
1498 void RunAppService(void *pHandle)
1500 Args *pArgs = (Args *)pHandle;
1502 /* Starts the app running */
1503 statserv_start(pArgs->argc, pArgs->argv);
1506 void StopAppService(void *pHandle)
1509 statserv_closedown();
1515 int statserv_main(int argc, char **argv,
1516 bend_initresult *(*bend_init)(bend_initrequest *r),
1517 void (*bend_close)(void *handle))
1521 control_block.bend_init = bend_init;
1522 control_block.bend_close = bend_close;
1524 ret = statserv_start (argc, argv);
1525 statserv_closedown ();
1533 * indent-tabs-mode: nil
1535 * vim: shiftwidth=4 tabstop=8 expandtab