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