2 * Copyright (C) 1995-2007, 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.48 2007-05-02 11:53:25 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 "server,session,request"
90 int check_options(int argc, char **argv);
91 statserv_options_block control_block = {
93 0, /* threaded mode */
94 0, /* one shot (single session) */
96 "", /* diagnostic output to stderr */
97 "tcp:@:9999", /* default listener port */
98 PROTO_Z3950, /* default application protocol */
99 15, /* idle timeout (minutes) */
100 1024*1024, /* maximum PDU size (approx.) to allow */
101 "default-config", /* configuration name to pass to backend */
102 "", /* set user id */
103 0, /* bend_start handler */
104 0, /* bend_stop handler */
105 check_options, /* Default routine, for checking the run-time arguments */
108 0, /* default value for inet deamon */
109 0, /* handle (for service, etc) */
110 0, /* bend_init handle */
111 0, /* bend_close handle */
113 "Z39.50 Server", /* NT Service Name */
114 "Server", /* NT application Name */
115 "", /* NT Service Dependencies */
116 "Z39.50 Server", /* NT Service Display Name */
118 0, /* SOAP handlers */
120 0, /* background daemon */
121 "", /* SSL certificate filename */
122 "" /* XML config filename */
125 static int max_sessions = 0;
127 static int logbits_set = 0;
128 static int log_session = 0; /* one-line logs for session */
129 static int log_sessiondetail = 0; /* more detailed stuff */
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_sessiondetail = yaz_log_module_level("sessiondetail");
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(void)
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(void)
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);
303 gfs_server_chdir(gfs);
309 statserv_setcontrol(0);
310 assoc->last_control = 0;
316 statserv_setcontrol(&control_block);
317 assoc->last_control = &control_block;
319 yaz_log(YLOG_DEBUG, "server select: config=%s",
320 assoc->last_control->configname);
322 assoc->maximumRecordSize = assoc->last_control->maxrecordsize;
323 assoc->preferredMessageSize = assoc->last_control->maxrecordsize;
324 cs_set_max_recv_bytes(assoc->client_link, assoc->maximumRecordSize);
328 static void xml_config_read(void)
330 struct gfs_server **gfsp = &gfs_server_list;
331 struct gfs_listen **gfslp = &gfs_listen_list;
333 xmlNodePtr ptr = xml_config_get_root();
337 for (ptr = ptr->children; ptr; ptr = ptr->next)
339 struct _xmlAttr *attr;
340 if (ptr->type != XML_ELEMENT_NODE)
342 attr = ptr->properties;
343 if (!strcmp((const char *) ptr->name, "listen"))
346 <listen id="listenerid">tcp:@:9999</listen>
349 const char *address =
350 nmem_dup_xml_content(gfs_nmem, ptr->children);
351 for ( ; attr; attr = attr->next)
352 if (!xmlStrcmp(attr->name, BAD_CAST "id")
353 && attr->children && attr->children->type == XML_TEXT_NODE)
354 id = nmem_dup_xml_content(gfs_nmem, attr->children);
357 *gfslp = gfs_listen_new(id, address);
358 gfslp = &(*gfslp)->next;
359 *gfslp = 0; /* make listener list consistent for search */
362 else if (!strcmp((const char *) ptr->name, "server"))
364 xmlNodePtr ptr_server = ptr;
366 const char *listenref = 0;
368 struct gfs_server *gfs;
370 for ( ; attr; attr = attr->next)
371 if (!xmlStrcmp(attr->name, BAD_CAST "listenref")
372 && attr->children && attr->children->type == XML_TEXT_NODE)
373 listenref = nmem_dup_xml_content(gfs_nmem, attr->children);
374 else if (!xmlStrcmp(attr->name, BAD_CAST "id")
376 && attr->children->type == XML_TEXT_NODE)
377 id = nmem_dup_xml_content(gfs_nmem, attr->children);
379 yaz_log(YLOG_WARN, "Unknown attribute '%s' for server",
381 gfs = *gfsp = gfs_server_new();
382 gfs->server_node_ptr = ptr_server;
386 struct gfs_listen *gl = gfs_listen_list;
387 for (id_no = 1; gl; gl = gl->next, id_no++)
388 if (gl->id && !strcmp(gl->id, listenref))
390 gfs->listen_ref = id_no;
394 yaz_log(YLOG_WARN, "Non-existent listenref '%s' in server "
395 "config element", listenref);
397 for (ptr = ptr_server->children; ptr; ptr = ptr->next)
399 if (ptr->type != XML_ELEMENT_NODE)
401 if (!strcmp((const char *) ptr->name, "host"))
403 gfs->host = nmem_dup_xml_content(gfs_nmem,
406 else if (!strcmp((const char *) ptr->name, "config"))
408 strcpy(gfs->cb.configname,
409 nmem_dup_xml_content(gfs_nmem, ptr->children));
411 else if (!strcmp((const char *) ptr->name, "cql2rpn"))
413 gfs->cql_transform = cql_transform_open_fname(
414 nmem_dup_xml_content(gfs_nmem, ptr->children)
417 else if (!strcmp((const char *) ptr->name, "directory"))
420 nmem_dup_xml_content(gfs_nmem, ptr->children);
422 else if (!strcmp((const char *) ptr->name, "docpath"))
425 nmem_dup_xml_content(gfs_nmem, ptr->children);
427 else if (!strcmp((const char *) ptr->name, "maximumrecordsize"))
429 gfs->cb.maxrecordsize = atoi(
430 nmem_dup_xml_content(gfs_nmem, ptr->children));
432 else if (!strcmp((const char *) ptr->name, "stylesheet"))
434 char *s = nmem_dup_xml_content(gfs_nmem, ptr->children);
436 nmem_malloc(gfs_nmem, strlen(s) + 2);
437 sprintf(gfs->stylesheet, "/%s", s);
439 else if (!strcmp((const char *) ptr->name, "explain"))
441 ; /* being processed separately */
443 else if (!strcmp((const char *) ptr->name, "retrievalinfo"))
445 if (yaz_retrieval_configure(gfs->retrieval, ptr))
447 yaz_log(YLOG_FATAL, "%s in config %s",
448 yaz_retrieval_get_error(gfs->retrieval),
449 control_block.xml_config);
455 yaz_log(YLOG_FATAL, "Unknown element '%s' in config %s",
456 ptr->name, control_block.xml_config);
460 gfsp = &(*gfsp)->next;
467 static void xml_config_open(void)
469 if (!getcwd(gfs_root_dir, FILENAME_MAX))
471 yaz_log(YLOG_WARN|YLOG_ERRNO, "getcwd failed");
472 gfs_root_dir[0] = '\0';
475 init_control_tls = 1;
476 current_control_tls = TlsAlloc();
477 #elif YAZ_POSIX_THREADS
478 init_control_tls = 1;
479 pthread_key_create(¤t_control_tls, 0);
482 gfs_nmem = nmem_create();
484 if (control_block.xml_config[0] == '\0')
489 xml_config_doc = xmlParseFile(control_block.xml_config);
492 yaz_log(YLOG_FATAL, "Could not parse %s", control_block.xml_config);
497 int noSubstitutions = xmlXIncludeProcess(xml_config_doc);
498 if (noSubstitutions == -1)
500 yaz_log(YLOG_WARN, "XInclude processing failed for config %s",
501 control_block.xml_config);
510 static void xml_config_close(void)
515 xmlFreeDoc(xml_config_doc);
520 nmem_destroy(gfs_nmem);
522 if (init_control_tls)
523 TlsFree(current_control_tls);
524 #elif YAZ_POSIX_THREADS
525 if (init_control_tls)
526 pthread_key_delete(current_control_tls);
530 static void xml_config_add_listeners(void)
532 struct gfs_listen *gfs = gfs_listen_list;
535 for (id_no = 1; gfs; gfs = gfs->next, id_no++)
538 add_listener(gfs->address, id_no);
542 static void xml_config_bend_start(void)
544 if (control_block.xml_config[0])
546 struct gfs_server *gfs = gfs_server_list;
547 for (; gfs; gfs = gfs->next)
549 yaz_log(YLOG_DEBUG, "xml_config_bend_start config=%s",
551 statserv_setcontrol(&gfs->cb);
552 if (control_block.bend_start)
554 gfs_server_chdir(gfs);
555 (control_block.bend_start)(&gfs->cb);
561 yaz_log(YLOG_DEBUG, "xml_config_bend_start default config");
562 statserv_setcontrol(&control_block);
563 if (control_block.bend_start)
564 (*control_block.bend_start)(&control_block);
568 static void xml_config_bend_stop(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_stop config=%s",
577 statserv_setcontrol(&gfs->cb);
578 if (control_block.bend_stop)
579 (control_block.bend_stop)(&gfs->cb);
584 yaz_log(YLOG_DEBUG, "xml_config_bend_stop default config");
585 statserv_setcontrol(&control_block);
586 if (control_block.bend_stop)
587 (*control_block.bend_stop)(&control_block);
592 * handle incoming connect requests.
593 * The dynamic mode is a bit tricky mostly because we want to avoid
594 * doing all of the listening and accepting in the parent - it's
599 typedef struct _ThreadList ThreadList;
608 static ThreadList *pFirstThread;
609 static CRITICAL_SECTION Thread_CritSect;
610 static BOOL bInitialized = FALSE;
612 static void ThreadList_Initialize()
614 /* Initialize the critical Sections */
615 InitializeCriticalSection(&Thread_CritSect);
617 /* Set the first thraed */
620 /* we have been initialized */
624 static void statserv_add(HANDLE hThread, IOCHAN pIOChannel)
626 /* Only one thread can go through this section at a time */
627 EnterCriticalSection(&Thread_CritSect);
630 /* Lets create our new object */
631 ThreadList *pNewThread = (ThreadList *)malloc(sizeof(ThreadList));
632 pNewThread->hThread = hThread;
633 pNewThread->pIOChannel = pIOChannel;
634 pNewThread->pNext = pFirstThread;
635 pFirstThread = pNewThread;
637 /* Lets let somebody else create a new object now */
638 LeaveCriticalSection(&Thread_CritSect);
642 void statserv_remove(IOCHAN pIOChannel)
644 /* Only one thread can go through this section at a time */
645 EnterCriticalSection(&Thread_CritSect);
648 ThreadList *pCurrentThread = pFirstThread;
649 ThreadList *pNextThread;
650 ThreadList *pPrevThread =NULL;
652 /* Step through all the threads */
653 for (; pCurrentThread != NULL; pCurrentThread = pNextThread)
655 /* We only need to compare on the IO Channel */
656 if (pCurrentThread->pIOChannel == pIOChannel)
658 /* We have found the thread we want to delete */
659 /* First of all reset the next pointers */
660 if (pPrevThread == NULL)
661 pFirstThread = pCurrentThread->pNext;
663 pPrevThread->pNext = pCurrentThread->pNext;
665 /* All we need todo now is delete the memory */
666 free(pCurrentThread);
668 /* No need to look at any more threads */
673 /* We need to look at another thread */
674 pNextThread = pCurrentThread->pNext;
675 pPrevThread = pCurrentThread;
679 /* Lets let somebody else remove an object now */
680 LeaveCriticalSection(&Thread_CritSect);
684 /* WIN32 statserv_closedown */
685 void statserv_closedown()
687 /* Shouldn't do anything if we are not initialized */
691 HANDLE *pThreadHandles = NULL;
693 /* We need to stop threads adding and removing while we */
694 /* start the closedown process */
695 EnterCriticalSection(&Thread_CritSect);
698 /* We have exclusive access to the thread stuff now */
699 /* Y didn't i use a semaphore - Oh well never mind */
700 ThreadList *pCurrentThread = pFirstThread;
702 /* Before we do anything else, we need to shutdown the listener */
703 if (pListener != NULL)
704 iochan_destroy(pListener);
706 for (; pCurrentThread != NULL; pCurrentThread = pCurrentThread->pNext)
708 /* Just destroy the IOCHAN, that should do the trick */
709 iochan_destroy(pCurrentThread->pIOChannel);
710 closesocket(pCurrentThread->pIOChannel->fd);
712 /* Keep a running count of our handles */
718 HANDLE *pCurrentHandle ;
720 /* Allocate the thread handle array */
721 pThreadHandles = (HANDLE *)malloc(sizeof(HANDLE) * iHandles);
722 pCurrentHandle = pThreadHandles;
724 for (pCurrentThread = pFirstThread;
725 pCurrentThread != NULL;
726 pCurrentThread = pCurrentThread->pNext, pCurrentHandle++)
728 /* Just the handle */
729 *pCurrentHandle = pCurrentThread->hThread;
733 /* We can now leave the critical section */
734 LeaveCriticalSection(&Thread_CritSect);
737 /* Now we can really do something */
740 yaz_log(log_server, "waiting for %d to die", iHandles);
741 /* This will now wait, until all the threads close */
742 WaitForMultipleObjects(iHandles, pThreadHandles, TRUE, INFINITE);
744 /* Free the memory we allocated for the handle array */
745 free(pThreadHandles);
748 xml_config_bend_stop();
749 /* No longer require the critical section, since all threads are dead */
750 DeleteCriticalSection(&Thread_CritSect);
755 void __cdecl event_loop_thread (IOCHAN iochan)
757 event_loop (&iochan);
761 static void listener(IOCHAN h, int event)
763 COMSTACK line = (COMSTACK) iochan_getdata(h);
764 IOCHAN parent_chan = line->user;
769 if (event == EVENT_INPUT)
774 if ((res = cs_listen(line, 0, 0)) < 0)
776 yaz_log(YLOG_FATAL|YLOG_ERRNO, "cs_listen failed");
780 return; /* incomplete */
781 yaz_log(YLOG_DEBUG, "listen ok");
782 new_line = cs_accept(line);
785 yaz_log(YLOG_FATAL, "Accept failed.");
788 yaz_log(YLOG_DEBUG, "Accept ok");
790 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session,
791 EVENT_INPUT, parent_chan->chan_id)))
793 yaz_log(YLOG_FATAL, "Failed to create iochan");
798 yaz_log(YLOG_DEBUG, "Creating association");
799 if (!(newas = create_association(new_chan, new_line,
800 control_block.apdufile)))
802 yaz_log(YLOG_FATAL, "Failed to create new assoc.");
806 newas->cs_get_mask = EVENT_INPUT;
807 newas->cs_put_mask = 0;
808 newas->cs_accept_mask = 0;
810 yaz_log(YLOG_DEBUG, "Setting timeout %d", control_block.idle_timeout);
811 iochan_setdata(new_chan, newas);
812 iochan_settimeout(new_chan, 60);
814 /* Now what we need todo is create a new thread with this iochan as
816 newHandle = (HANDLE) _beginthread(event_loop_thread, 0, new_chan);
817 if (newHandle == (HANDLE) -1)
820 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create new thread.");
824 /* We successfully created the thread, so add it to the list */
825 statserv_add(newHandle, new_chan);
827 yaz_log(YLOG_DEBUG, "Created new thread, id = %ld iochan %p",(long) newHandle, new_chan);
828 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
832 yaz_log(YLOG_FATAL, "Bad event on listener.");
838 int statserv_must_terminate(void)
845 static int term_flag = 0;
846 /* To save having an #ifdef in event_loop we need to
847 define this empty function
849 int statserv_must_terminate(void)
854 void statserv_remove(IOCHAN pIOChannel)
858 void statserv_closedown()
862 xml_config_bend_stop();
863 for (p = pListener; p; p = p->next)
870 void sigterm(int sig)
875 static void *new_session (void *vp);
876 static int no_sessions = 0;
879 static void listener(IOCHAN h, int event)
881 COMSTACK line = (COMSTACK) iochan_getdata(h);
884 if (event == EVENT_INPUT)
887 if ((res = cs_listen_check(line, 0, 0, control_block.check_ip,
888 control_block.daemon_name)) < 0)
890 yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_listen failed");
895 yaz_log(YLOG_WARN, "cs_listen incomplete");
898 new_line = cs_accept(line);
901 yaz_log(YLOG_FATAL, "Accept failed.");
902 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
906 yaz_log(log_sessiondetail, "Connect from %s", cs_addrstr(new_line));
909 if (control_block.dynamic)
911 if ((res = fork()) < 0)
913 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fork");
917 else if (res == 0) /* child */
922 for (pp = pListener; pp; pp = iochan_getnext(pp))
924 COMSTACK l = (COMSTACK)iochan_getdata(pp);
928 sprintf(nbuf, "%s(%d)", me, no_sessions);
929 yaz_log_init_prefix(nbuf);
930 /* ensure that bend_stop is not called when each child exits -
931 only for the main process .. */
932 control_block.bend_stop = 0;
941 if (control_block.threads)
943 #if YAZ_POSIX_THREADS
944 pthread_t child_thread;
945 pthread_create (&child_thread, 0, new_session, new_line);
946 pthread_detach (child_thread);
947 #elif YAZ_GNU_THREADS
951 attr = pth_attr_new ();
952 pth_attr_set (attr, PTH_ATTR_JOINABLE, FALSE);
953 pth_attr_set (attr, PTH_ATTR_STACK_SIZE, 32*1024);
954 pth_attr_set (attr, PTH_ATTR_NAME, "session");
955 yaz_log (YLOG_DEBUG, "pth_spawn begin");
956 child_thread = pth_spawn (attr, new_session, new_line);
957 yaz_log (YLOG_DEBUG, "pth_spawn finish");
958 pth_attr_destroy (attr);
960 new_session(new_line);
964 new_session(new_line);
966 else if (event == EVENT_TIMEOUT)
968 yaz_log(log_server, "Shutting down listener.");
973 yaz_log(YLOG_FATAL, "Bad event on listener.");
978 static void *new_session (void *vp)
983 COMSTACK new_line = (COMSTACK) vp;
984 IOCHAN parent_chan = new_line->user;
986 unsigned cs_get_mask, cs_accept_mask, mask =
987 ((new_line->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
988 ((new_line->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
992 cs_accept_mask = mask; /* accept didn't complete */
997 cs_accept_mask = 0; /* accept completed. */
998 cs_get_mask = mask = EVENT_INPUT;
1001 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session, mask,
1002 parent_chan->chan_id)))
1004 yaz_log(YLOG_FATAL, "Failed to create iochan");
1007 if (!(newas = create_association(new_chan, new_line,
1008 control_block.apdufile)))
1010 yaz_log(YLOG_FATAL, "Failed to create new assoc.");
1013 newas->cs_accept_mask = cs_accept_mask;
1014 newas->cs_get_mask = cs_get_mask;
1016 iochan_setdata(new_chan, newas);
1017 iochan_settimeout(new_chan, 60);
1019 a = cs_addrstr(new_line);
1023 yaz_log(log_session, "Session - OK %d %s %ld",
1024 no_sessions, a ? a : "[Unknown]", (long) getpid());
1025 if (max_sessions && no_sessions >= max_sessions)
1026 control_block.one_shot = 1;
1027 if (control_block.threads)
1029 event_loop(&new_chan);
1033 new_chan->next = pListener;
1034 pListener = new_chan;
1042 static void inetd_connection(int what)
1049 if ((line = cs_createbysocket(0, tcpip_type, 0, what)))
1051 if ((chan = iochan_create(cs_fileno(line), ir_session, EVENT_INPUT,
1054 if ((assoc = create_association(chan, line,
1055 control_block.apdufile)))
1057 iochan_setdata(chan, assoc);
1058 iochan_settimeout(chan, 60);
1059 addr = cs_addrstr(line);
1060 yaz_log(log_sessiondetail, "Inetd association from %s",
1061 addr ? addr : "[UNKNOWN]");
1062 assoc->cs_get_mask = EVENT_INPUT;
1066 yaz_log(YLOG_FATAL, "Failed to create association structure");
1068 chan->next = pListener;
1073 yaz_log(YLOG_FATAL, "Failed to create iochan");
1078 yaz_log(YLOG_ERRNO|YLOG_FATAL, "Failed to create comstack on socket 0");
1083 * Set up a listening endpoint, and give it to the event-handler.
1085 static int add_listener(char *where, int listen_id)
1092 if (control_block.dynamic)
1094 else if (control_block.threads)
1099 yaz_log(log_server, "Adding %s listener on %s id=%d", mode, where,
1102 l = cs_create_host(where, 2, &ap);
1105 yaz_log(YLOG_FATAL, "Failed to listen on %s", where);
1108 if (*control_block.cert_fname)
1109 cs_set_ssl_certificate_file(l, control_block.cert_fname);
1111 if (cs_bind(l, ap, CS_SERVER) < 0)
1113 if (cs_errno(l) == CSYSERR)
1114 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to bind to %s", where);
1116 yaz_log(YLOG_FATAL, "Failed to bind to %s: %s", where,
1121 if (!(lst = iochan_create(cs_fileno(l), listener, EVENT_INPUT |
1122 EVENT_EXCEPT, listen_id)))
1124 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create IOCHAN-type");
1128 iochan_setdata(lst, l); /* user-defined data for listener is COMSTACK */
1129 l->user = lst; /* user-defined data for COMSTACK is listener chan */
1131 /* Add listener to chain */
1132 lst->next = pListener;
1138 /* UNIX only (for windows we don't need to catch the signals) */
1139 static void catchchld(int num)
1141 while (waitpid(-1, 0, WNOHANG) > 0)
1143 signal(SIGCHLD, catchchld);
1147 statserv_options_block *statserv_getcontrol(void)
1150 if (init_control_tls)
1151 return (statserv_options_block *) TlsGetValue(current_control_tls);
1153 return &control_block;
1154 #elif YAZ_POSIX_THREADS
1155 if (init_control_tls)
1156 return pthread_getspecific(current_control_tls);
1158 return &control_block;
1160 if (current_control_block)
1161 return current_control_block;
1162 return &control_block;
1166 void statserv_setcontrol(statserv_options_block *block)
1168 chdir(gfs_root_dir);
1170 if (init_control_tls)
1171 TlsSetValue(current_control_tls, block);
1172 #elif YAZ_POSIX_THREADS
1173 if (init_control_tls)
1174 pthread_setspecific(current_control_tls, block);
1176 current_control_block = block;
1180 static void statserv_reset(void)
1184 int statserv_start(int argc, char **argv)
1188 /* We need to initialize the thread list */
1189 ThreadList_Initialize();
1199 if ((me = strrchr (argv[0], sep)))
1200 me++; /* get the basename */
1203 programname = argv[0];
1205 if (control_block.options_func(argc, argv))
1210 xml_config_bend_start();
1213 xml_config_add_listeners();
1215 yaz_log (log_server, "Starting server %s", me);
1216 if (!pListener && *control_block.default_listen)
1217 add_listener(control_block.default_listen, 0);
1220 if (control_block.inetd)
1221 inetd_connection(control_block.default_proto);
1225 if (control_block.background)
1227 /* create pipe so that parent waits until child has created
1231 yaz_log(YLOG_FATAL|YLOG_ERRNO, "pipe");
1245 int res = read(hand[0], dummy, 1);
1246 if (res < 0 && yaz_errno() != EINTR)
1248 yaz_log(YLOG_FATAL|YLOG_ERRNO, "read fork handshake");
1265 open("/dev/null", O_RDWR);
1268 xml_config_add_listeners();
1270 if (!pListener && *control_block.default_listen)
1271 add_listener(control_block.default_listen, 0);
1276 if (*control_block.pid_fname)
1278 FILE *f = fopen(control_block.pid_fname, "w");
1281 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Couldn't create %s",
1282 control_block.pid_fname);
1285 fprintf(f, "%ld", (long) getpid());
1289 if (control_block.background)
1293 yaz_log (log_server, "Starting server %s pid=%ld", programname,
1296 sigset_t sigs_to_block;
1298 sigemptyset(&sigs_to_block);
1299 sigaddset (&sigs_to_block, SIGTERM);
1300 pthread_sigmask (SIG_BLOCK, &sigs_to_block, 0);
1303 if (control_block.dynamic)
1304 signal(SIGCHLD, catchchld);
1306 signal (SIGPIPE, SIG_IGN);
1307 signal (SIGTERM, sigterm);
1308 if (*control_block.setuid)
1312 if (!(pw = getpwnam(control_block.setuid)))
1314 yaz_log(YLOG_FATAL, "%s: Unknown user", control_block.setuid);
1317 if (setuid(pw->pw_uid) < 0)
1319 yaz_log(YLOG_FATAL|YLOG_ERRNO, "setuid");
1325 if (pListener == NULL)
1327 yaz_log(YLOG_DEBUG, "Entering event loop.");
1328 return event_loop(&pListener);
1331 static void option_copy(char *dst, const char *src)
1333 strncpy(dst, src ? src : "", 127);
1337 int check_options(int argc, char **argv)
1342 yaz_log_init_level(yaz_log_mask_str(STAT_DEFAULT_LOG_LEVEL));
1345 while ((ret = options("1a:iszSTl:v:u:c:w:t:k:d:A:p:DC:f:m:r:",
1346 argv, argc, &arg)) != -2)
1351 if (add_listener(arg, 0))
1352 return 1; /* failed to create listener */
1355 control_block.one_shot = 1;
1356 control_block.dynamic = 0;
1359 control_block.default_proto = PROTO_Z3950;
1362 fprintf (stderr, "%s: SR protocol no longer supported\n", me);
1366 control_block.dynamic = 0;
1369 #if YAZ_POSIX_THREADS
1370 control_block.dynamic = 0;
1371 control_block.threads = 1;
1372 #elif YAZ_GNU_THREADS
1373 control_block.dynamic = 0;
1374 control_block.threads = 1;
1376 fprintf(stderr, "%s: Threaded mode not available.\n", me);
1381 option_copy(control_block.logfile, arg);
1382 yaz_log_init_file(control_block.logfile);
1386 fprintf(stderr, "%s: Specify time format for log file.\n", me);
1389 yaz_log_time_format(arg);
1392 yaz_log_init_level(yaz_log_mask_str(arg));
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 if (!arg || !(r = atoi(arg)))
1456 fprintf(stderr, "%s: Specify positive size for -r.\n", me);
1459 yaz_log_init_max_size(r * 1024);
1462 fprintf(stderr, "Usage: %s [ -a <pdufile> -v <loglevel>"
1463 " -l <logfile> -u <user> -c <config> -t <minutes>"
1464 " -k <kilobytes> -d <daemon> -p <pidfile> -C certfile"
1465 " -ziDST1 -m <time-format> -w <directory> <listener-addr>... ]\n", me);
1473 typedef struct _Args
1479 static Args ArgDetails;
1481 /* name of the executable */
1482 #define SZAPPNAME "server"
1484 /* list of service dependencies - "dep1\0dep2\0\0" */
1485 #define SZDEPENDENCIES ""
1487 int statserv_main(int argc, char **argv,
1488 bend_initresult *(*bend_init)(bend_initrequest *r),
1489 void (*bend_close)(void *handle))
1491 struct statserv_options_block *cb = &control_block;
1492 cb->bend_init = bend_init;
1493 cb->bend_close = bend_close;
1495 /* Lets setup the Arg structure */
1496 ArgDetails.argc = argc;
1497 ArgDetails.argv = argv;
1499 /* Now setup the service with the service controller */
1500 SetupService(argc, argv, &ArgDetails, SZAPPNAME,
1501 cb->service_name, /* internal service name */
1502 cb->service_display_name, /* displayed name */
1507 int StartAppService(void *pHandle, int argc, char **argv)
1509 /* Initializes the App */
1513 void RunAppService(void *pHandle)
1515 Args *pArgs = (Args *)pHandle;
1517 /* Starts the app running */
1518 statserv_start(pArgs->argc, pArgs->argv);
1521 void StopAppService(void *pHandle)
1524 statserv_closedown();
1530 int statserv_main(int argc, char **argv,
1531 bend_initresult *(*bend_init)(bend_initrequest *r),
1532 void (*bend_close)(void *handle))
1536 control_block.bend_init = bend_init;
1537 control_block.bend_close = bend_close;
1539 ret = statserv_start (argc, argv);
1540 statserv_closedown ();
1548 * indent-tabs-mode: nil
1550 * vim: shiftwidth=4 tabstop=8 expandtab