1 /* This file is part of the YAZ toolkit.
2 * Copyright (C) 1995-2010 Index Data
3 * See the file LICENSE for details.
8 * \brief Implements GFS logic
25 #include <sys/types.h>
38 #include <libxml/parser.h>
39 #include <libxml/tree.h>
40 #include <libxml/xinclude.h>
53 #include <yaz/comstack.h>
54 #include <yaz/tcpip.h>
55 #include <yaz/options.h>
56 #include <yaz/errno.h>
58 #include <yaz/xmosi.h>
63 #include <yaz/statserv.h>
65 static IOCHAN pListener = NULL;
67 static char gfs_root_dir[FILENAME_MAX+1];
68 static struct gfs_server *gfs_server_list = 0;
69 static struct gfs_listen *gfs_listen_list = 0;
70 static NMEM gfs_nmem = 0;
72 static char *me = "statserver"; /* log prefix */
73 static char *programname="statserver"; /* full program name */
75 DWORD current_control_tls;
76 static int init_control_tls = 0;
77 #elif YAZ_POSIX_THREADS
78 static pthread_key_t current_control_tls;
79 static int init_control_tls = 0;
81 static statserv_options_block *current_control_block = 0;
87 #define STAT_DEFAULT_LOG_LEVEL "server,session,request"
89 int check_options(int argc, char **argv);
90 statserv_options_block control_block = {
92 0, /* threaded mode */
93 0, /* one shot (single session) */
95 "", /* diagnostic output to stderr */
96 "tcp:@:9999", /* default listener port */
97 PROTO_Z3950, /* default application protocol */
98 15, /* idle timeout (minutes) */
99 1024*1024, /* maximum PDU size (approx.) to allow */
100 "default-config", /* configuration name to pass to backend */
101 "", /* set user id */
102 0, /* bend_start handler */
103 0, /* bend_stop handler */
104 check_options, /* Default routine, for checking the run-time arguments */
107 0, /* default value for inet deamon */
108 0, /* handle (for service, etc) */
109 0, /* bend_init handle */
110 0, /* bend_close handle */
112 "Z39.50 Server", /* NT Service Name */
113 "Server", /* NT application Name */
114 "", /* NT Service Dependencies */
115 "Z39.50 Server", /* NT Service Display Name */
117 0, /* SOAP handlers */
119 0, /* background daemon */
120 "", /* SSL certificate filename */
121 "" /* XML config filename */
124 static int max_sessions = 0;
126 static int logbits_set = 0;
127 static int log_session = 0; /* one-line logs for session */
128 static int log_sessiondetail = 0; /* more detailed stuff */
129 static int log_server = 0;
131 /** get_logbits sets global loglevel bits */
132 static void get_logbits(int force)
133 { /* needs to be called after parsing cmd-line args that can set loglevels!*/
134 if (force || !logbits_set)
137 log_session = yaz_log_module_level("session");
138 log_sessiondetail = yaz_log_module_level("sessiondetail");
139 log_server = yaz_log_module_level("server");
144 static int add_listener(char *where, int listen_id);
147 static xmlDocPtr xml_config_doc = 0;
151 static xmlNodePtr xml_config_get_root(void)
156 ptr = xmlDocGetRootElement(xml_config_doc);
157 if (!ptr || ptr->type != XML_ELEMENT_NODE ||
158 strcmp((const char *) ptr->name, "yazgfs"))
160 yaz_log(YLOG_WARN, "Bad/missing root element for config %s",
161 control_block.xml_config);
171 static char *nmem_dup_xml_content(NMEM n, xmlNodePtr ptr)
175 int len = 1; /* start with 1, because of trailing 0 */
177 int first = 1; /* whitespace lead flag .. */
178 /* determine length */
179 for (p = ptr; p; p = p->next)
181 if (p->type == XML_TEXT_NODE)
182 len += xmlStrlen(p->content);
184 /* now allocate for the string */
185 str = (unsigned char *) nmem_malloc(n, len);
186 *str = '\0'; /* so we can use strcat */
187 for (p = ptr; p; p = p->next)
189 if (p->type == XML_TEXT_NODE)
194 while(*cp && isspace(*cp))
197 first = 0; /* reset if we got non-whitespace out */
199 strcat((char *)str, (const char *)cp); /* append */
202 /* remove trailing whitespace */
203 cp = strlen((const char *)str) + str;
204 while (cp != str && isspace(cp[-1]))
207 /* return resulting string */
213 static struct gfs_server * gfs_server_new(void)
215 struct gfs_server *n = (struct gfs_server *)
216 nmem_malloc(gfs_nmem, sizeof(*n));
217 memcpy(&n->cb, &control_block, sizeof(control_block));
221 n->cql_transform = 0;
222 n->ccl_transform = 0;
223 n->server_node_ptr = 0;
227 n->retrieval = yaz_retrieval_create();
233 static struct gfs_listen * gfs_listen_new(const char *id,
236 struct gfs_listen *n = (struct gfs_listen *)
237 nmem_malloc(gfs_nmem, sizeof(*n));
239 n->id = nmem_strdup(gfs_nmem, id);
243 n->address = nmem_strdup(gfs_nmem, address);
248 static void gfs_server_chdir(struct gfs_server *gfs)
252 if (chdir(gfs_root_dir))
253 yaz_log(YLOG_WARN|YLOG_ERRNO, "chdir %s", gfs_root_dir);
257 if (chdir(gfs->directory))
258 yaz_log(YLOG_WARN|YLOG_ERRNO, "chdir %s",
263 int control_association(association *assoc, const char *host, int force_open)
265 char vhost[128], *cp;
268 strncpy(vhost, host, 127);
270 cp = strchr(vhost, ':');
276 if (control_block.xml_config[0])
278 struct gfs_server *gfs;
279 for (gfs = gfs_server_list; gfs; gfs = gfs->next)
281 int listen_match = 0;
283 if ( !gfs->host || (host && gfs->host && !strcmp(host, gfs->host)))
285 if (!gfs->listen_ref ||
286 gfs->listen_ref == assoc->client_chan->chan_id)
288 if (listen_match && host_match)
291 (assoc->last_control != &gfs->cb && assoc->backend))
293 statserv_setcontrol(assoc->last_control);
294 if (assoc->backend && assoc->init)
296 gfs_server_chdir(gfs);
297 (assoc->last_control->bend_close)(assoc->backend);
304 assoc->last_control = &gfs->cb;
305 statserv_setcontrol(&gfs->cb);
307 gfs_server_chdir(gfs);
313 statserv_setcontrol(0);
314 assoc->last_control = 0;
320 statserv_setcontrol(&control_block);
321 assoc->last_control = &control_block;
323 yaz_log(YLOG_DEBUG, "server select: config=%s",
324 assoc->last_control->configname);
326 assoc->maximumRecordSize = assoc->last_control->maxrecordsize;
327 assoc->preferredMessageSize = assoc->last_control->maxrecordsize;
328 cs_set_max_recv_bytes(assoc->client_link, assoc->maximumRecordSize);
333 static void xml_config_read(void)
335 struct gfs_server **gfsp = &gfs_server_list;
336 struct gfs_listen **gfslp = &gfs_listen_list;
337 xmlNodePtr ptr = xml_config_get_root();
341 for (ptr = ptr->children; ptr; ptr = ptr->next)
343 struct _xmlAttr *attr;
344 if (ptr->type != XML_ELEMENT_NODE)
346 attr = ptr->properties;
347 if (!strcmp((const char *) ptr->name, "listen"))
350 <listen id="listenerid">tcp:@:9999</listen>
353 const char *address =
354 nmem_dup_xml_content(gfs_nmem, ptr->children);
355 for ( ; attr; attr = attr->next)
356 if (!xmlStrcmp(attr->name, BAD_CAST "id")
357 && attr->children && attr->children->type == XML_TEXT_NODE)
358 id = nmem_dup_xml_content(gfs_nmem, attr->children);
361 *gfslp = gfs_listen_new(id, address);
362 gfslp = &(*gfslp)->next;
363 *gfslp = 0; /* make listener list consistent for search */
366 else if (!strcmp((const char *) ptr->name, "server"))
368 xmlNodePtr ptr_server = ptr;
370 const char *listenref = 0;
372 struct gfs_server *gfs;
374 for ( ; attr; attr = attr->next)
375 if (!xmlStrcmp(attr->name, BAD_CAST "listenref")
376 && attr->children && attr->children->type == XML_TEXT_NODE)
377 listenref = nmem_dup_xml_content(gfs_nmem, attr->children);
378 else if (!xmlStrcmp(attr->name, BAD_CAST "id")
380 && attr->children->type == XML_TEXT_NODE)
381 id = nmem_dup_xml_content(gfs_nmem, attr->children);
383 yaz_log(YLOG_WARN, "Unknown attribute '%s' for server",
385 gfs = *gfsp = gfs_server_new();
386 gfs->server_node_ptr = ptr_server;
390 struct gfs_listen *gl = gfs_listen_list;
391 for (id_no = 1; gl; gl = gl->next, id_no++)
392 if (gl->id && !strcmp(gl->id, listenref))
394 gfs->listen_ref = id_no;
398 yaz_log(YLOG_WARN, "Non-existent listenref '%s' in server "
399 "config element", listenref);
401 for (ptr = ptr_server->children; ptr; ptr = ptr->next)
403 if (ptr->type != XML_ELEMENT_NODE)
405 if (!strcmp((const char *) ptr->name, "host"))
407 gfs->host = nmem_dup_xml_content(gfs_nmem,
410 else if (!strcmp((const char *) ptr->name, "config"))
412 strcpy(gfs->cb.configname,
413 nmem_dup_xml_content(gfs_nmem, ptr->children));
415 else if (!strcmp((const char *) ptr->name, "cql2rpn"))
417 gfs->cql_transform = cql_transform_open_fname(
418 nmem_dup_xml_content(gfs_nmem, ptr->children)
421 else if (!strcmp((const char *) ptr->name, "ccl2rpn"))
426 name = nmem_dup_xml_content(gfs_nmem, ptr->children);
427 if ((f = fopen(name, "r")) == 0) {
428 yaz_log(YLOG_FATAL, "can't open CCL file '%s'", name);
431 gfs->ccl_transform = ccl_qual_mk();
432 ccl_qual_file (gfs->ccl_transform, f);
435 else if (!strcmp((const char *) ptr->name, "directory"))
438 nmem_dup_xml_content(gfs_nmem, ptr->children);
440 else if (!strcmp((const char *) ptr->name, "docpath"))
443 nmem_dup_xml_content(gfs_nmem, ptr->children);
445 else if (!strcmp((const char *) ptr->name, "maximumrecordsize"))
447 gfs->cb.maxrecordsize = atoi(
448 nmem_dup_xml_content(gfs_nmem, ptr->children));
450 else if (!strcmp((const char *) ptr->name, "stylesheet"))
452 char *s = nmem_dup_xml_content(gfs_nmem, ptr->children);
453 gfs->stylesheet = (char *)
454 nmem_malloc(gfs_nmem, strlen(s) + 2);
455 sprintf(gfs->stylesheet, "/%s", s);
457 else if (!strcmp((const char *) ptr->name, "explain"))
459 ; /* being processed separately */
461 else if (!strcmp((const char *) ptr->name, "retrievalinfo"))
463 if (yaz_retrieval_configure(gfs->retrieval, ptr))
465 yaz_log(YLOG_FATAL, "%s in config %s",
466 yaz_retrieval_get_error(gfs->retrieval),
467 control_block.xml_config);
473 yaz_log(YLOG_FATAL, "Unknown element '%s' in config %s",
474 ptr->name, control_block.xml_config);
478 gfsp = &(*gfsp)->next;
485 static void xml_config_open(void)
487 if (!getcwd(gfs_root_dir, FILENAME_MAX))
489 yaz_log(YLOG_WARN|YLOG_ERRNO, "getcwd failed");
490 gfs_root_dir[0] = '\0';
493 init_control_tls = 1;
494 current_control_tls = TlsAlloc();
495 #elif YAZ_POSIX_THREADS
496 init_control_tls = 1;
497 pthread_key_create(¤t_control_tls, 0);
500 gfs_nmem = nmem_create();
502 if (control_block.xml_config[0] == '\0')
507 xml_config_doc = xmlParseFile(control_block.xml_config);
510 yaz_log(YLOG_FATAL, "Could not parse %s", control_block.xml_config);
515 int noSubstitutions = xmlXIncludeProcess(xml_config_doc);
516 if (noSubstitutions == -1)
518 yaz_log(YLOG_WARN, "XInclude processing failed for config %s",
519 control_block.xml_config);
528 static void xml_config_close(void)
533 xmlFreeDoc(xml_config_doc);
538 nmem_destroy(gfs_nmem);
540 if (init_control_tls)
541 TlsFree(current_control_tls);
542 #elif YAZ_POSIX_THREADS
543 if (init_control_tls)
544 pthread_key_delete(current_control_tls);
548 static void xml_config_add_listeners(void)
550 struct gfs_listen *gfs = gfs_listen_list;
553 for (id_no = 1; gfs; gfs = gfs->next, id_no++)
556 add_listener(gfs->address, id_no);
560 static void xml_config_bend_start(void)
562 if (control_block.xml_config[0])
564 struct gfs_server *gfs = gfs_server_list;
565 for (; gfs; gfs = gfs->next)
567 yaz_log(YLOG_DEBUG, "xml_config_bend_start config=%s",
569 statserv_setcontrol(&gfs->cb);
570 if (control_block.bend_start)
572 gfs_server_chdir(gfs);
573 (control_block.bend_start)(&gfs->cb);
579 yaz_log(YLOG_DEBUG, "xml_config_bend_start default config");
580 statserv_setcontrol(&control_block);
581 if (control_block.bend_start)
582 (*control_block.bend_start)(&control_block);
586 static void xml_config_bend_stop(void)
588 if (control_block.xml_config[0])
590 struct gfs_server *gfs = gfs_server_list;
591 for (; gfs; gfs = gfs->next)
593 yaz_log(YLOG_DEBUG, "xml_config_bend_stop config=%s",
595 statserv_setcontrol(&gfs->cb);
596 if (control_block.bend_stop)
597 (control_block.bend_stop)(&gfs->cb);
602 yaz_log(YLOG_DEBUG, "xml_config_bend_stop default config");
603 statserv_setcontrol(&control_block);
604 if (control_block.bend_stop)
605 (*control_block.bend_stop)(&control_block);
610 * handle incoming connect requests.
611 * The dynamic mode is a bit tricky mostly because we want to avoid
612 * doing all of the listening and accepting in the parent - it's
617 typedef struct _ThreadList ThreadList;
626 static ThreadList *pFirstThread;
627 static CRITICAL_SECTION Thread_CritSect;
628 static BOOL bInitialized = FALSE;
630 static void ThreadList_Initialize()
632 /* Initialize the critical Sections */
633 InitializeCriticalSection(&Thread_CritSect);
635 /* Set the first thraed */
638 /* we have been initialized */
642 static void statserv_add(HANDLE hThread, IOCHAN pIOChannel)
644 /* Only one thread can go through this section at a time */
645 EnterCriticalSection(&Thread_CritSect);
648 /* Lets create our new object */
649 ThreadList *pNewThread = (ThreadList *)malloc(sizeof(ThreadList));
650 pNewThread->hThread = hThread;
651 pNewThread->pIOChannel = pIOChannel;
652 pNewThread->pNext = pFirstThread;
653 pFirstThread = pNewThread;
655 /* Lets let somebody else create a new object now */
656 LeaveCriticalSection(&Thread_CritSect);
660 void statserv_remove(IOCHAN pIOChannel)
662 /* Only one thread can go through this section at a time */
663 EnterCriticalSection(&Thread_CritSect);
666 ThreadList *pCurrentThread = pFirstThread;
667 ThreadList *pNextThread;
668 ThreadList *pPrevThread =NULL;
670 /* Step through all the threads */
671 for (; pCurrentThread != NULL; pCurrentThread = pNextThread)
673 /* We only need to compare on the IO Channel */
674 if (pCurrentThread->pIOChannel == pIOChannel)
676 /* We have found the thread we want to delete */
677 /* First of all reset the next pointers */
678 if (pPrevThread == NULL)
679 pFirstThread = pCurrentThread->pNext;
681 pPrevThread->pNext = pCurrentThread->pNext;
683 /* All we need todo now is delete the memory */
684 free(pCurrentThread);
686 /* No need to look at any more threads */
691 /* We need to look at another thread */
692 pNextThread = pCurrentThread->pNext;
693 pPrevThread = pCurrentThread;
697 /* Lets let somebody else remove an object now */
698 LeaveCriticalSection(&Thread_CritSect);
702 /* WIN32 statserv_closedown */
703 static void statserv_closedown()
705 /* Shouldn't do anything if we are not initialized */
709 HANDLE *pThreadHandles = NULL;
711 /* We need to stop threads adding and removing while we */
712 /* start the closedown process */
713 EnterCriticalSection(&Thread_CritSect);
716 /* We have exclusive access to the thread stuff now */
717 /* Y didn't i use a semaphore - Oh well never mind */
718 ThreadList *pCurrentThread = pFirstThread;
720 /* Before we do anything else, we need to shutdown the listener */
721 if (pListener != NULL)
722 iochan_destroy(pListener);
724 for (; pCurrentThread != NULL; pCurrentThread = pCurrentThread->pNext)
726 /* Just destroy the IOCHAN, that should do the trick */
727 iochan_destroy(pCurrentThread->pIOChannel);
728 closesocket(pCurrentThread->pIOChannel->fd);
730 /* Keep a running count of our handles */
736 HANDLE *pCurrentHandle ;
738 /* Allocate the thread handle array */
739 pThreadHandles = (HANDLE *)malloc(sizeof(HANDLE) * iHandles);
740 pCurrentHandle = pThreadHandles;
742 for (pCurrentThread = pFirstThread;
743 pCurrentThread != NULL;
744 pCurrentThread = pCurrentThread->pNext, pCurrentHandle++)
746 /* Just the handle */
747 *pCurrentHandle = pCurrentThread->hThread;
751 /* We can now leave the critical section */
752 LeaveCriticalSection(&Thread_CritSect);
755 /* Now we can really do something */
758 yaz_log(log_server, "waiting for %d to die", iHandles);
759 /* This will now wait, until all the threads close */
760 WaitForMultipleObjects(iHandles, pThreadHandles, TRUE, INFINITE);
762 /* Free the memory we allocated for the handle array */
763 free(pThreadHandles);
766 xml_config_bend_stop();
767 /* No longer require the critical section, since all threads are dead */
768 DeleteCriticalSection(&Thread_CritSect);
773 void __cdecl event_loop_thread(IOCHAN iochan)
775 iochan_event_loop(&iochan);
779 static void listener(IOCHAN h, int event)
781 COMSTACK line = (COMSTACK) iochan_getdata(h);
782 IOCHAN parent_chan = line->user;
787 if (event == EVENT_INPUT)
792 if ((res = cs_listen(line, 0, 0)) < 0)
794 yaz_log(YLOG_FATAL|YLOG_ERRNO, "cs_listen failed");
798 return; /* incomplete */
799 yaz_log(YLOG_DEBUG, "listen ok");
800 new_line = cs_accept(line);
803 yaz_log(YLOG_FATAL, "Accept failed.");
806 yaz_log(YLOG_DEBUG, "Accept ok");
808 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session,
809 EVENT_INPUT, parent_chan->chan_id)))
811 yaz_log(YLOG_FATAL, "Failed to create iochan");
816 yaz_log(YLOG_DEBUG, "Creating association");
817 if (!(newas = create_association(new_chan, new_line,
818 control_block.apdufile)))
820 yaz_log(YLOG_FATAL, "Failed to create new assoc.");
824 newas->cs_get_mask = EVENT_INPUT;
825 newas->cs_put_mask = 0;
826 newas->cs_accept_mask = 0;
828 yaz_log(YLOG_DEBUG, "Setting timeout %d", control_block.idle_timeout);
829 iochan_setdata(new_chan, newas);
830 iochan_settimeout(new_chan, 60);
832 /* Now what we need todo is create a new thread with this iochan as
834 newHandle = (HANDLE) _beginthread(event_loop_thread, 0, new_chan);
835 if (newHandle == (HANDLE) -1)
838 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create new thread.");
842 /* We successfully created the thread, so add it to the list */
843 statserv_add(newHandle, new_chan);
845 yaz_log(YLOG_DEBUG, "Created new thread, id = %ld iochan %p",(long) newHandle, new_chan);
846 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
850 yaz_log(YLOG_FATAL, "Bad event on listener.");
856 int statserv_must_terminate(void)
863 static int term_flag = 0;
864 /* To save having an #ifdef in event_loop we need to
865 define this empty function
867 int statserv_must_terminate(void)
872 void statserv_remove(IOCHAN pIOChannel)
876 static void statserv_closedown(void)
880 xml_config_bend_stop();
881 for (p = pListener; p; p = p->next)
888 void sigterm(int sig)
893 static void *new_session(void *vp);
894 static int no_sessions = 0;
897 static void listener(IOCHAN h, int event)
899 COMSTACK line = (COMSTACK) iochan_getdata(h);
902 if (event == EVENT_INPUT)
905 if ((res = cs_listen_check(line, 0, 0, control_block.check_ip,
906 control_block.daemon_name)) < 0)
908 yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_listen failed");
913 yaz_log(YLOG_WARN, "cs_listen incomplete");
916 new_line = cs_accept(line);
919 yaz_log(YLOG_FATAL, "Accept failed.");
920 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
924 yaz_log(log_sessiondetail, "Connect from %s", cs_addrstr(new_line));
927 if (control_block.dynamic)
929 if ((res = fork()) < 0)
931 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fork");
935 else if (res == 0) /* child */
940 for (pp = pListener; pp; pp = iochan_getnext(pp))
942 COMSTACK l = (COMSTACK)iochan_getdata(pp);
946 sprintf(nbuf, "%s(%d)", me, no_sessions);
947 yaz_log_init_prefix(nbuf);
948 /* ensure that bend_stop is not called when each child exits -
949 only for the main process .. */
950 control_block.bend_stop = 0;
959 if (control_block.threads)
961 #if YAZ_POSIX_THREADS
962 pthread_t child_thread;
963 pthread_create(&child_thread, 0, new_session, new_line);
964 pthread_detach(child_thread);
965 #elif YAZ_GNU_THREADS
969 attr = pth_attr_new();
970 pth_attr_set(attr, PTH_ATTR_JOINABLE, FALSE);
971 pth_attr_set(attr, PTH_ATTR_STACK_SIZE, 32*1024);
972 pth_attr_set(attr, PTH_ATTR_NAME, "session");
973 yaz_log(YLOG_DEBUG, "pth_spawn begin");
974 child_thread = pth_spawn(attr, new_session, new_line);
975 yaz_log(YLOG_DEBUG, "pth_spawn finish");
976 pth_attr_destroy(attr);
978 new_session(new_line);
982 new_session(new_line);
984 else if (event == EVENT_TIMEOUT)
986 yaz_log(log_server, "Shutting down listener.");
991 yaz_log(YLOG_FATAL, "Bad event on listener.");
996 static void *new_session(void *vp)
1001 COMSTACK new_line = (COMSTACK) vp;
1002 IOCHAN parent_chan = (IOCHAN) new_line->user;
1004 unsigned cs_get_mask, cs_accept_mask, mask =
1005 ((new_line->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
1006 ((new_line->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
1010 cs_accept_mask = mask; /* accept didn't complete */
1015 cs_accept_mask = 0; /* accept completed. */
1016 cs_get_mask = mask = EVENT_INPUT;
1019 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session, mask,
1020 parent_chan->chan_id)))
1022 yaz_log(YLOG_FATAL, "Failed to create iochan");
1025 if (!(newas = create_association(new_chan, new_line,
1026 control_block.apdufile)))
1028 yaz_log(YLOG_FATAL, "Failed to create new assoc.");
1031 newas->cs_accept_mask = cs_accept_mask;
1032 newas->cs_get_mask = cs_get_mask;
1034 iochan_setdata(new_chan, newas);
1035 iochan_settimeout(new_chan, 60);
1037 a = cs_addrstr(new_line);
1041 yaz_log_xml_errors(0, YLOG_WARN);
1042 yaz_log(log_session, "Session - OK %d %s %ld",
1043 no_sessions, a ? a : "[Unknown]", (long) getpid());
1044 if (max_sessions && no_sessions >= max_sessions)
1045 control_block.one_shot = 1;
1046 if (control_block.threads)
1048 iochan_event_loop(&new_chan);
1052 new_chan->next = pListener;
1053 pListener = new_chan;
1061 static void inetd_connection(int what)
1068 if ((line = cs_createbysocket(0, tcpip_type, 0, what)))
1070 if ((chan = iochan_create(cs_fileno(line), ir_session, EVENT_INPUT,
1073 if ((assoc = create_association(chan, line,
1074 control_block.apdufile)))
1076 iochan_setdata(chan, assoc);
1077 iochan_settimeout(chan, 60);
1078 addr = cs_addrstr(line);
1079 yaz_log(log_sessiondetail, "Inetd association from %s",
1080 addr ? addr : "[UNKNOWN]");
1081 assoc->cs_get_mask = EVENT_INPUT;
1085 yaz_log(YLOG_FATAL, "Failed to create association structure");
1087 chan->next = pListener;
1092 yaz_log(YLOG_FATAL, "Failed to create iochan");
1097 yaz_log(YLOG_ERRNO|YLOG_FATAL, "Failed to create comstack on socket 0");
1102 * Set up a listening endpoint, and give it to the event-handler.
1104 static int add_listener(char *where, int listen_id)
1111 if (control_block.dynamic)
1113 else if (control_block.threads)
1118 yaz_log(log_server, "Adding %s listener on %s id=%d", mode, where,
1121 l = cs_create_host(where, 2, &ap);
1124 yaz_log(YLOG_FATAL, "Failed to listen on %s", where);
1127 if (*control_block.cert_fname)
1128 cs_set_ssl_certificate_file(l, control_block.cert_fname);
1130 if (cs_bind(l, ap, CS_SERVER) < 0)
1132 if (cs_errno(l) == CSYSERR)
1133 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to bind to %s", where);
1135 yaz_log(YLOG_FATAL, "Failed to bind to %s: %s", where,
1140 if (!(lst = iochan_create(cs_fileno(l), listener, EVENT_INPUT |
1141 EVENT_EXCEPT, listen_id)))
1143 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create IOCHAN-type");
1147 iochan_setdata(lst, l); /* user-defined data for listener is COMSTACK */
1148 l->user = lst; /* user-defined data for COMSTACK is listener chan */
1150 /* Add listener to chain */
1151 lst->next = pListener;
1157 /* UNIX only (for windows we don't need to catch the signals) */
1158 static void catchchld(int num)
1160 while (waitpid(-1, 0, WNOHANG) > 0)
1162 signal(SIGCHLD, catchchld);
1166 statserv_options_block *statserv_getcontrol(void)
1169 if (init_control_tls)
1170 return (statserv_options_block *) TlsGetValue(current_control_tls);
1172 return &control_block;
1173 #elif YAZ_POSIX_THREADS
1174 if (init_control_tls)
1175 return (statserv_options_block *)
1176 pthread_getspecific(current_control_tls);
1178 return &control_block;
1180 if (current_control_block)
1181 return current_control_block;
1182 return &control_block;
1186 void statserv_setcontrol(statserv_options_block *block)
1188 if (gfs_root_dir[0])
1190 if (chdir(gfs_root_dir))
1191 yaz_log(YLOG_WARN|YLOG_ERRNO, "chdir %s", gfs_root_dir);
1194 if (init_control_tls)
1195 TlsSetValue(current_control_tls, block);
1196 #elif YAZ_POSIX_THREADS
1197 if (init_control_tls)
1198 pthread_setspecific(current_control_tls, block);
1200 current_control_block = block;
1204 static void statserv_reset(void)
1208 static int statserv_sc_main(yaz_sc_t s, int argc, char **argv)
1212 /* We need to initialize the thread list */
1213 ThreadList_Initialize();
1223 if ((me = strrchr(argv[0], sep)))
1224 me++; /* get the basename */
1227 programname = argv[0];
1229 if (control_block.options_func(argc, argv))
1234 xml_config_bend_start();
1237 xml_config_add_listeners();
1239 yaz_log(log_server, "Starting server %s", me);
1240 if (!pListener && *control_block.default_listen)
1241 add_listener(control_block.default_listen, 0);
1244 if (control_block.inetd)
1245 inetd_connection(control_block.default_proto);
1249 if (control_block.background)
1251 /* create pipe so that parent waits until child has created
1255 yaz_log(YLOG_FATAL|YLOG_ERRNO, "pipe");
1269 int res = read(hand[0], dummy, 1);
1270 if (res < 0 && yaz_errno() != EINTR)
1272 yaz_log(YLOG_FATAL|YLOG_ERRNO, "read fork handshake");
1289 open("/dev/null", O_RDWR);
1295 xml_config_add_listeners();
1297 if (!pListener && *control_block.default_listen)
1298 add_listener(control_block.default_listen, 0);
1303 if (*control_block.pid_fname)
1305 FILE *f = fopen(control_block.pid_fname, "w");
1308 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Couldn't create %s",
1309 control_block.pid_fname);
1312 fprintf(f, "%ld", (long) getpid());
1316 if (control_block.background)
1320 yaz_log(log_server, "Starting server %s pid=%ld", programname,
1323 sigset_t sigs_to_block;
1325 sigemptyset(&sigs_to_block);
1326 sigaddset(&sigs_to_block, SIGTERM);
1327 pthread_sigmask(SIG_BLOCK, &sigs_to_block, 0);
1330 if (control_block.dynamic)
1331 signal(SIGCHLD, catchchld);
1333 signal(SIGPIPE, SIG_IGN);
1334 signal(SIGTERM, sigterm);
1335 if (*control_block.setuid)
1339 if (!(pw = getpwnam(control_block.setuid)))
1341 yaz_log(YLOG_FATAL, "%s: Unknown user", control_block.setuid);
1344 if (setuid(pw->pw_uid) < 0)
1346 yaz_log(YLOG_FATAL|YLOG_ERRNO, "setuid");
1352 if (pListener == NULL)
1356 yaz_log(YLOG_DEBUG, "Entering event loop.");
1357 return iochan_event_loop(&pListener);
1360 static void option_copy(char *dst, const char *src)
1362 strncpy(dst, src ? src : "", 127);
1366 int check_options(int argc, char **argv)
1371 yaz_log_init_level(yaz_log_mask_str(STAT_DEFAULT_LOG_LEVEL));
1375 while ((ret = options("1a:iszSTl:v:u:c:w:t:k:d:A:p:DC:f:m:r:",
1376 argv, argc, &arg)) != -2)
1381 if (add_listener(arg, 0))
1382 return 1; /* failed to create listener */
1385 control_block.one_shot = 1;
1386 control_block.dynamic = 0;
1389 control_block.default_proto = PROTO_Z3950;
1392 fprintf(stderr, "%s: SR protocol no longer supported\n", me);
1396 control_block.dynamic = 0;
1399 #if YAZ_POSIX_THREADS
1400 control_block.dynamic = 0;
1401 control_block.threads = 1;
1402 #elif YAZ_GNU_THREADS
1403 control_block.dynamic = 0;
1404 control_block.threads = 1;
1406 fprintf(stderr, "%s: Threaded mode not available.\n", me);
1411 option_copy(control_block.logfile, arg);
1412 yaz_log_init_file(control_block.logfile);
1416 fprintf(stderr, "%s: Specify time format for log file.\n", me);
1419 yaz_log_time_format(arg);
1422 yaz_log_init_level(yaz_log_mask_str(arg));
1426 option_copy(control_block.apdufile, arg);
1429 option_copy(control_block.setuid, arg);
1432 option_copy(control_block.configname, arg);
1435 option_copy(control_block.cert_fname, arg);
1438 option_copy(control_block.daemon_name, arg);
1441 if (!arg || !(r = atoi(arg)))
1443 fprintf(stderr, "%s: Specify positive timeout for -t.\n", me);
1446 control_block.idle_timeout = r;
1449 if (!arg || !(r = atoi(arg)))
1451 fprintf(stderr, "%s: Specify positive size for -k.\n", me);
1454 control_block.maxrecordsize = r * 1024;
1457 control_block.inetd = 1;
1467 max_sessions = atoi(arg);
1470 option_copy(control_block.pid_fname, arg);
1474 option_copy(control_block.xml_config, arg);
1476 fprintf(stderr, "%s: Option -f unsupported since YAZ is compiled without Libxml2 support\n", me);
1481 control_block.background = 1;
1484 if (!arg || !(r = atoi(arg)))
1486 fprintf(stderr, "%s: Specify positive size for -r.\n", me);
1489 yaz_log_init_max_size(r * 1024);
1492 fprintf(stderr, "Usage: %s [ -a <pdufile> -v <loglevel>"
1493 " -l <logfile> -u <user> -c <config> -t <minutes>"
1494 " -k <kilobytes> -d <daemon> -p <pidfile> -C certfile"
1495 " -ziDST1 -m <time-format> -w <directory> <listener-addr>... ]\n", me);
1502 void statserv_sc_stop(yaz_sc_t s)
1504 statserv_closedown();
1508 int statserv_main(int argc, char **argv,
1509 bend_initresult *(*bend_init)(bend_initrequest *r),
1510 void (*bend_close)(void *handle))
1513 struct statserv_options_block *cb = &control_block;
1515 /* control block does not have service_name member on Unix */
1516 yaz_sc_t s = yaz_sc_create(
1518 cb->service_name, cb->service_display_name
1524 cb->bend_init = bend_init;
1525 cb->bend_close = bend_close;
1527 ret = yaz_sc_program(s, argc, argv, statserv_sc_main, statserv_sc_stop);
1535 * c-file-style: "Stroustrup"
1536 * indent-tabs-mode: nil
1538 * vim: shiftwidth=4 tabstop=8 expandtab