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