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.27 2005-03-08 11:48:09 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 char gfs_root_dir[FILENAME_MAX+1];
67 static struct gfs_server *gfs_server_list = 0;
68 static struct gfs_listen *gfs_listen_list = 0;
69 static NMEM gfs_nmem = 0;
71 static char *me = "statserver"; /* log prefix */
72 static char *programname="statserver"; /* full program name */
74 DWORD current_control_tls;
75 static int init_control_tls = 0;
76 #elif YAZ_POSIX_THREADS
77 static pthread_key_t current_control_tls;
78 static int init_control_tls = 0;
80 static statserv_options_block *current_control_block = 0;
86 #define STAT_DEFAULT_LOG_LEVEL "none,fatal,warn,log,server,session,request"
87 /* the 'none' clears yaz' own default settings, including [log] */
89 int check_options(int argc, char **argv);
90 statserv_options_block control_block = {
92 0, /* threaded mode */
93 0, /* one shot (single session) */
94 YLOG_DEFAULT_LEVEL, /* log level */
96 "", /* diagnostic output to stderr */
97 "tcp:@:9999", /* default listener port */
98 PROTO_Z3950, /* default application protocol */
99 15, /* idle timeout (minutes) */
100 1024*1024, /* maximum PDU size (approx.) to allow */
101 "default-config", /* configuration name to pass to backend */
102 "", /* set user id */
103 0, /* bend_start handler */
104 0, /* bend_stop handler */
105 check_options, /* Default routine, for checking the run-time arguments */
108 0, /* default value for inet deamon */
109 0, /* handle (for service, etc) */
110 0, /* bend_init handle */
111 0, /* bend_close handle */
113 "Z39.50 Server", /* NT Service Name */
114 "Server", /* NT application Name */
115 "", /* NT Service Dependencies */
116 "Z39.50 Server", /* NT Service Display Name */
118 0, /* SOAP handlers */
120 0, /* background daemon */
121 "", /* SSL certificate filename */
122 "" /* XML config filename */
125 static int max_sessions = 0;
127 static int logbits_set = 0;
128 static int log_session = 0;
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_server = yaz_log_module_level("server");
143 static int add_listener(char *where, int listen_id);
146 static xmlDocPtr xml_config_doc = 0;
150 static xmlNodePtr xml_config_get_root()
155 ptr = xmlDocGetRootElement(xml_config_doc);
156 if (!ptr || ptr->type != XML_ELEMENT_NODE ||
157 strcmp((const char *) ptr->name, "yazgfs"))
159 yaz_log(YLOG_WARN, "Bad/missing root element for config %s",
160 control_block.xml_config);
170 static char *nmem_dup_xml_content(NMEM n, xmlNodePtr ptr)
174 int len = 1; /* start with 1, because of trailing 0 */
176 int first = 1; /* whitespace lead flag .. */
177 /* determine length */
178 for (p = ptr; p; p = p->next)
180 if (p->type == XML_TEXT_NODE)
181 len += strlen(p->content);
183 /* now allocate for the string */
184 str = nmem_malloc(n, len);
185 *str = '\0'; /* so we can use strcat */
186 for (p = ptr; p; p = p->next)
188 if (p->type == XML_TEXT_NODE)
193 while(*cp && isspace(*cp))
196 first = 0; /* reset if we got non-whitespace out */
198 strcat(str, cp); /* append */
201 /* remove trailing whitespace */
202 cp = strlen(str) + str;
203 while ((char*) cp != str && isspace(cp[-1]))
206 /* return resulting string */
211 static struct gfs_server * gfs_server_new()
213 struct gfs_server *n = nmem_malloc(gfs_nmem, sizeof(*n));
214 memcpy(&n->cb, &control_block, sizeof(control_block));
218 n->cql_transform = 0;
219 n->server_node_ptr = 0;
224 static struct gfs_listen * gfs_listen_new(const char *id,
227 struct gfs_listen *n = nmem_malloc(gfs_nmem, sizeof(*n));
229 n->id = nmem_strdup(gfs_nmem, id);
233 n->address = nmem_strdup(gfs_nmem, address);
237 static void gfs_server_chdir(struct gfs_server *gfs)
241 if (chdir(gfs_root_dir))
242 yaz_log(YLOG_WARN|YLOG_ERRNO, "chdir %s", gfs_root_dir);
246 if (chdir(gfs->directory))
247 yaz_log(YLOG_WARN|YLOG_ERRNO, "chdir %s",
252 int control_association(association *assoc, const char *host, int force_open)
254 char vhost[128], *cp;
257 strncpy(vhost, host, 127);
259 cp = strchr(vhost, ':');
264 if (control_block.xml_config[0])
266 struct gfs_server *gfs;
267 for (gfs = gfs_server_list; gfs; gfs = gfs->next)
269 int listen_match = 0;
271 if ( !gfs->host || (host && gfs->host && !strcmp(host, gfs->host)))
273 if (!gfs->listen_ref ||
274 gfs->listen_ref == assoc->client_chan->chan_id)
276 if (listen_match && host_match)
279 (assoc->last_control != &gfs->cb && assoc->backend))
281 statserv_setcontrol(assoc->last_control);
282 if (assoc->backend && assoc->init)
284 gfs_server_chdir(gfs);
285 (assoc->last_control->bend_close)(assoc->backend);
291 assoc->cql_transform = gfs->cql_transform;
292 assoc->server_node_ptr = gfs->server_node_ptr;
293 assoc->last_control = &gfs->cb;
294 statserv_setcontrol(&gfs->cb);
295 gfs_server_chdir(gfs);
296 yaz_log(YLOG_DEBUG, "server select: %s", gfs->cb.configname);
300 statserv_setcontrol(0);
301 assoc->last_control = 0;
302 assoc->cql_transform = 0;
303 assoc->server_node_ptr = 0;
304 yaz_log(YLOG_DEBUG, "server select: no match");
309 statserv_setcontrol(&control_block);
310 assoc->last_control = &control_block;
311 assoc->cql_transform = 0;
312 assoc->server_node_ptr = 0;
313 yaz_log(YLOG_DEBUG, "server select: config=%s", control_block.configname);
318 static void xml_config_read()
320 struct gfs_server **gfsp = &gfs_server_list;
321 struct gfs_listen **gfslp = &gfs_listen_list;
323 xmlNodePtr ptr = xml_config_get_root();
327 for (ptr = ptr->children; ptr; ptr = ptr->next)
329 struct _xmlAttr *attr;
330 if (ptr->type != XML_ELEMENT_NODE)
332 attr = ptr->properties;
333 if (!strcmp((const char *) ptr->name, "listen"))
336 <listen id="listenerid">tcp:@:9999</listen>
339 const char *address =
340 nmem_dup_xml_content(gfs_nmem, ptr->children);
341 for ( ; attr; attr = attr->next)
342 if (!strcmp(attr->name, "id")
343 && attr->children && attr->children->type == XML_TEXT_NODE)
344 id = nmem_dup_xml_content(gfs_nmem, attr->children);
347 *gfslp = gfs_listen_new(id, address);
348 gfslp = &(*gfslp)->next;
349 *gfslp = 0; /* make listener list consistent for search */
352 else if (!strcmp((const char *) ptr->name, "server"))
354 xmlNodePtr ptr_server = ptr;
356 const char *listenref = 0;
359 for ( ; attr; attr = attr->next)
360 if (!strcmp(attr->name, "listenref") && attr->children &&
361 attr->children->type == XML_TEXT_NODE)
362 listenref = nmem_dup_xml_content(gfs_nmem, attr->children);
363 else if (!strcmp(attr->name, "id") && attr->children &&
364 attr->children->type == XML_TEXT_NODE)
365 id = nmem_dup_xml_content(gfs_nmem, attr->children);
367 yaz_log(YLOG_WARN, "Unknown attribute '%s' for server",
369 *gfsp = gfs_server_new();
370 (*gfsp)->server_node_ptr = ptr_server;
374 struct gfs_listen *gl = gfs_listen_list;
375 for (id_no = 1; gl; gl = gl->next, id_no++)
376 if (gl->id && !strcmp(gl->id, listenref))
378 (*gfsp)->listen_ref = id_no;
382 yaz_log(YLOG_WARN, "Non-existent listenref '%s' in server "
383 "config element", listenref);
385 for (ptr = ptr_server->children; ptr; ptr = ptr->next)
387 if (ptr->type != XML_ELEMENT_NODE)
389 if (!strcmp((const char *) ptr->name, "host"))
391 (*gfsp)->host = nmem_dup_xml_content(gfs_nmem,
394 else if (!strcmp((const char *) ptr->name, "config"))
396 strcpy((*gfsp)->cb.configname,
397 nmem_dup_xml_content(gfs_nmem, ptr->children));
399 else if (!strcmp((const char *) ptr->name, "cql2rpn"))
401 (*gfsp)->cql_transform = cql_transform_open_fname(
402 nmem_dup_xml_content(gfs_nmem, ptr->children)
405 else if (!strcmp((const char *) ptr->name, "directory"))
408 nmem_dup_xml_content(gfs_nmem, ptr->children);
411 gfsp = &(*gfsp)->next;
418 static void xml_config_open()
420 if (!getcwd(gfs_root_dir, FILENAME_MAX))
422 yaz_log(YLOG_WARN|YLOG_ERRNO, "getcwd failed");
423 gfs_root_dir[0] = '\0';
426 init_control_tls = 1;
427 current_control_tls = TlsAlloc();
428 #elif YAZ_POSIX_THREADS
429 init_control_tls = 1;
430 pthread_key_create(¤t_control_tls, 0);
433 gfs_nmem = nmem_create();
435 if (control_block.xml_config[0] == '\0')
440 xml_config_doc = xmlParseFile(control_block.xml_config);
443 yaz_log(YLOG_WARN, "Could not parse %s", control_block.xml_config);
451 static void xml_config_close()
456 xmlFreeDoc(xml_config_doc);
461 nmem_destroy(gfs_nmem);
463 if (init_control_tls)
464 TlsFree(current_control_tls);
465 #elif YAZ_POSIX_THREADS
466 if (init_control_tls)
467 pthread_key_delete(current_control_tls);
471 static void xml_config_add_listeners()
473 struct gfs_listen *gfs = gfs_listen_list;
476 for (id_no = 1; gfs; gfs = gfs->next, id_no++)
479 add_listener(gfs->address, id_no);
483 static void xml_config_bend_start()
485 if (control_block.xml_config[0])
487 struct gfs_server *gfs = gfs_server_list;
488 for (; gfs; gfs = gfs->next)
490 yaz_log(YLOG_DEBUG, "xml_config_bend_start config=%s",
492 statserv_setcontrol(&gfs->cb);
493 if (control_block.bend_start)
495 gfs_server_chdir(gfs);
496 (control_block.bend_start)(&gfs->cb);
502 yaz_log(YLOG_DEBUG, "xml_config_bend_start default config");
503 statserv_setcontrol(&control_block);
504 if (control_block.bend_start)
505 (*control_block.bend_start)(&control_block);
509 static void xml_config_bend_stop()
511 if (control_block.xml_config[0])
513 struct gfs_server *gfs = gfs_server_list;
514 for (; gfs; gfs = gfs->next)
516 yaz_log(YLOG_DEBUG, "xml_config_bend_stop config=%s",
518 statserv_setcontrol(&gfs->cb);
519 if (control_block.bend_stop)
520 (control_block.bend_stop)(&gfs->cb);
525 yaz_log(YLOG_DEBUG, "xml_config_bend_stop default config");
526 statserv_setcontrol(&control_block);
527 if (control_block.bend_stop)
528 (*control_block.bend_stop)(&control_block);
533 * handle incoming connect requests.
534 * The dynamic mode is a bit tricky mostly because we want to avoid
535 * doing all of the listening and accepting in the parent - it's
540 typedef struct _ThreadList ThreadList;
549 static ThreadList *pFirstThread;
550 static CRITICAL_SECTION Thread_CritSect;
551 static BOOL bInitialized = FALSE;
553 static void ThreadList_Initialize()
555 /* Initialize the critical Sections */
556 InitializeCriticalSection(&Thread_CritSect);
558 /* Set the first thraed */
561 /* we have been initialized */
565 static void statserv_add(HANDLE hThread, IOCHAN pIOChannel)
567 /* Only one thread can go through this section at a time */
568 EnterCriticalSection(&Thread_CritSect);
571 /* Lets create our new object */
572 ThreadList *pNewThread = (ThreadList *)malloc(sizeof(ThreadList));
573 pNewThread->hThread = hThread;
574 pNewThread->pIOChannel = pIOChannel;
575 pNewThread->pNext = pFirstThread;
576 pFirstThread = pNewThread;
578 /* Lets let somebody else create a new object now */
579 LeaveCriticalSection(&Thread_CritSect);
583 void statserv_remove(IOCHAN pIOChannel)
585 /* Only one thread can go through this section at a time */
586 EnterCriticalSection(&Thread_CritSect);
589 ThreadList *pCurrentThread = pFirstThread;
590 ThreadList *pNextThread;
591 ThreadList *pPrevThread =NULL;
593 /* Step through all the threads */
594 for (; pCurrentThread != NULL; pCurrentThread = pNextThread)
596 /* We only need to compare on the IO Channel */
597 if (pCurrentThread->pIOChannel == pIOChannel)
599 /* We have found the thread we want to delete */
600 /* First of all reset the next pointers */
601 if (pPrevThread == NULL)
602 pFirstThread = pCurrentThread->pNext;
604 pPrevThread->pNext = pCurrentThread->pNext;
606 /* All we need todo now is delete the memory */
607 free(pCurrentThread);
609 /* No need to look at any more threads */
614 /* We need to look at another thread */
615 pNextThread = pCurrentThread->pNext;
616 pPrevThread = pCurrentThread;
620 /* Lets let somebody else remove an object now */
621 LeaveCriticalSection(&Thread_CritSect);
625 /* WIN32 statserv_closedown */
626 void statserv_closedown()
628 /* Shouldn't do anything if we are not initialized */
632 HANDLE *pThreadHandles = NULL;
634 /* We need to stop threads adding and removing while we */
635 /* start the closedown process */
636 EnterCriticalSection(&Thread_CritSect);
639 /* We have exclusive access to the thread stuff now */
640 /* Y didn't i use a semaphore - Oh well never mind */
641 ThreadList *pCurrentThread = pFirstThread;
643 /* Before we do anything else, we need to shutdown the listener */
644 if (pListener != NULL)
645 iochan_destroy(pListener);
647 for (; pCurrentThread != NULL; pCurrentThread = pCurrentThread->pNext)
649 /* Just destroy the IOCHAN, that should do the trick */
650 iochan_destroy(pCurrentThread->pIOChannel);
651 closesocket(pCurrentThread->pIOChannel->fd);
653 /* Keep a running count of our handles */
659 HANDLE *pCurrentHandle ;
661 /* Allocate the thread handle array */
662 pThreadHandles = (HANDLE *)malloc(sizeof(HANDLE) * iHandles);
663 pCurrentHandle = pThreadHandles;
665 for (pCurrentThread = pFirstThread;
666 pCurrentThread != NULL;
667 pCurrentThread = pCurrentThread->pNext, pCurrentHandle++)
669 /* Just the handle */
670 *pCurrentHandle = pCurrentThread->hThread;
674 /* We can now leave the critical section */
675 LeaveCriticalSection(&Thread_CritSect);
678 /* Now we can really do something */
681 yaz_log(log_server, "waiting for %d to die", iHandles);
682 /* This will now wait, until all the threads close */
683 WaitForMultipleObjects(iHandles, pThreadHandles, TRUE, INFINITE);
685 /* Free the memory we allocated for the handle array */
686 free(pThreadHandles);
689 xml_config_bend_stop();
690 /* No longer require the critical section, since all threads are dead */
691 DeleteCriticalSection(&Thread_CritSect);
696 void __cdecl event_loop_thread (IOCHAN iochan)
698 event_loop (&iochan);
702 static void listener(IOCHAN h, int event)
704 COMSTACK line = (COMSTACK) iochan_getdata(h);
705 IOCHAN parent_chan = line->user;
710 if (event == EVENT_INPUT)
712 if ((res = cs_listen(line, 0, 0)) < 0)
714 yaz_log(YLOG_FATAL, "cs_listen failed");
719 yaz_log(YLOG_DEBUG, "listen ok");
720 iochan_setevent(h, EVENT_OUTPUT);
721 iochan_setflags(h, EVENT_OUTPUT | EVENT_EXCEPT); /* set up for acpt */
723 else if (event == EVENT_OUTPUT)
725 COMSTACK new_line = cs_accept(line);
731 yaz_log(YLOG_FATAL, "Accept failed.");
732 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT);
735 yaz_log(YLOG_DEBUG, "Accept ok");
737 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session,
738 EVENT_INPUT, parent_chan->chan_id)))
740 yaz_log(YLOG_FATAL, "Failed to create iochan");
745 yaz_log(YLOG_DEBUG, "Creating association");
746 if (!(newas = create_association(new_chan, new_line,
747 control_block.apdufile)))
749 yaz_log(YLOG_FATAL, "Failed to create new assoc.");
753 newas->cs_get_mask = EVENT_INPUT;
754 newas->cs_put_mask = 0;
755 newas->cs_accept_mask = 0;
757 yaz_log(YLOG_DEBUG, "Setting timeout %d", control_block.idle_timeout);
758 iochan_setdata(new_chan, newas);
759 iochan_settimeout(new_chan, 60);
761 /* Now what we need todo is create a new thread with this iochan as
763 newHandle = (HANDLE) _beginthread(event_loop_thread, 0, new_chan);
764 if (newHandle == (HANDLE) -1)
767 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create new thread.");
771 /* We successfully created the thread, so add it to the list */
772 statserv_add(newHandle, new_chan);
774 yaz_log(YLOG_DEBUG, "Created new thread, id = %ld iochan %p",(long) newHandle, new_chan);
775 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
779 yaz_log(YLOG_FATAL, "Bad event on listener.");
785 int statserv_must_terminate(void)
792 static int term_flag = 0;
793 /* To save having an #ifdef in event_loop we need to
794 define this empty function
796 int statserv_must_terminate(void)
801 void statserv_remove(IOCHAN pIOChannel)
805 void statserv_closedown()
809 xml_config_bend_stop();
810 for (p = pListener; p; p = p->next)
817 void sigterm(int sig)
822 static void *new_session (void *vp);
823 static int no_sessions = 0;
826 static void listener(IOCHAN h, int event)
828 COMSTACK line = (COMSTACK) iochan_getdata(h);
831 if (event == EVENT_INPUT)
834 if ((res = cs_listen_check(line, 0, 0, control_block.check_ip,
835 control_block.daemon_name)) < 0)
837 yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_listen failed");
842 yaz_log(YLOG_WARN, "cs_listen incomplete");
845 new_line = cs_accept(line);
848 yaz_log(YLOG_FATAL, "Accept failed.");
849 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
853 yaz_log(log_session, "Connect from %s", cs_addrstr(new_line));
856 if (control_block.dynamic)
858 if ((res = fork()) < 0)
860 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fork");
864 else if (res == 0) /* child */
869 for (pp = pListener; pp; pp = iochan_getnext(pp))
871 COMSTACK l = (COMSTACK)iochan_getdata(pp);
875 sprintf(nbuf, "%s(%d)", me, no_sessions);
876 yaz_log_init(control_block.loglevel, nbuf, 0);
877 /* ensure that bend_stop is not called when each child exits -
878 only for the main process .. */
879 control_block.bend_stop = 0;
888 if (control_block.threads)
890 #if YAZ_POSIX_THREADS
891 pthread_t child_thread;
892 pthread_create (&child_thread, 0, new_session, new_line);
893 pthread_detach (child_thread);
894 #elif YAZ_GNU_THREADS
898 attr = pth_attr_new ();
899 pth_attr_set (attr, PTH_ATTR_JOINABLE, FALSE);
900 pth_attr_set (attr, PTH_ATTR_STACK_SIZE, 32*1024);
901 pth_attr_set (attr, PTH_ATTR_NAME, "session");
902 yaz_log (YLOG_DEBUG, "pth_spawn begin");
903 child_thread = pth_spawn (attr, new_session, new_line);
904 yaz_log (YLOG_DEBUG, "pth_spawn finish");
905 pth_attr_destroy (attr);
907 new_session(new_line);
911 new_session(new_line);
913 else if (event == EVENT_TIMEOUT)
915 yaz_log(log_server, "Shutting down listener.");
920 yaz_log(YLOG_FATAL, "Bad event on listener.");
925 static void *new_session (void *vp)
930 COMSTACK new_line = (COMSTACK) vp;
931 IOCHAN parent_chan = new_line->user;
933 unsigned cs_get_mask, cs_accept_mask, mask =
934 ((new_line->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
935 ((new_line->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
939 cs_accept_mask = mask; /* accept didn't complete */
944 cs_accept_mask = 0; /* accept completed. */
945 cs_get_mask = mask = EVENT_INPUT;
948 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session, mask,
949 parent_chan->chan_id)))
951 yaz_log(YLOG_FATAL, "Failed to create iochan");
954 if (!(newas = create_association(new_chan, new_line,
955 control_block.apdufile)))
957 yaz_log(YLOG_FATAL, "Failed to create new assoc.");
960 newas->cs_accept_mask = cs_accept_mask;
961 newas->cs_get_mask = cs_get_mask;
963 iochan_setdata(new_chan, newas);
964 iochan_settimeout(new_chan, 60);
966 a = cs_addrstr(new_line);
970 yaz_log(log_session, "Starting session %d from %s (pid=%ld)",
971 no_sessions, a ? a : "[Unknown]", (long) getpid());
972 if (max_sessions && no_sessions >= max_sessions)
973 control_block.one_shot = 1;
974 if (control_block.threads)
976 event_loop(&new_chan);
980 new_chan->next = pListener;
981 pListener = new_chan;
989 static void inetd_connection(int what)
996 if ((line = cs_createbysocket(0, tcpip_type, 0, what)))
998 if ((chan = iochan_create(cs_fileno(line), ir_session, EVENT_INPUT,
1001 if ((assoc = create_association(chan, line,
1002 control_block.apdufile)))
1004 iochan_setdata(chan, assoc);
1005 iochan_settimeout(chan, 60);
1006 addr = cs_addrstr(line);
1007 yaz_log(log_session, "Inetd association from %s",
1008 addr ? addr : "[UNKNOWN]");
1009 assoc->cs_get_mask = EVENT_INPUT;
1013 yaz_log(YLOG_FATAL, "Failed to create association structure");
1015 chan->next = pListener;
1020 yaz_log(YLOG_FATAL, "Failed to create iochan");
1025 yaz_log(YLOG_ERRNO|YLOG_FATAL, "Failed to create comstack on socket 0");
1030 * Set up a listening endpoint, and give it to the event-handler.
1032 static int add_listener(char *where, int listen_id)
1039 if (control_block.dynamic)
1041 else if (control_block.threads)
1046 yaz_log(log_server, "Adding %s listener on %s id=%d", mode, where,
1049 l = cs_create_host(where, 2, &ap);
1052 yaz_log(YLOG_FATAL, "Failed to listen on %s", where);
1055 if (*control_block.cert_fname)
1056 cs_set_ssl_certificate_file(l, control_block.cert_fname);
1058 if (cs_bind(l, ap, CS_SERVER) < 0)
1060 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to bind to %s", where);
1064 if (!(lst = iochan_create(cs_fileno(l), listener, EVENT_INPUT |
1065 EVENT_EXCEPT, listen_id)))
1067 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create IOCHAN-type");
1071 iochan_setdata(lst, l); /* user-defined data for listener is COMSTACK */
1072 l->user = lst; /* user-defined data for COMSTACK is listener chan */
1074 /* Add listener to chain */
1075 lst->next = pListener;
1081 /* UNIX only (for windows we don't need to catch the signals) */
1082 static void catchchld(int num)
1084 while (waitpid(-1, 0, WNOHANG) > 0)
1086 signal(SIGCHLD, catchchld);
1090 statserv_options_block *statserv_getcontrol(void)
1093 if (init_control_tls)
1094 return (statserv_options_block *) TlsGetValue(current_control_tls);
1096 return &control_block;
1097 #elif YAZ_POSIX_THREADS
1098 if (init_control_tls)
1099 return pthread_getspecific(current_control_tls);
1101 return &control_block;
1103 if (current_control_block)
1104 return current_control_block;
1105 return &control_block;
1109 void statserv_setcontrol(statserv_options_block *block)
1111 chdir(gfs_root_dir);
1113 if (init_control_tls)
1114 TlsSetValue(current_control_tls, block);
1115 #elif YAZ_POSIX_THREADS
1116 if (init_control_tls)
1117 pthread_setspecific(current_control_tls, block);
1119 current_control_block = block;
1123 static void statserv_reset(void)
1127 int statserv_start(int argc, char **argv)
1131 /* We need to initialize the thread list */
1132 ThreadList_Initialize();
1142 if ((me = strrchr (argv[0], sep)))
1143 me++; /* get the basename */
1146 programname = argv[0];
1148 if (control_block.options_func(argc, argv))
1153 xml_config_bend_start();
1156 xml_config_add_listeners();
1158 yaz_log (log_server, "Starting server %s", me);
1159 if (!pListener && *control_block.default_listen)
1160 add_listener(control_block.default_listen, 0);
1163 if (control_block.inetd)
1164 inetd_connection(control_block.default_proto);
1168 if (control_block.background)
1170 /* create pipe so that parent waits until child has created
1174 yaz_log(YLOG_FATAL|YLOG_ERRNO, "pipe");
1188 int res = read(hand[0], dummy, 1);
1189 if (res < 0 && yaz_errno() != EINTR)
1191 yaz_log(YLOG_FATAL|YLOG_ERRNO, "read fork handshake");
1208 open("/dev/null", O_RDWR);
1211 xml_config_add_listeners();
1213 if (!pListener && *control_block.default_listen)
1214 add_listener(control_block.default_listen, 0);
1219 if (*control_block.pid_fname)
1221 FILE *f = fopen(control_block.pid_fname, "w");
1224 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Couldn't create %s",
1225 control_block.pid_fname);
1228 fprintf(f, "%ld", (long) getpid());
1232 if (control_block.background)
1236 yaz_log (log_server, "Starting server %s pid=%ld", programname,
1239 sigset_t sigs_to_block;
1241 sigemptyset(&sigs_to_block);
1242 sigaddset (&sigs_to_block, SIGTERM);
1243 pthread_sigmask (SIG_BLOCK, &sigs_to_block, 0);
1246 if (control_block.dynamic)
1247 signal(SIGCHLD, catchchld);
1249 signal (SIGPIPE, SIG_IGN);
1250 signal (SIGTERM, sigterm);
1251 if (*control_block.setuid)
1255 if (!(pw = getpwnam(control_block.setuid)))
1257 yaz_log(YLOG_FATAL, "%s: Unknown user", control_block.setuid);
1260 if (setuid(pw->pw_uid) < 0)
1262 yaz_log(YLOG_FATAL|YLOG_ERRNO, "setuid");
1268 if (pListener == NULL)
1270 yaz_log(YLOG_DEBUG, "Entering event loop.");
1271 return event_loop(&pListener);
1274 static void option_copy(char *dst, const char *src)
1276 strncpy(dst, src ? src : "", 127);
1280 int check_options(int argc, char **argv)
1285 /* set default log level */
1286 control_block.loglevel = yaz_log_mask_str(STAT_DEFAULT_LOG_LEVEL);
1287 yaz_log_init_level(control_block.loglevel);
1289 while ((ret = options("1a:iszSTl:v:u:c:w:t:k:d:A:p:DC:f:",
1290 argv, argc, &arg)) != -2)
1295 if (add_listener(arg, 0))
1296 return 1; /* failed to create listener */
1299 control_block.one_shot = 1;
1300 control_block.dynamic = 0;
1303 control_block.default_proto = PROTO_Z3950;
1306 fprintf (stderr, "%s: SR protocol no longer supported\n", me);
1310 control_block.dynamic = 0;
1313 #if YAZ_POSIX_THREADS
1314 control_block.dynamic = 0;
1315 control_block.threads = 1;
1316 #elif YAZ_GNU_THREADS
1317 control_block.dynamic = 0;
1318 control_block.threads = 1;
1320 fprintf(stderr, "%s: Threaded mode not available.\n", me);
1325 option_copy(control_block.logfile, arg);
1326 yaz_log_init(control_block.loglevel, me, control_block.logfile);
1329 control_block.loglevel =
1330 yaz_log_mask_str_x(arg,control_block.loglevel);
1331 yaz_log_init(control_block.loglevel, me, control_block.logfile);
1334 option_copy(control_block.apdufile, arg);
1337 option_copy(control_block.setuid, arg);
1340 option_copy(control_block.configname, arg);
1343 option_copy(control_block.cert_fname, arg);
1346 option_copy(control_block.daemon_name, arg);
1349 if (!arg || !(r = atoi(arg)))
1351 fprintf(stderr, "%s: Specify positive timeout for -t.\n", me);
1354 control_block.idle_timeout = r;
1357 if (!arg || !(r = atoi(arg)))
1359 fprintf(stderr, "%s: Specify positive size for -k.\n", me);
1362 control_block.maxrecordsize = r * 1024;
1365 control_block.inetd = 1;
1375 max_sessions = atoi(arg);
1378 option_copy(control_block.pid_fname, arg);
1382 option_copy(control_block.xml_config, arg);
1384 fprintf(stderr, "%s: Option -f unsupported since YAZ is compiled without Libxml2 support\n", me);
1389 control_block.background = 1;
1392 fprintf(stderr, "Usage: %s [ -a <pdufile> -v <loglevel>"
1393 " -l <logfile> -u <user> -c <config> -t <minutes>"
1394 " -k <kilobytes> -d <daemon> -p <pidfile> -C certfile"
1395 " -ziDST1 -w <directory> <listener-addr>... ]\n", me);
1404 typedef struct _Args
1410 static Args ArgDetails;
1412 /* name of the executable */
1413 #define SZAPPNAME "server"
1415 /* list of service dependencies - "dep1\0dep2\0\0" */
1416 #define SZDEPENDENCIES ""
1418 int statserv_main(int argc, char **argv,
1419 bend_initresult *(*bend_init)(bend_initrequest *r),
1420 void (*bend_close)(void *handle))
1422 struct statserv_options_block *cb = &control_block;
1423 cb->bend_init = bend_init;
1424 cb->bend_close = bend_close;
1426 /* Lets setup the Arg structure */
1427 ArgDetails.argc = argc;
1428 ArgDetails.argv = argv;
1430 /* Now setup the service with the service controller */
1431 SetupService(argc, argv, &ArgDetails, SZAPPNAME,
1432 cb->service_name, /* internal service name */
1433 cb->service_display_name, /* displayed name */
1438 int StartAppService(void *pHandle, int argc, char **argv)
1440 /* Initializes the App */
1444 void RunAppService(void *pHandle)
1446 Args *pArgs = (Args *)pHandle;
1448 /* Starts the app running */
1449 statserv_start(pArgs->argc, pArgs->argv);
1452 void StopAppService(void *pHandle)
1455 statserv_closedown();
1461 int statserv_main(int argc, char **argv,
1462 bend_initresult *(*bend_init)(bend_initrequest *r),
1463 void (*bend_close)(void *handle))
1467 control_block.bend_init = bend_init;
1468 control_block.bend_close = bend_close;
1470 ret = statserv_start (argc, argv);
1471 statserv_closedown ();