1 /* This file is part of the YAZ toolkit.
2 * Copyright (C) 1995-2008 Index Data
3 * See the file LICENSE for details.
8 * \brief Implements GFS logic
22 #include <sys/types.h>
35 #include <libxml/parser.h>
36 #include <libxml/tree.h>
37 #include <libxml/xinclude.h>
50 #include <yaz/comstack.h>
51 #include <yaz/tcpip.h>
52 #include <yaz/options.h>
54 #include <yaz/xmosi.h>
59 #include <yaz/statserv.h>
61 static IOCHAN pListener = NULL;
63 static char gfs_root_dir[FILENAME_MAX+1];
64 static struct gfs_server *gfs_server_list = 0;
65 static struct gfs_listen *gfs_listen_list = 0;
66 static NMEM gfs_nmem = 0;
68 static char *me = "statserver"; /* log prefix */
69 static char *programname="statserver"; /* full program name */
71 DWORD current_control_tls;
72 static int init_control_tls = 0;
73 #elif YAZ_POSIX_THREADS
74 static pthread_key_t current_control_tls;
75 static int init_control_tls = 0;
77 static statserv_options_block *current_control_block = 0;
83 #define STAT_DEFAULT_LOG_LEVEL "server,session,request"
85 int check_options(int argc, char **argv);
86 statserv_options_block control_block = {
88 0, /* threaded mode */
89 0, /* one shot (single session) */
91 "", /* diagnostic output to stderr */
92 "tcp:@:9999", /* default listener port */
93 PROTO_Z3950, /* default application protocol */
94 15, /* idle timeout (minutes) */
95 1024*1024, /* maximum PDU size (approx.) to allow */
96 "default-config", /* configuration name to pass to backend */
98 0, /* bend_start handler */
99 0, /* bend_stop handler */
100 check_options, /* Default routine, for checking the run-time arguments */
103 0, /* default value for inet deamon */
104 0, /* handle (for service, etc) */
105 0, /* bend_init handle */
106 0, /* bend_close handle */
108 "Z39.50 Server", /* NT Service Name */
109 "Server", /* NT application Name */
110 "", /* NT Service Dependencies */
111 "Z39.50 Server", /* NT Service Display Name */
113 0, /* SOAP handlers */
115 0, /* background daemon */
116 "", /* SSL certificate filename */
117 "" /* XML config filename */
120 static int max_sessions = 0;
122 static int logbits_set = 0;
123 static int log_session = 0; /* one-line logs for session */
124 static int log_sessiondetail = 0; /* more detailed stuff */
125 static int log_server = 0;
127 /** get_logbits sets global loglevel bits */
128 static void get_logbits(int force)
129 { /* needs to be called after parsing cmd-line args that can set loglevels!*/
130 if (force || !logbits_set)
133 log_session = yaz_log_module_level("session");
134 log_sessiondetail = yaz_log_module_level("sessiondetail");
135 log_server = yaz_log_module_level("server");
140 static int add_listener(char *where, int listen_id);
143 static xmlDocPtr xml_config_doc = 0;
147 static xmlNodePtr xml_config_get_root(void)
152 ptr = xmlDocGetRootElement(xml_config_doc);
153 if (!ptr || ptr->type != XML_ELEMENT_NODE ||
154 strcmp((const char *) ptr->name, "yazgfs"))
156 yaz_log(YLOG_WARN, "Bad/missing root element for config %s",
157 control_block.xml_config);
167 static char *nmem_dup_xml_content(NMEM n, xmlNodePtr ptr)
171 int len = 1; /* start with 1, because of trailing 0 */
173 int first = 1; /* whitespace lead flag .. */
174 /* determine length */
175 for (p = ptr; p; p = p->next)
177 if (p->type == XML_TEXT_NODE)
178 len += xmlStrlen(p->content);
180 /* now allocate for the string */
181 str = (unsigned char *) nmem_malloc(n, len);
182 *str = '\0'; /* so we can use strcat */
183 for (p = ptr; p; p = p->next)
185 if (p->type == XML_TEXT_NODE)
190 while(*cp && isspace(*cp))
193 first = 0; /* reset if we got non-whitespace out */
195 strcat((char *)str, (const char *)cp); /* append */
198 /* remove trailing whitespace */
199 cp = strlen((const char *)str) + str;
200 while (cp != str && isspace(cp[-1]))
203 /* return resulting string */
208 static struct gfs_server * gfs_server_new(void)
210 struct gfs_server *n = (struct gfs_server *)
211 nmem_malloc(gfs_nmem, sizeof(*n));
212 memcpy(&n->cb, &control_block, sizeof(control_block));
216 n->cql_transform = 0;
217 n->ccl_transform = 0;
218 n->server_node_ptr = 0;
223 n->retrieval = yaz_retrieval_create();
228 static struct gfs_listen * gfs_listen_new(const char *id,
231 struct gfs_listen *n = (struct gfs_listen *)
232 nmem_malloc(gfs_nmem, sizeof(*n));
234 n->id = nmem_strdup(gfs_nmem, id);
238 n->address = nmem_strdup(gfs_nmem, address);
242 static void gfs_server_chdir(struct gfs_server *gfs)
246 if (chdir(gfs_root_dir))
247 yaz_log(YLOG_WARN|YLOG_ERRNO, "chdir %s", gfs_root_dir);
251 if (chdir(gfs->directory))
252 yaz_log(YLOG_WARN|YLOG_ERRNO, "chdir %s",
257 int control_association(association *assoc, const char *host, int force_open)
259 char vhost[128], *cp;
262 strncpy(vhost, host, 127);
264 cp = strchr(vhost, ':');
270 if (control_block.xml_config[0])
272 struct gfs_server *gfs;
273 for (gfs = gfs_server_list; gfs; gfs = gfs->next)
275 int listen_match = 0;
277 if ( !gfs->host || (host && gfs->host && !strcmp(host, gfs->host)))
279 if (!gfs->listen_ref ||
280 gfs->listen_ref == assoc->client_chan->chan_id)
282 if (listen_match && host_match)
285 (assoc->last_control != &gfs->cb && assoc->backend))
287 statserv_setcontrol(assoc->last_control);
288 if (assoc->backend && assoc->init)
290 gfs_server_chdir(gfs);
291 (assoc->last_control->bend_close)(assoc->backend);
298 assoc->last_control = &gfs->cb;
299 statserv_setcontrol(&gfs->cb);
301 gfs_server_chdir(gfs);
307 statserv_setcontrol(0);
308 assoc->last_control = 0;
314 statserv_setcontrol(&control_block);
315 assoc->last_control = &control_block;
317 yaz_log(YLOG_DEBUG, "server select: config=%s",
318 assoc->last_control->configname);
320 assoc->maximumRecordSize = assoc->last_control->maxrecordsize;
321 assoc->preferredMessageSize = assoc->last_control->maxrecordsize;
322 cs_set_max_recv_bytes(assoc->client_link, assoc->maximumRecordSize);
326 static void xml_config_read(void)
328 struct gfs_server **gfsp = &gfs_server_list;
329 struct gfs_listen **gfslp = &gfs_listen_list;
331 xmlNodePtr ptr = xml_config_get_root();
335 for (ptr = ptr->children; ptr; ptr = ptr->next)
337 struct _xmlAttr *attr;
338 if (ptr->type != XML_ELEMENT_NODE)
340 attr = ptr->properties;
341 if (!strcmp((const char *) ptr->name, "listen"))
344 <listen id="listenerid">tcp:@:9999</listen>
347 const char *address =
348 nmem_dup_xml_content(gfs_nmem, ptr->children);
349 for ( ; attr; attr = attr->next)
350 if (!xmlStrcmp(attr->name, BAD_CAST "id")
351 && attr->children && attr->children->type == XML_TEXT_NODE)
352 id = nmem_dup_xml_content(gfs_nmem, attr->children);
355 *gfslp = gfs_listen_new(id, address);
356 gfslp = &(*gfslp)->next;
357 *gfslp = 0; /* make listener list consistent for search */
360 else if (!strcmp((const char *) ptr->name, "server"))
362 xmlNodePtr ptr_server = ptr;
364 const char *listenref = 0;
366 struct gfs_server *gfs;
368 for ( ; attr; attr = attr->next)
369 if (!xmlStrcmp(attr->name, BAD_CAST "listenref")
370 && attr->children && attr->children->type == XML_TEXT_NODE)
371 listenref = nmem_dup_xml_content(gfs_nmem, attr->children);
372 else if (!xmlStrcmp(attr->name, BAD_CAST "id")
374 && attr->children->type == XML_TEXT_NODE)
375 id = nmem_dup_xml_content(gfs_nmem, attr->children);
377 yaz_log(YLOG_WARN, "Unknown attribute '%s' for server",
379 gfs = *gfsp = gfs_server_new();
380 gfs->server_node_ptr = ptr_server;
384 struct gfs_listen *gl = gfs_listen_list;
385 for (id_no = 1; gl; gl = gl->next, id_no++)
386 if (gl->id && !strcmp(gl->id, listenref))
388 gfs->listen_ref = id_no;
392 yaz_log(YLOG_WARN, "Non-existent listenref '%s' in server "
393 "config element", listenref);
395 for (ptr = ptr_server->children; ptr; ptr = ptr->next)
397 if (ptr->type != XML_ELEMENT_NODE)
399 if (!strcmp((const char *) ptr->name, "host"))
401 gfs->host = nmem_dup_xml_content(gfs_nmem,
404 else if (!strcmp((const char *) ptr->name, "config"))
406 strcpy(gfs->cb.configname,
407 nmem_dup_xml_content(gfs_nmem, ptr->children));
409 else if (!strcmp((const char *) ptr->name, "cql2rpn"))
411 gfs->cql_transform = cql_transform_open_fname(
412 nmem_dup_xml_content(gfs_nmem, ptr->children)
415 else if (!strcmp((const char *) ptr->name, "ccl2rpn"))
420 name = nmem_dup_xml_content(gfs_nmem, ptr->children);
421 if ((f = fopen(name, "r")) == 0) {
422 yaz_log(YLOG_FATAL, "can't open CCL file '%s'", name);
425 gfs->ccl_transform = ccl_qual_mk();
426 ccl_qual_file (gfs->ccl_transform, f);
429 else if (!strcmp((const char *) ptr->name, "directory"))
432 nmem_dup_xml_content(gfs_nmem, ptr->children);
434 else if (!strcmp((const char *) ptr->name, "docpath"))
437 nmem_dup_xml_content(gfs_nmem, ptr->children);
439 else if (!strcmp((const char *) ptr->name, "maximumrecordsize"))
441 gfs->cb.maxrecordsize = atoi(
442 nmem_dup_xml_content(gfs_nmem, ptr->children));
444 else if (!strcmp((const char *) ptr->name, "stylesheet"))
446 char *s = nmem_dup_xml_content(gfs_nmem, ptr->children);
447 gfs->stylesheet = (char *)
448 nmem_malloc(gfs_nmem, strlen(s) + 2);
449 sprintf(gfs->stylesheet, "/%s", s);
451 else if (!strcmp((const char *) ptr->name, "explain"))
453 ; /* being processed separately */
455 else if (!strcmp((const char *) ptr->name, "retrievalinfo"))
457 if (yaz_retrieval_configure(gfs->retrieval, ptr))
459 yaz_log(YLOG_FATAL, "%s in config %s",
460 yaz_retrieval_get_error(gfs->retrieval),
461 control_block.xml_config);
467 yaz_log(YLOG_FATAL, "Unknown element '%s' in config %s",
468 ptr->name, control_block.xml_config);
472 gfsp = &(*gfsp)->next;
479 static void xml_config_open(void)
481 if (!getcwd(gfs_root_dir, FILENAME_MAX))
483 yaz_log(YLOG_WARN|YLOG_ERRNO, "getcwd failed");
484 gfs_root_dir[0] = '\0';
487 init_control_tls = 1;
488 current_control_tls = TlsAlloc();
489 #elif YAZ_POSIX_THREADS
490 init_control_tls = 1;
491 pthread_key_create(¤t_control_tls, 0);
494 gfs_nmem = nmem_create();
496 if (control_block.xml_config[0] == '\0')
501 xml_config_doc = xmlParseFile(control_block.xml_config);
504 yaz_log(YLOG_FATAL, "Could not parse %s", control_block.xml_config);
509 int noSubstitutions = xmlXIncludeProcess(xml_config_doc);
510 if (noSubstitutions == -1)
512 yaz_log(YLOG_WARN, "XInclude processing failed for config %s",
513 control_block.xml_config);
522 static void xml_config_close(void)
527 xmlFreeDoc(xml_config_doc);
532 nmem_destroy(gfs_nmem);
534 if (init_control_tls)
535 TlsFree(current_control_tls);
536 #elif YAZ_POSIX_THREADS
537 if (init_control_tls)
538 pthread_key_delete(current_control_tls);
542 static void xml_config_add_listeners(void)
544 struct gfs_listen *gfs = gfs_listen_list;
547 for (id_no = 1; gfs; gfs = gfs->next, id_no++)
550 add_listener(gfs->address, id_no);
554 static void xml_config_bend_start(void)
556 if (control_block.xml_config[0])
558 struct gfs_server *gfs = gfs_server_list;
559 for (; gfs; gfs = gfs->next)
561 yaz_log(YLOG_DEBUG, "xml_config_bend_start config=%s",
563 statserv_setcontrol(&gfs->cb);
564 if (control_block.bend_start)
566 gfs_server_chdir(gfs);
567 (control_block.bend_start)(&gfs->cb);
573 yaz_log(YLOG_DEBUG, "xml_config_bend_start default config");
574 statserv_setcontrol(&control_block);
575 if (control_block.bend_start)
576 (*control_block.bend_start)(&control_block);
580 static void xml_config_bend_stop(void)
582 if (control_block.xml_config[0])
584 struct gfs_server *gfs = gfs_server_list;
585 for (; gfs; gfs = gfs->next)
587 yaz_log(YLOG_DEBUG, "xml_config_bend_stop config=%s",
589 statserv_setcontrol(&gfs->cb);
590 if (control_block.bend_stop)
591 (control_block.bend_stop)(&gfs->cb);
596 yaz_log(YLOG_DEBUG, "xml_config_bend_stop default config");
597 statserv_setcontrol(&control_block);
598 if (control_block.bend_stop)
599 (*control_block.bend_stop)(&control_block);
604 * handle incoming connect requests.
605 * The dynamic mode is a bit tricky mostly because we want to avoid
606 * doing all of the listening and accepting in the parent - it's
611 typedef struct _ThreadList ThreadList;
620 static ThreadList *pFirstThread;
621 static CRITICAL_SECTION Thread_CritSect;
622 static BOOL bInitialized = FALSE;
624 static void ThreadList_Initialize()
626 /* Initialize the critical Sections */
627 InitializeCriticalSection(&Thread_CritSect);
629 /* Set the first thraed */
632 /* we have been initialized */
636 static void statserv_add(HANDLE hThread, IOCHAN pIOChannel)
638 /* Only one thread can go through this section at a time */
639 EnterCriticalSection(&Thread_CritSect);
642 /* Lets create our new object */
643 ThreadList *pNewThread = (ThreadList *)malloc(sizeof(ThreadList));
644 pNewThread->hThread = hThread;
645 pNewThread->pIOChannel = pIOChannel;
646 pNewThread->pNext = pFirstThread;
647 pFirstThread = pNewThread;
649 /* Lets let somebody else create a new object now */
650 LeaveCriticalSection(&Thread_CritSect);
654 void statserv_remove(IOCHAN pIOChannel)
656 /* Only one thread can go through this section at a time */
657 EnterCriticalSection(&Thread_CritSect);
660 ThreadList *pCurrentThread = pFirstThread;
661 ThreadList *pNextThread;
662 ThreadList *pPrevThread =NULL;
664 /* Step through all the threads */
665 for (; pCurrentThread != NULL; pCurrentThread = pNextThread)
667 /* We only need to compare on the IO Channel */
668 if (pCurrentThread->pIOChannel == pIOChannel)
670 /* We have found the thread we want to delete */
671 /* First of all reset the next pointers */
672 if (pPrevThread == NULL)
673 pFirstThread = pCurrentThread->pNext;
675 pPrevThread->pNext = pCurrentThread->pNext;
677 /* All we need todo now is delete the memory */
678 free(pCurrentThread);
680 /* No need to look at any more threads */
685 /* We need to look at another thread */
686 pNextThread = pCurrentThread->pNext;
687 pPrevThread = pCurrentThread;
691 /* Lets let somebody else remove an object now */
692 LeaveCriticalSection(&Thread_CritSect);
696 /* WIN32 statserv_closedown */
697 void statserv_closedown()
699 /* Shouldn't do anything if we are not initialized */
703 HANDLE *pThreadHandles = NULL;
705 /* We need to stop threads adding and removing while we */
706 /* start the closedown process */
707 EnterCriticalSection(&Thread_CritSect);
710 /* We have exclusive access to the thread stuff now */
711 /* Y didn't i use a semaphore - Oh well never mind */
712 ThreadList *pCurrentThread = pFirstThread;
714 /* Before we do anything else, we need to shutdown the listener */
715 if (pListener != NULL)
716 iochan_destroy(pListener);
718 for (; pCurrentThread != NULL; pCurrentThread = pCurrentThread->pNext)
720 /* Just destroy the IOCHAN, that should do the trick */
721 iochan_destroy(pCurrentThread->pIOChannel);
722 closesocket(pCurrentThread->pIOChannel->fd);
724 /* Keep a running count of our handles */
730 HANDLE *pCurrentHandle ;
732 /* Allocate the thread handle array */
733 pThreadHandles = (HANDLE *)malloc(sizeof(HANDLE) * iHandles);
734 pCurrentHandle = pThreadHandles;
736 for (pCurrentThread = pFirstThread;
737 pCurrentThread != NULL;
738 pCurrentThread = pCurrentThread->pNext, pCurrentHandle++)
740 /* Just the handle */
741 *pCurrentHandle = pCurrentThread->hThread;
745 /* We can now leave the critical section */
746 LeaveCriticalSection(&Thread_CritSect);
749 /* Now we can really do something */
752 yaz_log(log_server, "waiting for %d to die", iHandles);
753 /* This will now wait, until all the threads close */
754 WaitForMultipleObjects(iHandles, pThreadHandles, TRUE, INFINITE);
756 /* Free the memory we allocated for the handle array */
757 free(pThreadHandles);
760 xml_config_bend_stop();
761 /* No longer require the critical section, since all threads are dead */
762 DeleteCriticalSection(&Thread_CritSect);
767 void __cdecl event_loop_thread (IOCHAN iochan)
769 iochan_event_loop (&iochan);
773 static void listener(IOCHAN h, int event)
775 COMSTACK line = (COMSTACK) iochan_getdata(h);
776 IOCHAN parent_chan = line->user;
781 if (event == EVENT_INPUT)
786 if ((res = cs_listen(line, 0, 0)) < 0)
788 yaz_log(YLOG_FATAL|YLOG_ERRNO, "cs_listen failed");
792 return; /* incomplete */
793 yaz_log(YLOG_DEBUG, "listen ok");
794 new_line = cs_accept(line);
797 yaz_log(YLOG_FATAL, "Accept failed.");
800 yaz_log(YLOG_DEBUG, "Accept ok");
802 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session,
803 EVENT_INPUT, parent_chan->chan_id)))
805 yaz_log(YLOG_FATAL, "Failed to create iochan");
810 yaz_log(YLOG_DEBUG, "Creating association");
811 if (!(newas = create_association(new_chan, new_line,
812 control_block.apdufile)))
814 yaz_log(YLOG_FATAL, "Failed to create new assoc.");
818 newas->cs_get_mask = EVENT_INPUT;
819 newas->cs_put_mask = 0;
820 newas->cs_accept_mask = 0;
822 yaz_log(YLOG_DEBUG, "Setting timeout %d", control_block.idle_timeout);
823 iochan_setdata(new_chan, newas);
824 iochan_settimeout(new_chan, 60);
826 /* Now what we need todo is create a new thread with this iochan as
828 newHandle = (HANDLE) _beginthread(event_loop_thread, 0, new_chan);
829 if (newHandle == (HANDLE) -1)
832 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create new thread.");
836 /* We successfully created the thread, so add it to the list */
837 statserv_add(newHandle, new_chan);
839 yaz_log(YLOG_DEBUG, "Created new thread, id = %ld iochan %p",(long) newHandle, new_chan);
840 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
844 yaz_log(YLOG_FATAL, "Bad event on listener.");
850 int statserv_must_terminate(void)
857 static int term_flag = 0;
858 /* To save having an #ifdef in event_loop we need to
859 define this empty function
861 int statserv_must_terminate(void)
866 void statserv_remove(IOCHAN pIOChannel)
870 void statserv_closedown()
874 xml_config_bend_stop();
875 for (p = pListener; p; p = p->next)
882 void sigterm(int sig)
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 yaz_log(log_sessiondetail, "Connect from %s", cs_addrstr(new_line));
921 if (control_block.dynamic)
923 if ((res = fork()) < 0)
925 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fork");
929 else if (res == 0) /* child */
934 for (pp = pListener; pp; pp = iochan_getnext(pp))
936 COMSTACK l = (COMSTACK)iochan_getdata(pp);
940 sprintf(nbuf, "%s(%d)", me, no_sessions);
941 yaz_log_init_prefix(nbuf);
942 /* ensure that bend_stop is not called when each child exits -
943 only for the main process .. */
944 control_block.bend_stop = 0;
953 if (control_block.threads)
955 #if YAZ_POSIX_THREADS
956 pthread_t child_thread;
957 pthread_create (&child_thread, 0, new_session, new_line);
958 pthread_detach (child_thread);
959 #elif YAZ_GNU_THREADS
963 attr = pth_attr_new ();
964 pth_attr_set (attr, PTH_ATTR_JOINABLE, FALSE);
965 pth_attr_set (attr, PTH_ATTR_STACK_SIZE, 32*1024);
966 pth_attr_set (attr, PTH_ATTR_NAME, "session");
967 yaz_log (YLOG_DEBUG, "pth_spawn begin");
968 child_thread = pth_spawn (attr, new_session, new_line);
969 yaz_log (YLOG_DEBUG, "pth_spawn finish");
970 pth_attr_destroy (attr);
972 new_session(new_line);
976 new_session(new_line);
978 else if (event == EVENT_TIMEOUT)
980 yaz_log(log_server, "Shutting down listener.");
985 yaz_log(YLOG_FATAL, "Bad event on listener.");
990 static void *new_session (void *vp)
995 COMSTACK new_line = (COMSTACK) vp;
996 IOCHAN parent_chan = (IOCHAN) new_line->user;
998 unsigned cs_get_mask, cs_accept_mask, mask =
999 ((new_line->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
1000 ((new_line->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
1004 cs_accept_mask = mask; /* accept didn't complete */
1009 cs_accept_mask = 0; /* accept completed. */
1010 cs_get_mask = mask = EVENT_INPUT;
1013 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session, mask,
1014 parent_chan->chan_id)))
1016 yaz_log(YLOG_FATAL, "Failed to create iochan");
1019 if (!(newas = create_association(new_chan, new_line,
1020 control_block.apdufile)))
1022 yaz_log(YLOG_FATAL, "Failed to create new assoc.");
1025 newas->cs_accept_mask = cs_accept_mask;
1026 newas->cs_get_mask = cs_get_mask;
1028 iochan_setdata(new_chan, newas);
1029 iochan_settimeout(new_chan, 60);
1031 a = cs_addrstr(new_line);
1035 yaz_log(log_session, "Session - OK %d %s %ld",
1036 no_sessions, a ? a : "[Unknown]", (long) getpid());
1037 if (max_sessions && no_sessions >= max_sessions)
1038 control_block.one_shot = 1;
1039 if (control_block.threads)
1041 iochan_event_loop(&new_chan);
1045 new_chan->next = pListener;
1046 pListener = new_chan;
1054 static void inetd_connection(int what)
1061 if ((line = cs_createbysocket(0, tcpip_type, 0, what)))
1063 if ((chan = iochan_create(cs_fileno(line), ir_session, EVENT_INPUT,
1066 if ((assoc = create_association(chan, line,
1067 control_block.apdufile)))
1069 iochan_setdata(chan, assoc);
1070 iochan_settimeout(chan, 60);
1071 addr = cs_addrstr(line);
1072 yaz_log(log_sessiondetail, "Inetd association from %s",
1073 addr ? addr : "[UNKNOWN]");
1074 assoc->cs_get_mask = EVENT_INPUT;
1078 yaz_log(YLOG_FATAL, "Failed to create association structure");
1080 chan->next = pListener;
1085 yaz_log(YLOG_FATAL, "Failed to create iochan");
1090 yaz_log(YLOG_ERRNO|YLOG_FATAL, "Failed to create comstack on socket 0");
1095 * Set up a listening endpoint, and give it to the event-handler.
1097 static int add_listener(char *where, int listen_id)
1104 if (control_block.dynamic)
1106 else if (control_block.threads)
1111 yaz_log(log_server, "Adding %s listener on %s id=%d", mode, where,
1114 l = cs_create_host(where, 2, &ap);
1117 yaz_log(YLOG_FATAL, "Failed to listen on %s", where);
1120 if (*control_block.cert_fname)
1121 cs_set_ssl_certificate_file(l, control_block.cert_fname);
1123 if (cs_bind(l, ap, CS_SERVER) < 0)
1125 if (cs_errno(l) == CSYSERR)
1126 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to bind to %s", where);
1128 yaz_log(YLOG_FATAL, "Failed to bind to %s: %s", where,
1133 if (!(lst = iochan_create(cs_fileno(l), listener, EVENT_INPUT |
1134 EVENT_EXCEPT, listen_id)))
1136 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create IOCHAN-type");
1140 iochan_setdata(lst, l); /* user-defined data for listener is COMSTACK */
1141 l->user = lst; /* user-defined data for COMSTACK is listener chan */
1143 /* Add listener to chain */
1144 lst->next = pListener;
1150 /* UNIX only (for windows we don't need to catch the signals) */
1151 static void catchchld(int num)
1153 while (waitpid(-1, 0, WNOHANG) > 0)
1155 signal(SIGCHLD, catchchld);
1159 statserv_options_block *statserv_getcontrol(void)
1162 if (init_control_tls)
1163 return (statserv_options_block *) TlsGetValue(current_control_tls);
1165 return &control_block;
1166 #elif YAZ_POSIX_THREADS
1167 if (init_control_tls)
1168 return (statserv_options_block *)
1169 pthread_getspecific(current_control_tls);
1171 return &control_block;
1173 if (current_control_block)
1174 return current_control_block;
1175 return &control_block;
1179 void statserv_setcontrol(statserv_options_block *block)
1181 chdir(gfs_root_dir);
1183 if (init_control_tls)
1184 TlsSetValue(current_control_tls, block);
1185 #elif YAZ_POSIX_THREADS
1186 if (init_control_tls)
1187 pthread_setspecific(current_control_tls, block);
1189 current_control_block = block;
1193 static void statserv_reset(void)
1197 int statserv_start(int argc, char **argv)
1201 /* We need to initialize the thread list */
1202 ThreadList_Initialize();
1212 if ((me = strrchr (argv[0], sep)))
1213 me++; /* get the basename */
1216 programname = argv[0];
1218 if (control_block.options_func(argc, argv))
1223 xml_config_bend_start();
1226 xml_config_add_listeners();
1228 yaz_log (log_server, "Starting server %s", me);
1229 if (!pListener && *control_block.default_listen)
1230 add_listener(control_block.default_listen, 0);
1233 if (control_block.inetd)
1234 inetd_connection(control_block.default_proto);
1238 if (control_block.background)
1240 /* create pipe so that parent waits until child has created
1244 yaz_log(YLOG_FATAL|YLOG_ERRNO, "pipe");
1258 int res = read(hand[0], dummy, 1);
1259 if (res < 0 && yaz_errno() != EINTR)
1261 yaz_log(YLOG_FATAL|YLOG_ERRNO, "read fork handshake");
1278 open("/dev/null", O_RDWR);
1281 xml_config_add_listeners();
1283 if (!pListener && *control_block.default_listen)
1284 add_listener(control_block.default_listen, 0);
1289 if (*control_block.pid_fname)
1291 FILE *f = fopen(control_block.pid_fname, "w");
1294 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Couldn't create %s",
1295 control_block.pid_fname);
1298 fprintf(f, "%ld", (long) getpid());
1302 if (control_block.background)
1306 yaz_log (log_server, "Starting server %s pid=%ld", programname,
1309 sigset_t sigs_to_block;
1311 sigemptyset(&sigs_to_block);
1312 sigaddset (&sigs_to_block, SIGTERM);
1313 pthread_sigmask (SIG_BLOCK, &sigs_to_block, 0);
1316 if (control_block.dynamic)
1317 signal(SIGCHLD, catchchld);
1319 signal (SIGPIPE, SIG_IGN);
1320 signal (SIGTERM, sigterm);
1321 if (*control_block.setuid)
1325 if (!(pw = getpwnam(control_block.setuid)))
1327 yaz_log(YLOG_FATAL, "%s: Unknown user", control_block.setuid);
1330 if (setuid(pw->pw_uid) < 0)
1332 yaz_log(YLOG_FATAL|YLOG_ERRNO, "setuid");
1338 if (pListener == NULL)
1340 yaz_log(YLOG_DEBUG, "Entering event loop.");
1341 return iochan_event_loop(&pListener);
1344 static void option_copy(char *dst, const char *src)
1346 strncpy(dst, src ? src : "", 127);
1350 int check_options(int argc, char **argv)
1355 yaz_log_init_level(yaz_log_mask_str(STAT_DEFAULT_LOG_LEVEL));
1357 yaz_log_xml_errors(0, YLOG_WARN);
1360 while ((ret = options("1a:iszSTl:v:u:c:w:t:k:d:A:p:DC:f:m:r:",
1361 argv, argc, &arg)) != -2)
1366 if (add_listener(arg, 0))
1367 return 1; /* failed to create listener */
1370 control_block.one_shot = 1;
1371 control_block.dynamic = 0;
1374 control_block.default_proto = PROTO_Z3950;
1377 fprintf (stderr, "%s: SR protocol no longer supported\n", me);
1381 control_block.dynamic = 0;
1384 #if YAZ_POSIX_THREADS
1385 control_block.dynamic = 0;
1386 control_block.threads = 1;
1387 #elif YAZ_GNU_THREADS
1388 control_block.dynamic = 0;
1389 control_block.threads = 1;
1391 fprintf(stderr, "%s: Threaded mode not available.\n", me);
1396 option_copy(control_block.logfile, arg);
1397 yaz_log_init_file(control_block.logfile);
1401 fprintf(stderr, "%s: Specify time format for log file.\n", me);
1404 yaz_log_time_format(arg);
1407 yaz_log_init_level(yaz_log_mask_str(arg));
1411 option_copy(control_block.apdufile, arg);
1414 option_copy(control_block.setuid, arg);
1417 option_copy(control_block.configname, arg);
1420 option_copy(control_block.cert_fname, arg);
1423 option_copy(control_block.daemon_name, arg);
1426 if (!arg || !(r = atoi(arg)))
1428 fprintf(stderr, "%s: Specify positive timeout for -t.\n", me);
1431 control_block.idle_timeout = r;
1434 if (!arg || !(r = atoi(arg)))
1436 fprintf(stderr, "%s: Specify positive size for -k.\n", me);
1439 control_block.maxrecordsize = r * 1024;
1442 control_block.inetd = 1;
1452 max_sessions = atoi(arg);
1455 option_copy(control_block.pid_fname, arg);
1459 option_copy(control_block.xml_config, arg);
1461 fprintf(stderr, "%s: Option -f unsupported since YAZ is compiled without Libxml2 support\n", me);
1466 control_block.background = 1;
1469 if (!arg || !(r = atoi(arg)))
1471 fprintf(stderr, "%s: Specify positive size for -r.\n", me);
1474 yaz_log_init_max_size(r * 1024);
1477 fprintf(stderr, "Usage: %s [ -a <pdufile> -v <loglevel>"
1478 " -l <logfile> -u <user> -c <config> -t <minutes>"
1479 " -k <kilobytes> -d <daemon> -p <pidfile> -C certfile"
1480 " -ziDST1 -m <time-format> -w <directory> <listener-addr>... ]\n", me);
1488 typedef struct _Args
1494 static Args ArgDetails;
1496 /* name of the executable */
1497 #define SZAPPNAME "server"
1499 /* list of service dependencies - "dep1\0dep2\0\0" */
1500 #define SZDEPENDENCIES ""
1502 int statserv_main(int argc, char **argv,
1503 bend_initresult *(*bend_init)(bend_initrequest *r),
1504 void (*bend_close)(void *handle))
1506 struct statserv_options_block *cb = &control_block;
1507 cb->bend_init = bend_init;
1508 cb->bend_close = bend_close;
1510 /* Lets setup the Arg structure */
1511 ArgDetails.argc = argc;
1512 ArgDetails.argv = argv;
1514 /* Now setup the service with the service controller */
1515 SetupService(argc, argv, &ArgDetails, SZAPPNAME,
1516 cb->service_name, /* internal service name */
1517 cb->service_display_name, /* displayed name */
1522 int StartAppService(void *pHandle, int argc, char **argv)
1524 /* Initializes the App */
1528 void RunAppService(void *pHandle)
1530 Args *pArgs = (Args *)pHandle;
1532 /* Starts the app running */
1533 statserv_start(pArgs->argc, pArgs->argv);
1536 void StopAppService(void *pHandle)
1539 statserv_closedown();
1545 int statserv_main(int argc, char **argv,
1546 bend_initresult *(*bend_init)(bend_initrequest *r),
1547 void (*bend_close)(void *handle))
1551 control_block.bend_init = bend_init;
1552 control_block.bend_close = bend_close;
1554 ret = statserv_start (argc, argv);
1555 statserv_closedown ();
1563 * indent-tabs-mode: nil
1565 * vim: shiftwidth=4 tabstop=8 expandtab