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