2 * Copyright (C) 1995-2006, 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.44 2006-09-29 13:20:23 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 "none,fatal,warn,log,server,session,request"
89 /* the 'none' clears yaz' own default settings, including [log] */
91 int check_options(int argc, char **argv);
92 statserv_options_block control_block = {
94 0, /* threaded mode */
95 0, /* one shot (single session) */
96 0, /* __UNUSED_loglevel */
98 "", /* diagnostic output to stderr */
99 "tcp:@:9999", /* default listener port */
100 PROTO_Z3950, /* default application protocol */
101 15, /* idle timeout (minutes) */
102 1024*1024, /* maximum PDU size (approx.) to allow */
103 "default-config", /* configuration name to pass to backend */
104 "", /* set user id */
105 0, /* bend_start handler */
106 0, /* bend_stop handler */
107 check_options, /* Default routine, for checking the run-time arguments */
110 0, /* default value for inet deamon */
111 0, /* handle (for service, etc) */
112 0, /* bend_init handle */
113 0, /* bend_close handle */
115 "Z39.50 Server", /* NT Service Name */
116 "Server", /* NT application Name */
117 "", /* NT Service Dependencies */
118 "Z39.50 Server", /* NT Service Display Name */
120 0, /* SOAP handlers */
122 0, /* background daemon */
123 "", /* SSL certificate filename */
124 "" /* XML config filename */
127 static int max_sessions = 0;
129 static int logbits_set = 0;
130 static int log_session = 0; /* one-line logs for session */
131 static int log_sessiondetail = 0; /* more detailed stuff */
132 static int log_server = 0;
134 /** get_logbits sets global loglevel bits */
135 static void get_logbits(int force)
136 { /* needs to be called after parsing cmd-line args that can set loglevels!*/
137 if (force || !logbits_set)
140 log_session = yaz_log_module_level("session");
141 log_sessiondetail = yaz_log_module_level("sessiondetail");
142 log_server = yaz_log_module_level("server");
147 static int add_listener(char *where, int listen_id);
150 static xmlDocPtr xml_config_doc = 0;
154 static xmlNodePtr xml_config_get_root(void)
159 ptr = xmlDocGetRootElement(xml_config_doc);
160 if (!ptr || ptr->type != XML_ELEMENT_NODE ||
161 strcmp((const char *) ptr->name, "yazgfs"))
163 yaz_log(YLOG_WARN, "Bad/missing root element for config %s",
164 control_block.xml_config);
174 static char *nmem_dup_xml_content(NMEM n, xmlNodePtr ptr)
178 int len = 1; /* start with 1, because of trailing 0 */
180 int first = 1; /* whitespace lead flag .. */
181 /* determine length */
182 for (p = ptr; p; p = p->next)
184 if (p->type == XML_TEXT_NODE)
185 len += xmlStrlen(p->content);
187 /* now allocate for the string */
188 str = nmem_malloc(n, len);
189 *str = '\0'; /* so we can use strcat */
190 for (p = ptr; p; p = p->next)
192 if (p->type == XML_TEXT_NODE)
197 while(*cp && isspace(*cp))
200 first = 0; /* reset if we got non-whitespace out */
202 strcat((char *)str, (const char *)cp); /* append */
205 /* remove trailing whitespace */
206 cp = strlen((const char *)str) + str;
207 while (cp != str && isspace(cp[-1]))
210 /* return resulting string */
215 static struct gfs_server * gfs_server_new(void)
217 struct gfs_server *n = nmem_malloc(gfs_nmem, sizeof(*n));
218 memcpy(&n->cb, &control_block, sizeof(control_block));
222 n->cql_transform = 0;
223 n->server_node_ptr = 0;
228 n->retrieval = yaz_retrieval_create();
233 static struct gfs_listen * gfs_listen_new(const char *id,
236 struct gfs_listen *n = nmem_malloc(gfs_nmem, sizeof(*n));
238 n->id = nmem_strdup(gfs_nmem, id);
242 n->address = nmem_strdup(gfs_nmem, address);
246 static void gfs_server_chdir(struct gfs_server *gfs)
250 if (chdir(gfs_root_dir))
251 yaz_log(YLOG_WARN|YLOG_ERRNO, "chdir %s", gfs_root_dir);
255 if (chdir(gfs->directory))
256 yaz_log(YLOG_WARN|YLOG_ERRNO, "chdir %s",
261 int control_association(association *assoc, const char *host, int force_open)
263 char vhost[128], *cp;
266 strncpy(vhost, host, 127);
268 cp = strchr(vhost, ':');
274 if (control_block.xml_config[0])
276 struct gfs_server *gfs;
277 for (gfs = gfs_server_list; gfs; gfs = gfs->next)
279 int listen_match = 0;
281 if ( !gfs->host || (host && gfs->host && !strcmp(host, gfs->host)))
283 if (!gfs->listen_ref ||
284 gfs->listen_ref == assoc->client_chan->chan_id)
286 if (listen_match && host_match)
289 (assoc->last_control != &gfs->cb && assoc->backend))
291 statserv_setcontrol(assoc->last_control);
292 if (assoc->backend && assoc->init)
294 gfs_server_chdir(gfs);
295 (assoc->last_control->bend_close)(assoc->backend);
302 assoc->last_control = &gfs->cb;
303 statserv_setcontrol(&gfs->cb);
305 gfs_server_chdir(gfs);
311 statserv_setcontrol(0);
312 assoc->last_control = 0;
318 statserv_setcontrol(&control_block);
319 assoc->last_control = &control_block;
321 yaz_log(YLOG_DEBUG, "server select: config=%s",
322 assoc->last_control->configname);
324 assoc->maximumRecordSize = assoc->last_control->maxrecordsize;
325 assoc->preferredMessageSize = assoc->last_control->maxrecordsize;
326 cs_set_max_recv_bytes(assoc->client_link, assoc->maximumRecordSize);
330 static void xml_config_read(void)
332 struct gfs_server **gfsp = &gfs_server_list;
333 struct gfs_listen **gfslp = &gfs_listen_list;
335 xmlNodePtr ptr = xml_config_get_root();
339 for (ptr = ptr->children; ptr; ptr = ptr->next)
341 struct _xmlAttr *attr;
342 if (ptr->type != XML_ELEMENT_NODE)
344 attr = ptr->properties;
345 if (!strcmp((const char *) ptr->name, "listen"))
348 <listen id="listenerid">tcp:@:9999</listen>
351 const char *address =
352 nmem_dup_xml_content(gfs_nmem, ptr->children);
353 for ( ; attr; attr = attr->next)
354 if (!xmlStrcmp(attr->name, BAD_CAST "id")
355 && attr->children && attr->children->type == XML_TEXT_NODE)
356 id = nmem_dup_xml_content(gfs_nmem, attr->children);
359 *gfslp = gfs_listen_new(id, address);
360 gfslp = &(*gfslp)->next;
361 *gfslp = 0; /* make listener list consistent for search */
364 else if (!strcmp((const char *) ptr->name, "server"))
366 xmlNodePtr ptr_server = ptr;
368 const char *listenref = 0;
370 struct gfs_server *gfs;
372 for ( ; attr; attr = attr->next)
373 if (!xmlStrcmp(attr->name, BAD_CAST "listenref")
374 && attr->children && attr->children->type == XML_TEXT_NODE)
375 listenref = nmem_dup_xml_content(gfs_nmem, attr->children);
376 else if (!xmlStrcmp(attr->name, BAD_CAST "id")
378 && attr->children->type == XML_TEXT_NODE)
379 id = nmem_dup_xml_content(gfs_nmem, attr->children);
381 yaz_log(YLOG_WARN, "Unknown attribute '%s' for server",
383 gfs = *gfsp = gfs_server_new();
384 gfs->server_node_ptr = ptr_server;
388 struct gfs_listen *gl = gfs_listen_list;
389 for (id_no = 1; gl; gl = gl->next, id_no++)
390 if (gl->id && !strcmp(gl->id, listenref))
392 gfs->listen_ref = id_no;
396 yaz_log(YLOG_WARN, "Non-existent listenref '%s' in server "
397 "config element", listenref);
399 for (ptr = ptr_server->children; ptr; ptr = ptr->next)
401 if (ptr->type != XML_ELEMENT_NODE)
403 if (!strcmp((const char *) ptr->name, "host"))
405 gfs->host = nmem_dup_xml_content(gfs_nmem,
408 else if (!strcmp((const char *) ptr->name, "config"))
410 strcpy(gfs->cb.configname,
411 nmem_dup_xml_content(gfs_nmem, ptr->children));
413 else if (!strcmp((const char *) ptr->name, "cql2rpn"))
415 gfs->cql_transform = cql_transform_open_fname(
416 nmem_dup_xml_content(gfs_nmem, ptr->children)
419 else if (!strcmp((const char *) ptr->name, "directory"))
422 nmem_dup_xml_content(gfs_nmem, ptr->children);
424 else if (!strcmp((const char *) ptr->name, "docpath"))
427 nmem_dup_xml_content(gfs_nmem, ptr->children);
429 else if (!strcmp((const char *) ptr->name, "maximumrecordsize"))
431 gfs->cb.maxrecordsize = atoi(
432 nmem_dup_xml_content(gfs_nmem, ptr->children));
434 else if (!strcmp((const char *) ptr->name, "stylesheet"))
436 char *s = nmem_dup_xml_content(gfs_nmem, ptr->children);
438 nmem_malloc(gfs_nmem, strlen(s) + 2);
439 sprintf(gfs->stylesheet, "/%s", s);
441 else if (!strcmp((const char *) ptr->name, "explain"))
443 ; /* being processed separately */
445 else if (!strcmp((const char *) ptr->name, "retrievalinfo"))
447 if (yaz_retrieval_configure(gfs->retrieval, ptr))
449 yaz_log(YLOG_FATAL, "%s in config %s",
450 yaz_retrieval_get_error(gfs->retrieval),
451 control_block.xml_config);
457 yaz_log(YLOG_FATAL, "Unknown element '%s' in config %s",
458 ptr->name, control_block.xml_config);
462 gfsp = &(*gfsp)->next;
469 static void xml_config_open(void)
471 if (!getcwd(gfs_root_dir, FILENAME_MAX))
473 yaz_log(YLOG_WARN|YLOG_ERRNO, "getcwd failed");
474 gfs_root_dir[0] = '\0';
477 init_control_tls = 1;
478 current_control_tls = TlsAlloc();
479 #elif YAZ_POSIX_THREADS
480 init_control_tls = 1;
481 pthread_key_create(¤t_control_tls, 0);
484 gfs_nmem = nmem_create();
486 if (control_block.xml_config[0] == '\0')
491 xml_config_doc = xmlParseFile(control_block.xml_config);
494 yaz_log(YLOG_FATAL, "Could not parse %s", control_block.xml_config);
499 int noSubstitutions = xmlXIncludeProcess(xml_config_doc);
500 if (noSubstitutions == -1)
502 yaz_log(YLOG_WARN, "XInclude processing failed for config %s",
503 control_block.xml_config);
512 static void xml_config_close(void)
517 xmlFreeDoc(xml_config_doc);
522 nmem_destroy(gfs_nmem);
524 if (init_control_tls)
525 TlsFree(current_control_tls);
526 #elif YAZ_POSIX_THREADS
527 if (init_control_tls)
528 pthread_key_delete(current_control_tls);
532 static void xml_config_add_listeners(void)
534 struct gfs_listen *gfs = gfs_listen_list;
537 for (id_no = 1; gfs; gfs = gfs->next, id_no++)
540 add_listener(gfs->address, id_no);
544 static void xml_config_bend_start(void)
546 if (control_block.xml_config[0])
548 struct gfs_server *gfs = gfs_server_list;
549 for (; gfs; gfs = gfs->next)
551 yaz_log(YLOG_DEBUG, "xml_config_bend_start config=%s",
553 statserv_setcontrol(&gfs->cb);
554 if (control_block.bend_start)
556 gfs_server_chdir(gfs);
557 (control_block.bend_start)(&gfs->cb);
563 yaz_log(YLOG_DEBUG, "xml_config_bend_start default config");
564 statserv_setcontrol(&control_block);
565 if (control_block.bend_start)
566 (*control_block.bend_start)(&control_block);
570 static void xml_config_bend_stop(void)
572 if (control_block.xml_config[0])
574 struct gfs_server *gfs = gfs_server_list;
575 for (; gfs; gfs = gfs->next)
577 yaz_log(YLOG_DEBUG, "xml_config_bend_stop config=%s",
579 statserv_setcontrol(&gfs->cb);
580 if (control_block.bend_stop)
581 (control_block.bend_stop)(&gfs->cb);
586 yaz_log(YLOG_DEBUG, "xml_config_bend_stop default config");
587 statserv_setcontrol(&control_block);
588 if (control_block.bend_stop)
589 (*control_block.bend_stop)(&control_block);
594 * handle incoming connect requests.
595 * The dynamic mode is a bit tricky mostly because we want to avoid
596 * doing all of the listening and accepting in the parent - it's
601 typedef struct _ThreadList ThreadList;
610 static ThreadList *pFirstThread;
611 static CRITICAL_SECTION Thread_CritSect;
612 static BOOL bInitialized = FALSE;
614 static void ThreadList_Initialize()
616 /* Initialize the critical Sections */
617 InitializeCriticalSection(&Thread_CritSect);
619 /* Set the first thraed */
622 /* we have been initialized */
626 static void statserv_add(HANDLE hThread, IOCHAN pIOChannel)
628 /* Only one thread can go through this section at a time */
629 EnterCriticalSection(&Thread_CritSect);
632 /* Lets create our new object */
633 ThreadList *pNewThread = (ThreadList *)malloc(sizeof(ThreadList));
634 pNewThread->hThread = hThread;
635 pNewThread->pIOChannel = pIOChannel;
636 pNewThread->pNext = pFirstThread;
637 pFirstThread = pNewThread;
639 /* Lets let somebody else create a new object now */
640 LeaveCriticalSection(&Thread_CritSect);
644 void statserv_remove(IOCHAN pIOChannel)
646 /* Only one thread can go through this section at a time */
647 EnterCriticalSection(&Thread_CritSect);
650 ThreadList *pCurrentThread = pFirstThread;
651 ThreadList *pNextThread;
652 ThreadList *pPrevThread =NULL;
654 /* Step through all the threads */
655 for (; pCurrentThread != NULL; pCurrentThread = pNextThread)
657 /* We only need to compare on the IO Channel */
658 if (pCurrentThread->pIOChannel == pIOChannel)
660 /* We have found the thread we want to delete */
661 /* First of all reset the next pointers */
662 if (pPrevThread == NULL)
663 pFirstThread = pCurrentThread->pNext;
665 pPrevThread->pNext = pCurrentThread->pNext;
667 /* All we need todo now is delete the memory */
668 free(pCurrentThread);
670 /* No need to look at any more threads */
675 /* We need to look at another thread */
676 pNextThread = pCurrentThread->pNext;
677 pPrevThread = pCurrentThread;
681 /* Lets let somebody else remove an object now */
682 LeaveCriticalSection(&Thread_CritSect);
686 /* WIN32 statserv_closedown */
687 void statserv_closedown()
689 /* Shouldn't do anything if we are not initialized */
693 HANDLE *pThreadHandles = NULL;
695 /* We need to stop threads adding and removing while we */
696 /* start the closedown process */
697 EnterCriticalSection(&Thread_CritSect);
700 /* We have exclusive access to the thread stuff now */
701 /* Y didn't i use a semaphore - Oh well never mind */
702 ThreadList *pCurrentThread = pFirstThread;
704 /* Before we do anything else, we need to shutdown the listener */
705 if (pListener != NULL)
706 iochan_destroy(pListener);
708 for (; pCurrentThread != NULL; pCurrentThread = pCurrentThread->pNext)
710 /* Just destroy the IOCHAN, that should do the trick */
711 iochan_destroy(pCurrentThread->pIOChannel);
712 closesocket(pCurrentThread->pIOChannel->fd);
714 /* Keep a running count of our handles */
720 HANDLE *pCurrentHandle ;
722 /* Allocate the thread handle array */
723 pThreadHandles = (HANDLE *)malloc(sizeof(HANDLE) * iHandles);
724 pCurrentHandle = pThreadHandles;
726 for (pCurrentThread = pFirstThread;
727 pCurrentThread != NULL;
728 pCurrentThread = pCurrentThread->pNext, pCurrentHandle++)
730 /* Just the handle */
731 *pCurrentHandle = pCurrentThread->hThread;
735 /* We can now leave the critical section */
736 LeaveCriticalSection(&Thread_CritSect);
739 /* Now we can really do something */
742 yaz_log(log_server, "waiting for %d to die", iHandles);
743 /* This will now wait, until all the threads close */
744 WaitForMultipleObjects(iHandles, pThreadHandles, TRUE, INFINITE);
746 /* Free the memory we allocated for the handle array */
747 free(pThreadHandles);
750 xml_config_bend_stop();
751 /* No longer require the critical section, since all threads are dead */
752 DeleteCriticalSection(&Thread_CritSect);
757 void __cdecl event_loop_thread (IOCHAN iochan)
759 event_loop (&iochan);
763 static void listener(IOCHAN h, int event)
765 COMSTACK line = (COMSTACK) iochan_getdata(h);
766 IOCHAN parent_chan = line->user;
771 if (event == EVENT_INPUT)
776 if ((res = cs_listen(line, 0, 0)) < 0)
778 yaz_log(YLOG_FATAL|YLOG_ERRNO, "cs_listen failed");
782 return; /* incomplete */
783 yaz_log(YLOG_DEBUG, "listen ok");
784 new_line = cs_accept(line);
787 yaz_log(YLOG_FATAL, "Accept failed.");
790 yaz_log(YLOG_DEBUG, "Accept ok");
792 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session,
793 EVENT_INPUT, parent_chan->chan_id)))
795 yaz_log(YLOG_FATAL, "Failed to create iochan");
800 yaz_log(YLOG_DEBUG, "Creating association");
801 if (!(newas = create_association(new_chan, new_line,
802 control_block.apdufile)))
804 yaz_log(YLOG_FATAL, "Failed to create new assoc.");
808 newas->cs_get_mask = EVENT_INPUT;
809 newas->cs_put_mask = 0;
810 newas->cs_accept_mask = 0;
812 yaz_log(YLOG_DEBUG, "Setting timeout %d", control_block.idle_timeout);
813 iochan_setdata(new_chan, newas);
814 iochan_settimeout(new_chan, 60);
816 /* Now what we need todo is create a new thread with this iochan as
818 newHandle = (HANDLE) _beginthread(event_loop_thread, 0, new_chan);
819 if (newHandle == (HANDLE) -1)
822 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create new thread.");
826 /* We successfully created the thread, so add it to the list */
827 statserv_add(newHandle, new_chan);
829 yaz_log(YLOG_DEBUG, "Created new thread, id = %ld iochan %p",(long) newHandle, new_chan);
830 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
834 yaz_log(YLOG_FATAL, "Bad event on listener.");
840 int statserv_must_terminate(void)
847 static int term_flag = 0;
848 /* To save having an #ifdef in event_loop we need to
849 define this empty function
851 int statserv_must_terminate(void)
856 void statserv_remove(IOCHAN pIOChannel)
860 void statserv_closedown()
864 xml_config_bend_stop();
865 for (p = pListener; p; p = p->next)
872 void sigterm(int sig)
877 static void *new_session (void *vp);
878 static int no_sessions = 0;
881 static void listener(IOCHAN h, int event)
883 COMSTACK line = (COMSTACK) iochan_getdata(h);
886 if (event == EVENT_INPUT)
889 if ((res = cs_listen_check(line, 0, 0, control_block.check_ip,
890 control_block.daemon_name)) < 0)
892 yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_listen failed");
897 yaz_log(YLOG_WARN, "cs_listen incomplete");
900 new_line = cs_accept(line);
903 yaz_log(YLOG_FATAL, "Accept failed.");
904 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
908 yaz_log(log_sessiondetail, "Connect from %s", cs_addrstr(new_line));
911 if (control_block.dynamic)
913 if ((res = fork()) < 0)
915 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fork");
919 else if (res == 0) /* child */
924 for (pp = pListener; pp; pp = iochan_getnext(pp))
926 COMSTACK l = (COMSTACK)iochan_getdata(pp);
930 sprintf(nbuf, "%s(%d)", me, no_sessions);
931 yaz_log_init_prefix(nbuf);
932 /* ensure that bend_stop is not called when each child exits -
933 only for the main process .. */
934 control_block.bend_stop = 0;
943 if (control_block.threads)
945 #if YAZ_POSIX_THREADS
946 pthread_t child_thread;
947 pthread_create (&child_thread, 0, new_session, new_line);
948 pthread_detach (child_thread);
949 #elif YAZ_GNU_THREADS
953 attr = pth_attr_new ();
954 pth_attr_set (attr, PTH_ATTR_JOINABLE, FALSE);
955 pth_attr_set (attr, PTH_ATTR_STACK_SIZE, 32*1024);
956 pth_attr_set (attr, PTH_ATTR_NAME, "session");
957 yaz_log (YLOG_DEBUG, "pth_spawn begin");
958 child_thread = pth_spawn (attr, new_session, new_line);
959 yaz_log (YLOG_DEBUG, "pth_spawn finish");
960 pth_attr_destroy (attr);
962 new_session(new_line);
966 new_session(new_line);
968 else if (event == EVENT_TIMEOUT)
970 yaz_log(log_server, "Shutting down listener.");
975 yaz_log(YLOG_FATAL, "Bad event on listener.");
980 static void *new_session (void *vp)
985 COMSTACK new_line = (COMSTACK) vp;
986 IOCHAN parent_chan = new_line->user;
988 unsigned cs_get_mask, cs_accept_mask, mask =
989 ((new_line->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
990 ((new_line->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
994 cs_accept_mask = mask; /* accept didn't complete */
999 cs_accept_mask = 0; /* accept completed. */
1000 cs_get_mask = mask = EVENT_INPUT;
1003 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session, mask,
1004 parent_chan->chan_id)))
1006 yaz_log(YLOG_FATAL, "Failed to create iochan");
1009 if (!(newas = create_association(new_chan, new_line,
1010 control_block.apdufile)))
1012 yaz_log(YLOG_FATAL, "Failed to create new assoc.");
1015 newas->cs_accept_mask = cs_accept_mask;
1016 newas->cs_get_mask = cs_get_mask;
1018 iochan_setdata(new_chan, newas);
1019 iochan_settimeout(new_chan, 60);
1021 a = cs_addrstr(new_line);
1025 yaz_log(log_session, "Session - OK %d %s %ld",
1026 no_sessions, a ? a : "[Unknown]", (long) getpid());
1027 if (max_sessions && no_sessions >= max_sessions)
1028 control_block.one_shot = 1;
1029 if (control_block.threads)
1031 event_loop(&new_chan);
1035 new_chan->next = pListener;
1036 pListener = new_chan;
1044 static void inetd_connection(int what)
1051 if ((line = cs_createbysocket(0, tcpip_type, 0, what)))
1053 if ((chan = iochan_create(cs_fileno(line), ir_session, EVENT_INPUT,
1056 if ((assoc = create_association(chan, line,
1057 control_block.apdufile)))
1059 iochan_setdata(chan, assoc);
1060 iochan_settimeout(chan, 60);
1061 addr = cs_addrstr(line);
1062 yaz_log(log_sessiondetail, "Inetd association from %s",
1063 addr ? addr : "[UNKNOWN]");
1064 assoc->cs_get_mask = EVENT_INPUT;
1068 yaz_log(YLOG_FATAL, "Failed to create association structure");
1070 chan->next = pListener;
1075 yaz_log(YLOG_FATAL, "Failed to create iochan");
1080 yaz_log(YLOG_ERRNO|YLOG_FATAL, "Failed to create comstack on socket 0");
1085 * Set up a listening endpoint, and give it to the event-handler.
1087 static int add_listener(char *where, int listen_id)
1094 if (control_block.dynamic)
1096 else if (control_block.threads)
1101 yaz_log(log_server, "Adding %s listener on %s id=%d", mode, where,
1104 l = cs_create_host(where, 2, &ap);
1107 yaz_log(YLOG_FATAL, "Failed to listen on %s", where);
1110 if (*control_block.cert_fname)
1111 cs_set_ssl_certificate_file(l, control_block.cert_fname);
1113 if (cs_bind(l, ap, CS_SERVER) < 0)
1115 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to bind to %s", where);
1119 if (!(lst = iochan_create(cs_fileno(l), listener, EVENT_INPUT |
1120 EVENT_EXCEPT, listen_id)))
1122 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create IOCHAN-type");
1126 iochan_setdata(lst, l); /* user-defined data for listener is COMSTACK */
1127 l->user = lst; /* user-defined data for COMSTACK is listener chan */
1129 /* Add listener to chain */
1130 lst->next = pListener;
1136 /* UNIX only (for windows we don't need to catch the signals) */
1137 static void catchchld(int num)
1139 while (waitpid(-1, 0, WNOHANG) > 0)
1141 signal(SIGCHLD, catchchld);
1145 statserv_options_block *statserv_getcontrol(void)
1148 if (init_control_tls)
1149 return (statserv_options_block *) TlsGetValue(current_control_tls);
1151 return &control_block;
1152 #elif YAZ_POSIX_THREADS
1153 if (init_control_tls)
1154 return pthread_getspecific(current_control_tls);
1156 return &control_block;
1158 if (current_control_block)
1159 return current_control_block;
1160 return &control_block;
1164 void statserv_setcontrol(statserv_options_block *block)
1166 chdir(gfs_root_dir);
1168 if (init_control_tls)
1169 TlsSetValue(current_control_tls, block);
1170 #elif YAZ_POSIX_THREADS
1171 if (init_control_tls)
1172 pthread_setspecific(current_control_tls, block);
1174 current_control_block = block;
1178 static void statserv_reset(void)
1182 int statserv_start(int argc, char **argv)
1186 /* We need to initialize the thread list */
1187 ThreadList_Initialize();
1197 if ((me = strrchr (argv[0], sep)))
1198 me++; /* get the basename */
1201 programname = argv[0];
1203 if (control_block.options_func(argc, argv))
1208 xml_config_bend_start();
1211 xml_config_add_listeners();
1213 yaz_log (log_server, "Starting server %s", me);
1214 if (!pListener && *control_block.default_listen)
1215 add_listener(control_block.default_listen, 0);
1218 if (control_block.inetd)
1219 inetd_connection(control_block.default_proto);
1223 if (control_block.background)
1225 /* create pipe so that parent waits until child has created
1229 yaz_log(YLOG_FATAL|YLOG_ERRNO, "pipe");
1243 int res = read(hand[0], dummy, 1);
1244 if (res < 0 && yaz_errno() != EINTR)
1246 yaz_log(YLOG_FATAL|YLOG_ERRNO, "read fork handshake");
1263 open("/dev/null", O_RDWR);
1266 xml_config_add_listeners();
1268 if (!pListener && *control_block.default_listen)
1269 add_listener(control_block.default_listen, 0);
1274 if (*control_block.pid_fname)
1276 FILE *f = fopen(control_block.pid_fname, "w");
1279 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Couldn't create %s",
1280 control_block.pid_fname);
1283 fprintf(f, "%ld", (long) getpid());
1287 if (control_block.background)
1291 yaz_log (log_server, "Starting server %s pid=%ld", programname,
1294 sigset_t sigs_to_block;
1296 sigemptyset(&sigs_to_block);
1297 sigaddset (&sigs_to_block, SIGTERM);
1298 pthread_sigmask (SIG_BLOCK, &sigs_to_block, 0);
1301 if (control_block.dynamic)
1302 signal(SIGCHLD, catchchld);
1304 signal (SIGPIPE, SIG_IGN);
1305 signal (SIGTERM, sigterm);
1306 if (*control_block.setuid)
1310 if (!(pw = getpwnam(control_block.setuid)))
1312 yaz_log(YLOG_FATAL, "%s: Unknown user", control_block.setuid);
1315 if (setuid(pw->pw_uid) < 0)
1317 yaz_log(YLOG_FATAL|YLOG_ERRNO, "setuid");
1323 if (pListener == NULL)
1325 yaz_log(YLOG_DEBUG, "Entering event loop.");
1326 return event_loop(&pListener);
1329 static void option_copy(char *dst, const char *src)
1331 strncpy(dst, src ? src : "", 127);
1335 int check_options(int argc, char **argv)
1340 if (getenv("YAZ_LOG") == 0) {
1342 * Set default log level. We want to avoid doing this if the
1343 * user has already explicitly specified a preferred default
1344 * log-level, hence the inelegant peek at the YAZ_LOG
1345 * environment variable that will subsequently be interpreted
1346 * by the YAZ logging module itself.
1348 yaz_log_init_level(yaz_log_mask_str(STAT_DEFAULT_LOG_LEVEL));
1352 while ((ret = options("1a:iszSTl:v:u:c:w:t:k:d:A:p:DC:f:m:r:",
1353 argv, argc, &arg)) != -2)
1358 if (add_listener(arg, 0))
1359 return 1; /* failed to create listener */
1362 control_block.one_shot = 1;
1363 control_block.dynamic = 0;
1366 control_block.default_proto = PROTO_Z3950;
1369 fprintf (stderr, "%s: SR protocol no longer supported\n", me);
1373 control_block.dynamic = 0;
1376 #if YAZ_POSIX_THREADS
1377 control_block.dynamic = 0;
1378 control_block.threads = 1;
1379 #elif YAZ_GNU_THREADS
1380 control_block.dynamic = 0;
1381 control_block.threads = 1;
1383 fprintf(stderr, "%s: Threaded mode not available.\n", me);
1388 option_copy(control_block.logfile, arg);
1389 yaz_log_init_file(control_block.logfile);
1393 fprintf(stderr, "%s: Specify time format for log file.\n", me);
1396 yaz_log_time_format(arg);
1399 int default_level = yaz_log_mask_str(STAT_DEFAULT_LOG_LEVEL);
1400 yaz_log_init_level(yaz_log_mask_str_x(arg, default_level));
1405 option_copy(control_block.apdufile, arg);
1408 option_copy(control_block.setuid, arg);
1411 option_copy(control_block.configname, arg);
1414 option_copy(control_block.cert_fname, arg);
1417 option_copy(control_block.daemon_name, arg);
1420 if (!arg || !(r = atoi(arg)))
1422 fprintf(stderr, "%s: Specify positive timeout for -t.\n", me);
1425 control_block.idle_timeout = r;
1428 if (!arg || !(r = atoi(arg)))
1430 fprintf(stderr, "%s: Specify positive size for -k.\n", me);
1433 control_block.maxrecordsize = r * 1024;
1436 control_block.inetd = 1;
1446 max_sessions = atoi(arg);
1449 option_copy(control_block.pid_fname, arg);
1453 option_copy(control_block.xml_config, arg);
1455 fprintf(stderr, "%s: Option -f unsupported since YAZ is compiled without Libxml2 support\n", me);
1460 control_block.background = 1;
1463 if (!arg || !(r = atoi(arg)))
1465 fprintf(stderr, "%s: Specify positive size for -r.\n", me);
1468 yaz_log_init_max_size(r * 1024);
1471 fprintf(stderr, "Usage: %s [ -a <pdufile> -v <loglevel>"
1472 " -l <logfile> -u <user> -c <config> -t <minutes>"
1473 " -k <kilobytes> -d <daemon> -p <pidfile> -C certfile"
1474 " -ziDST1 -m <time-format> -w <directory> <listener-addr>... ]\n", me);
1482 typedef struct _Args
1488 static Args ArgDetails;
1490 /* name of the executable */
1491 #define SZAPPNAME "server"
1493 /* list of service dependencies - "dep1\0dep2\0\0" */
1494 #define SZDEPENDENCIES ""
1496 int statserv_main(int argc, char **argv,
1497 bend_initresult *(*bend_init)(bend_initrequest *r),
1498 void (*bend_close)(void *handle))
1500 struct statserv_options_block *cb = &control_block;
1501 cb->bend_init = bend_init;
1502 cb->bend_close = bend_close;
1504 /* Lets setup the Arg structure */
1505 ArgDetails.argc = argc;
1506 ArgDetails.argv = argv;
1508 /* Now setup the service with the service controller */
1509 SetupService(argc, argv, &ArgDetails, SZAPPNAME,
1510 cb->service_name, /* internal service name */
1511 cb->service_display_name, /* displayed name */
1516 int StartAppService(void *pHandle, int argc, char **argv)
1518 /* Initializes the App */
1522 void RunAppService(void *pHandle)
1524 Args *pArgs = (Args *)pHandle;
1526 /* Starts the app running */
1527 statserv_start(pArgs->argc, pArgs->argv);
1530 void StopAppService(void *pHandle)
1533 statserv_closedown();
1539 int statserv_main(int argc, char **argv,
1540 bend_initresult *(*bend_init)(bend_initrequest *r),
1541 void (*bend_close)(void *handle))
1545 control_block.bend_init = bend_init;
1546 control_block.bend_close = bend_close;
1548 ret = statserv_start (argc, argv);
1549 statserv_closedown ();
1557 * indent-tabs-mode: nil
1559 * vim: shiftwidth=4 tabstop=8 expandtab