2 * Copyright (C) 1995-2005, 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.25 2005-03-05 12:14:12 adam Exp $
13 * \brief Implements GFS logic
26 #include <sys/types.h>
39 #include <libxml/parser.h>
40 #include <libxml/tree.h>
53 #include <yaz/comstack.h>
54 #include <yaz/tcpip.h>
55 #include <yaz/options.h>
57 #include <yaz/xmosi.h>
62 #include <yaz/statserv.h>
64 static IOCHAN pListener = NULL;
66 static struct gfs_server *gfs_server_list = 0;
67 static struct gfs_listen *gfs_listen_list = 0;
68 static NMEM gfs_nmem = 0;
70 static char *me = "statserver"; /* log prefix */
71 static char *programname="statserver"; /* full program name */
73 DWORD current_control_tls;
74 static int init_control_tls = 0;
75 #elif YAZ_POSIX_THREADS
76 static pthread_key_t current_control_tls;
77 static int init_control_tls = 0;
79 static statserv_options_block *current_control_block = 0;
85 #define STAT_DEFAULT_LOG_LEVEL "none,fatal,warn,log,server,session,request"
86 /* the 'none' clears yaz' own default settings, including [log] */
88 int check_options(int argc, char **argv);
89 statserv_options_block control_block = {
91 0, /* threaded mode */
92 0, /* one shot (single session) */
93 YLOG_DEFAULT_LEVEL, /* log level */
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;
128 static int log_server = 0;
130 /** get_logbits sets global loglevel bits */
131 static void get_logbits(int force)
132 { /* needs to be called after parsing cmd-line args that can set loglevels!*/
133 if (force || !logbits_set)
136 log_session = yaz_log_module_level("session");
137 log_server = yaz_log_module_level("server");
142 static int add_listener(char *where, int listen_id);
145 static xmlDocPtr xml_config_doc = 0;
149 static xmlNodePtr xml_config_get_root()
154 ptr = xmlDocGetRootElement(xml_config_doc);
155 if (!ptr || ptr->type != XML_ELEMENT_NODE ||
156 strcmp((const char *) ptr->name, "yazgfs"))
158 yaz_log(YLOG_WARN, "Bad/missing root element for config %s",
159 control_block.xml_config);
169 static char *nmem_dup_xml_content(NMEM n, xmlNodePtr ptr)
173 int len = 1; /* start with 1, because of trailing 0 */
175 int first = 1; /* whitespace lead flag .. */
176 /* determine length */
177 for (p = ptr; p; p = p->next)
179 if (p->type == XML_TEXT_NODE)
180 len += strlen(p->content);
182 /* now allocate for the string */
183 str = nmem_malloc(n, len);
184 *str = '\0'; /* so we can use strcat */
185 for (p = ptr; p; p = p->next)
187 if (p->type == XML_TEXT_NODE)
192 while(*cp && isspace(*cp))
195 first = 0; /* reset if we got non-whitespace out */
197 strcat(str, cp); /* append */
200 /* remove trailing whitespace */
201 cp = strlen(str) + str;
202 while ((char*) cp != str && isspace(cp[-1]))
205 /* return resulting string */
210 static struct gfs_server * gfs_server_new()
212 struct gfs_server *n = nmem_malloc(gfs_nmem, sizeof(*n));
213 memcpy(&n->cb, &control_block, sizeof(control_block));
217 n->cql_transform = 0;
218 n->server_node_ptr = 0;
222 static struct gfs_listen * gfs_listen_new(const char *id,
225 struct gfs_listen *n = nmem_malloc(gfs_nmem, sizeof(*n));
227 n->id = nmem_strdup(gfs_nmem, id);
231 n->address = nmem_strdup(gfs_nmem, address);
235 int control_association(association *assoc, const char *host, int force_open)
237 char vhost[128], *cp;
240 strncpy(vhost, host, 127);
242 cp = strchr(vhost, ':');
247 if (control_block.xml_config[0])
249 struct gfs_server *gfs;
250 for (gfs = gfs_server_list; gfs; gfs = gfs->next)
252 int listen_match = 0;
254 if ( !gfs->host || (host && gfs->host && !strcmp(host, gfs->host)))
256 if (!gfs->listen_ref ||
257 gfs->listen_ref == assoc->client_chan->chan_id)
259 if (listen_match && host_match)
262 (assoc->last_control != &gfs->cb && assoc->backend))
264 statserv_setcontrol(assoc->last_control);
265 if (assoc->backend && assoc->init)
266 (assoc->last_control->bend_close)(assoc->backend);
271 assoc->cql_transform = gfs->cql_transform;
272 assoc->server_node_ptr = gfs->server_node_ptr;
273 assoc->last_control = &gfs->cb;
274 statserv_setcontrol(&gfs->cb);
275 yaz_log(YLOG_DEBUG, "server select: %s", gfs->cb.configname);
279 statserv_setcontrol(0);
280 assoc->last_control = 0;
281 assoc->cql_transform = 0;
282 assoc->server_node_ptr = 0;
283 yaz_log(YLOG_DEBUG, "server select: no match");
288 statserv_setcontrol(&control_block);
289 assoc->last_control = &control_block;
290 assoc->cql_transform = 0;
291 assoc->server_node_ptr = 0;
292 yaz_log(YLOG_DEBUG, "server select: config=%s", control_block.configname);
297 static void xml_config_read()
299 struct gfs_server **gfsp = &gfs_server_list;
300 struct gfs_listen **gfslp = &gfs_listen_list;
302 xmlNodePtr ptr = xml_config_get_root();
306 for (ptr = ptr->children; ptr; ptr = ptr->next)
308 struct _xmlAttr *attr;
309 if (ptr->type != XML_ELEMENT_NODE)
311 attr = ptr->properties;
312 if (!strcmp((const char *) ptr->name, "listen"))
315 <listen id="listenerid">tcp:@:9999</listen>
318 const char *address =
319 nmem_dup_xml_content(gfs_nmem, ptr->children);
320 for ( ; attr; attr = attr->next)
321 if (!strcmp(attr->name, "id")
322 && attr->children && attr->children->type == XML_TEXT_NODE)
323 id = nmem_dup_xml_content(gfs_nmem, attr->children);
326 *gfslp = gfs_listen_new(id, address);
327 gfslp = &(*gfslp)->next;
328 *gfslp = 0; /* make listener list consistent for search */
331 else if (!strcmp((const char *) ptr->name, "server"))
333 xmlNodePtr ptr_server = ptr;
335 const char *listenref = 0;
337 for ( ; attr; attr = attr->next)
338 if (!strcmp(attr->name, "listenref")
339 && attr->children && attr->children->type == XML_TEXT_NODE)
340 listenref = nmem_dup_xml_content(gfs_nmem, attr->children);
341 *gfsp = gfs_server_new();
342 (*gfsp)->server_node_ptr = ptr_server;
346 struct gfs_listen *gl = gfs_listen_list;
347 for (id_no = 1; gl; gl = gl->next, id_no++)
348 if (gl->id && !strcmp(gl->id, listenref))
350 (*gfsp)->listen_ref = id_no;
354 yaz_log(YLOG_WARN, "Non-existent listenref '%s' in server "
355 "config element", listenref);
357 for (ptr = ptr_server->children; ptr; ptr = ptr->next)
359 if (ptr->type != XML_ELEMENT_NODE)
361 if (!strcmp((const char *) ptr->name, "host"))
363 (*gfsp)->host = nmem_dup_xml_content(gfs_nmem,
366 if (!strcmp((const char *) ptr->name, "config"))
368 strcpy((*gfsp)->cb.configname,
369 nmem_dup_xml_content(gfs_nmem, ptr->children));
371 if (!strcmp((const char *) ptr->name, "cql2rpn"))
373 (*gfsp)->cql_transform = cql_transform_open_fname(
374 nmem_dup_xml_content(gfs_nmem, ptr->children)
378 gfsp = &(*gfsp)->next;
385 static void xml_config_open()
388 init_control_tls = 1;
389 current_control_tls = TlsAlloc();
390 #elif YAZ_POSIX_THREADS
391 init_control_tls = 1;
392 pthread_key_create(¤t_control_tls, 0);
395 gfs_nmem = nmem_create();
397 if (control_block.xml_config[0] == '\0')
402 xml_config_doc = xmlParseFile(control_block.xml_config);
405 yaz_log(YLOG_WARN, "Could not parse %s", control_block.xml_config);
413 static void xml_config_close()
418 xmlFreeDoc(xml_config_doc);
423 nmem_destroy(gfs_nmem);
425 if (init_control_tls)
426 TlsFree(current_control_tls);
427 #elif YAZ_POSIX_THREADS
428 if (init_control_tls)
429 pthread_key_delete(current_control_tls);
433 static void xml_config_add_listeners()
435 struct gfs_listen *gfs = gfs_listen_list;
438 for (id_no = 1; gfs; gfs = gfs->next, id_no++)
441 add_listener(gfs->address, id_no);
445 static void xml_config_bend_start()
447 if (control_block.xml_config[0])
449 struct gfs_server *gfs = gfs_server_list;
450 for (; gfs; gfs = gfs->next)
452 yaz_log(YLOG_DEBUG, "xml_config_bend_start config=%s",
454 statserv_setcontrol(&gfs->cb);
455 if (control_block.bend_start)
456 (control_block.bend_start)(&gfs->cb);
461 yaz_log(YLOG_DEBUG, "xml_config_bend_start default config");
462 statserv_setcontrol(&control_block);
463 if (control_block.bend_start)
464 (*control_block.bend_start)(&control_block);
469 static void xml_config_bend_stop()
471 if (control_block.xml_config[0])
473 struct gfs_server *gfs = gfs_server_list;
474 for (; gfs; gfs = gfs->next)
476 yaz_log(YLOG_DEBUG, "xml_config_bend_stop config=%s",
478 statserv_setcontrol(&gfs->cb);
479 if (control_block.bend_stop)
480 (control_block.bend_stop)(&gfs->cb);
485 yaz_log(YLOG_DEBUG, "xml_config_bend_stop default config");
486 statserv_setcontrol(&control_block);
487 if (control_block.bend_stop)
488 (*control_block.bend_stop)(&control_block);
493 * handle incoming connect requests.
494 * The dynamic mode is a bit tricky mostly because we want to avoid
495 * doing all of the listening and accepting in the parent - it's
500 typedef struct _ThreadList ThreadList;
509 static ThreadList *pFirstThread;
510 static CRITICAL_SECTION Thread_CritSect;
511 static BOOL bInitialized = FALSE;
513 static void ThreadList_Initialize()
515 /* Initialize the critical Sections */
516 InitializeCriticalSection(&Thread_CritSect);
518 /* Set the first thraed */
521 /* we have been initialized */
525 static void statserv_add(HANDLE hThread, IOCHAN pIOChannel)
527 /* Only one thread can go through this section at a time */
528 EnterCriticalSection(&Thread_CritSect);
531 /* Lets create our new object */
532 ThreadList *pNewThread = (ThreadList *)malloc(sizeof(ThreadList));
533 pNewThread->hThread = hThread;
534 pNewThread->pIOChannel = pIOChannel;
535 pNewThread->pNext = pFirstThread;
536 pFirstThread = pNewThread;
538 /* Lets let somebody else create a new object now */
539 LeaveCriticalSection(&Thread_CritSect);
543 void statserv_remove(IOCHAN pIOChannel)
545 /* Only one thread can go through this section at a time */
546 EnterCriticalSection(&Thread_CritSect);
549 ThreadList *pCurrentThread = pFirstThread;
550 ThreadList *pNextThread;
551 ThreadList *pPrevThread =NULL;
553 /* Step through all the threads */
554 for (; pCurrentThread != NULL; pCurrentThread = pNextThread)
556 /* We only need to compare on the IO Channel */
557 if (pCurrentThread->pIOChannel == pIOChannel)
559 /* We have found the thread we want to delete */
560 /* First of all reset the next pointers */
561 if (pPrevThread == NULL)
562 pFirstThread = pCurrentThread->pNext;
564 pPrevThread->pNext = pCurrentThread->pNext;
566 /* All we need todo now is delete the memory */
567 free(pCurrentThread);
569 /* No need to look at any more threads */
574 /* We need to look at another thread */
575 pNextThread = pCurrentThread->pNext;
576 pPrevThread = pCurrentThread;
580 /* Lets let somebody else remove an object now */
581 LeaveCriticalSection(&Thread_CritSect);
585 /* WIN32 statserv_closedown */
586 void statserv_closedown()
588 /* Shouldn't do anything if we are not initialized */
592 HANDLE *pThreadHandles = NULL;
594 /* We need to stop threads adding and removing while we */
595 /* start the closedown process */
596 EnterCriticalSection(&Thread_CritSect);
599 /* We have exclusive access to the thread stuff now */
600 /* Y didn't i use a semaphore - Oh well never mind */
601 ThreadList *pCurrentThread = pFirstThread;
603 /* Before we do anything else, we need to shutdown the listener */
604 if (pListener != NULL)
605 iochan_destroy(pListener);
607 for (; pCurrentThread != NULL; pCurrentThread = pCurrentThread->pNext)
609 /* Just destroy the IOCHAN, that should do the trick */
610 iochan_destroy(pCurrentThread->pIOChannel);
611 closesocket(pCurrentThread->pIOChannel->fd);
613 /* Keep a running count of our handles */
619 HANDLE *pCurrentHandle ;
621 /* Allocate the thread handle array */
622 pThreadHandles = (HANDLE *)malloc(sizeof(HANDLE) * iHandles);
623 pCurrentHandle = pThreadHandles;
625 for (pCurrentThread = pFirstThread;
626 pCurrentThread != NULL;
627 pCurrentThread = pCurrentThread->pNext, pCurrentHandle++)
629 /* Just the handle */
630 *pCurrentHandle = pCurrentThread->hThread;
634 /* We can now leave the critical section */
635 LeaveCriticalSection(&Thread_CritSect);
638 /* Now we can really do something */
641 yaz_log(log_server, "waiting for %d to die", iHandles);
642 /* This will now wait, until all the threads close */
643 WaitForMultipleObjects(iHandles, pThreadHandles, TRUE, INFINITE);
645 /* Free the memory we allocated for the handle array */
646 free(pThreadHandles);
649 xml_config_bend_stop();
650 /* No longer require the critical section, since all threads are dead */
651 DeleteCriticalSection(&Thread_CritSect);
656 void __cdecl event_loop_thread (IOCHAN iochan)
658 event_loop (&iochan);
662 static void listener(IOCHAN h, int event)
664 COMSTACK line = (COMSTACK) iochan_getdata(h);
665 IOCHAN parent_chan = line->user;
670 if (event == EVENT_INPUT)
672 if ((res = cs_listen(line, 0, 0)) < 0)
674 yaz_log(YLOG_FATAL, "cs_listen failed");
679 yaz_log(YLOG_DEBUG, "listen ok");
680 iochan_setevent(h, EVENT_OUTPUT);
681 iochan_setflags(h, EVENT_OUTPUT | EVENT_EXCEPT); /* set up for acpt */
683 else if (event == EVENT_OUTPUT)
685 COMSTACK new_line = cs_accept(line);
691 yaz_log(YLOG_FATAL, "Accept failed.");
692 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT);
695 yaz_log(YLOG_DEBUG, "Accept ok");
697 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session,
698 EVENT_INPUT, parent_chan->chan_id)))
700 yaz_log(YLOG_FATAL, "Failed to create iochan");
705 yaz_log(YLOG_DEBUG, "Creating association");
706 if (!(newas = create_association(new_chan, new_line,
707 control_block.apdufile)))
709 yaz_log(YLOG_FATAL, "Failed to create new assoc.");
713 newas->cs_get_mask = EVENT_INPUT;
714 newas->cs_put_mask = 0;
715 newas->cs_accept_mask = 0;
717 yaz_log(YLOG_DEBUG, "Setting timeout %d", control_block.idle_timeout);
718 iochan_setdata(new_chan, newas);
719 iochan_settimeout(new_chan, 60);
721 /* Now what we need todo is create a new thread with this iochan as
723 newHandle = (HANDLE) _beginthread(event_loop_thread, 0, new_chan);
724 if (newHandle == (HANDLE) -1)
727 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create new thread.");
731 /* We successfully created the thread, so add it to the list */
732 statserv_add(newHandle, new_chan);
734 yaz_log(YLOG_DEBUG, "Created new thread, id = %ld iochan %p",(long) newHandle, new_chan);
735 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
739 yaz_log(YLOG_FATAL, "Bad event on listener.");
745 int statserv_must_terminate(void)
752 static int term_flag = 0;
753 /* To save having an #ifdef in event_loop we need to
754 define this empty function
756 int statserv_must_terminate(void)
761 void statserv_remove(IOCHAN pIOChannel)
765 void statserv_closedown()
769 xml_config_bend_stop();
770 for (p = pListener; p; p = p->next)
777 void sigterm(int sig)
782 static void *new_session (void *vp);
783 static int no_sessions = 0;
786 static void listener(IOCHAN h, int event)
788 COMSTACK line = (COMSTACK) iochan_getdata(h);
791 if (event == EVENT_INPUT)
794 if ((res = cs_listen_check(line, 0, 0, control_block.check_ip,
795 control_block.daemon_name)) < 0)
797 yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_listen failed");
802 yaz_log(YLOG_WARN, "cs_listen incomplete");
805 new_line = cs_accept(line);
808 yaz_log(YLOG_FATAL, "Accept failed.");
809 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
813 yaz_log(log_session, "Connect from %s", cs_addrstr(new_line));
816 if (control_block.dynamic)
818 if ((res = fork()) < 0)
820 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fork");
824 else if (res == 0) /* child */
829 for (pp = pListener; pp; pp = iochan_getnext(pp))
831 COMSTACK l = (COMSTACK)iochan_getdata(pp);
835 sprintf(nbuf, "%s(%d)", me, no_sessions);
836 yaz_log_init(control_block.loglevel, nbuf, 0);
837 /* ensure that bend_stop is not called when each child exits -
838 only for the main process .. */
839 control_block.bend_stop = 0;
848 if (control_block.threads)
850 #if YAZ_POSIX_THREADS
851 pthread_t child_thread;
852 pthread_create (&child_thread, 0, new_session, new_line);
853 pthread_detach (child_thread);
854 #elif YAZ_GNU_THREADS
858 attr = pth_attr_new ();
859 pth_attr_set (attr, PTH_ATTR_JOINABLE, FALSE);
860 pth_attr_set (attr, PTH_ATTR_STACK_SIZE, 32*1024);
861 pth_attr_set (attr, PTH_ATTR_NAME, "session");
862 yaz_log (YLOG_DEBUG, "pth_spawn begin");
863 child_thread = pth_spawn (attr, new_session, new_line);
864 yaz_log (YLOG_DEBUG, "pth_spawn finish");
865 pth_attr_destroy (attr);
867 new_session(new_line);
871 new_session(new_line);
873 else if (event == EVENT_TIMEOUT)
875 yaz_log(log_server, "Shutting down listener.");
880 yaz_log(YLOG_FATAL, "Bad event on listener.");
885 static void *new_session (void *vp)
890 COMSTACK new_line = (COMSTACK) vp;
891 IOCHAN parent_chan = new_line->user;
893 unsigned cs_get_mask, cs_accept_mask, mask =
894 ((new_line->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
895 ((new_line->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
899 cs_accept_mask = mask; /* accept didn't complete */
904 cs_accept_mask = 0; /* accept completed. */
905 cs_get_mask = mask = EVENT_INPUT;
908 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session, mask,
909 parent_chan->chan_id)))
911 yaz_log(YLOG_FATAL, "Failed to create iochan");
914 if (!(newas = create_association(new_chan, new_line,
915 control_block.apdufile)))
917 yaz_log(YLOG_FATAL, "Failed to create new assoc.");
920 newas->cs_accept_mask = cs_accept_mask;
921 newas->cs_get_mask = cs_get_mask;
923 iochan_setdata(new_chan, newas);
924 iochan_settimeout(new_chan, 60);
926 a = cs_addrstr(new_line);
930 yaz_log(log_session, "Starting session %d from %s (pid=%ld)",
931 no_sessions, a ? a : "[Unknown]", (long) getpid());
932 if (max_sessions && no_sessions >= max_sessions)
933 control_block.one_shot = 1;
934 if (control_block.threads)
936 event_loop(&new_chan);
940 new_chan->next = pListener;
941 pListener = new_chan;
949 static void inetd_connection(int what)
956 if ((line = cs_createbysocket(0, tcpip_type, 0, what)))
958 if ((chan = iochan_create(cs_fileno(line), ir_session, EVENT_INPUT,
961 if ((assoc = create_association(chan, line,
962 control_block.apdufile)))
964 iochan_setdata(chan, assoc);
965 iochan_settimeout(chan, 60);
966 addr = cs_addrstr(line);
967 yaz_log(log_session, "Inetd association from %s",
968 addr ? addr : "[UNKNOWN]");
969 assoc->cs_get_mask = EVENT_INPUT;
973 yaz_log(YLOG_FATAL, "Failed to create association structure");
975 chan->next = pListener;
980 yaz_log(YLOG_FATAL, "Failed to create iochan");
985 yaz_log(YLOG_ERRNO|YLOG_FATAL, "Failed to create comstack on socket 0");
990 * Set up a listening endpoint, and give it to the event-handler.
992 static int add_listener(char *where, int listen_id)
999 if (control_block.dynamic)
1001 else if (control_block.threads)
1006 yaz_log(log_server, "Adding %s listener on %s id=%d", mode, where,
1009 l = cs_create_host(where, 2, &ap);
1012 yaz_log(YLOG_FATAL, "Failed to listen on %s", where);
1015 if (*control_block.cert_fname)
1016 cs_set_ssl_certificate_file(l, control_block.cert_fname);
1018 if (cs_bind(l, ap, CS_SERVER) < 0)
1020 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to bind to %s", where);
1024 if (!(lst = iochan_create(cs_fileno(l), listener, EVENT_INPUT |
1025 EVENT_EXCEPT, listen_id)))
1027 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create IOCHAN-type");
1031 iochan_setdata(lst, l); /* user-defined data for listener is COMSTACK */
1032 l->user = lst; /* user-defined data for COMSTACK is listener chan */
1034 /* Add listener to chain */
1035 lst->next = pListener;
1041 /* UNIX only (for windows we don't need to catch the signals) */
1042 static void catchchld(int num)
1044 while (waitpid(-1, 0, WNOHANG) > 0)
1046 signal(SIGCHLD, catchchld);
1050 statserv_options_block *statserv_getcontrol(void)
1053 if (init_control_tls)
1054 return (statserv_options_block *) TlsGetValue(current_control_tls);
1056 return &control_block;
1057 #elif YAZ_POSIX_THREADS
1058 if (init_control_tls)
1059 return pthread_getspecific(current_control_tls);
1061 return &control_block;
1063 if (current_control_block)
1064 return current_control_block;
1065 return &control_block;
1069 void statserv_setcontrol(statserv_options_block *block)
1072 if (init_control_tls)
1073 TlsSetValue(current_control_tls, block);
1074 #elif YAZ_POSIX_THREADS
1075 if (init_control_tls)
1076 pthread_setspecific(current_control_tls, block);
1078 current_control_block = block;
1082 static void statserv_reset(void)
1086 int statserv_start(int argc, char **argv)
1090 /* We need to initialize the thread list */
1091 ThreadList_Initialize();
1101 if ((me = strrchr (argv[0], sep)))
1102 me++; /* get the basename */
1105 programname = argv[0];
1107 if (control_block.options_func(argc, argv))
1112 xml_config_bend_start();
1115 xml_config_add_listeners();
1117 yaz_log (log_server, "Starting server %s", me);
1118 if (!pListener && *control_block.default_listen)
1119 add_listener(control_block.default_listen, 0);
1122 if (control_block.inetd)
1123 inetd_connection(control_block.default_proto);
1127 if (control_block.background)
1129 /* create pipe so that parent waits until child has created
1133 yaz_log(YLOG_FATAL|YLOG_ERRNO, "pipe");
1147 int res = read(hand[0], dummy, 1);
1148 if (res < 0 && yaz_errno() != EINTR)
1150 yaz_log(YLOG_FATAL|YLOG_ERRNO, "read fork handshake");
1167 open("/dev/null", O_RDWR);
1170 xml_config_add_listeners();
1172 if (!pListener && *control_block.default_listen)
1173 add_listener(control_block.default_listen, 0);
1178 if (*control_block.pid_fname)
1180 FILE *f = fopen(control_block.pid_fname, "w");
1183 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Couldn't create %s",
1184 control_block.pid_fname);
1187 fprintf(f, "%ld", (long) getpid());
1191 if (control_block.background)
1195 yaz_log (log_server, "Starting server %s pid=%ld", programname,
1198 sigset_t sigs_to_block;
1200 sigemptyset(&sigs_to_block);
1201 sigaddset (&sigs_to_block, SIGTERM);
1202 pthread_sigmask (SIG_BLOCK, &sigs_to_block, 0);
1205 if (control_block.dynamic)
1206 signal(SIGCHLD, catchchld);
1208 signal (SIGPIPE, SIG_IGN);
1209 signal (SIGTERM, sigterm);
1210 if (*control_block.setuid)
1214 if (!(pw = getpwnam(control_block.setuid)))
1216 yaz_log(YLOG_FATAL, "%s: Unknown user", control_block.setuid);
1219 if (setuid(pw->pw_uid) < 0)
1221 yaz_log(YLOG_FATAL|YLOG_ERRNO, "setuid");
1227 if (pListener == NULL)
1229 yaz_log(YLOG_DEBUG, "Entering event loop.");
1230 return event_loop(&pListener);
1233 static void option_copy(char *dst, const char *src)
1235 strncpy(dst, src ? src : "", 127);
1239 int check_options(int argc, char **argv)
1244 /* set default log level */
1245 control_block.loglevel = yaz_log_mask_str(STAT_DEFAULT_LOG_LEVEL);
1246 yaz_log_init_level(control_block.loglevel);
1248 while ((ret = options("1a:iszSTl:v:u:c:w:t:k:d:A:p:DC:f:",
1249 argv, argc, &arg)) != -2)
1254 if (add_listener(arg, 0))
1255 return 1; /* failed to create listener */
1258 control_block.one_shot = 1;
1259 control_block.dynamic = 0;
1262 control_block.default_proto = PROTO_Z3950;
1265 fprintf (stderr, "%s: SR protocol no longer supported\n", me);
1269 control_block.dynamic = 0;
1272 #if YAZ_POSIX_THREADS
1273 control_block.dynamic = 0;
1274 control_block.threads = 1;
1275 #elif YAZ_GNU_THREADS
1276 control_block.dynamic = 0;
1277 control_block.threads = 1;
1279 fprintf(stderr, "%s: Threaded mode not available.\n", me);
1284 option_copy(control_block.logfile, arg);
1285 yaz_log_init(control_block.loglevel, me, control_block.logfile);
1288 control_block.loglevel =
1289 yaz_log_mask_str_x(arg,control_block.loglevel);
1290 yaz_log_init(control_block.loglevel, me, control_block.logfile);
1293 option_copy(control_block.apdufile, arg);
1296 option_copy(control_block.setuid, arg);
1299 option_copy(control_block.configname, arg);
1302 option_copy(control_block.cert_fname, arg);
1305 option_copy(control_block.daemon_name, arg);
1308 if (!arg || !(r = atoi(arg)))
1310 fprintf(stderr, "%s: Specify positive timeout for -t.\n", me);
1313 control_block.idle_timeout = r;
1316 if (!arg || !(r = atoi(arg)))
1318 fprintf(stderr, "%s: Specify positive size for -k.\n", me);
1321 control_block.maxrecordsize = r * 1024;
1324 control_block.inetd = 1;
1334 max_sessions = atoi(arg);
1337 option_copy(control_block.pid_fname, arg);
1341 option_copy(control_block.xml_config, arg);
1343 fprintf(stderr, "%s: Option -f unsupported since YAZ is compiled without Libxml2 support\n", me);
1348 control_block.background = 1;
1351 fprintf(stderr, "Usage: %s [ -a <pdufile> -v <loglevel>"
1352 " -l <logfile> -u <user> -c <config> -t <minutes>"
1353 " -k <kilobytes> -d <daemon> -p <pidfile> -C certfile"
1354 " -ziDST1 -w <directory> <listener-addr>... ]\n", me);
1363 typedef struct _Args
1369 static Args ArgDetails;
1371 /* name of the executable */
1372 #define SZAPPNAME "server"
1374 /* list of service dependencies - "dep1\0dep2\0\0" */
1375 #define SZDEPENDENCIES ""
1377 int statserv_main(int argc, char **argv,
1378 bend_initresult *(*bend_init)(bend_initrequest *r),
1379 void (*bend_close)(void *handle))
1381 struct statserv_options_block *cb = &control_block;
1382 cb->bend_init = bend_init;
1383 cb->bend_close = bend_close;
1385 /* Lets setup the Arg structure */
1386 ArgDetails.argc = argc;
1387 ArgDetails.argv = argv;
1389 /* Now setup the service with the service controller */
1390 SetupService(argc, argv, &ArgDetails, SZAPPNAME,
1391 cb->service_name, /* internal service name */
1392 cb->service_display_name, /* displayed name */
1397 int StartAppService(void *pHandle, int argc, char **argv)
1399 /* Initializes the App */
1403 void RunAppService(void *pHandle)
1405 Args *pArgs = (Args *)pHandle;
1407 /* Starts the app running */
1408 statserv_start(pArgs->argc, pArgs->argv);
1411 void StopAppService(void *pHandle)
1414 statserv_closedown();
1420 int statserv_main(int argc, char **argv,
1421 bend_initresult *(*bend_init)(bend_initrequest *r),
1422 void (*bend_close)(void *handle))
1426 control_block.bend_init = bend_init;
1427 control_block.bend_close = bend_close;
1429 ret = statserv_start (argc, argv);
1430 statserv_closedown ();