Implemented XML/SGML attributes for data1 so that d1_read reads them
[yaz-moved-to-github.git] / server / statserv.c
1 /*
2  * Copyright (c) 1995-2000, Index Data
3  * See the file LICENSE for details.
4  * Sebastian Hammer, Adam Dickmeiss
5  *
6  * NT server based on threads by
7  *   Chas Woodfield, Fretwell Downing Informatics.
8  *
9  * $Log: statserv.c,v $
10  * Revision 1.68  2000-11-29 14:22:47  adam
11  * Implemented XML/SGML attributes for data1 so that d1_read reads them
12  * and d1_write generates proper attributes for XML/SGML records. Added
13  * register locking for threaded version.
14  *
15  * Revision 1.67  2000/11/23 10:58:32  adam
16  * SSL comstack support. Separate POSIX thread support library.
17  *
18  * Revision 1.66  2000/10/06 12:00:28  adam
19  * Fixed Handle leak for WIN32.
20  *
21  * Revision 1.65  2000/09/04 08:58:15  adam
22  * Added prefix yaz_ for most logging utility functions.
23  *
24  * Revision 1.64  2000/04/05 07:39:55  adam
25  * Added shared library support (libtool).
26  *
27  * Revision 1.63  2000/03/20 19:06:25  adam
28  * Added Segment request for fronend server. Work on admin for client.
29  *
30  * Revision 1.62  2000/03/17 12:47:02  adam
31  * Minor changes to admin client.
32  *
33  * Revision 1.61  2000/03/15 12:59:49  adam
34  * Added handle member to statserv_control.
35  *
36  * Revision 1.60  2000/03/14 09:06:11  adam
37  * Added POSIX threads support for frontend server.
38  *
39  * Revision 1.59  1999/11/30 13:47:12  adam
40  * Improved installation. Moved header files to include/yaz.
41  *
42  * Revision 1.58  1999/08/27 09:40:32  adam
43  * Renamed logf function to yaz_log. Removed VC++ project files.
44  *
45  * Revision 1.57  1999/07/06 12:17:15  adam
46  * Added option -1 that runs server once (for profiling purposes).
47  *
48  * Revision 1.56  1999/06/10 11:45:30  adam
49  * Added bend_start, bend_stop handlers and removed pre_init.
50  * Handlers bend_start/bend_stop are called when service/daemon is
51  * started/stopped.
52  *
53  * Revision 1.55  1999/06/10 09:18:54  adam
54  * Modified so that pre_init is called when service/server is started.
55  *
56  * Revision 1.54  1999/04/16 14:45:55  adam
57  * Added interface for tcpd wrapper for access control.
58  *
59  * Revision 1.53  1999/02/02 13:57:39  adam
60  * Uses preprocessor define WIN32 instead of WINDOWS to build code
61  * for Microsoft WIN32.
62  *
63  * Revision 1.52  1998/08/21 14:13:34  adam
64  * Added GNU Configure script to build Makefiles.
65  *
66  * Revision 1.51  1998/07/07 15:51:03  adam
67  * Changed server so that it stops if bind fails - "address already in
68  * use" typically causes this.
69  *
70  * Revision 1.50  1998/06/22 11:32:39  adam
71  * Added 'conditional cs_listen' feature.
72  *
73  * Revision 1.49  1998/02/27 14:04:55  adam
74  * Fixed bug in statserv_remove.
75  *
76  * Revision 1.48  1998/02/11 11:53:36  adam
77  * Changed code so that it compiles as C++.
78  *
79  * Revision 1.47  1998/02/10 10:28:57  adam
80  * Added app_name, service_dependencies, service_display_name and
81  * options_func. options_func allows us to specify a different function
82  * to interogate the command line arguments. The other members allow us
83  * to pass the full service details accross to the service manager (CW).
84  *
85  *
86  * Revision 1.46  1998/01/30 15:24:57  adam
87  * Fixed bug in inetd code. The server listened on tcp:@:9999 even
88  * though it was started in inetd mode.
89  *
90  * Revision 1.45  1998/01/29 13:30:23  adam
91  * Better event handle system for NT/Unix.
92  *
93  * Revision 1.44  1997/11/07 13:31:52  adam
94  * Added NT Service name part of statserv_options_block. Moved NT
95  * service utility to server library.
96  *
97  * Revision 1.43  1997/10/31 12:20:09  adam
98  * Improved memory debugging for xmalloc/nmem.c. References to NMEM
99  * instead of ODR in n ESPEC-1 handling in source d1_espec.c.
100  * Bug fix: missing fclose in data1_read_espec1.
101  *
102  * Revision 1.42  1997/10/27 14:03:02  adam
103  * Added new member to statserver_options_block, pre_init, which
104  * specifies a callback to be invoked after command line parsing and
105  * before the server listens for the first time.
106  *
107  * Revision 1.41  1997/09/29 07:19:32  adam
108  * Server library uses nmem_init/nmem_exit. The log prefix no longer
109  * includes leading path on NT.
110  *
111  * Revision 1.40  1997/09/17 12:10:41  adam
112  * YAZ version 1.4.
113  *
114  * Revision 1.39  1997/09/09 10:10:19  adam
115  * Another MSV5.0 port. Changed projects to include proper
116  * library/include paths.
117  * Server starts server in test-mode when no options are given.
118  *
119  * Revision 1.38  1997/09/04 14:19:14  adam
120  * Added credits.
121  *
122  * Revision 1.37  1997/09/01 08:53:01  adam
123  * New windows NT/95 port using MSV5.0. The test server 'ztest' was
124  * moved a separate directory. MSV5.0 project server.dsp created.
125  * As an option, the server can now operate as an NT service.
126  *
127  * Revision 1.36  1996/07/06 19:58:36  quinn
128  * System headerfiles gathered in yconfig
129  *
130  * Revision 1.35  1996/05/29  10:03:28  quinn
131  * Options work
132  *
133  * Revision 1.34  1996/02/21  13:12:07  quinn
134  * *** empty log message ***
135  *
136  * Revision 1.33  1996/02/10  12:23:49  quinn
137  * Enable inetd operations fro TCP/IP stack
138  *
139  * Revision 1.32  1996/01/19  15:41:52  quinn
140  * *** empty log message ***
141  *
142  * Revision 1.31  1995/11/17  11:09:39  adam
143  * Added new option '-c' to specify configuration name in control block.
144  *
145  * Revision 1.30  1995/11/01  13:54:59  quinn
146  * Minor adjustments
147  *
148  * Revision 1.29  1995/10/30  12:41:29  quinn
149  * Added hostname lookup for server.
150  *
151  * Revision 1.28  1995/09/29  17:12:30  quinn
152  * Smallish
153  *
154  * Revision 1.27  1995/09/27  15:03:02  quinn
155  * Modified function heads & prototypes.
156  *
157  * Revision 1.26  1995/08/29  14:44:51  quinn
158  * Reset timeouts.
159  *
160  * Revision 1.25  1995/08/29  11:18:02  quinn
161  * Added code to receive close
162  *
163  * Revision 1.24  1995/06/16  10:31:39  quinn
164  * Added session timeout.
165  *
166  * Revision 1.23  1995/06/15  12:30:48  quinn
167  * Setuid-facility.
168  *
169  * Revision 1.22  1995/06/15  07:45:17  quinn
170  * Moving to v3.
171  *
172  * Revision 1.21  1995/06/06  08:15:40  quinn
173  * Cosmetic.
174  *
175  * Revision 1.20  1995/05/29  08:12:09  quinn
176  * Moved oid to util
177  *
178  * Revision 1.19  1995/05/16  09:37:27  quinn
179  * Fixed bug
180  *
181  * Revision 1.18  1995/05/16  08:51:09  quinn
182  * License, documentation, and memory fixes
183  *
184  * Revision 1.17  1995/05/15  11:56:42  quinn
185  * Asynchronous facilities. Restructuring of seshigh code.
186  *
187  * Revision 1.16  1995/04/10  10:23:40  quinn
188  * Some work to add scan and other things.
189  *
190  * Revision 1.15  1995/03/31  10:16:51  quinn
191  * Fixed logging.
192  *
193  * Revision 1.14  1995/03/31  09:18:58  quinn
194  * Added logging.
195  *
196  * Revision 1.13  1995/03/30  16:08:39  quinn
197  * Little mods.
198  *
199  * Revision 1.12  1995/03/30  13:29:02  quinn
200  * Smallish
201  *
202  * Revision 1.11  1995/03/30  12:18:17  quinn
203  * Fixed bug.
204  *
205  * Revision 1.10  1995/03/29  15:40:16  quinn
206  * Ongoing work. Statserv is now dynamic by default
207  *
208  * Revision 1.9  1995/03/27  08:34:30  quinn
209  * Added dynamic server functionality.
210  * Released bindings to session.c (is now redundant)
211  *
212  * Revision 1.8  1995/03/20  09:46:26  quinn
213  * Added osi support.
214  *
215  * Revision 1.7  1995/03/16  13:29:04  quinn
216  * Partitioned server.
217  *
218  * Revision 1.6  1995/03/15  15:18:52  quinn
219  * Little changes to better support nonblocking I/O
220  * Added backend.h
221  *
222  * Revision 1.5  1995/03/15  08:37:45  quinn
223  * Now we're pretty much set for nonblocking I/O.
224  *
225  * Revision 1.4  1995/03/14  16:59:48  quinn
226  * Bug-fixes
227  *
228  * Revision 1.3  1995/03/14  11:30:15  quinn
229  * Works better now.
230  *
231  * Revision 1.2  1995/03/14  10:28:03  quinn
232  * More work on demo server.
233  *
234  * Revision 1.1  1995/03/10  18:22:45  quinn
235  * The rudiments of an asynchronous server.
236  *
237  */
238
239 #include <stdio.h>
240 #include <string.h>
241 #ifdef WIN32
242 #include <process.h>
243 #include <winsock.h>
244 #include <direct.h>
245 #include "service.h"
246 #else
247 #if HAVE_PTHREAD_H
248 #include <pthread.h>
249 #endif
250 #include <unistd.h>
251 #include <pwd.h>
252 #endif
253 #include <fcntl.h>
254 #include <signal.h>
255 #include <errno.h>
256
257 #include <yaz/comstack.h>
258 #include <yaz/tcpip.h>
259 #include <yaz/options.h>
260 #ifdef USE_XTIMOSI
261 #include <yaz/xmosi.h>
262 #endif
263 #include <yaz/log.h>
264 #include "eventl.h"
265 #include "session.h"
266 #include <yaz/statserv.h>
267
268 static IOCHAN pListener = NULL;
269
270 static char *me = "statserver";
271 /*
272  * default behavior.
273  */
274 int check_options(int argc, char **argv);
275 statserv_options_block control_block = {
276     1,                          /* dynamic mode */
277     0,                          /* threaded mode */
278     0,                          /* one shot (single session) */
279     LOG_DEFAULT_LEVEL,          /* log level */
280     "",                         /* no PDUs */
281     "",                         /* diagnostic output to stderr */
282     "tcp:@:9999",               /* default listener port */
283     PROTO_Z3950,                /* default application protocol */
284     60,                         /* idle timeout (minutes) */
285     1024*1024,                  /* maximum PDU size (approx.) to allow */
286     "default-config",           /* configuration name to pass to backend */
287     "",                         /* set user id */
288     0,                          /* bend_start handler */
289     0,                          /* bend_stop handler */
290     check_options,              /* Default routine, for checking the run-time arguments */
291     check_ip_tcpd,
292     "",
293     0,                          /* default value for inet deamon */
294     0,                          /* handle (for service, etc) */
295     0,                          /* bend_init handle */
296     0                           /* bend_close handle */
297 #ifdef WIN32
298     ,"Z39.50 Server",           /* NT Service Name */
299     "Server",                   /* NT application Name */
300     "",                         /* NT Service Dependencies */
301     "Z39.50 Server"             /* NT Service Display Name */
302 #endif /* WIN32 */
303 };
304
305 /*
306  * handle incoming connect requests.
307  * The dynamic mode is a bit tricky mostly because we want to avoid
308  * doing all of the listening and accepting in the parent - it's
309  * safer that way.
310  */
311 #ifdef WIN32
312
313 typedef struct _ThreadList ThreadList;
314
315 struct _ThreadList
316 {
317     HANDLE hThread;
318     IOCHAN pIOChannel;
319     ThreadList *pNext;
320 };
321
322 static ThreadList *pFirstThread;
323 static CRITICAL_SECTION Thread_CritSect;
324 static BOOL bInitialized = FALSE;
325
326 static void ThreadList_Initialize()
327 {
328     /* Initialize the critical Sections */
329     InitializeCriticalSection(&Thread_CritSect);
330
331      /* Set the first thraed */
332     pFirstThread = NULL;
333
334     /* we have been initialized */
335     bInitialized = TRUE;
336 }
337
338 static void statserv_add(HANDLE hThread, IOCHAN pIOChannel)
339 {
340     /* Only one thread can go through this section at a time */
341     EnterCriticalSection(&Thread_CritSect);
342
343     {
344         /* Lets create our new object */
345         ThreadList *pNewThread = (ThreadList *)malloc(sizeof(ThreadList));
346         pNewThread->hThread = hThread;
347         pNewThread->pIOChannel = pIOChannel;
348         pNewThread->pNext = pFirstThread;
349         pFirstThread = pNewThread;
350
351         /* Lets let somebody else create a new object now */
352         LeaveCriticalSection(&Thread_CritSect);
353     }
354 }
355
356 void statserv_remove(IOCHAN pIOChannel)
357 {
358     /* Only one thread can go through this section at a time */
359     EnterCriticalSection(&Thread_CritSect);
360
361     {
362         ThreadList *pCurrentThread = pFirstThread;
363         ThreadList *pNextThread;
364         ThreadList *pPrevThread =NULL;
365
366         /* Step through alll the threads */
367         for (; pCurrentThread != NULL; pCurrentThread = pNextThread)
368         {
369             /* We only need to compare on the IO Channel */
370             if (pCurrentThread->pIOChannel == pIOChannel)
371             {
372                 /* We have found the thread we want to delete */
373                 /* First of all reset the next pointers */
374                 if (pPrevThread == NULL)
375                     pFirstThread = pCurrentThread->pNext;
376                 else
377                     pPrevThread->pNext = pCurrentThread->pNext;
378
379                 /* All we need todo now is delete the memory */
380                 free(pCurrentThread);
381
382                 /* No need to look at any more threads */
383                 pNextThread = NULL;
384             }
385             else
386             {
387                 /* We need to look at another thread */
388                 pNextThread = pCurrentThread->pNext;
389                 pPrevThread = pCurrentThread;
390             }
391         }
392
393         /* Lets let somebody else remove an object now */
394         LeaveCriticalSection(&Thread_CritSect);
395     }
396 }
397
398 /* WIN32 statserv_closedown */
399 void statserv_closedown()
400 {
401     /* Shouldn't do anything if we are not initialized */
402     if (bInitialized)
403     {
404         int iHandles = 0;
405         HANDLE *pThreadHandles = NULL;
406
407         /* We need to stop threads adding and removing while we */
408         /* start the closedown process */
409         EnterCriticalSection(&Thread_CritSect);
410
411         {
412             /* We have exclusive access to the thread stuff now */
413             /* Y didn't i use a semaphore - Oh well never mind */
414             ThreadList *pCurrentThread = pFirstThread;
415
416             /* Before we do anything else, we need to shutdown the listener */
417             if (pListener != NULL)
418                 iochan_destroy(pListener);
419
420             for (; pCurrentThread != NULL; pCurrentThread = pCurrentThread->pNext)
421             {
422                 /* Just destroy the IOCHAN, that should do the trick */
423                 iochan_destroy(pCurrentThread->pIOChannel);
424
425                 /* Keep a running count of our handles */
426                 iHandles++;
427             }
428
429             if (iHandles > 0)
430             {
431                 HANDLE *pCurrentHandle ;
432
433                 /* Allocate the thread handle array */
434                 pThreadHandles = (HANDLE *)malloc(sizeof(HANDLE) * iHandles);
435                 pCurrentHandle = pThreadHandles; 
436
437                 for (pCurrentThread = pFirstThread;
438                      pCurrentThread != NULL;
439                      pCurrentThread = pCurrentThread->pNext, pCurrentHandle++)
440                 {
441                     /* Just the handle */
442                     *pCurrentHandle = pCurrentThread->hThread;
443                 }
444             }
445
446             /* We can now leave the critical section */
447             LeaveCriticalSection(&Thread_CritSect);
448         }
449
450         /* Now we can really do something */
451         if (iHandles > 0)
452         {
453             /* This will now wait, until all the threads close */
454             WaitForMultipleObjects(iHandles, pThreadHandles, TRUE, INFINITE);
455
456             /* Free the memory we allocated for the handle array */
457             free(pThreadHandles);
458         }
459
460         if (control_block.bend_stop)
461             (*control_block.bend_stop)(&control_block);
462         /* No longer require the critical section, since all threads are dead */
463         DeleteCriticalSection(&Thread_CritSect);
464     }
465 }
466
467 void event_loop_thread (IOCHAN iochan)
468 {
469     event_loop (&iochan);
470 }
471
472 /* WIN32 listener */
473 static void listener(IOCHAN h, int event)   
474 {
475     COMSTACK line = (COMSTACK) iochan_getdata(h);
476     association *newas;
477     int res;
478     HANDLE newHandle;
479
480     if (event == EVENT_INPUT)
481     {
482         if ((res = cs_listen(line, 0, 0)) < 0)
483         {
484             yaz_log(LOG_FATAL, "cs_listen failed");
485             return;
486         }
487         else if (res == 1)
488             return;
489         yaz_log(LOG_DEBUG, "listen ok");
490         iochan_setevent(h, EVENT_OUTPUT);
491         iochan_setflags(h, EVENT_OUTPUT | EVENT_EXCEPT); /* set up for acpt */
492     }
493     else if (event == EVENT_OUTPUT)
494     {
495         COMSTACK new_line = cs_accept(line);
496         IOCHAN new_chan;
497         char *a = NULL;
498
499         if (!new_line)
500         {
501             yaz_log(LOG_FATAL, "Accept failed.");
502             iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT);
503             return;
504         }
505         yaz_log(LOG_DEBUG, "Accept ok");
506
507         if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session,
508                                        EVENT_INPUT)))
509         {
510             yaz_log(LOG_FATAL, "Failed to create iochan");
511             iochan_destroy(h);
512             return;
513         }
514
515         yaz_log(LOG_DEBUG, "Creating association");
516         if (!(newas = create_association(new_chan, new_line)))
517         {
518             yaz_log(LOG_FATAL, "Failed to create new assoc.");
519             iochan_destroy(h);
520             return;
521         }
522         newas->cs_get_mask = EVENT_INPUT;
523         newas->cs_put_mask = 0;
524         newas->cs_accept_mask = 0;
525
526         yaz_log(LOG_DEBUG, "Setting timeout %d", control_block.idle_timeout);
527         iochan_setdata(new_chan, newas);
528         iochan_settimeout(new_chan, control_block.idle_timeout * 60);
529
530         /* Now what we need todo is create a new thread with this iochan as
531            the parameter */
532         newHandle = (HANDLE) _beginthread(event_loop_thread, 0, new_chan);
533         if (newHandle == (HANDLE) -1)
534         {
535             
536             yaz_log(LOG_FATAL|LOG_ERRNO, "Failed to create new thread.");
537             iochan_destroy(h);
538             return;
539         }
540         /* We successfully created the thread, so add it to the list */
541         statserv_add(newHandle, new_chan);
542
543         yaz_log(LOG_DEBUG, "Created new thread, id = %ld iochan %p",(long) newHandle, new_chan);
544         iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
545     }
546     else
547     {
548         yaz_log(LOG_FATAL, "Bad event on listener.");
549         iochan_destroy(h);
550         return;
551     }
552 }
553
554 #else /* ! WIN32 */
555
556 /* To save having an #ifdef in event_loop we need to define this empty function */
557 void statserv_remove(IOCHAN pIOChannel)
558 {
559 }
560
561 void statserv_closedown()
562 {
563     IOCHAN p;
564
565     if (control_block.bend_stop)
566         (*control_block.bend_stop)(&control_block);
567
568     for (p = pListener; p; p = p->next)
569         iochan_destroy(p);
570 }
571
572 void sigterm(int sig)
573 {
574     statserv_closedown();
575     exit (0);
576 }
577
578 static void *new_session (void *vp);
579
580 /* UNIX listener */
581 static void listener(IOCHAN h, int event)
582 {
583     COMSTACK line = (COMSTACK) iochan_getdata(h);
584     static int hand[2];
585     static int child = 0;
586     int res;
587
588     if (event == EVENT_INPUT)
589     {
590         if (control_block.dynamic && !child) 
591         {
592             int res;
593
594             if (pipe(hand) < 0)
595             {
596                 yaz_log(LOG_FATAL|LOG_ERRNO, "pipe");
597                 iochan_destroy(h);
598                 return;
599             }
600             if ((res = fork()) < 0)
601             {
602                 yaz_log(LOG_FATAL|LOG_ERRNO, "fork");
603                 iochan_destroy(h);
604                 return;
605             }
606             else if (res == 0) /* child */
607             {
608                 char nbuf[100];
609                 IOCHAN pp;
610
611                 close(hand[0]);
612                 child = 1;
613                 for (pp = pListener; pp; pp = iochan_getnext(pp))
614                 {
615                     if (pp != h)
616                     {
617                         COMSTACK l = (COMSTACK)iochan_getdata(pp);
618                         cs_close(l);
619                         iochan_destroy(pp);
620                     }
621                 }
622                 sprintf(nbuf, "%s(%d)", me, getpid());
623                 yaz_log_init(control_block.loglevel, nbuf, 0);
624             }
625             else /* parent */
626             {
627                 close(hand[1]);
628                 /* wait for child to take the call */
629                 for (;;)
630                 {
631                     char dummy[1];
632                     int res;
633                     
634                     if ((res = read(hand[0], dummy, 1)) < 0 && errno != EINTR)
635                     {
636                         yaz_log(LOG_FATAL|LOG_ERRNO, "handshake read");
637                         return;
638                     }
639                     else if (res >= 0)
640                         break;
641                 }
642                 yaz_log(LOG_DEBUG, "P: Child has taken the call");
643                 close(hand[0]);
644                 return;
645             }
646         }
647         if ((res = cs_listen_check(line, 0, 0, control_block.check_ip,
648                                    control_block.daemon_name)) < 0)
649         {
650             yaz_log(LOG_WARN, "cs_listen failed");
651             return;
652         }
653         else if (res == 1)
654             return;
655         yaz_log(LOG_DEBUG, "listen ok");
656         iochan_setevent(h, EVENT_OUTPUT);
657         iochan_setflags(h, EVENT_OUTPUT | EVENT_EXCEPT); /* set up for acpt */
658     }
659     /* in dynamic mode, only the child ever comes down here */
660     else if (event == EVENT_OUTPUT)
661     {
662         COMSTACK new_line = cs_accept(line);
663
664         if (!new_line)
665         {
666             yaz_log(LOG_FATAL, "Accept failed.");
667             iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
668             return;
669         }
670         yaz_log(LOG_DEBUG, "accept ok");
671         if (control_block.dynamic)
672         {
673             IOCHAN pp;
674             /* close our half of the listener socket */
675             for (pp = pListener; pp; pp = iochan_getnext(pp))
676             {
677                 COMSTACK l = (COMSTACK)iochan_getdata(pp);
678                 cs_close(l);
679                 iochan_destroy(pp);
680             }
681             /* release dad */
682             yaz_log(LOG_DEBUG, "Releasing parent");
683             close(hand[1]);
684         }
685         else
686             iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
687
688 #if HAVE_PTHREAD_H
689         if (control_block.threads)
690         {
691             pthread_t child_thread;
692             pthread_create (&child_thread, 0, new_session, new_line);
693             pthread_detach (child_thread);
694         }
695         else
696             new_session(new_line);
697 #else
698         new_session(new_line);
699 #endif
700     }
701     else
702     {
703         yaz_log(LOG_FATAL, "Bad event on listener.");
704         iochan_destroy(h);
705         return;
706     }
707 }
708
709 static void *new_session (void *vp)
710 {
711     char *a;
712     association *newas;
713     IOCHAN new_chan;
714     COMSTACK new_line = (COMSTACK) vp;
715
716     unsigned cs_get_mask, cs_accept_mask, mask =  
717         ((new_line->io_pending & CS_WANT_WRITE) ? EVENT_OUTPUT : 0) |
718         ((new_line->io_pending & CS_WANT_READ) ? EVENT_INPUT : 0);
719
720     if (mask)    
721     {
722         cs_accept_mask = mask;  /* accept didn't complete */
723         cs_get_mask = 0;
724     }
725     else
726     {
727         cs_accept_mask = 0;     /* accept completed.  */
728         cs_get_mask = mask = EVENT_INPUT;
729     }
730
731     if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session, mask)))
732     {
733         yaz_log(LOG_FATAL, "Failed to create iochan");
734         return 0;
735     }
736     if (!(newas = create_association(new_chan, new_line)))
737     {
738         yaz_log(LOG_FATAL, "Failed to create new assoc.");
739         return 0;
740     }
741     newas->cs_accept_mask = cs_accept_mask;
742     newas->cs_get_mask = cs_get_mask;
743
744     iochan_setdata(new_chan, newas);
745     iochan_settimeout(new_chan, control_block.idle_timeout * 60);
746     a = cs_addrstr(new_line);
747     yaz_log(LOG_LOG, "Accepted connection from %s", a ? a : "[Unknown]");
748     
749     if (control_block.threads)
750     {
751         event_loop(&new_chan);
752     }
753     else
754     {
755         new_chan->next = pListener;
756         pListener = new_chan;
757     }
758     return 0;
759 }
760
761 #endif /* WIN32 */
762
763 static void inetd_connection(int what)
764 {
765     COMSTACK line;
766     IOCHAN chan;
767     association *assoc;
768     char *addr;
769
770     if ((line = cs_createbysocket(0, tcpip_type, 0, what)))
771     {
772         if ((chan = iochan_create(cs_fileno(line), ir_session, EVENT_INPUT)))
773         {
774             if ((assoc = create_association(chan, line)))
775             {
776                 iochan_setdata(chan, assoc);
777                 iochan_settimeout(chan, control_block.idle_timeout * 60);
778                 addr = cs_addrstr(line);
779                 yaz_log(LOG_LOG, "Inetd association from %s", addr ? addr : "[UNKNOWN]");
780             }
781             else
782             {
783                 yaz_log(LOG_FATAL, "Failed to create association structure");
784             }
785             chan->next = pListener;
786             pListener = chan;
787         }
788         else
789         {
790             yaz_log(LOG_FATAL, "Failed to create iochan");
791         }
792     }
793     else
794     {
795         yaz_log(LOG_ERRNO|LOG_FATAL, "Failed to create comstack on socket 0");
796     }
797 }
798
799 /*
800  * Set up a listening endpoint, and give it to the event-handler.
801  */
802 static void add_listener(char *where, int what)
803 {
804     COMSTACK l;
805     CS_TYPE type;
806     char mode[100], addr[100];
807     void *ap;
808     IOCHAN lst = NULL;
809
810     if (!where || sscanf(where, "%[^:]:%s", mode, addr) != 2)
811     {
812         yaz_log (LOG_WARN, "%s: Address format: ('tcp'|'ssl')':'<address>",
813                  me);
814         return;
815     }
816     if (!strcmp(mode, "tcp"))
817         type = tcpip_type;
818     else if (!strcmp(mode, "ssl"))
819     {
820 #if HAVE_OPENSSL_SSL_H
821         type = ssl_type;
822 #else
823         yaz_log (LOG_WARN, "SSL Transport not allowed by configuration.");
824         return;
825 #endif
826     }
827     else
828     {
829         yaz_log (LOG_WARN, "You must specify either 'ssl:' or 'tcp:'");
830         return;
831     }
832     yaz_log(LOG_LOG, "Adding %s %s listener on %s",
833             control_block.dynamic ? "dynamic" : 
834             (control_block.threads ? "threaded" : "static"),
835         what == PROTO_SR ? "SR" : "Z3950", where);
836     if (!(l = cs_create(type, 0, what)))
837     {
838         yaz_log(LOG_FATAL|LOG_ERRNO, "Failed to create listener");
839         return;
840     }
841     ap = cs_straddr (l, addr);
842     if (!ap)
843     {
844         fprintf(stderr, "Address resolution failed.\n");
845         cs_close (l);
846         return;
847     }
848     if (cs_bind(l, ap, CS_SERVER) < 0)
849     {
850         yaz_log(LOG_FATAL|LOG_ERRNO, "Failed to bind to %s", where);
851         cs_close (l);
852         return;
853     }
854     if (!(lst = iochan_create(cs_fileno(l), listener, EVENT_INPUT |
855          EVENT_EXCEPT)))
856     {
857         yaz_log(LOG_FATAL|LOG_ERRNO, "Failed to create IOCHAN-type");
858         cs_close (l);
859         return;
860     }
861     iochan_setdata(lst, l);
862
863     /* Ensure our listener chain is setup properly */
864     lst->next = pListener;
865     pListener = lst;
866 }
867
868 #ifndef WIN32
869 /* For windows we don't need to catch the signals */
870 static void catchchld(int num)
871 {
872     while (waitpid(-1, 0, WNOHANG) > 0)
873         ;
874     signal(SIGCHLD, catchchld);
875 }
876 #endif /* WIN32 */
877
878 statserv_options_block *statserv_getcontrol(void)
879 {
880     static statserv_options_block cb;
881
882     memcpy(&cb, &control_block, sizeof(cb));
883     return &cb;
884 }
885
886 void statserv_setcontrol(statserv_options_block *block)
887 {
888     memcpy(&control_block, block, sizeof(*block));
889 }
890
891 int statserv_start(int argc, char **argv)
892 {
893     int ret;
894
895     nmem_init ();
896 #ifdef WIN32
897     /* We need to initialize the thread list */
898     ThreadList_Initialize();
899 #endif /* WIN32 */
900     
901 #ifdef WIN32
902     if ((me = strrchr (argv[0], '\\')))
903         me++;
904     else
905         me = argv[0];
906 #else
907     me = argv[0];
908 #endif
909     if (control_block.options_func(argc, argv))
910         return(1);
911     
912     if (control_block.bend_start)
913         (*control_block.bend_start)(&control_block);
914 #ifdef WIN32
915     logf (LOG_LOG, "Starting server %s", me);
916 #else
917     if (control_block.inetd)
918         inetd_connection(control_block.default_proto);
919     else
920     {
921         logf (LOG_LOG, "Starting server %s pid=%d", me, getpid());
922 #if 0
923         sigset_t sigs_to_block;
924         
925         sigemptyset(&sigs_to_block);
926         sigaddset (&sigs_to_block, SIGTERM);
927         pthread_sigmask (SIG_BLOCK, &sigs_to_block, 0);
928         /* missing... */
929 #endif
930         if (control_block.dynamic)
931             signal(SIGCHLD, catchchld);
932     }
933     signal (SIGPIPE, SIG_IGN);
934     signal (SIGTERM, sigterm);
935     if (*control_block.setuid)
936     {
937         struct passwd *pw;
938         
939         if (!(pw = getpwnam(control_block.setuid)))
940         {
941             yaz_log(LOG_FATAL, "%s: Unknown user", control_block.setuid);
942             return(1);
943         }
944         if (setuid(pw->pw_uid) < 0)
945         {
946             yaz_log(LOG_FATAL|LOG_ERRNO, "setuid");
947             exit(1);
948         }
949     }
950 #endif /* WIN32 */
951
952     if ((pListener == NULL) && *control_block.default_listen)
953         add_listener(control_block.default_listen,
954                      control_block.default_proto);
955         
956     if (pListener == NULL)
957         ret = 1;
958     else
959     {
960         yaz_log(LOG_LOG, "Entering event loop.");
961         ret = event_loop(&pListener);
962     }
963     nmem_exit ();
964     return ret;
965 }
966
967 int check_options(int argc, char **argv)
968 {
969     int ret = 0, r;
970     char *arg;
971
972     while ((ret = options("1a:iszSTl:v:u:c:w:t:k:d:", argv, argc, &arg)) != -2)
973     {
974         switch (ret)
975         {
976         case 0:
977             add_listener(arg, control_block.default_proto);
978             break;
979         case '1':        
980             control_block.one_shot = 1;
981             control_block.dynamic = 0;
982             break;
983         case 'z':
984             control_block.default_proto = PROTO_Z3950;
985             break;
986         case 's':
987             control_block.default_proto = PROTO_SR;
988             break;
989         case 'S':
990             control_block.dynamic = 0;
991             break;
992         case 'T':
993 #if HAVE_PTHREAD_H
994             control_block.dynamic = 0;
995             control_block.threads = 1;
996 #else
997             fprintf(stderr, "%s: Threaded mode not available.\n", me);
998             return 1;
999 #endif
1000             break;
1001         case 'l':
1002             strcpy(control_block.logfile, arg ? arg : "");
1003             yaz_log_init(control_block.loglevel, me, control_block.logfile);
1004             break;
1005         case 'v':
1006             control_block.loglevel = yaz_log_mask_str(arg);
1007             yaz_log_init(control_block.loglevel, me, control_block.logfile);
1008             break;
1009         case 'a':
1010             strcpy(control_block.apdufile, arg ? arg : "");
1011             break;
1012         case 'u':
1013             strcpy(control_block.setuid, arg ? arg : "");
1014             break;
1015         case 'c':
1016             strcpy(control_block.configname, arg ? arg : "");
1017             break;
1018         case 'd':
1019             strcpy(control_block.daemon_name, arg ? arg : "");
1020             break;
1021         case 't':
1022             if (!arg || !(r = atoi(arg)))
1023             {
1024                 fprintf(stderr, "%s: Specify positive timeout for -t.\n", me);
1025                 return(1);
1026             }
1027             control_block.idle_timeout = r;
1028             break;
1029         case  'k':
1030             if (!arg || !(r = atoi(arg)))
1031             {
1032                 fprintf(stderr, "%s: Specify positive size for -k.\n", me);
1033                 return(1);
1034             }
1035             control_block.maxrecordsize = r * 1024;
1036             break;
1037         case 'i':
1038             control_block.inetd = 1;
1039             break;
1040         case 'w':
1041             if (chdir(arg))
1042             {
1043                 perror(arg);            
1044                 return 1;
1045             }
1046             break;
1047         default:
1048             fprintf(stderr, "Usage: %s [ -a <pdufile> -v <loglevel>"
1049                     " -l <logfile> -u <user> -c <config> -t <minutes>"
1050                     " -k <kilobytes> -d <daemon>"
1051                         " -zsiST -w <directory> <listender-addr>... ]\n", me);
1052             return 1;
1053         }
1054     }
1055     return 0;
1056 }
1057
1058 #ifdef WIN32
1059 typedef struct _Args
1060 {
1061     char **argv;
1062     int argc;
1063 } Args; 
1064
1065 static Args ArgDetails;
1066
1067 /* name of the executable */
1068 #define SZAPPNAME            "server"
1069
1070 /* list of service dependencies - "dep1\0dep2\0\0" */
1071 #define SZDEPENDENCIES       ""
1072
1073 int statserv_main(int argc, char **argv,
1074                   bend_initresult *(*bend_init)(bend_initrequest *r),
1075                   void (*bend_close)(void *handle))
1076 {
1077     statserv_options_block *cb = statserv_getcontrol();
1078     
1079     cb->bend_init = bend_init;
1080     cb->bend_close = bend_close;
1081
1082     statserv_setcontrol(cb);
1083
1084     /* Lets setup the Arg structure */
1085     ArgDetails.argc = argc;
1086     ArgDetails.argv = argv;
1087     
1088     /* Now setup the service with the service controller */
1089     SetupService(argc, argv, &ArgDetails, SZAPPNAME,
1090                  cb->service_name, /* internal service name */
1091                  cb->service_name, /* displayed name of the service */
1092                  SZDEPENDENCIES);
1093     return 0;
1094 }
1095
1096 int StartAppService(void *pHandle, int argc, char **argv)
1097 {
1098     /* Initializes the App */
1099     return 1;
1100 }
1101
1102 void RunAppService(void *pHandle)
1103 {
1104     Args *pArgs = (Args *)pHandle;
1105     
1106     /* Starts the app running */
1107     statserv_start(pArgs->argc, pArgs->argv);
1108 }
1109
1110 void StopAppService(void *pHandle)
1111 {
1112     /* Stops the app */
1113     statserv_closedown();
1114 }
1115 #else
1116 int statserv_main(int argc, char **argv,
1117                   bend_initresult *(*bend_init)(bend_initrequest *r),
1118                   void (*bend_close)(void *handle))
1119 {
1120     int ret;
1121     statserv_options_block *cb = statserv_getcontrol();
1122     
1123     cb->bend_init = bend_init;
1124     cb->bend_close = bend_close;
1125
1126     statserv_setcontrol(cb);
1127     ret = statserv_start (argc, argv);
1128     statserv_closedown ();
1129     return ret;
1130 }
1131 #endif