Add new function nmem_strsplitx.
[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
19 #ifdef WIN32
20 #include <process.h>
21 #include <winsock.h>
22 #include <direct.h>
23 #endif
24
25 #include <yaz/sc.h>
26
27 #if HAVE_SYS_TYPES_H
28 #include <sys/types.h>
29 #endif
30 #if HAVE_SYS_WAIT_H
31 #include <sys/wait.h>
32 #endif
33 #if HAVE_UNISTD_H
34 #include <unistd.h>
35 #endif
36 #if HAVE_PWD_H
37 #include <pwd.h>
38 #endif
39
40 #if YAZ_HAVE_XML2
41 #include <libxml/parser.h>
42 #include <libxml/tree.h>
43 #include <libxml/xinclude.h>
44 #endif
45
46 #if YAZ_POSIX_THREADS
47 #include <pthread.h>
48 #endif
49
50 #include <fcntl.h>
51 #include <signal.h>
52 #include <errno.h>
53
54 #include <yaz/comstack.h>
55 #include <yaz/tcpip.h>
56 #include <yaz/options.h>
57 #include <yaz/errno.h>
58 #ifdef USE_XTIMOSI
59 #include <yaz/xmosi.h>
60 #endif
61 #include <yaz/log.h>
62 #include "eventl.h"
63 #include "session.h"
64 #include <yaz/statserv.h>
65 #include <yaz/daemon.h>
66 #include <yaz/yaz-iconv.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 && yaz_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 && yaz_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                     char *name = nmem_dup_xml_content(gfs_nmem, ptr->children);
422                     gfs->cql_transform = cql_transform_open_fname(name);
423                     if (!gfs->cql_transform)
424                     {
425                         yaz_log(YLOG_FATAL|YLOG_ERRNO,
426                                 "open CQL transform file '%s'", name);
427                         exit(1);
428                     }
429                 }
430                 else if (!strcmp((const char *) ptr->name, "ccl2rpn"))
431                 {
432                     char *name;
433                     FILE *f;
434
435                     name = nmem_dup_xml_content(gfs_nmem, ptr->children);
436                     if ((f = fopen(name, "r")) == 0) {
437                         yaz_log(YLOG_FATAL, "can't open CCL file '%s'", name);
438                         exit(1);
439                     }
440                     gfs->ccl_transform = ccl_qual_mk();
441                     ccl_qual_file (gfs->ccl_transform, f);
442                     fclose(f);
443                 }
444                 else if (!strcmp((const char *) ptr->name, "directory"))
445                 {
446                     gfs->directory = 
447                         nmem_dup_xml_content(gfs_nmem, ptr->children);
448                 }
449                 else if (!strcmp((const char *) ptr->name, "docpath"))
450                 {
451                     gfs->docpath = 
452                         nmem_dup_xml_content(gfs_nmem, ptr->children);
453                 }
454                 else if (!strcmp((const char *) ptr->name, "maximumrecordsize"))
455                 {
456                     gfs->cb.maxrecordsize = atoi(
457                         nmem_dup_xml_content(gfs_nmem, ptr->children));
458                 }
459                 else if (!strcmp((const char *) ptr->name, "stylesheet"))
460                 {
461                     char *s = nmem_dup_xml_content(gfs_nmem, ptr->children);
462                     gfs->stylesheet = (char *)
463                         nmem_malloc(gfs_nmem, strlen(s) + 2);
464                     sprintf(gfs->stylesheet, "/%s", s);
465                 }
466                 else if (!strcmp((const char *) ptr->name, "explain"))
467                 {
468                     ; /* being processed separately */
469                 }
470                 else if (!strcmp((const char *) ptr->name, "retrievalinfo"))
471                 {
472                     if (yaz_retrieval_configure(gfs->retrieval, ptr))
473                     {       
474                         yaz_log(YLOG_FATAL, "%s in config %s",
475                                 yaz_retrieval_get_error(gfs->retrieval),
476                                 control_block.xml_config);
477                         exit(1);
478                     }
479                 }
480                 else
481                 {
482                     yaz_log(YLOG_FATAL, "Unknown element '%s' in config %s",
483                             ptr->name, control_block.xml_config);
484                     exit(1);
485                 }
486             }
487             gfsp = &(*gfsp)->next;
488         }
489     }
490     *gfsp = 0;
491 }
492 #endif
493
494 static void xml_config_open(void)
495 {
496     if (!getcwd(gfs_root_dir, FILENAME_MAX))
497     {
498         yaz_log(YLOG_WARN|YLOG_ERRNO, "getcwd failed");
499         gfs_root_dir[0] = '\0';
500     }
501 #ifdef WIN32
502     init_control_tls = 1;
503     current_control_tls = TlsAlloc();
504 #elif YAZ_POSIX_THREADS
505     init_control_tls = 1;
506     pthread_key_create(&current_control_tls, 0);
507 #endif
508     
509     gfs_nmem = nmem_create();
510 #if YAZ_HAVE_XML2
511     if (control_block.xml_config[0] == '\0')
512         return;
513
514     if (!xml_config_doc)
515     {
516         xml_config_doc = xmlParseFile(control_block.xml_config);
517         if (!xml_config_doc)
518         {
519             yaz_log(YLOG_FATAL, "Could not parse %s", control_block.xml_config);
520             exit(1);
521         }
522         else
523         {
524             int noSubstitutions = xmlXIncludeProcess(xml_config_doc);
525             if (noSubstitutions == -1)
526             {
527                 yaz_log(YLOG_WARN, "XInclude processing failed for config %s",
528                         control_block.xml_config);
529                 exit(1);
530             }
531         }
532     }
533     xml_config_read();
534 #endif
535 }
536
537 static void xml_config_close(void)
538 {
539 #if YAZ_HAVE_XML2
540     if (xml_config_doc)
541     {
542         xmlFreeDoc(xml_config_doc);
543         xml_config_doc = 0;
544     }
545 #endif
546     gfs_server_list = 0;
547     nmem_destroy(gfs_nmem);
548 #ifdef WIN32
549     if (init_control_tls)
550         TlsFree(current_control_tls);
551 #elif YAZ_POSIX_THREADS
552     if (init_control_tls)
553         pthread_key_delete(current_control_tls);
554 #endif
555 }
556
557 static void xml_config_add_listeners(void)
558 {
559     struct gfs_listen *gfs = gfs_listen_list;
560     int id_no;
561
562     for (id_no = 1; gfs; gfs = gfs->next, id_no++)
563     {
564         if (gfs->address)
565             add_listener(gfs->address, id_no);
566     }
567 }
568
569 static void xml_config_bend_start(void)
570 {
571     if (control_block.xml_config[0])
572     {
573         struct gfs_server *gfs = gfs_server_list;
574         for (; gfs; gfs = gfs->next)
575         {
576             yaz_log(YLOG_DEBUG, "xml_config_bend_start config=%s",
577                     gfs->cb.configname);
578             statserv_setcontrol(&gfs->cb);
579             if (control_block.bend_start)
580             {
581                 gfs_server_chdir(gfs);
582                 (control_block.bend_start)(&gfs->cb);
583             }
584         }
585     }
586     else
587     {
588         yaz_log(YLOG_DEBUG, "xml_config_bend_start default config");
589         statserv_setcontrol(&control_block);
590         if (control_block.bend_start)
591             (*control_block.bend_start)(&control_block);
592     }
593 }
594
595 static void xml_config_bend_stop(void)
596 {
597     if (control_block.xml_config[0])
598     {
599         struct gfs_server *gfs = gfs_server_list;
600         for (; gfs; gfs = gfs->next)
601         {
602             yaz_log(YLOG_DEBUG, "xml_config_bend_stop config=%s",
603                     gfs->cb.configname);
604             statserv_setcontrol(&gfs->cb);
605             if (control_block.bend_stop)
606                 (control_block.bend_stop)(&gfs->cb);
607         }
608     }
609     else
610     {
611         yaz_log(YLOG_DEBUG, "xml_config_bend_stop default config");
612         statserv_setcontrol(&control_block);
613         if (control_block.bend_stop)
614             (*control_block.bend_stop)(&control_block);
615     }
616 }
617
618 static void remove_listeners(void);
619
620 /*
621  * handle incoming connect requests.
622  * The dynamic mode is a bit tricky mostly because we want to avoid
623  * doing all of the listening and accepting in the parent - it's
624  * safer that way.
625  */
626 #ifdef WIN32
627
628 typedef struct _ThreadList ThreadList;
629
630 struct _ThreadList
631 {
632     HANDLE hThread;
633     IOCHAN pIOChannel;
634     ThreadList *pNext;
635 };
636
637 static ThreadList *pFirstThread;
638 static CRITICAL_SECTION Thread_CritSect;
639 static BOOL bInitialized = FALSE;
640
641 static void ThreadList_Initialize()
642 {
643     /* Initialize the critical Sections */
644     InitializeCriticalSection(&Thread_CritSect);
645
646     /* Set the first thraed */
647     pFirstThread = NULL;
648
649     /* we have been initialized */
650     bInitialized = TRUE;
651 }
652
653 static void statserv_add(HANDLE hThread, IOCHAN pIOChannel)
654 {
655     /* Only one thread can go through this section at a time */
656     EnterCriticalSection(&Thread_CritSect);
657
658     {
659         /* Lets create our new object */
660         ThreadList *pNewThread = (ThreadList *)malloc(sizeof(ThreadList));
661         pNewThread->hThread = hThread;
662         pNewThread->pIOChannel = pIOChannel;
663         pNewThread->pNext = pFirstThread;
664         pFirstThread = pNewThread;
665
666         /* Lets let somebody else create a new object now */
667         LeaveCriticalSection(&Thread_CritSect);
668     }
669 }
670
671 void statserv_remove(IOCHAN pIOChannel)
672 {
673     /* Only one thread can go through this section at a time */
674     EnterCriticalSection(&Thread_CritSect);
675
676     {
677         ThreadList *pCurrentThread = pFirstThread;
678         ThreadList *pNextThread;
679         ThreadList *pPrevThread =NULL;
680
681         /* Step through all the threads */
682         for (; pCurrentThread != NULL; pCurrentThread = pNextThread)
683         {
684             /* We only need to compare on the IO Channel */
685             if (pCurrentThread->pIOChannel == pIOChannel)
686             {
687                 /* We have found the thread we want to delete */
688                 /* First of all reset the next pointers */
689                 if (pPrevThread == NULL)
690                     pFirstThread = pCurrentThread->pNext;
691                 else
692                     pPrevThread->pNext = pCurrentThread->pNext;
693
694                 /* All we need todo now is delete the memory */
695                 free(pCurrentThread);
696
697                 /* No need to look at any more threads */
698                 pNextThread = NULL;
699             }
700             else
701             {
702                 /* We need to look at another thread */
703                 pNextThread = pCurrentThread->pNext;
704                 pPrevThread = pCurrentThread;
705             }
706         }
707
708         /* Lets let somebody else remove an object now */
709         LeaveCriticalSection(&Thread_CritSect);
710     }
711 }
712
713 /* WIN32 statserv_closedown */
714 static void statserv_closedown()
715 {
716     /* Shouldn't do anything if we are not initialized */
717     if (bInitialized)
718     {
719         int iHandles = 0;
720         HANDLE *pThreadHandles = NULL;
721
722         /* We need to stop threads adding and removing while we */
723         /* start the closedown process */
724         EnterCriticalSection(&Thread_CritSect);
725
726         {
727             /* We have exclusive access to the thread stuff now */
728             /* Y didn't i use a semaphore - Oh well never mind */
729             ThreadList *pCurrentThread = pFirstThread;
730
731             /* Before we do anything else, we need to shutdown the listener */
732             if (pListener != NULL)
733                 iochan_destroy(pListener);
734
735             for (; pCurrentThread != NULL; pCurrentThread = pCurrentThread->pNext)
736             {
737                 /* Just destroy the IOCHAN, that should do the trick */
738                 iochan_destroy(pCurrentThread->pIOChannel);
739                 closesocket(pCurrentThread->pIOChannel->fd);
740
741                 /* Keep a running count of our handles */
742                 iHandles++;
743             }
744
745             if (iHandles > 0)
746             {
747                 HANDLE *pCurrentHandle ;
748
749                 /* Allocate the thread handle array */
750                 pThreadHandles = (HANDLE *)malloc(sizeof(HANDLE) * iHandles);
751                 pCurrentHandle = pThreadHandles; 
752
753                 for (pCurrentThread = pFirstThread;
754                      pCurrentThread != NULL;
755                      pCurrentThread = pCurrentThread->pNext, pCurrentHandle++)
756                 {
757                     /* Just the handle */
758                     *pCurrentHandle = pCurrentThread->hThread;
759                 }
760             }
761
762             /* We can now leave the critical section */
763             LeaveCriticalSection(&Thread_CritSect);
764         }
765
766         /* Now we can really do something */
767         if (iHandles > 0)
768         {
769             yaz_log(log_server, "waiting for %d to die", iHandles);
770             /* This will now wait, until all the threads close */
771             WaitForMultipleObjects(iHandles, pThreadHandles, TRUE, INFINITE);
772
773             /* Free the memory we allocated for the handle array */
774             free(pThreadHandles);
775         }
776
777         xml_config_bend_stop();
778         /* No longer require the critical section, since all threads are dead */
779         DeleteCriticalSection(&Thread_CritSect);
780     }
781     xml_config_close();
782 }
783
784 void __cdecl event_loop_thread(IOCHAN iochan)
785 {
786     iochan_event_loop(&iochan);
787 }
788
789 /* WIN32 listener */
790 static void listener(IOCHAN h, int event)   
791 {
792     COMSTACK line = (COMSTACK) iochan_getdata(h);
793     IOCHAN parent_chan = line->user;
794     association *newas;
795     int res;
796     HANDLE newHandle;
797
798     if (event == EVENT_INPUT)
799     {
800         COMSTACK new_line;
801         IOCHAN new_chan;
802
803         if ((res = cs_listen(line, 0, 0)) < 0)
804         {
805             yaz_log(YLOG_FATAL|YLOG_ERRNO, "cs_listen failed");
806             return;
807         }
808         else if (res == 1)
809             return; /* incomplete */
810         yaz_log(YLOG_DEBUG, "listen ok");
811         new_line = cs_accept(line);
812         if (!new_line)
813         {
814             yaz_log(YLOG_FATAL, "Accept failed.");
815             return;
816         }
817         yaz_log(YLOG_DEBUG, "Accept ok");
818
819         if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session,
820                                        EVENT_INPUT, parent_chan->chan_id)))
821         {
822             yaz_log(YLOG_FATAL, "Failed to create iochan");
823             iochan_destroy(h);
824             return;
825         }
826
827         yaz_log(YLOG_DEBUG, "Creating association");
828         if (!(newas = create_association(new_chan, new_line,
829                                          control_block.apdufile)))
830         {
831             yaz_log(YLOG_FATAL, "Failed to create new assoc.");
832             iochan_destroy(h);
833             return;
834         }
835         newas->cs_get_mask = EVENT_INPUT;
836         newas->cs_put_mask = 0;
837         newas->cs_accept_mask = 0;
838
839         yaz_log(YLOG_DEBUG, "Setting timeout %d", control_block.idle_timeout);
840         iochan_setdata(new_chan, newas);
841         iochan_settimeout(new_chan, 60);
842
843         /* Now what we need todo is create a new thread with this iochan as
844            the parameter */
845         newHandle = (HANDLE) _beginthread(event_loop_thread, 0, new_chan);
846         if (newHandle == (HANDLE) -1)
847         {
848             
849             yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create new thread.");
850             iochan_destroy(h);
851             return;
852         }
853         /* We successfully created the thread, so add it to the list */
854         statserv_add(newHandle, new_chan);
855
856         yaz_log(YLOG_DEBUG, "Created new thread, id = %ld iochan %p",(long) newHandle, new_chan);
857         iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
858     }
859     else
860     {
861         yaz_log(YLOG_FATAL, "Bad event on listener.");
862         iochan_destroy(h);
863         return;
864     }
865 }
866
867 #else /* ! WIN32 */
868
869 /* To save having an #ifdef in event_loop we need to
870    define this empty function 
871 */
872 void statserv_remove(IOCHAN pIOChannel)
873 {
874 }
875
876 static void statserv_closedown(void)
877 {
878     IOCHAN p;
879
880     xml_config_bend_stop();
881     for (p = pListener; p; p = p->next)
882     {
883         iochan_destroy(p);
884     }
885     xml_config_close();
886 }
887
888 static void *new_session(void *vp);
889 static int no_sessions = 0;
890
891 /* UNIX listener */
892 static void listener(IOCHAN h, int event)
893 {
894     COMSTACK line = (COMSTACK) iochan_getdata(h);
895     int res;
896
897     if (event == EVENT_INPUT)
898     {
899         COMSTACK new_line;
900         if ((res = cs_listen_check(line, 0, 0, control_block.check_ip,
901                                    control_block.daemon_name)) < 0)
902         {
903             yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_listen failed");
904             return;
905         }
906         else if (res == 1)
907         {
908             yaz_log(YLOG_WARN, "cs_listen incomplete");
909             return;
910         }
911         new_line = cs_accept(line);
912         if (!new_line)
913         {
914             yaz_log(YLOG_FATAL, "Accept failed.");
915             iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
916             return;
917         }
918
919         if (control_block.one_shot)
920             remove_listeners();
921
922         yaz_log(log_sessiondetail, "Connect from %s", cs_addrstr(new_line));
923
924         no_sessions++;
925         if (control_block.dynamic)
926         {
927             if ((res = fork()) < 0)
928             {
929                 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fork");
930                 iochan_destroy(h);
931                 return;
932             }
933             else if (res == 0) /* child */
934             {
935                 char nbuf[100];
936                 IOCHAN pp;
937
938                 for (pp = pListener; pp; pp = iochan_getnext(pp))
939                 {
940                     COMSTACK l = (COMSTACK)iochan_getdata(pp);
941                     cs_close(l);
942                     iochan_destroy(pp);
943                 }
944                 sprintf(nbuf, "%s(%d)", me, no_sessions);
945                 yaz_log_init_prefix(nbuf);
946                 /* ensure that bend_stop is not called when each child exits -
947                    only for the main process ..  */
948                 control_block.bend_stop = 0;
949             }
950             else /* parent */
951             {
952                 cs_close(new_line);
953                 return;
954             }
955         }
956
957         if (control_block.threads)
958         {
959 #if YAZ_POSIX_THREADS
960             pthread_t child_thread;
961             pthread_create(&child_thread, 0, new_session, new_line);
962             pthread_detach(child_thread);
963 #else
964             new_session(new_line);
965 #endif
966         }
967         else
968             new_session(new_line);
969     }
970     else if (event == EVENT_TIMEOUT)
971     {
972         yaz_log(log_server, "Shutting down listener.");
973         iochan_destroy(h);
974     }
975     else
976     {
977         yaz_log(YLOG_FATAL, "Bad event on listener.");
978         iochan_destroy(h);
979     }
980 }
981
982 static void *new_session(void *vp)
983 {
984     const char *a;
985     association *newas;
986     IOCHAN new_chan;
987     COMSTACK new_line = (COMSTACK) vp;
988     IOCHAN parent_chan = (IOCHAN) new_line->user;
989
990     unsigned cs_get_mask, cs_accept_mask, mask =  
991         ((new_line->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
992         ((new_line->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
993
994     if (mask)
995     {
996         cs_accept_mask = mask;  /* accept didn't complete */
997         cs_get_mask = 0;
998     }
999     else
1000     {
1001         cs_accept_mask = 0;     /* accept completed.  */
1002         cs_get_mask = mask = EVENT_INPUT;
1003     }
1004
1005     if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session, mask,
1006                                    parent_chan->chan_id)))
1007     {
1008         yaz_log(YLOG_FATAL, "Failed to create iochan");
1009         return 0;
1010     }
1011     if (!(newas = create_association(new_chan, new_line,
1012                                      control_block.apdufile)))
1013     {
1014         yaz_log(YLOG_FATAL, "Failed to create new assoc.");
1015         return 0;
1016     }
1017     newas->cs_accept_mask = cs_accept_mask;
1018     newas->cs_get_mask = cs_get_mask;
1019
1020     iochan_setdata(new_chan, newas);
1021     iochan_settimeout(new_chan, 60);
1022 #if 1
1023     a = cs_addrstr(new_line);
1024 #else
1025     a = 0;
1026 #endif
1027     yaz_log_xml_errors(0, YLOG_WARN);
1028     yaz_log(log_session, "Session - OK %d %s %ld",
1029             no_sessions, a ? a : "[Unknown]", (long) getpid());
1030     if (max_sessions && no_sessions >= max_sessions)
1031         control_block.one_shot = 1;
1032     if (control_block.threads)
1033     {
1034         iochan_event_loop(&new_chan);
1035     }
1036     else
1037     {
1038         new_chan->next = pListener;
1039         pListener = new_chan;
1040     }
1041     return 0;
1042 }
1043
1044 /* UNIX */
1045 #endif
1046
1047 static void inetd_connection(int what)
1048 {
1049     COMSTACK line;
1050     IOCHAN chan;
1051     association *assoc;
1052     const char *addr;
1053
1054     if ((line = cs_createbysocket(0, tcpip_type, 0, what)))
1055     {
1056         if ((chan = iochan_create(cs_fileno(line), ir_session, EVENT_INPUT,
1057                                   0)))
1058         {
1059             if ((assoc = create_association(chan, line,
1060                                             control_block.apdufile)))
1061             {
1062                 iochan_setdata(chan, assoc);
1063                 iochan_settimeout(chan, 60);
1064                 addr = cs_addrstr(line);
1065                 yaz_log(log_sessiondetail, "Inetd association from %s",
1066                         addr ? addr : "[UNKNOWN]");
1067                 assoc->cs_get_mask = EVENT_INPUT;
1068             }
1069             else
1070             {
1071                 yaz_log(YLOG_FATAL, "Failed to create association structure");
1072             }
1073             chan->next = pListener;
1074             pListener = chan;
1075         }
1076         else
1077         {
1078             yaz_log(YLOG_FATAL, "Failed to create iochan");
1079         }
1080     }
1081     else
1082     {
1083         yaz_log(YLOG_ERRNO|YLOG_FATAL, "Failed to create comstack on socket 0");
1084     }
1085 }
1086
1087 /*
1088  * Set up a listening endpoint, and give it to the event-handler.
1089  */
1090 static int add_listener(char *where, int listen_id)
1091 {
1092     COMSTACK l;
1093     void *ap;
1094     IOCHAN lst = NULL;
1095     const char *mode;
1096
1097     if (control_block.dynamic)
1098         mode = "dynamic";
1099     else if (control_block.threads)
1100         mode = "threaded";
1101     else
1102         mode = "static";
1103
1104     yaz_log(log_server, "Adding %s listener on %s id=%d", mode, where,
1105             listen_id);
1106
1107     l = cs_create_host(where, 2, &ap);
1108     if (!l)
1109     {
1110         yaz_log(YLOG_FATAL, "Failed to listen on %s", where);
1111         return -1;
1112     }
1113     if (*control_block.cert_fname)
1114         cs_set_ssl_certificate_file(l, control_block.cert_fname);
1115
1116     if (cs_bind(l, ap, CS_SERVER) < 0)
1117     {
1118         if (cs_errno(l) == CSYSERR)
1119             yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to bind to %s", where);
1120         else
1121             yaz_log(YLOG_FATAL, "Failed to bind to %s: %s", where,
1122                     cs_strerror(l));
1123         cs_close(l);
1124         return -1;
1125     }
1126     if (!(lst = iochan_create(cs_fileno(l), listener, EVENT_INPUT |
1127                               EVENT_EXCEPT, listen_id)))
1128     {
1129         yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create IOCHAN-type");
1130         cs_close(l);
1131         return -1;
1132     }
1133     iochan_setdata(lst, l); /* user-defined data for listener is COMSTACK */
1134     l->user = lst;  /* user-defined data for COMSTACK is listener chan */
1135
1136     /* Add listener to chain */
1137     lst->next = pListener;
1138     pListener = lst;
1139     return 0; /* OK */
1140 }
1141
1142 static void remove_listeners(void)
1143 {
1144     IOCHAN l = pListener;
1145     for (; l; l = l->next)
1146         iochan_destroy(l);
1147 }
1148
1149 #ifndef WIN32
1150 /* UNIX only (for windows we don't need to catch the signals) */
1151 static void catchchld(int num)
1152 {
1153     while (waitpid(-1, 0, WNOHANG) > 0)
1154         ;
1155     signal(SIGCHLD, catchchld);
1156 }
1157 #endif
1158
1159 statserv_options_block *statserv_getcontrol(void)
1160 {
1161 #ifdef WIN32
1162     if (init_control_tls)
1163         return (statserv_options_block *) TlsGetValue(current_control_tls);
1164     else
1165         return &control_block;
1166 #elif YAZ_POSIX_THREADS
1167     if (init_control_tls)
1168         return (statserv_options_block *)
1169             pthread_getspecific(current_control_tls);
1170     else
1171         return &control_block;
1172 #else
1173     if (current_control_block)
1174         return current_control_block;
1175     return &control_block;
1176 #endif
1177 }
1178
1179 void statserv_setcontrol(statserv_options_block *block)
1180 {
1181     if (gfs_root_dir[0])
1182     {
1183         if (chdir(gfs_root_dir))
1184             yaz_log(YLOG_WARN|YLOG_ERRNO, "chdir %s", gfs_root_dir);
1185     }
1186 #ifdef WIN32
1187     if (init_control_tls)
1188         TlsSetValue(current_control_tls, block);
1189 #elif YAZ_POSIX_THREADS
1190     if (init_control_tls)
1191         pthread_setspecific(current_control_tls, block);
1192 #else
1193     current_control_block = block;
1194 #endif
1195 }
1196
1197 static void statserv_reset(void)
1198 {
1199 }
1200
1201 static void daemon_handler(void *data)
1202 {
1203     IOCHAN *pListener = data;
1204     iochan_event_loop(pListener);
1205 }
1206
1207 static int statserv_sc_main(yaz_sc_t s, int argc, char **argv)
1208 {
1209     char sep;
1210 #ifdef WIN32
1211     /* We need to initialize the thread list */
1212     ThreadList_Initialize();
1213 /* WIN32 */
1214 #endif
1215
1216
1217 #ifdef WIN32
1218     sep = '\\';
1219 #else
1220     sep = '/';
1221 #endif
1222     if ((me = strrchr(argv[0], sep)))
1223         me++; /* get the basename */
1224     else
1225         me = argv[0];
1226     programname = argv[0];
1227
1228     if (control_block.options_func(argc, argv))
1229         return 1;
1230
1231     xml_config_open();
1232     
1233     xml_config_bend_start();
1234
1235     if (control_block.inetd)
1236     {
1237 #ifdef WIN32
1238         ; /* no inetd on Windows */
1239 #else
1240         inetd_connection(control_block.default_proto);
1241 #endif
1242     }
1243     else
1244     {
1245         xml_config_add_listeners();
1246
1247         if (!pListener && *control_block.default_listen)
1248             add_listener(control_block.default_listen, 0);
1249
1250 #ifndef WIN32
1251         if (control_block.dynamic)
1252             signal(SIGCHLD, catchchld);
1253 #endif
1254     }
1255     if (pListener == NULL)
1256         return 1;
1257     if (s)
1258         yaz_sc_running(s);
1259     yaz_log(YLOG_DEBUG, "Entering event loop.");
1260
1261     yaz_daemon(programname,
1262                (control_block.background ? YAZ_DAEMON_FORK : 0),
1263                daemon_handler, &pListener,
1264                *control_block.pid_fname ? control_block.pid_fname : 0,
1265                *control_block.setuid ? control_block.setuid : 0);
1266     return 0;
1267 }
1268
1269 static void option_copy(char *dst, const char *src)
1270 {
1271     strncpy(dst, src ? src : "", 127);
1272     dst[127] = '\0';
1273 }
1274
1275 int check_options(int argc, char **argv)
1276 {
1277     int ret = 0, r;
1278     char *arg;
1279
1280     yaz_log_init_level(yaz_log_mask_str(STAT_DEFAULT_LOG_LEVEL)); 
1281
1282     get_logbits(1); 
1283
1284     while ((ret = options("1a:iszSTl:v:u:c:w:t:k:Kd:A:p:DC:f:m:r:",
1285                           argv, argc, &arg)) != -2)
1286     {
1287         switch (ret)
1288         {
1289         case 0:
1290             if (add_listener(arg, 0))
1291                 return 1;  /* failed to create listener */
1292             break;
1293         case '1':        
1294             control_block.one_shot = 1;
1295             control_block.dynamic = 0;
1296             break;
1297         case 'z':
1298             control_block.default_proto = PROTO_Z3950;
1299             break;
1300         case 's':
1301             fprintf(stderr, "%s: SR protocol no longer supported\n", me);
1302             exit(1);
1303             break;
1304         case 'S':
1305             control_block.dynamic = 0;
1306             break;
1307         case 'T':
1308 #if YAZ_POSIX_THREADS
1309             control_block.dynamic = 0;
1310             control_block.threads = 1;
1311 #else
1312             fprintf(stderr, "%s: Threaded mode not available.\n", me);
1313             return 1;
1314 #endif
1315             break;
1316         case 'l':
1317             option_copy(control_block.logfile, arg);
1318             yaz_log_init_file(control_block.logfile);
1319             break;
1320         case 'm':
1321             if (!arg) {
1322                 fprintf(stderr, "%s: Specify time format for log file.\n", me);
1323                 return(1);
1324             }
1325             yaz_log_time_format(arg);
1326             break;
1327         case 'v':
1328             yaz_log_init_level(yaz_log_mask_str(arg));
1329             get_logbits(1); 
1330             break;
1331         case 'a':
1332             option_copy(control_block.apdufile, arg);
1333             break;
1334         case 'u':
1335             option_copy(control_block.setuid, arg);
1336             break;
1337         case 'c':
1338             option_copy(control_block.configname, arg);
1339             break;
1340         case 'C':
1341             option_copy(control_block.cert_fname, arg);
1342             break;
1343         case 'd':
1344             option_copy(control_block.daemon_name, arg);
1345             break;
1346         case 't':
1347             if (!arg || !(r = atoi(arg)))
1348             {
1349                 fprintf(stderr, "%s: Specify positive timeout for -t.\n", me);
1350                 return(1);
1351             }
1352             control_block.idle_timeout = strchr(arg, 's') ? r : 60 * r;
1353             break;
1354         case  'k':
1355             if (!arg || !(r = atoi(arg)))
1356             {
1357                 fprintf(stderr, "%s: Specify positive size for -k.\n", me);
1358                 return(1);
1359             }
1360             control_block.maxrecordsize = r * 1024;
1361             break;
1362         case 'K':
1363             control_block.keepalive = 0;
1364             break;
1365         case 'i':
1366             control_block.inetd = 1;
1367             break;
1368         case 'w':
1369             if (chdir(arg))
1370             {
1371                 perror(arg);            
1372                 return 1;
1373             }
1374             break;
1375         case 'A':
1376             max_sessions = atoi(arg);
1377             break;
1378         case 'p':
1379             option_copy(control_block.pid_fname, arg);
1380             break;
1381         case 'f':
1382 #if YAZ_HAVE_XML2
1383             option_copy(control_block.xml_config, arg);
1384 #else
1385             fprintf(stderr, "%s: Option -f unsupported since YAZ is compiled without Libxml2 support\n", me);
1386             exit(1);
1387 #endif
1388             break;
1389         case 'D':
1390             control_block.background = 1;
1391             break;
1392         case 'r':
1393             if (!arg || !(r = atoi(arg)))
1394             {
1395                 fprintf(stderr, "%s: Specify positive size for -r.\n", me);
1396                 return(1);
1397             }
1398             yaz_log_init_max_size(r * 1024);
1399             break;
1400         default:
1401             fprintf(stderr, "Usage: %s [ -a <pdufile> -v <loglevel>"
1402                     " -l <logfile> -u <user> -c <config> -t <minutes>"
1403                     " -k <kilobytes> -d <daemon> -p <pidfile> -C certfile"
1404                     " -ziDST1 -m <time-format> -w <directory> <listener-addr>... ]\n", me);
1405             return 1;
1406         }
1407     }
1408     return 0;
1409 }
1410
1411 void statserv_sc_stop(yaz_sc_t s)
1412 {
1413     statserv_closedown();
1414     statserv_reset();
1415 }
1416
1417 int statserv_main(int argc, char **argv,
1418                   bend_initresult *(*bend_init)(bend_initrequest *r),
1419                   void (*bend_close)(void *handle))
1420 {
1421     int ret;
1422     struct statserv_options_block *cb = &control_block;
1423
1424     /* control block does not have service_name member on Unix */
1425     yaz_sc_t s = yaz_sc_create(
1426 #ifdef WIN32
1427         cb->service_name, cb->service_display_name
1428 #else
1429         0, 0
1430 #endif
1431         );
1432
1433     cb->bend_init = bend_init;
1434     cb->bend_close = bend_close;
1435
1436     ret = yaz_sc_program(s, argc, argv, statserv_sc_main, statserv_sc_stop);
1437     yaz_sc_destroy(&s);
1438     return ret;
1439 }
1440
1441 /*
1442  * Local variables:
1443  * c-basic-offset: 4
1444  * c-file-style: "Stroustrup"
1445  * indent-tabs-mode: nil
1446  * End:
1447  * vim: shiftwidth=4 tabstop=8 expandtab
1448  */
1449