1 /* This file is part of the YAZ toolkit.
2 * Copyright (C) 1995-2013 Index Data
3 * See the file LICENSE for details.
8 * \brief Implements GFS logic
28 #include <sys/types.h>
41 #include <libxml/parser.h>
42 #include <libxml/tree.h>
43 #include <libxml/xinclude.h>
54 #include <yaz/comstack.h>
55 #include <yaz/tcpip.h>
56 #include <yaz/options.h>
57 #include <yaz/errno.h>
59 #include <yaz/xmosi.h>
64 #include <yaz/statserv.h>
65 #include <yaz/daemon.h>
66 #include <yaz/yaz-iconv.h>
68 static IOCHAN pListener = NULL;
70 static char gfs_root_dir[FILENAME_MAX+1];
71 static struct gfs_server *gfs_server_list = 0;
72 static struct gfs_listen *gfs_listen_list = 0;
73 static NMEM gfs_nmem = 0;
75 static char *me = "statserver"; /* log prefix */
76 static char *programname="statserver"; /* full program name */
78 DWORD current_control_tls;
79 static int init_control_tls = 0;
80 #elif YAZ_POSIX_THREADS
81 static pthread_key_t current_control_tls;
82 static int init_control_tls = 0;
84 static statserv_options_block *current_control_block = 0;
90 #define STAT_DEFAULT_LOG_LEVEL "server,session,request"
92 int check_options(int argc, char **argv);
93 statserv_options_block control_block = {
95 0, /* threaded mode */
96 0, /* one shot (single session) */
98 "", /* diagnostic output to stderr */
99 PROTO_Z3950, /* default application protocol */
100 900, /* idle timeout (seconds) */
101 64*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 */
120 0, /* background daemon */
121 "", /* SSL certificate filename */
122 "", /* XML config filename */
126 static int max_sessions = 0;
128 static int logbits_set = 0;
129 static int log_session = 0; /* one-line logs for session */
130 static int log_sessiondetail = 0; /* more detailed stuff */
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_sessiondetail = yaz_log_module_level("sessiondetail");
141 log_server = yaz_log_module_level("server");
146 static int add_listener(char *where, int listen_id);
149 static xmlDocPtr xml_config_doc = 0;
153 static xmlNodePtr xml_config_get_root(void)
158 ptr = xmlDocGetRootElement(xml_config_doc);
159 if (!ptr || ptr->type != XML_ELEMENT_NODE ||
160 strcmp((const char *) ptr->name, "yazgfs"))
162 yaz_log(YLOG_WARN, "Bad/missing root element for config %s",
163 control_block.xml_config);
173 static char *nmem_dup_xml_content(NMEM n, xmlNodePtr ptr)
177 int len = 1; /* start with 1, because of trailing 0 */
179 int first = 1; /* whitespace lead flag .. */
180 /* determine length */
181 for (p = ptr; p; p = p->next)
183 if (p->type == XML_TEXT_NODE)
184 len += xmlStrlen(p->content);
186 /* now allocate for the string */
187 str = (unsigned char *) nmem_malloc(n, len);
188 *str = '\0'; /* so we can use strcat */
189 for (p = ptr; p; p = p->next)
191 if (p->type == XML_TEXT_NODE)
196 while(*cp && yaz_isspace(*cp))
199 first = 0; /* reset if we got non-whitespace out */
201 strcat((char *)str, (const char *)cp); /* append */
204 /* remove trailing whitespace */
205 cp = strlen((const char *)str) + str;
206 while (cp != str && yaz_isspace(cp[-1]))
209 /* return resulting string */
215 static struct gfs_server * gfs_server_new(const char *id)
217 struct gfs_server *n = (struct gfs_server *)
218 nmem_malloc(gfs_nmem, sizeof(*n));
219 memcpy(&n->cb, &control_block, sizeof(control_block));
223 n->cql_transform = 0;
224 n->ccl_transform = 0;
225 n->server_node_ptr = 0;
229 n->id = nmem_strdup_null(gfs_nmem, id);
230 n->retrieval = yaz_retrieval_create();
236 static struct gfs_listen * gfs_listen_new(const char *id,
239 struct gfs_listen *n = (struct gfs_listen *)
240 nmem_malloc(gfs_nmem, sizeof(*n));
242 n->id = nmem_strdup(gfs_nmem, id);
246 n->address = nmem_strdup(gfs_nmem, address);
251 static void gfs_server_chdir(struct gfs_server *gfs)
255 if (chdir(gfs_root_dir))
256 yaz_log(YLOG_WARN|YLOG_ERRNO, "chdir %s", gfs_root_dir);
260 if (chdir(gfs->directory))
261 yaz_log(YLOG_WARN|YLOG_ERRNO, "chdir %s",
266 int control_association(association *assoc, const char *host, int force_open)
268 char vhost[128], *cp;
271 strncpy(vhost, host, 127);
273 cp = strchr(vhost, ':');
279 if (control_block.xml_config[0])
281 struct gfs_server *gfs;
282 for (gfs = gfs_server_list; gfs; gfs = gfs->next)
284 int listen_match = 0;
286 if ( !gfs->host || (host && gfs->host && !strcmp(host, gfs->host)))
288 if (!gfs->listen_ref ||
289 gfs->listen_ref == assoc->client_chan->chan_id)
291 if (listen_match && host_match)
294 (assoc->last_control != &gfs->cb && assoc->backend))
296 statserv_setcontrol(assoc->last_control);
297 if (assoc->backend && assoc->init)
299 gfs_server_chdir(gfs);
300 (assoc->last_control->bend_close)(assoc->backend);
307 assoc->last_control = &gfs->cb;
308 statserv_setcontrol(&gfs->cb);
310 gfs_server_chdir(gfs);
316 statserv_setcontrol(0);
317 assoc->last_control = 0;
323 statserv_setcontrol(&control_block);
324 assoc->last_control = &control_block;
326 yaz_log(YLOG_DEBUG, "server select: config=%s",
327 assoc->last_control->configname);
329 assoc->maximumRecordSize = assoc->last_control->maxrecordsize;
330 assoc->preferredMessageSize = assoc->last_control->maxrecordsize;
331 cs_set_max_recv_bytes(assoc->client_link, assoc->maximumRecordSize);
336 static void xml_config_read(void)
338 struct gfs_server **gfsp = &gfs_server_list;
339 struct gfs_listen **gfslp = &gfs_listen_list;
340 xmlNodePtr ptr = xml_config_get_root();
344 for (ptr = ptr->children; ptr; ptr = ptr->next)
346 struct _xmlAttr *attr;
347 if (ptr->type != XML_ELEMENT_NODE)
349 attr = ptr->properties;
350 if (!strcmp((const char *) ptr->name, "listen"))
353 <listen id="listenerid">tcp:@:9999</listen>
356 const char *address =
357 nmem_dup_xml_content(gfs_nmem, ptr->children);
358 for ( ; attr; attr = attr->next)
359 if (!xmlStrcmp(attr->name, BAD_CAST "id")
360 && attr->children && attr->children->type == XML_TEXT_NODE)
361 id = nmem_dup_xml_content(gfs_nmem, attr->children);
364 *gfslp = gfs_listen_new(id, address);
365 gfslp = &(*gfslp)->next;
366 *gfslp = 0; /* make listener list consistent for search */
369 else if (!strcmp((const char *) ptr->name, "server"))
371 xmlNodePtr ptr_server = ptr;
373 const char *listenref = 0;
375 struct gfs_server *gfs;
377 for ( ; attr; attr = attr->next)
378 if (!xmlStrcmp(attr->name, BAD_CAST "listenref")
379 && attr->children && attr->children->type == XML_TEXT_NODE)
380 listenref = nmem_dup_xml_content(gfs_nmem, attr->children);
381 else if (!xmlStrcmp(attr->name, BAD_CAST "id")
383 && attr->children->type == XML_TEXT_NODE)
384 id = nmem_dup_xml_content(gfs_nmem, attr->children);
386 yaz_log(YLOG_WARN, "Unknown attribute '%s' for server",
388 gfs = *gfsp = gfs_server_new(id);
389 gfs->server_node_ptr = ptr_server;
393 struct gfs_listen *gl = gfs_listen_list;
394 for (id_no = 1; gl; gl = gl->next, id_no++)
395 if (gl->id && !strcmp(gl->id, listenref))
397 gfs->listen_ref = id_no;
401 yaz_log(YLOG_WARN, "Non-existent listenref '%s' in server "
402 "config element", listenref);
404 for (ptr = ptr_server->children; ptr; ptr = ptr->next)
406 if (ptr->type != XML_ELEMENT_NODE)
408 if (!strcmp((const char *) ptr->name, "host"))
410 gfs->host = nmem_dup_xml_content(gfs_nmem,
413 else if (!strcmp((const char *) ptr->name, "config"))
415 strcpy(gfs->cb.configname,
416 nmem_dup_xml_content(gfs_nmem, ptr->children));
418 else if (!strcmp((const char *) ptr->name, "cql2rpn"))
420 char *name = nmem_dup_xml_content(gfs_nmem, ptr->children);
421 gfs->cql_transform = cql_transform_open_fname(name);
422 if (!gfs->cql_transform)
424 yaz_log(YLOG_FATAL|YLOG_ERRNO,
425 "open CQL transform file '%s'", name);
429 else if (!strcmp((const char *) ptr->name, "ccl2rpn"))
434 name = nmem_dup_xml_content(gfs_nmem, ptr->children);
435 if ((f = fopen(name, "r")) == 0) {
436 yaz_log(YLOG_FATAL, "can't open CCL file '%s'", name);
439 gfs->ccl_transform = ccl_qual_mk();
440 ccl_qual_file (gfs->ccl_transform, f);
443 else if (!strcmp((const char *) ptr->name, "directory"))
446 nmem_dup_xml_content(gfs_nmem, ptr->children);
448 else if (!strcmp((const char *) ptr->name, "docpath"))
451 nmem_dup_xml_content(gfs_nmem, ptr->children);
453 else if (!strcmp((const char *) ptr->name, "maximumrecordsize"))
455 gfs->cb.maxrecordsize = atoi(
456 nmem_dup_xml_content(gfs_nmem, ptr->children));
458 else if (!strcmp((const char *) ptr->name, "stylesheet"))
460 char *s = nmem_dup_xml_content(gfs_nmem, ptr->children);
461 gfs->stylesheet = (char *)
462 nmem_malloc(gfs_nmem, strlen(s) + 2);
463 sprintf(gfs->stylesheet, "/%s", s);
465 else if (!strcmp((const char *) ptr->name, "explain"))
467 ; /* being processed separately */
469 else if (!strcmp((const char *) ptr->name, "retrievalinfo"))
471 if (yaz_retrieval_configure(gfs->retrieval, ptr))
473 yaz_log(YLOG_FATAL, "%s in config %s",
474 yaz_retrieval_get_error(gfs->retrieval),
475 control_block.xml_config);
481 yaz_log(YLOG_FATAL, "Unknown element '%s' in config %s",
482 ptr->name, control_block.xml_config);
486 gfsp = &(*gfsp)->next;
493 static void xml_config_open(void)
495 if (!getcwd(gfs_root_dir, FILENAME_MAX))
497 yaz_log(YLOG_WARN|YLOG_ERRNO, "getcwd failed");
498 gfs_root_dir[0] = '\0';
501 init_control_tls = 1;
502 current_control_tls = TlsAlloc();
503 #elif YAZ_POSIX_THREADS
504 init_control_tls = 1;
505 pthread_key_create(¤t_control_tls, 0);
508 gfs_nmem = nmem_create();
510 if (control_block.xml_config[0] == '\0')
515 xml_config_doc = xmlParseFile(control_block.xml_config);
518 yaz_log(YLOG_FATAL, "Could not parse %s", control_block.xml_config);
523 int noSubstitutions = xmlXIncludeProcess(xml_config_doc);
524 if (noSubstitutions == -1)
526 yaz_log(YLOG_WARN, "XInclude processing failed for config %s",
527 control_block.xml_config);
536 static void xml_config_close(void)
541 xmlFreeDoc(xml_config_doc);
546 nmem_destroy(gfs_nmem);
548 if (init_control_tls)
549 TlsFree(current_control_tls);
550 #elif YAZ_POSIX_THREADS
551 if (init_control_tls)
552 pthread_key_delete(current_control_tls);
556 static void xml_config_add_listeners(void)
558 struct gfs_listen *gfs = gfs_listen_list;
561 for (id_no = 1; gfs; gfs = gfs->next, id_no++)
564 add_listener(gfs->address, id_no);
568 static void xml_config_bend_start(void)
570 if (control_block.xml_config[0])
572 struct gfs_server *gfs = gfs_server_list;
573 for (; gfs; gfs = gfs->next)
575 yaz_log(YLOG_DEBUG, "xml_config_bend_start config=%s",
577 statserv_setcontrol(&gfs->cb);
578 if (control_block.bend_start)
580 gfs_server_chdir(gfs);
581 (control_block.bend_start)(&gfs->cb);
587 yaz_log(YLOG_DEBUG, "xml_config_bend_start default config");
588 statserv_setcontrol(&control_block);
589 if (control_block.bend_start)
590 (*control_block.bend_start)(&control_block);
594 static void xml_config_bend_stop(void)
596 if (control_block.xml_config[0])
598 struct gfs_server *gfs = gfs_server_list;
599 for (; gfs; gfs = gfs->next)
601 yaz_log(YLOG_DEBUG, "xml_config_bend_stop config=%s",
603 statserv_setcontrol(&gfs->cb);
604 if (control_block.bend_stop)
605 (control_block.bend_stop)(&gfs->cb);
610 yaz_log(YLOG_DEBUG, "xml_config_bend_stop default config");
611 statserv_setcontrol(&control_block);
612 if (control_block.bend_stop)
613 (*control_block.bend_stop)(&control_block);
617 static void remove_listeners(void);
620 * handle incoming connect requests.
621 * The dynamic mode is a bit tricky mostly because we want to avoid
622 * doing all of the listening and accepting in the parent - it's
627 typedef struct _ThreadList ThreadList;
636 static ThreadList *pFirstThread;
637 static CRITICAL_SECTION Thread_CritSect;
638 static BOOL bInitialized = FALSE;
640 static void ThreadList_Initialize()
642 /* Initialize the critical Sections */
643 InitializeCriticalSection(&Thread_CritSect);
645 /* Set the first thraed */
648 /* we have been initialized */
652 static void statserv_add(HANDLE hThread, IOCHAN pIOChannel)
654 /* Only one thread can go through this section at a time */
655 EnterCriticalSection(&Thread_CritSect);
658 /* Lets create our new object */
659 ThreadList *pNewThread = (ThreadList *)malloc(sizeof(ThreadList));
660 pNewThread->hThread = hThread;
661 pNewThread->pIOChannel = pIOChannel;
662 pNewThread->pNext = pFirstThread;
663 pFirstThread = pNewThread;
665 /* Lets let somebody else create a new object now */
666 LeaveCriticalSection(&Thread_CritSect);
670 void statserv_remove(IOCHAN pIOChannel)
672 /* Only one thread can go through this section at a time */
673 EnterCriticalSection(&Thread_CritSect);
676 ThreadList *pCurrentThread = pFirstThread;
677 ThreadList *pNextThread;
678 ThreadList *pPrevThread =NULL;
680 /* Step through all the threads */
681 for (; pCurrentThread != NULL; pCurrentThread = pNextThread)
683 /* We only need to compare on the IO Channel */
684 if (pCurrentThread->pIOChannel == pIOChannel)
686 /* We have found the thread we want to delete */
687 /* First of all reset the next pointers */
688 if (pPrevThread == NULL)
689 pFirstThread = pCurrentThread->pNext;
691 pPrevThread->pNext = pCurrentThread->pNext;
693 /* All we need todo now is delete the memory */
694 free(pCurrentThread);
696 /* No need to look at any more threads */
701 /* We need to look at another thread */
702 pNextThread = pCurrentThread->pNext;
703 pPrevThread = pCurrentThread;
707 /* Lets let somebody else remove an object now */
708 LeaveCriticalSection(&Thread_CritSect);
712 /* WIN32 statserv_closedown */
713 static void statserv_closedown()
715 /* Shouldn't do anything if we are not initialized */
719 HANDLE *pThreadHandles = NULL;
721 /* We need to stop threads adding and removing while we */
722 /* start the closedown process */
723 EnterCriticalSection(&Thread_CritSect);
726 /* We have exclusive access to the thread stuff now */
727 /* Y didn't i use a semaphore - Oh well never mind */
728 ThreadList *pCurrentThread = pFirstThread;
730 /* Before we do anything else, we need to shutdown the listener */
731 if (pListener != NULL)
732 iochan_destroy(pListener);
734 for (; pCurrentThread != NULL; pCurrentThread = pCurrentThread->pNext)
736 /* Just destroy the IOCHAN, that should do the trick */
737 iochan_destroy(pCurrentThread->pIOChannel);
738 closesocket(pCurrentThread->pIOChannel->fd);
740 /* Keep a running count of our handles */
746 HANDLE *pCurrentHandle ;
748 /* Allocate the thread handle array */
749 pThreadHandles = (HANDLE *)malloc(sizeof(HANDLE) * iHandles);
750 pCurrentHandle = pThreadHandles;
752 for (pCurrentThread = pFirstThread;
753 pCurrentThread != NULL;
754 pCurrentThread = pCurrentThread->pNext, pCurrentHandle++)
756 /* Just the handle */
757 *pCurrentHandle = pCurrentThread->hThread;
761 /* We can now leave the critical section */
762 LeaveCriticalSection(&Thread_CritSect);
765 /* Now we can really do something */
768 yaz_log(log_server, "waiting for %d to die", iHandles);
769 /* This will now wait, until all the threads close */
770 WaitForMultipleObjects(iHandles, pThreadHandles, TRUE, INFINITE);
772 /* Free the memory we allocated for the handle array */
773 free(pThreadHandles);
776 xml_config_bend_stop();
777 /* No longer require the critical section, since all threads are dead */
778 DeleteCriticalSection(&Thread_CritSect);
783 void __cdecl event_loop_thread(IOCHAN iochan)
785 iochan_event_loop(&iochan);
789 static void listener(IOCHAN h, int event)
791 COMSTACK line = (COMSTACK) iochan_getdata(h);
792 IOCHAN parent_chan = line->user;
797 if (event == EVENT_INPUT)
802 if ((res = cs_listen(line, 0, 0)) < 0)
804 yaz_log(YLOG_FATAL|YLOG_ERRNO, "cs_listen failed");
808 return; /* incomplete */
809 yaz_log(YLOG_DEBUG, "listen ok");
810 new_line = cs_accept(line);
813 yaz_log(YLOG_FATAL, "Accept failed.");
816 yaz_log(YLOG_DEBUG, "Accept ok");
818 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session,
819 EVENT_INPUT, parent_chan->chan_id)))
821 yaz_log(YLOG_FATAL, "Failed to create iochan");
826 yaz_log(YLOG_DEBUG, "Creating association");
827 if (!(newas = create_association(new_chan, new_line,
828 control_block.apdufile)))
830 yaz_log(YLOG_FATAL, "Failed to create new assoc.");
834 newas->cs_get_mask = EVENT_INPUT;
835 newas->cs_put_mask = 0;
836 newas->cs_accept_mask = 0;
838 yaz_log(YLOG_DEBUG, "Setting timeout %d", control_block.idle_timeout);
839 iochan_setdata(new_chan, newas);
840 iochan_settimeout(new_chan, 60);
842 /* Now what we need todo is create a new thread with this iochan as
844 newHandle = (HANDLE) _beginthread(event_loop_thread, 0, new_chan);
845 if (newHandle == (HANDLE) -1)
848 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create new thread.");
852 /* We successfully created the thread, so add it to the list */
853 statserv_add(newHandle, new_chan);
855 yaz_log(YLOG_DEBUG, "Created new thread, id = %ld iochan %p",(long) newHandle, new_chan);
856 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
860 yaz_log(YLOG_FATAL, "Bad event on listener.");
868 /* To save having an #ifdef in event_loop we need to
869 define this empty function
871 void statserv_remove(IOCHAN pIOChannel)
875 static void statserv_closedown(void)
879 xml_config_bend_stop();
880 for (p = pListener; p; p = p->next)
887 static void *new_session(void *vp);
888 static int no_sessions = 0;
891 static void listener(IOCHAN h, int event)
893 COMSTACK line = (COMSTACK) iochan_getdata(h);
896 if (event == EVENT_INPUT)
899 if ((res = cs_listen_check(line, 0, 0, control_block.check_ip,
900 control_block.daemon_name)) < 0)
902 yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_listen failed");
907 yaz_log(YLOG_WARN, "cs_listen incomplete");
910 new_line = cs_accept(line);
913 yaz_log(YLOG_FATAL, "Accept failed.");
914 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
918 if (control_block.one_shot)
921 yaz_log(log_sessiondetail, "Connect from %s", cs_addrstr(new_line));
924 if (control_block.dynamic)
926 if ((res = fork()) < 0)
928 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fork");
932 else if (res == 0) /* child */
937 for (pp = pListener; pp; pp = iochan_getnext(pp))
939 COMSTACK l = (COMSTACK)iochan_getdata(pp);
943 sprintf(nbuf, "%s(%d)", me, no_sessions);
944 yaz_log_init_prefix(nbuf);
945 /* ensure that bend_stop is not called when each child exits -
946 only for the main process .. */
947 control_block.bend_stop = 0;
956 if (control_block.threads)
958 #if YAZ_POSIX_THREADS
959 pthread_t child_thread;
960 pthread_create(&child_thread, 0, new_session, new_line);
961 pthread_detach(child_thread);
963 new_session(new_line);
967 new_session(new_line);
969 else if (event == EVENT_TIMEOUT)
971 yaz_log(log_server, "Shutting down listener.");
976 yaz_log(YLOG_FATAL, "Bad event on listener.");
981 static void *new_session(void *vp)
986 COMSTACK new_line = (COMSTACK) vp;
987 IOCHAN parent_chan = (IOCHAN) new_line->user;
989 unsigned cs_get_mask, cs_accept_mask, mask =
990 ((new_line->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
991 ((new_line->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
995 cs_accept_mask = mask; /* accept didn't complete */
1000 cs_accept_mask = 0; /* accept completed. */
1001 cs_get_mask = mask = EVENT_INPUT;
1004 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session, mask,
1005 parent_chan->chan_id)))
1007 yaz_log(YLOG_FATAL, "Failed to create iochan");
1010 if (!(newas = create_association(new_chan, new_line,
1011 control_block.apdufile)))
1013 yaz_log(YLOG_FATAL, "Failed to create new assoc.");
1016 newas->cs_accept_mask = cs_accept_mask;
1017 newas->cs_get_mask = cs_get_mask;
1019 iochan_setdata(new_chan, newas);
1020 iochan_settimeout(new_chan, 60);
1022 a = cs_addrstr(new_line);
1026 yaz_log_xml_errors(0, YLOG_WARN);
1027 yaz_log(log_session, "Session - OK %d %s PID=%ld",
1028 no_sessions, a ? a : "[Unknown]", (long) getpid());
1029 if (max_sessions && no_sessions >= max_sessions)
1030 control_block.one_shot = 1;
1031 if (control_block.threads)
1033 iochan_event_loop(&new_chan);
1037 new_chan->next = pListener;
1038 pListener = new_chan;
1046 static void inetd_connection(int what)
1053 if ((line = cs_createbysocket(0, tcpip_type, 0, what)))
1055 if ((chan = iochan_create(cs_fileno(line), ir_session, EVENT_INPUT,
1058 if ((assoc = create_association(chan, line,
1059 control_block.apdufile)))
1061 iochan_setdata(chan, assoc);
1062 iochan_settimeout(chan, 60);
1063 addr = cs_addrstr(line);
1064 yaz_log(log_sessiondetail, "Inetd association from %s",
1065 addr ? addr : "[UNKNOWN]");
1066 assoc->cs_get_mask = EVENT_INPUT;
1070 yaz_log(YLOG_FATAL, "Failed to create association structure");
1072 chan->next = pListener;
1077 yaz_log(YLOG_FATAL, "Failed to create iochan");
1082 yaz_log(YLOG_ERRNO|YLOG_FATAL, "Failed to create comstack on socket 0");
1087 * Set up a listening endpoint, and give it to the event-handler.
1089 static int add_listener(char *where, int listen_id)
1096 if (control_block.dynamic)
1098 else if (control_block.threads)
1103 yaz_log(log_server, "Adding %s listener on %s id=%d PID=%ld", mode, where,
1104 listen_id, (long) getpid());
1106 l = cs_create_host(where, 2, &ap);
1109 yaz_log(YLOG_FATAL, "Failed to listen on %s", where);
1112 if (*control_block.cert_fname)
1113 cs_set_ssl_certificate_file(l, control_block.cert_fname);
1115 if (cs_bind(l, ap, CS_SERVER) < 0)
1117 if (cs_errno(l) == CSYSERR)
1118 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to bind to %s", where);
1120 yaz_log(YLOG_FATAL, "Failed to bind to %s: %s", where,
1125 if (!(lst = iochan_create(cs_fileno(l), listener, EVENT_INPUT |
1126 EVENT_EXCEPT, listen_id)))
1128 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create IOCHAN-type");
1132 iochan_setdata(lst, l); /* user-defined data for listener is COMSTACK */
1133 l->user = lst; /* user-defined data for COMSTACK is listener chan */
1135 /* Add listener to chain */
1136 lst->next = pListener;
1141 static void remove_listeners(void)
1143 IOCHAN l = pListener;
1144 for (; l; l = l->next)
1149 /* UNIX only (for windows we don't need to catch the signals) */
1150 static void catchchld(int num)
1152 while (waitpid(-1, 0, WNOHANG) > 0)
1154 signal(SIGCHLD, catchchld);
1158 statserv_options_block *statserv_getcontrol(void)
1161 if (init_control_tls)
1162 return (statserv_options_block *) TlsGetValue(current_control_tls);
1164 return &control_block;
1165 #elif YAZ_POSIX_THREADS
1166 if (init_control_tls)
1167 return (statserv_options_block *)
1168 pthread_getspecific(current_control_tls);
1170 return &control_block;
1172 if (current_control_block)
1173 return current_control_block;
1174 return &control_block;
1178 void statserv_setcontrol(statserv_options_block *block)
1180 if (gfs_root_dir[0])
1182 if (chdir(gfs_root_dir))
1183 yaz_log(YLOG_WARN|YLOG_ERRNO, "chdir %s", gfs_root_dir);
1186 if (init_control_tls)
1187 TlsSetValue(current_control_tls, block);
1188 #elif YAZ_POSIX_THREADS
1189 if (init_control_tls)
1190 pthread_setspecific(current_control_tls, block);
1192 current_control_block = block;
1196 static void statserv_reset(void)
1200 static void daemon_handler(void *data)
1202 IOCHAN *pListener = data;
1203 iochan_event_loop(pListener);
1207 static void normal_stop_handler(int num)
1209 yaz_log(log_server, "Received SIGTERM. PID=%ld", (long) getpid());
1214 static int statserv_sc_main(yaz_sc_t s, int argc, char **argv)
1218 /* We need to initialize the thread list */
1219 ThreadList_Initialize();
1229 if ((me = strrchr(argv[0], sep)))
1230 me++; /* get the basename */
1233 programname = argv[0];
1235 if (control_block.options_func(argc, argv))
1240 xml_config_bend_start();
1242 if (control_block.inetd)
1245 ; /* no inetd on Windows */
1247 inetd_connection(control_block.default_proto);
1252 xml_config_add_listeners();
1255 add_listener("tcp:@:9999", 0);
1258 if (control_block.dynamic)
1259 signal(SIGCHLD, catchchld);
1262 if (pListener == NULL)
1268 signal(SIGTERM, normal_stop_handler);
1270 yaz_daemon(programname,
1271 (control_block.background ? YAZ_DAEMON_FORK : 0),
1272 daemon_handler, &pListener,
1273 *control_block.pid_fname ? control_block.pid_fname : 0,
1274 *control_block.setuid ? control_block.setuid : 0);
1278 static void option_copy(char *dst, const char *src)
1280 strncpy(dst, src ? src : "", BEND_NAME_MAX-1);
1281 dst[BEND_NAME_MAX-1] = '\0';
1284 int check_options(int argc, char **argv)
1289 yaz_log_init_level(yaz_log_mask_str(STAT_DEFAULT_LOG_LEVEL));
1293 while ((ret = options("1a:iszSTl:v:u:c:w:t:k:Kd:A:p:DC:f:m:r:",
1294 argv, argc, &arg)) != -2)
1299 if (add_listener(arg, 0))
1300 return 1; /* failed to create listener */
1303 control_block.one_shot = 1;
1304 control_block.dynamic = 0;
1307 control_block.default_proto = PROTO_Z3950;
1310 fprintf(stderr, "%s: SR protocol no longer supported\n", me);
1314 control_block.dynamic = 0;
1317 #if YAZ_POSIX_THREADS
1318 control_block.dynamic = 0;
1319 control_block.threads = 1;
1321 fprintf(stderr, "%s: Threaded mode not available.\n", me);
1326 option_copy(control_block.logfile, arg);
1327 yaz_log_init_file(control_block.logfile);
1331 fprintf(stderr, "%s: Specify time format for log file.\n", me);
1334 yaz_log_time_format(arg);
1337 yaz_log_init_level(yaz_log_mask_str(arg));
1341 option_copy(control_block.apdufile, arg);
1344 option_copy(control_block.setuid, arg);
1347 option_copy(control_block.configname, arg);
1350 option_copy(control_block.cert_fname, arg);
1353 option_copy(control_block.daemon_name, arg);
1356 if (!arg || !(r = atoi(arg)))
1358 fprintf(stderr, "%s: Specify positive timeout for -t.\n", me);
1361 control_block.idle_timeout = strchr(arg, 's') ? r : 60 * r;
1364 if (!arg || !(r = atoi(arg)))
1366 fprintf(stderr, "%s: Specify positive size for -k.\n", me);
1369 control_block.maxrecordsize = r * 1024;
1372 control_block.keepalive = 0;
1375 control_block.inetd = 1;
1385 max_sessions = atoi(arg);
1388 option_copy(control_block.pid_fname, arg);
1392 option_copy(control_block.xml_config, arg);
1394 fprintf(stderr, "%s: Option -f unsupported since YAZ is compiled without Libxml2 support\n", me);
1399 control_block.background = 1;
1402 if (!arg || !(r = atoi(arg)))
1404 fprintf(stderr, "%s: Specify positive size for -r.\n", me);
1407 yaz_log_init_max_size(r * 1024);
1410 fprintf(stderr, "Usage: %s [ -a <pdufile> -v <loglevel>"
1411 " -l <logfile> -u <user> -c <config> -t <minutes>"
1412 " -k <kilobytes> -d <daemon> -p <pidfile> -C certfile"
1413 " -zKiDST1 -m <time-format> -w <directory> <listener-addr>... ]\n", me);
1420 void statserv_sc_stop(yaz_sc_t s)
1422 statserv_closedown();
1426 int statserv_main(int argc, char **argv,
1427 bend_initresult *(*bend_init)(bend_initrequest *r),
1428 void (*bend_close)(void *handle))
1431 struct statserv_options_block *cb = &control_block;
1433 /* control block does not have service_name member on Unix */
1434 yaz_sc_t s = yaz_sc_create(
1436 cb->service_name, cb->service_display_name
1442 cb->bend_init = bend_init;
1443 cb->bend_close = bend_close;
1445 ret = yaz_sc_program(s, argc, argv, statserv_sc_main, statserv_sc_stop);
1453 * c-file-style: "Stroustrup"
1454 * indent-tabs-mode: nil
1456 * vim: shiftwidth=4 tabstop=8 expandtab