GFS: make statserv_main return for one-shot mode.
[yaz-moved-to-github.git] / src / statserv.c
1 /* This file is part of the YAZ toolkit.
2  * Copyright (C) 1995-2011 Index Data
3  * See the file LICENSE for details.
4  */
5
6 /**
7  * \file statserv.c
8  * \brief Implements GFS logic
9  */
10
11 #if HAVE_CONFIG_H
12 #include <config.h>
13 #endif
14
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include <string.h>
18 #include <ctype.h>
19
20 #ifdef WIN32
21 #include <process.h>
22 #include <winsock.h>
23 #include <direct.h>
24 #endif
25
26 #include <yaz/sc.h>
27
28 #if HAVE_SYS_TYPES_H
29 #include <sys/types.h>
30 #endif
31 #if HAVE_SYS_WAIT_H
32 #include <sys/wait.h>
33 #endif
34 #if HAVE_UNISTD_H
35 #include <unistd.h>
36 #endif
37 #if HAVE_PWD_H
38 #include <pwd.h>
39 #endif
40
41 #if YAZ_HAVE_XML2
42 #include <libxml/parser.h>
43 #include <libxml/tree.h>
44 #include <libxml/xinclude.h>
45 #endif
46
47 #if YAZ_POSIX_THREADS
48 #include <pthread.h>
49 #endif
50
51 #include <fcntl.h>
52 #include <signal.h>
53 #include <errno.h>
54
55 #include <yaz/comstack.h>
56 #include <yaz/tcpip.h>
57 #include <yaz/options.h>
58 #include <yaz/errno.h>
59 #ifdef USE_XTIMOSI
60 #include <yaz/xmosi.h>
61 #endif
62 #include <yaz/log.h>
63 #include "eventl.h"
64 #include "session.h"
65 #include <yaz/statserv.h>
66 #include <yaz/daemon.h>
67
68 static IOCHAN pListener = NULL;
69
70 static char gfs_root_dir[FILENAME_MAX+1];
71 static struct gfs_server *gfs_server_list = 0;
72 static struct gfs_listen *gfs_listen_list = 0;
73 static NMEM gfs_nmem = 0;
74
75 static char *me = "statserver"; /* log prefix */
76 static char *programname="statserver"; /* full program name */
77 #ifdef WIN32
78 DWORD current_control_tls;
79 static int init_control_tls = 0;
80 #elif YAZ_POSIX_THREADS
81 static pthread_key_t current_control_tls;
82 static int init_control_tls = 0;
83 #else
84 static statserv_options_block *current_control_block = 0;
85 #endif
86
87 /*
88  * default behavior.
89  */
90 #define STAT_DEFAULT_LOG_LEVEL "server,session,request"
91
92 int check_options(int argc, char **argv);
93 statserv_options_block control_block = {
94     1,                          /* dynamic mode */
95     0,                          /* threaded mode */
96     0,                          /* one shot (single session) */
97     "",                         /* no PDUs */
98     "",                         /* diagnostic output to stderr */
99     "tcp:@:9999",               /* default listener port */
100     PROTO_Z3950,                /* default application protocol */
101     900,                        /* idle timeout (seconds) */
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 */
108     check_ip_tcpd,
109     "",
110     0,                          /* default value for inet deamon */
111     0,                          /* handle (for service, etc) */
112     0,                          /* bend_init handle */
113     0,                          /* bend_close handle */
114 #ifdef WIN32
115     "Z39.50 Server",            /* NT Service Name */
116     "Server",                   /* NT application Name */
117     "",                         /* NT Service Dependencies */
118     "Z39.50 Server",            /* NT Service Display Name */
119 #endif /* WIN32 */
120     0,                          /* SOAP handlers */
121     "",                         /* PID fname */
122     0,                          /* background daemon */
123     "",                         /* SSL certificate filename */
124     "",                         /* XML config filename */
125     1                           /* keepalive */
126 };
127
128 static int max_sessions = 0;
129
130 static int logbits_set = 0;
131 static int log_session = 0; /* one-line logs for session */
132 static int log_sessiondetail = 0; /* more detailed stuff */
133 static int log_server = 0;
134
135 /** get_logbits sets global loglevel bits */
136 static void get_logbits(int force)
137 { /* needs to be called after parsing cmd-line args that can set loglevels!*/
138     if (force || !logbits_set)
139     {
140         logbits_set = 1;
141         log_session = yaz_log_module_level("session");
142         log_sessiondetail = yaz_log_module_level("sessiondetail");
143         log_server = yaz_log_module_level("server");
144     }
145 }
146
147
148 static int add_listener(char *where, int listen_id);
149
150 #if YAZ_HAVE_XML2
151 static xmlDocPtr xml_config_doc = 0;
152 #endif
153
154 #if YAZ_HAVE_XML2
155 static xmlNodePtr xml_config_get_root(void)
156 {
157     xmlNodePtr ptr = 0;
158     if (xml_config_doc)
159     {
160         ptr = xmlDocGetRootElement(xml_config_doc);
161         if (!ptr || ptr->type != XML_ELEMENT_NODE ||
162             strcmp((const char *) ptr->name, "yazgfs"))
163         {
164             yaz_log(YLOG_WARN, "Bad/missing root element for config %s",
165                     control_block.xml_config);
166             return 0;
167         
168         }
169     }
170     return ptr;
171 }
172 #endif
173
174 #if YAZ_HAVE_XML2
175 static char *nmem_dup_xml_content(NMEM n, xmlNodePtr ptr)
176 {
177     unsigned char *cp;
178     xmlNodePtr p;
179     int len = 1;  /* start with 1, because of trailing 0 */
180     unsigned char *str;
181     int first = 1; /* whitespace lead flag .. */
182     /* determine length */
183     for (p = ptr; p; p = p->next)
184     {
185         if (p->type == XML_TEXT_NODE)
186             len += xmlStrlen(p->content);
187     }
188     /* now allocate for the string */
189     str = (unsigned char *) nmem_malloc(n, len);
190     *str = '\0'; /* so we can use strcat */
191     for (p = ptr; p; p = p->next)
192     {
193         if (p->type == XML_TEXT_NODE)
194         {
195             cp = p->content;
196             if (first)
197             {
198                 while(*cp && isspace(*cp))
199                     cp++;
200                 if (*cp)
201                     first = 0;  /* reset if we got non-whitespace out */
202             }
203             strcat((char *)str, (const char *)cp); /* append */
204         }
205     }
206     /* remove trailing whitespace */
207     cp = strlen((const char *)str) + str;
208     while (cp != str && isspace(cp[-1]))
209         cp--;
210     *cp = '\0';
211     /* return resulting string */
212     return (char *) str;
213 }
214 #endif
215
216 #if YAZ_HAVE_XML2
217 static struct gfs_server * gfs_server_new(void)
218 {
219     struct gfs_server *n = (struct gfs_server *)
220         nmem_malloc(gfs_nmem, sizeof(*n));
221     memcpy(&n->cb, &control_block, sizeof(control_block));
222     n->next = 0;
223     n->host = 0;
224     n->listen_ref = 0;
225     n->cql_transform = 0;
226     n->ccl_transform = 0;
227     n->server_node_ptr = 0;
228     n->directory = 0;
229     n->docpath = 0;
230     n->stylesheet = 0;
231     n->retrieval = yaz_retrieval_create();
232     return n;
233 }
234 #endif
235
236 #if YAZ_HAVE_XML2
237 static struct gfs_listen * gfs_listen_new(const char *id, 
238                                           const char *address)
239 {
240     struct gfs_listen *n = (struct gfs_listen *)
241         nmem_malloc(gfs_nmem, sizeof(*n));
242     if (id)
243         n->id = nmem_strdup(gfs_nmem, id);
244     else
245         n->id = 0;
246     n->next = 0;
247     n->address = nmem_strdup(gfs_nmem, address);
248     return n;
249 }
250 #endif
251
252 static void gfs_server_chdir(struct gfs_server *gfs)
253 {
254     if (gfs_root_dir[0])
255     {
256         if (chdir(gfs_root_dir))
257             yaz_log(YLOG_WARN|YLOG_ERRNO, "chdir %s", gfs_root_dir);
258     }
259     if (gfs->directory)
260     {
261         if (chdir(gfs->directory))
262             yaz_log(YLOG_WARN|YLOG_ERRNO, "chdir %s",
263                     gfs->directory);
264     }
265 }
266
267 int control_association(association *assoc, const char *host, int force_open)
268 {
269     char vhost[128], *cp;
270     if (host)
271     {
272         strncpy(vhost, host, 127);
273         vhost[127] = '\0';
274         cp = strchr(vhost, ':');
275         if (cp)
276             *cp = '\0';
277         host = vhost;
278     }
279     assoc->server = 0;
280     if (control_block.xml_config[0])
281     {
282         struct gfs_server *gfs;
283         for (gfs = gfs_server_list; gfs; gfs = gfs->next)
284         {
285             int listen_match = 0;
286             int host_match = 0;
287             if ( !gfs->host || (host && gfs->host && !strcmp(host, gfs->host)))
288                 host_match = 1;
289             if (!gfs->listen_ref ||
290                 gfs->listen_ref == assoc->client_chan->chan_id)
291                 listen_match = 1;
292             if (listen_match && host_match)
293             {
294                 if (force_open ||
295                     (assoc->last_control != &gfs->cb && assoc->backend))
296                 {
297                     statserv_setcontrol(assoc->last_control);
298                     if (assoc->backend && assoc->init)
299                     {
300                         gfs_server_chdir(gfs);
301                         (assoc->last_control->bend_close)(assoc->backend);
302                     }
303                     assoc->backend = 0;
304                     xfree(assoc->init);
305                     assoc->init = 0;
306                 }
307                 assoc->server = gfs;
308                 assoc->last_control = &gfs->cb;
309                 statserv_setcontrol(&gfs->cb);
310                 
311                 gfs_server_chdir(gfs);
312                 break;
313             }
314         }
315         if (!gfs)
316         {
317             statserv_setcontrol(0);
318             assoc->last_control = 0;
319             return 0;
320         }
321     }
322     else
323     {
324         statserv_setcontrol(&control_block);
325         assoc->last_control = &control_block;
326     }
327     yaz_log(YLOG_DEBUG, "server select: config=%s", 
328             assoc->last_control->configname);
329
330     assoc->maximumRecordSize = assoc->last_control->maxrecordsize;
331     assoc->preferredMessageSize = assoc->last_control->maxrecordsize;
332     cs_set_max_recv_bytes(assoc->client_link, assoc->maximumRecordSize);
333     return 1;
334 }
335
336 #if YAZ_HAVE_XML2
337 static void xml_config_read(void)
338 {
339     struct gfs_server **gfsp = &gfs_server_list;
340     struct gfs_listen **gfslp = &gfs_listen_list;
341     xmlNodePtr ptr = xml_config_get_root();
342
343     if (!ptr)
344         return;
345     for (ptr = ptr->children; ptr; ptr = ptr->next)
346     {
347         struct _xmlAttr *attr;
348         if (ptr->type != XML_ELEMENT_NODE)
349             continue;
350         attr = ptr->properties;
351         if (!strcmp((const char *) ptr->name, "listen"))
352         {
353             /*
354               <listen id="listenerid">tcp:@:9999</listen>
355             */
356             const char *id = 0;
357             const char *address =
358                 nmem_dup_xml_content(gfs_nmem, ptr->children);
359             for ( ; attr; attr = attr->next)
360                 if (!xmlStrcmp(attr->name, BAD_CAST "id")
361                     && attr->children && attr->children->type == XML_TEXT_NODE)
362                     id = nmem_dup_xml_content(gfs_nmem, attr->children);
363             if (address)
364             {
365                 *gfslp = gfs_listen_new(id, address);
366                 gfslp = &(*gfslp)->next;
367                 *gfslp = 0; /* make listener list consistent for search */
368             }
369         }
370         else if (!strcmp((const char *) ptr->name, "server"))
371         {
372             xmlNodePtr ptr_server = ptr;
373             xmlNodePtr ptr;
374             const char *listenref = 0;
375             const char *id = 0;
376             struct gfs_server *gfs;
377
378             for ( ; attr; attr = attr->next)
379                 if (!xmlStrcmp(attr->name, BAD_CAST "listenref") 
380                     && attr->children && attr->children->type == XML_TEXT_NODE)
381                     listenref = nmem_dup_xml_content(gfs_nmem, attr->children);
382                 else if (!xmlStrcmp(attr->name, BAD_CAST "id")
383                          && attr->children
384                          && attr->children->type == XML_TEXT_NODE)
385                     id = nmem_dup_xml_content(gfs_nmem, attr->children);
386                 else
387                     yaz_log(YLOG_WARN, "Unknown attribute '%s' for server",
388                             attr->name);
389             gfs = *gfsp = gfs_server_new();
390             gfs->server_node_ptr = ptr_server;
391             if (listenref)
392             {
393                 int id_no;
394                 struct gfs_listen *gl = gfs_listen_list;
395                 for (id_no = 1; gl; gl = gl->next, id_no++)
396                     if (gl->id && !strcmp(gl->id, listenref))
397                     {
398                         gfs->listen_ref = id_no;
399                         break;
400                     }
401                 if (!gl)
402                     yaz_log(YLOG_WARN, "Non-existent listenref '%s' in server "
403                             "config element", listenref);
404             }
405             for (ptr = ptr_server->children; ptr; ptr = ptr->next)
406             {
407                 if (ptr->type != XML_ELEMENT_NODE)
408                     continue;
409                 if (!strcmp((const char *) ptr->name, "host"))
410                 {
411                     gfs->host = nmem_dup_xml_content(gfs_nmem,
412                                                      ptr->children);
413                 }
414                 else if (!strcmp((const char *) ptr->name, "config"))
415                 {
416                     strcpy(gfs->cb.configname,
417                            nmem_dup_xml_content(gfs_nmem, ptr->children));
418                 }
419                 else if (!strcmp((const char *) ptr->name, "cql2rpn"))
420                 {
421                     gfs->cql_transform = cql_transform_open_fname(
422                         nmem_dup_xml_content(gfs_nmem, ptr->children)
423                         );
424                 }
425                 else if (!strcmp((const char *) ptr->name, "ccl2rpn"))
426                 {
427                     char *name;
428                     FILE *f;
429
430                     name = nmem_dup_xml_content(gfs_nmem, ptr->children);
431                     if ((f = fopen(name, "r")) == 0) {
432                         yaz_log(YLOG_FATAL, "can't open CCL file '%s'", name);
433                         exit(1);
434                     }
435                     gfs->ccl_transform = ccl_qual_mk();
436                     ccl_qual_file (gfs->ccl_transform, f);
437                     fclose(f);
438                 }
439                 else if (!strcmp((const char *) ptr->name, "directory"))
440                 {
441                     gfs->directory = 
442                         nmem_dup_xml_content(gfs_nmem, ptr->children);
443                 }
444                 else if (!strcmp((const char *) ptr->name, "docpath"))
445                 {
446                     gfs->docpath = 
447                         nmem_dup_xml_content(gfs_nmem, ptr->children);
448                 }
449                 else if (!strcmp((const char *) ptr->name, "maximumrecordsize"))
450                 {
451                     gfs->cb.maxrecordsize = atoi(
452                         nmem_dup_xml_content(gfs_nmem, ptr->children));
453                 }
454                 else if (!strcmp((const char *) ptr->name, "stylesheet"))
455                 {
456                     char *s = nmem_dup_xml_content(gfs_nmem, ptr->children);
457                     gfs->stylesheet = (char *)
458                         nmem_malloc(gfs_nmem, strlen(s) + 2);
459                     sprintf(gfs->stylesheet, "/%s", s);
460                 }
461                 else if (!strcmp((const char *) ptr->name, "explain"))
462                 {
463                     ; /* being processed separately */
464                 }
465                 else if (!strcmp((const char *) ptr->name, "retrievalinfo"))
466                 {
467                     if (yaz_retrieval_configure(gfs->retrieval, ptr))
468                     {       
469                         yaz_log(YLOG_FATAL, "%s in config %s",
470                                 yaz_retrieval_get_error(gfs->retrieval),
471                                 control_block.xml_config);
472                         exit(1);
473                     }
474                 }
475                 else
476                 {
477                     yaz_log(YLOG_FATAL, "Unknown element '%s' in config %s",
478                             ptr->name, control_block.xml_config);
479                     exit(1);
480                 }
481             }
482             gfsp = &(*gfsp)->next;
483         }
484     }
485     *gfsp = 0;
486 }
487 #endif
488
489 static void xml_config_open(void)
490 {
491     if (!getcwd(gfs_root_dir, FILENAME_MAX))
492     {
493         yaz_log(YLOG_WARN|YLOG_ERRNO, "getcwd failed");
494         gfs_root_dir[0] = '\0';
495     }
496 #ifdef WIN32
497     init_control_tls = 1;
498     current_control_tls = TlsAlloc();
499 #elif YAZ_POSIX_THREADS
500     init_control_tls = 1;
501     pthread_key_create(&current_control_tls, 0);
502 #endif
503     
504     gfs_nmem = nmem_create();
505 #if YAZ_HAVE_XML2
506     if (control_block.xml_config[0] == '\0')
507         return;
508
509     if (!xml_config_doc)
510     {
511         xml_config_doc = xmlParseFile(control_block.xml_config);
512         if (!xml_config_doc)
513         {
514             yaz_log(YLOG_FATAL, "Could not parse %s", control_block.xml_config);
515             exit(1);
516         }
517         else
518         {
519             int noSubstitutions = xmlXIncludeProcess(xml_config_doc);
520             if (noSubstitutions == -1)
521             {
522                 yaz_log(YLOG_WARN, "XInclude processing failed for config %s",
523                         control_block.xml_config);
524                 exit(1);
525             }
526         }
527     }
528     xml_config_read();
529 #endif
530 }
531
532 static void xml_config_close(void)
533 {
534 #if YAZ_HAVE_XML2
535     if (xml_config_doc)
536     {
537         xmlFreeDoc(xml_config_doc);
538         xml_config_doc = 0;
539     }
540 #endif
541     gfs_server_list = 0;
542     nmem_destroy(gfs_nmem);
543 #ifdef WIN32
544     if (init_control_tls)
545         TlsFree(current_control_tls);
546 #elif YAZ_POSIX_THREADS
547     if (init_control_tls)
548         pthread_key_delete(current_control_tls);
549 #endif
550 }
551
552 static void xml_config_add_listeners(void)
553 {
554     struct gfs_listen *gfs = gfs_listen_list;
555     int id_no;
556
557     for (id_no = 1; gfs; gfs = gfs->next, id_no++)
558     {
559         if (gfs->address)
560             add_listener(gfs->address, id_no);
561     }
562 }
563
564 static void xml_config_bend_start(void)
565 {
566     if (control_block.xml_config[0])
567     {
568         struct gfs_server *gfs = gfs_server_list;
569         for (; gfs; gfs = gfs->next)
570         {
571             yaz_log(YLOG_DEBUG, "xml_config_bend_start config=%s",
572                     gfs->cb.configname);
573             statserv_setcontrol(&gfs->cb);
574             if (control_block.bend_start)
575             {
576                 gfs_server_chdir(gfs);
577                 (control_block.bend_start)(&gfs->cb);
578             }
579         }
580     }
581     else
582     {
583         yaz_log(YLOG_DEBUG, "xml_config_bend_start default config");
584         statserv_setcontrol(&control_block);
585         if (control_block.bend_start)
586             (*control_block.bend_start)(&control_block);
587     }
588 }
589
590 static void xml_config_bend_stop(void)
591 {
592     if (control_block.xml_config[0])
593     {
594         struct gfs_server *gfs = gfs_server_list;
595         for (; gfs; gfs = gfs->next)
596         {
597             yaz_log(YLOG_DEBUG, "xml_config_bend_stop config=%s",
598                     gfs->cb.configname);
599             statserv_setcontrol(&gfs->cb);
600             if (control_block.bend_stop)
601                 (control_block.bend_stop)(&gfs->cb);
602         }
603     }
604     else
605     {
606         yaz_log(YLOG_DEBUG, "xml_config_bend_stop default config");
607         statserv_setcontrol(&control_block);
608         if (control_block.bend_stop)
609             (*control_block.bend_stop)(&control_block);
610     }
611 }
612
613 static void remove_listeners(void);
614
615 /*
616  * handle incoming connect requests.
617  * The dynamic mode is a bit tricky mostly because we want to avoid
618  * doing all of the listening and accepting in the parent - it's
619  * safer that way.
620  */
621 #ifdef WIN32
622
623 typedef struct _ThreadList ThreadList;
624
625 struct _ThreadList
626 {
627     HANDLE hThread;
628     IOCHAN pIOChannel;
629     ThreadList *pNext;
630 };
631
632 static ThreadList *pFirstThread;
633 static CRITICAL_SECTION Thread_CritSect;
634 static BOOL bInitialized = FALSE;
635
636 static void ThreadList_Initialize()
637 {
638     /* Initialize the critical Sections */
639     InitializeCriticalSection(&Thread_CritSect);
640
641     /* Set the first thraed */
642     pFirstThread = NULL;
643
644     /* we have been initialized */
645     bInitialized = TRUE;
646 }
647
648 static void statserv_add(HANDLE hThread, IOCHAN pIOChannel)
649 {
650     /* Only one thread can go through this section at a time */
651     EnterCriticalSection(&Thread_CritSect);
652
653     {
654         /* Lets create our new object */
655         ThreadList *pNewThread = (ThreadList *)malloc(sizeof(ThreadList));
656         pNewThread->hThread = hThread;
657         pNewThread->pIOChannel = pIOChannel;
658         pNewThread->pNext = pFirstThread;
659         pFirstThread = pNewThread;
660
661         /* Lets let somebody else create a new object now */
662         LeaveCriticalSection(&Thread_CritSect);
663     }
664 }
665
666 void statserv_remove(IOCHAN pIOChannel)
667 {
668     /* Only one thread can go through this section at a time */
669     EnterCriticalSection(&Thread_CritSect);
670
671     {
672         ThreadList *pCurrentThread = pFirstThread;
673         ThreadList *pNextThread;
674         ThreadList *pPrevThread =NULL;
675
676         /* Step through all the threads */
677         for (; pCurrentThread != NULL; pCurrentThread = pNextThread)
678         {
679             /* We only need to compare on the IO Channel */
680             if (pCurrentThread->pIOChannel == pIOChannel)
681             {
682                 /* We have found the thread we want to delete */
683                 /* First of all reset the next pointers */
684                 if (pPrevThread == NULL)
685                     pFirstThread = pCurrentThread->pNext;
686                 else
687                     pPrevThread->pNext = pCurrentThread->pNext;
688
689                 /* All we need todo now is delete the memory */
690                 free(pCurrentThread);
691
692                 /* No need to look at any more threads */
693                 pNextThread = NULL;
694             }
695             else
696             {
697                 /* We need to look at another thread */
698                 pNextThread = pCurrentThread->pNext;
699                 pPrevThread = pCurrentThread;
700             }
701         }
702
703         /* Lets let somebody else remove an object now */
704         LeaveCriticalSection(&Thread_CritSect);
705     }
706 }
707
708 /* WIN32 statserv_closedown */
709 static void statserv_closedown()
710 {
711     /* Shouldn't do anything if we are not initialized */
712     if (bInitialized)
713     {
714         int iHandles = 0;
715         HANDLE *pThreadHandles = NULL;
716
717         /* We need to stop threads adding and removing while we */
718         /* start the closedown process */
719         EnterCriticalSection(&Thread_CritSect);
720
721         {
722             /* We have exclusive access to the thread stuff now */
723             /* Y didn't i use a semaphore - Oh well never mind */
724             ThreadList *pCurrentThread = pFirstThread;
725
726             /* Before we do anything else, we need to shutdown the listener */
727             if (pListener != NULL)
728                 iochan_destroy(pListener);
729
730             for (; pCurrentThread != NULL; pCurrentThread = pCurrentThread->pNext)
731             {
732                 /* Just destroy the IOCHAN, that should do the trick */
733                 iochan_destroy(pCurrentThread->pIOChannel);
734                 closesocket(pCurrentThread->pIOChannel->fd);
735
736                 /* Keep a running count of our handles */
737                 iHandles++;
738             }
739
740             if (iHandles > 0)
741             {
742                 HANDLE *pCurrentHandle ;
743
744                 /* Allocate the thread handle array */
745                 pThreadHandles = (HANDLE *)malloc(sizeof(HANDLE) * iHandles);
746                 pCurrentHandle = pThreadHandles; 
747
748                 for (pCurrentThread = pFirstThread;
749                      pCurrentThread != NULL;
750                      pCurrentThread = pCurrentThread->pNext, pCurrentHandle++)
751                 {
752                     /* Just the handle */
753                     *pCurrentHandle = pCurrentThread->hThread;
754                 }
755             }
756
757             /* We can now leave the critical section */
758             LeaveCriticalSection(&Thread_CritSect);
759         }
760
761         /* Now we can really do something */
762         if (iHandles > 0)
763         {
764             yaz_log(log_server, "waiting for %d to die", iHandles);
765             /* This will now wait, until all the threads close */
766             WaitForMultipleObjects(iHandles, pThreadHandles, TRUE, INFINITE);
767
768             /* Free the memory we allocated for the handle array */
769             free(pThreadHandles);
770         }
771
772         xml_config_bend_stop();
773         /* No longer require the critical section, since all threads are dead */
774         DeleteCriticalSection(&Thread_CritSect);
775     }
776     xml_config_close();
777 }
778
779 void __cdecl event_loop_thread(IOCHAN iochan)
780 {
781     iochan_event_loop(&iochan);
782 }
783
784 /* WIN32 listener */
785 static void listener(IOCHAN h, int event)   
786 {
787     COMSTACK line = (COMSTACK) iochan_getdata(h);
788     IOCHAN parent_chan = line->user;
789     association *newas;
790     int res;
791     HANDLE newHandle;
792
793     if (event == EVENT_INPUT)
794     {
795         COMSTACK new_line;
796         IOCHAN new_chan;
797
798         if ((res = cs_listen(line, 0, 0)) < 0)
799         {
800             yaz_log(YLOG_FATAL|YLOG_ERRNO, "cs_listen failed");
801             return;
802         }
803         else if (res == 1)
804             return; /* incomplete */
805         yaz_log(YLOG_DEBUG, "listen ok");
806         new_line = cs_accept(line);
807         if (!new_line)
808         {
809             yaz_log(YLOG_FATAL, "Accept failed.");
810             return;
811         }
812         yaz_log(YLOG_DEBUG, "Accept ok");
813
814         if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session,
815                                        EVENT_INPUT, parent_chan->chan_id)))
816         {
817             yaz_log(YLOG_FATAL, "Failed to create iochan");
818             iochan_destroy(h);
819             return;
820         }
821
822         yaz_log(YLOG_DEBUG, "Creating association");
823         if (!(newas = create_association(new_chan, new_line,
824                                          control_block.apdufile)))
825         {
826             yaz_log(YLOG_FATAL, "Failed to create new assoc.");
827             iochan_destroy(h);
828             return;
829         }
830         newas->cs_get_mask = EVENT_INPUT;
831         newas->cs_put_mask = 0;
832         newas->cs_accept_mask = 0;
833
834         yaz_log(YLOG_DEBUG, "Setting timeout %d", control_block.idle_timeout);
835         iochan_setdata(new_chan, newas);
836         iochan_settimeout(new_chan, 60);
837
838         /* Now what we need todo is create a new thread with this iochan as
839            the parameter */
840         newHandle = (HANDLE) _beginthread(event_loop_thread, 0, new_chan);
841         if (newHandle == (HANDLE) -1)
842         {
843             
844             yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create new thread.");
845             iochan_destroy(h);
846             return;
847         }
848         /* We successfully created the thread, so add it to the list */
849         statserv_add(newHandle, new_chan);
850
851         yaz_log(YLOG_DEBUG, "Created new thread, id = %ld iochan %p",(long) newHandle, new_chan);
852         iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
853     }
854     else
855     {
856         yaz_log(YLOG_FATAL, "Bad event on listener.");
857         iochan_destroy(h);
858         return;
859     }
860 }
861
862 #else /* ! WIN32 */
863
864 /* To save having an #ifdef in event_loop we need to
865    define this empty function 
866 */
867 void statserv_remove(IOCHAN pIOChannel)
868 {
869 }
870
871 static void statserv_closedown(void)
872 {
873     IOCHAN p;
874
875     xml_config_bend_stop();
876     for (p = pListener; p; p = p->next)
877     {
878         iochan_destroy(p);
879     }
880     xml_config_close();
881 }
882
883 static void *new_session(void *vp);
884 static int no_sessions = 0;
885
886 /* UNIX listener */
887 static void listener(IOCHAN h, int event)
888 {
889     COMSTACK line = (COMSTACK) iochan_getdata(h);
890     int res;
891
892     if (event == EVENT_INPUT)
893     {
894         COMSTACK new_line;
895         if ((res = cs_listen_check(line, 0, 0, control_block.check_ip,
896                                    control_block.daemon_name)) < 0)
897         {
898             yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_listen failed");
899             return;
900         }
901         else if (res == 1)
902         {
903             yaz_log(YLOG_WARN, "cs_listen incomplete");
904             return;
905         }
906         new_line = cs_accept(line);
907         if (!new_line)
908         {
909             yaz_log(YLOG_FATAL, "Accept failed.");
910             iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
911             return;
912         }
913
914         if (control_block.one_shot)
915             remove_listeners();
916
917         yaz_log(log_sessiondetail, "Connect from %s", cs_addrstr(new_line));
918
919         no_sessions++;
920         if (control_block.dynamic)
921         {
922             if ((res = fork()) < 0)
923             {
924                 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fork");
925                 iochan_destroy(h);
926                 return;
927             }
928             else if (res == 0) /* child */
929             {
930                 char nbuf[100];
931                 IOCHAN pp;
932
933                 for (pp = pListener; pp; pp = iochan_getnext(pp))
934                 {
935                     COMSTACK l = (COMSTACK)iochan_getdata(pp);
936                     cs_close(l);
937                     iochan_destroy(pp);
938                 }
939                 sprintf(nbuf, "%s(%d)", me, no_sessions);
940                 yaz_log_init_prefix(nbuf);
941                 /* ensure that bend_stop is not called when each child exits -
942                    only for the main process ..  */
943                 control_block.bend_stop = 0;
944             }
945             else /* parent */
946             {
947                 cs_close(new_line);
948                 return;
949             }
950         }
951
952         if (control_block.threads)
953         {
954 #if YAZ_POSIX_THREADS
955             pthread_t child_thread;
956             pthread_create(&child_thread, 0, new_session, new_line);
957             pthread_detach(child_thread);
958 #else
959             new_session(new_line);
960 #endif
961         }
962         else
963             new_session(new_line);
964     }
965     else if (event == EVENT_TIMEOUT)
966     {
967         yaz_log(log_server, "Shutting down listener.");
968         iochan_destroy(h);
969     }
970     else
971     {
972         yaz_log(YLOG_FATAL, "Bad event on listener.");
973         iochan_destroy(h);
974     }
975 }
976
977 static void *new_session(void *vp)
978 {
979     const char *a;
980     association *newas;
981     IOCHAN new_chan;
982     COMSTACK new_line = (COMSTACK) vp;
983     IOCHAN parent_chan = (IOCHAN) new_line->user;
984
985     unsigned cs_get_mask, cs_accept_mask, mask =  
986         ((new_line->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
987         ((new_line->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
988
989     if (mask)
990     {
991         cs_accept_mask = mask;  /* accept didn't complete */
992         cs_get_mask = 0;
993     }
994     else
995     {
996         cs_accept_mask = 0;     /* accept completed.  */
997         cs_get_mask = mask = EVENT_INPUT;
998     }
999
1000     if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session, mask,
1001                                    parent_chan->chan_id)))
1002     {
1003         yaz_log(YLOG_FATAL, "Failed to create iochan");
1004         return 0;
1005     }
1006     if (!(newas = create_association(new_chan, new_line,
1007                                      control_block.apdufile)))
1008     {
1009         yaz_log(YLOG_FATAL, "Failed to create new assoc.");
1010         return 0;
1011     }
1012     newas->cs_accept_mask = cs_accept_mask;
1013     newas->cs_get_mask = cs_get_mask;
1014
1015     iochan_setdata(new_chan, newas);
1016     iochan_settimeout(new_chan, 60);
1017 #if 1
1018     a = cs_addrstr(new_line);
1019 #else
1020     a = 0;
1021 #endif
1022     yaz_log_xml_errors(0, YLOG_WARN);
1023     yaz_log(log_session, "Session - OK %d %s %ld",
1024             no_sessions, a ? a : "[Unknown]", (long) getpid());
1025     if (max_sessions && no_sessions >= max_sessions)
1026         control_block.one_shot = 1;
1027     if (control_block.threads)
1028     {
1029         iochan_event_loop(&new_chan);
1030     }
1031     else
1032     {
1033         new_chan->next = pListener;
1034         pListener = new_chan;
1035     }
1036     return 0;
1037 }
1038
1039 /* UNIX */
1040 #endif
1041
1042 static void inetd_connection(int what)
1043 {
1044     COMSTACK line;
1045     IOCHAN chan;
1046     association *assoc;
1047     const char *addr;
1048
1049     if ((line = cs_createbysocket(0, tcpip_type, 0, what)))
1050     {
1051         if ((chan = iochan_create(cs_fileno(line), ir_session, EVENT_INPUT,
1052                                   0)))
1053         {
1054             if ((assoc = create_association(chan, line,
1055                                             control_block.apdufile)))
1056             {
1057                 iochan_setdata(chan, assoc);
1058                 iochan_settimeout(chan, 60);
1059                 addr = cs_addrstr(line);
1060                 yaz_log(log_sessiondetail, "Inetd association from %s",
1061                         addr ? addr : "[UNKNOWN]");
1062                 assoc->cs_get_mask = EVENT_INPUT;
1063             }
1064             else
1065             {
1066                 yaz_log(YLOG_FATAL, "Failed to create association structure");
1067             }
1068             chan->next = pListener;
1069             pListener = chan;
1070         }
1071         else
1072         {
1073             yaz_log(YLOG_FATAL, "Failed to create iochan");
1074         }
1075     }
1076     else
1077     {
1078         yaz_log(YLOG_ERRNO|YLOG_FATAL, "Failed to create comstack on socket 0");
1079     }
1080 }
1081
1082 /*
1083  * Set up a listening endpoint, and give it to the event-handler.
1084  */
1085 static int add_listener(char *where, int listen_id)
1086 {
1087     COMSTACK l;
1088     void *ap;
1089     IOCHAN lst = NULL;
1090     const char *mode;
1091
1092     if (control_block.dynamic)
1093         mode = "dynamic";
1094     else if (control_block.threads)
1095         mode = "threaded";
1096     else
1097         mode = "static";
1098
1099     yaz_log(log_server, "Adding %s listener on %s id=%d", mode, where,
1100             listen_id);
1101
1102     l = cs_create_host(where, 2, &ap);
1103     if (!l)
1104     {
1105         yaz_log(YLOG_FATAL, "Failed to listen on %s", where);
1106         return -1;
1107     }
1108     if (*control_block.cert_fname)
1109         cs_set_ssl_certificate_file(l, control_block.cert_fname);
1110
1111     if (cs_bind(l, ap, CS_SERVER) < 0)
1112     {
1113         if (cs_errno(l) == CSYSERR)
1114             yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to bind to %s", where);
1115         else
1116             yaz_log(YLOG_FATAL, "Failed to bind to %s: %s", where,
1117                     cs_strerror(l));
1118         cs_close(l);
1119         return -1;
1120     }
1121     if (!(lst = iochan_create(cs_fileno(l), listener, EVENT_INPUT |
1122                               EVENT_EXCEPT, listen_id)))
1123     {
1124         yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create IOCHAN-type");
1125         cs_close(l);
1126         return -1;
1127     }
1128     iochan_setdata(lst, l); /* user-defined data for listener is COMSTACK */
1129     l->user = lst;  /* user-defined data for COMSTACK is listener chan */
1130
1131     /* Add listener to chain */
1132     lst->next = pListener;
1133     pListener = lst;
1134     return 0; /* OK */
1135 }
1136
1137 static void remove_listeners(void)
1138 {
1139     IOCHAN l = pListener;
1140     for (; l; l = l->next)
1141         iochan_destroy(l);
1142 }
1143
1144 #ifndef WIN32
1145 /* UNIX only (for windows we don't need to catch the signals) */
1146 static void catchchld(int num)
1147 {
1148     while (waitpid(-1, 0, WNOHANG) > 0)
1149         ;
1150     signal(SIGCHLD, catchchld);
1151 }
1152 #endif
1153
1154 statserv_options_block *statserv_getcontrol(void)
1155 {
1156 #ifdef WIN32
1157     if (init_control_tls)
1158         return (statserv_options_block *) TlsGetValue(current_control_tls);
1159     else
1160         return &control_block;
1161 #elif YAZ_POSIX_THREADS
1162     if (init_control_tls)
1163         return (statserv_options_block *)
1164             pthread_getspecific(current_control_tls);
1165     else
1166         return &control_block;
1167 #else
1168     if (current_control_block)
1169         return current_control_block;
1170     return &control_block;
1171 #endif
1172 }
1173
1174 void statserv_setcontrol(statserv_options_block *block)
1175 {
1176     if (gfs_root_dir[0])
1177     {
1178         if (chdir(gfs_root_dir))
1179             yaz_log(YLOG_WARN|YLOG_ERRNO, "chdir %s", gfs_root_dir);
1180     }
1181 #ifdef WIN32
1182     if (init_control_tls)
1183         TlsSetValue(current_control_tls, block);
1184 #elif YAZ_POSIX_THREADS
1185     if (init_control_tls)
1186         pthread_setspecific(current_control_tls, block);
1187 #else
1188     current_control_block = block;
1189 #endif
1190 }
1191
1192 static void statserv_reset(void)
1193 {
1194 }
1195
1196 static void daemon_handler(void *data)
1197 {
1198     IOCHAN *pListener = data;
1199     iochan_event_loop(pListener);
1200 }
1201
1202 static int statserv_sc_main(yaz_sc_t s, int argc, char **argv)
1203 {
1204     char sep;
1205 #ifdef WIN32
1206     /* We need to initialize the thread list */
1207     ThreadList_Initialize();
1208 /* WIN32 */
1209 #endif
1210
1211
1212 #ifdef WIN32
1213     sep = '\\';
1214 #else
1215     sep = '/';
1216 #endif
1217     if ((me = strrchr(argv[0], sep)))
1218         me++; /* get the basename */
1219     else
1220         me = argv[0];
1221     programname = argv[0];
1222
1223     if (control_block.options_func(argc, argv))
1224         return 1;
1225
1226     xml_config_open();
1227     
1228     xml_config_bend_start();
1229
1230     if (control_block.inetd)
1231     {
1232 #ifdef WIN32
1233         ; /* no inetd on Windows */
1234 #else
1235         inetd_connection(control_block.default_proto);
1236 #endif
1237     }
1238     else
1239     {
1240         xml_config_add_listeners();
1241
1242         if (!pListener && *control_block.default_listen)
1243             add_listener(control_block.default_listen, 0);
1244
1245 #ifndef WIN32
1246         if (control_block.dynamic)
1247             signal(SIGCHLD, catchchld);
1248 #endif
1249     }
1250     if (pListener == NULL)
1251         return 1;
1252     if (s)
1253         yaz_sc_running(s);
1254     yaz_log(YLOG_DEBUG, "Entering event loop.");
1255
1256     yaz_daemon(programname,
1257                (control_block.background ? YAZ_DAEMON_FORK : 0),
1258                daemon_handler, &pListener,
1259                *control_block.pid_fname ? control_block.pid_fname : 0,
1260                *control_block.setuid ? control_block.setuid : 0);
1261     return 0;
1262 }
1263
1264 static void option_copy(char *dst, const char *src)
1265 {
1266     strncpy(dst, src ? src : "", 127);
1267     dst[127] = '\0';
1268 }
1269
1270 int check_options(int argc, char **argv)
1271 {
1272     int ret = 0, r;
1273     char *arg;
1274
1275     yaz_log_init_level(yaz_log_mask_str(STAT_DEFAULT_LOG_LEVEL)); 
1276
1277     get_logbits(1); 
1278
1279     while ((ret = options("1a:iszSTl:v:u:c:w:t:k:Kd:A:p:DC:f:m:r:",
1280                           argv, argc, &arg)) != -2)
1281     {
1282         switch (ret)
1283         {
1284         case 0:
1285             if (add_listener(arg, 0))
1286                 return 1;  /* failed to create listener */
1287             break;
1288         case '1':        
1289             control_block.one_shot = 1;
1290             control_block.dynamic = 0;
1291             break;
1292         case 'z':
1293             control_block.default_proto = PROTO_Z3950;
1294             break;
1295         case 's':
1296             fprintf(stderr, "%s: SR protocol no longer supported\n", me);
1297             exit(1);
1298             break;
1299         case 'S':
1300             control_block.dynamic = 0;
1301             break;
1302         case 'T':
1303 #if YAZ_POSIX_THREADS
1304             control_block.dynamic = 0;
1305             control_block.threads = 1;
1306 #else
1307             fprintf(stderr, "%s: Threaded mode not available.\n", me);
1308             return 1;
1309 #endif
1310             break;
1311         case 'l':
1312             option_copy(control_block.logfile, arg);
1313             yaz_log_init_file(control_block.logfile);
1314             break;
1315         case 'm':
1316             if (!arg) {
1317                 fprintf(stderr, "%s: Specify time format for log file.\n", me);
1318                 return(1);
1319             }
1320             yaz_log_time_format(arg);
1321             break;
1322         case 'v':
1323             yaz_log_init_level(yaz_log_mask_str(arg));
1324             get_logbits(1); 
1325             break;
1326         case 'a':
1327             option_copy(control_block.apdufile, arg);
1328             break;
1329         case 'u':
1330             option_copy(control_block.setuid, arg);
1331             break;
1332         case 'c':
1333             option_copy(control_block.configname, arg);
1334             break;
1335         case 'C':
1336             option_copy(control_block.cert_fname, arg);
1337             break;
1338         case 'd':
1339             option_copy(control_block.daemon_name, arg);
1340             break;
1341         case 't':
1342             if (!arg || !(r = atoi(arg)))
1343             {
1344                 fprintf(stderr, "%s: Specify positive timeout for -t.\n", me);
1345                 return(1);
1346             }
1347             control_block.idle_timeout = strchr(arg, 's') ? r : 60 * r;
1348             break;
1349         case  'k':
1350             if (!arg || !(r = atoi(arg)))
1351             {
1352                 fprintf(stderr, "%s: Specify positive size for -k.\n", me);
1353                 return(1);
1354             }
1355             control_block.maxrecordsize = r * 1024;
1356             break;
1357         case 'K':
1358             control_block.keepalive = 0;
1359             break;
1360         case 'i':
1361             control_block.inetd = 1;
1362             break;
1363         case 'w':
1364             if (chdir(arg))
1365             {
1366                 perror(arg);            
1367                 return 1;
1368             }
1369             break;
1370         case 'A':
1371             max_sessions = atoi(arg);
1372             break;
1373         case 'p':
1374             option_copy(control_block.pid_fname, arg);
1375             break;
1376         case 'f':
1377 #if YAZ_HAVE_XML2
1378             option_copy(control_block.xml_config, arg);
1379 #else
1380             fprintf(stderr, "%s: Option -f unsupported since YAZ is compiled without Libxml2 support\n", me);
1381             exit(1);
1382 #endif
1383             break;
1384         case 'D':
1385             control_block.background = 1;
1386             break;
1387         case 'r':
1388             if (!arg || !(r = atoi(arg)))
1389             {
1390                 fprintf(stderr, "%s: Specify positive size for -r.\n", me);
1391                 return(1);
1392             }
1393             yaz_log_init_max_size(r * 1024);
1394             break;
1395         default:
1396             fprintf(stderr, "Usage: %s [ -a <pdufile> -v <loglevel>"
1397                     " -l <logfile> -u <user> -c <config> -t <minutes>"
1398                     " -k <kilobytes> -d <daemon> -p <pidfile> -C certfile"
1399                     " -ziDST1 -m <time-format> -w <directory> <listener-addr>... ]\n", me);
1400             return 1;
1401         }
1402     }
1403     return 0;
1404 }
1405
1406 void statserv_sc_stop(yaz_sc_t s)
1407 {
1408     statserv_closedown();
1409     statserv_reset();
1410 }
1411
1412 int statserv_main(int argc, char **argv,
1413                   bend_initresult *(*bend_init)(bend_initrequest *r),
1414                   void (*bend_close)(void *handle))
1415 {
1416     int ret;
1417     struct statserv_options_block *cb = &control_block;
1418
1419     /* control block does not have service_name member on Unix */
1420     yaz_sc_t s = yaz_sc_create(
1421 #ifdef WIN32
1422         cb->service_name, cb->service_display_name
1423 #else
1424         0, 0
1425 #endif
1426         );
1427
1428     cb->bend_init = bend_init;
1429     cb->bend_close = bend_close;
1430
1431     ret = yaz_sc_program(s, argc, argv, statserv_sc_main, statserv_sc_stop);
1432     yaz_sc_destroy(&s);
1433     return ret;
1434 }
1435
1436 /*
1437  * Local variables:
1438  * c-basic-offset: 4
1439  * c-file-style: "Stroustrup"
1440  * indent-tabs-mode: nil
1441  * End:
1442  * vim: shiftwidth=4 tabstop=8 expandtab
1443  */
1444