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