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