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