2 * Copyright (c) 1995-1999, Index Data
3 * See the file LICENSE for details.
4 * Sebastian Hammer, Adam Dickmeiss
6 * NT server based on threads by
7 * Chas Woodfield, Fretwell Downing Datasystems.
10 * Revision 1.54 1999-04-16 14:45:55 adam
11 * Added interface for tcpd wrapper for access control.
13 * Revision 1.53 1999/02/02 13:57:39 adam
14 * Uses preprocessor define WIN32 instead of WINDOWS to build code
15 * for Microsoft WIN32.
17 * Revision 1.52 1998/08/21 14:13:34 adam
18 * Added GNU Configure script to build Makefiles.
20 * Revision 1.51 1998/07/07 15:51:03 adam
21 * Changed server so that it stops if bind fails - "address already in
22 * use" typically causes this.
24 * Revision 1.50 1998/06/22 11:32:39 adam
25 * Added 'conditional cs_listen' feature.
27 * Revision 1.49 1998/02/27 14:04:55 adam
28 * Fixed bug in statserv_remove.
30 * Revision 1.48 1998/02/11 11:53:36 adam
31 * Changed code so that it compiles as C++.
33 * Revision 1.47 1998/02/10 10:28:57 adam
34 * Added app_name, service_dependencies, service_display_name and
35 * options_func. options_func allows us to specify a different function
36 * to interogate the command line arguments. The other members allow us
37 * to pass the full service details accross to the service manager (CW).
40 * Revision 1.46 1998/01/30 15:24:57 adam
41 * Fixed bug in inetd code. The server listened on tcp:@:9999 even
42 * though it was started in inetd mode.
44 * Revision 1.45 1998/01/29 13:30:23 adam
45 * Better event handle system for NT/Unix.
47 * Revision 1.44 1997/11/07 13:31:52 adam
48 * Added NT Service name part of statserv_options_block. Moved NT
49 * service utility to server library.
51 * Revision 1.43 1997/10/31 12:20:09 adam
52 * Improved memory debugging for xmalloc/nmem.c. References to NMEM
53 * instead of ODR in n ESPEC-1 handling in source d1_espec.c.
54 * Bug fix: missing fclose in data1_read_espec1.
56 * Revision 1.42 1997/10/27 14:03:02 adam
57 * Added new member to statserver_options_block, pre_init, which
58 * specifies a callback to be invoked after command line parsing and
59 * before the server listens for the first time.
61 * Revision 1.41 1997/09/29 07:19:32 adam
62 * Server library uses nmem_init/nmem_exit. The log prefix no longer
63 * includes leading path on NT.
65 * Revision 1.40 1997/09/17 12:10:41 adam
68 * Revision 1.39 1997/09/09 10:10:19 adam
69 * Another MSV5.0 port. Changed projects to include proper
70 * library/include paths.
71 * Server starts server in test-mode when no options are given.
73 * Revision 1.38 1997/09/04 14:19:14 adam
76 * Revision 1.37 1997/09/01 08:53:01 adam
77 * New windows NT/95 port using MSV5.0. The test server 'ztest' was
78 * moved a separate directory. MSV5.0 project server.dsp created.
79 * As an option, the server can now operate as an NT service.
81 * Revision 1.36 1996/07/06 19:58:36 quinn
82 * System headerfiles gathered in yconfig
84 * Revision 1.35 1996/05/29 10:03:28 quinn
87 * Revision 1.34 1996/02/21 13:12:07 quinn
88 * *** empty log message ***
90 * Revision 1.33 1996/02/10 12:23:49 quinn
91 * Enable inetd operations fro TCP/IP stack
93 * Revision 1.32 1996/01/19 15:41:52 quinn
94 * *** empty log message ***
96 * Revision 1.31 1995/11/17 11:09:39 adam
97 * Added new option '-c' to specify configuration name in control block.
99 * Revision 1.30 1995/11/01 13:54:59 quinn
102 * Revision 1.29 1995/10/30 12:41:29 quinn
103 * Added hostname lookup for server.
105 * Revision 1.28 1995/09/29 17:12:30 quinn
108 * Revision 1.27 1995/09/27 15:03:02 quinn
109 * Modified function heads & prototypes.
111 * Revision 1.26 1995/08/29 14:44:51 quinn
114 * Revision 1.25 1995/08/29 11:18:02 quinn
115 * Added code to receive close
117 * Revision 1.24 1995/06/16 10:31:39 quinn
118 * Added session timeout.
120 * Revision 1.23 1995/06/15 12:30:48 quinn
123 * Revision 1.22 1995/06/15 07:45:17 quinn
126 * Revision 1.21 1995/06/06 08:15:40 quinn
129 * Revision 1.20 1995/05/29 08:12:09 quinn
132 * Revision 1.19 1995/05/16 09:37:27 quinn
135 * Revision 1.18 1995/05/16 08:51:09 quinn
136 * License, documentation, and memory fixes
138 * Revision 1.17 1995/05/15 11:56:42 quinn
139 * Asynchronous facilities. Restructuring of seshigh code.
141 * Revision 1.16 1995/04/10 10:23:40 quinn
142 * Some work to add scan and other things.
144 * Revision 1.15 1995/03/31 10:16:51 quinn
147 * Revision 1.14 1995/03/31 09:18:58 quinn
150 * Revision 1.13 1995/03/30 16:08:39 quinn
153 * Revision 1.12 1995/03/30 13:29:02 quinn
156 * Revision 1.11 1995/03/30 12:18:17 quinn
159 * Revision 1.10 1995/03/29 15:40:16 quinn
160 * Ongoing work. Statserv is now dynamic by default
162 * Revision 1.9 1995/03/27 08:34:30 quinn
163 * Added dynamic server functionality.
164 * Released bindings to session.c (is now redundant)
166 * Revision 1.8 1995/03/20 09:46:26 quinn
169 * Revision 1.7 1995/03/16 13:29:04 quinn
170 * Partitioned server.
172 * Revision 1.6 1995/03/15 15:18:52 quinn
173 * Little changes to better support nonblocking I/O
176 * Revision 1.5 1995/03/15 08:37:45 quinn
177 * Now we're pretty much set for nonblocking I/O.
179 * Revision 1.4 1995/03/14 16:59:48 quinn
182 * Revision 1.3 1995/03/14 11:30:15 quinn
185 * Revision 1.2 1995/03/14 10:28:03 quinn
186 * More work on demo server.
188 * Revision 1.1 1995/03/10 18:22:45 quinn
189 * The rudiments of an asynchronous server.
208 #include <comstack.h>
217 #include <statserv.h>
219 static IOCHAN pListener = NULL;
221 static char *me = "statserver";
225 int check_options(int argc, char **argv);
226 statserv_options_block control_block = {
227 1, /* dynamic mode */
228 LOG_DEFAULT_LEVEL, /* log level */
230 "", /* diagnostic output to stderr */
231 "tcp:@:9999", /* default listener port */
232 PROTO_Z3950, /* default application protocol */
233 60, /* idle timeout (minutes) */
234 1024*1024, /* maximum PDU size (approx.) to allow */
235 "default-config", /* configuration name to pass to backend */
236 "", /* set user id */
237 NULL, /* pre init handler */
238 check_options, /* Default routine, for checking the run-time arguments */
241 0 /* default value for inet deamon */
244 ,"Z39.50 Server", /* NT Service Name */
245 "Server", /* NT application Name */
246 "", /* NT Service Dependencies */
247 "Z39.50 Server" /* NT Service Display Name */
252 * handle incoming connect requests.
253 * The dynamic mode is a bit tricky mostly because we want to avoid
254 * doing all of the listening and accepting in the parent - it's
259 typedef struct _ThreadList ThreadList;
268 static ThreadList *pFirstThread;
269 static CRITICAL_SECTION Thread_CritSect;
270 static BOOL bInitialized = FALSE;
272 static void ThreadList_Initialize()
274 /* Initialize the critical Sections */
275 InitializeCriticalSection(&Thread_CritSect);
277 /* Set the first thraed */
280 /* we have been initialized */
284 static void statserv_add(HANDLE hThread, IOCHAN pIOChannel)
286 /* Only one thread can go through this section at a time */
287 EnterCriticalSection(&Thread_CritSect);
290 /* Lets create our new object */
291 ThreadList *pNewThread = (ThreadList *)malloc(sizeof(ThreadList));
292 pNewThread->hThread = hThread;
293 pNewThread->pIOChannel = pIOChannel;
294 pNewThread->pNext = pFirstThread;
295 pFirstThread = pNewThread;
297 /* Lets let somebody else create a new object now */
298 LeaveCriticalSection(&Thread_CritSect);
302 void statserv_remove(IOCHAN pIOChannel)
304 /* Only one thread can go through this section at a time */
305 EnterCriticalSection(&Thread_CritSect);
308 ThreadList *pCurrentThread = pFirstThread;
309 ThreadList *pNextThread;
310 ThreadList *pPrevThread =NULL;
312 /* Step through alll the threads */
313 for (; pCurrentThread != NULL; pCurrentThread = pNextThread)
315 /* We only need to compare on the IO Channel */
316 if (pCurrentThread->pIOChannel == pIOChannel)
318 /* We have found the thread we want to delete */
319 /* First of all reset the next pointers */
320 if (pPrevThread == NULL)
321 pFirstThread = pCurrentThread->pNext;
323 pPrevThread->pNext = pCurrentThread->pNext;
325 /* All we need todo now is delete the memory */
326 free(pCurrentThread);
328 /* No need to look at any more threads */
333 /* We need to look at another thread */
334 pNextThread = pCurrentThread->pNext;
335 pPrevThread = pCurrentThread;
339 /* Lets let somebody else remove an object now */
340 LeaveCriticalSection(&Thread_CritSect);
344 void statserv_closedown()
346 /* Shouldn't do anything if we are not initialized */
350 HANDLE *pThreadHandles = NULL;
352 /* We need to stop threads adding and removing while we */
353 /* start the closedown process */
354 EnterCriticalSection(&Thread_CritSect);
357 /* We have exclusive access to the thread stuff now */
358 /* Y didn't i use a semaphore - Oh well never mind */
359 ThreadList *pCurrentThread = pFirstThread;
361 /* Before we do anything else, we need to shutdown the listener */
362 if (pListener != NULL)
363 iochan_destroy(pListener);
365 for (; pCurrentThread != NULL; pCurrentThread = pCurrentThread->pNext)
367 /* Just destroy the IOCHAN, that should do the trick */
368 iochan_destroy(pCurrentThread->pIOChannel);
370 /* Keep a running count of our handles */
376 HANDLE *pCurrentHandle ;
378 /* Allocate the thread handle array */
379 pThreadHandles = (HANDLE *)malloc(sizeof(HANDLE) * iHandles);
380 pCurrentHandle = pThreadHandles;
382 for (pCurrentThread = pFirstThread;
383 pCurrentThread != NULL;
384 pCurrentThread = pCurrentThread->pNext, pCurrentHandle++)
386 /* Just the handle */
387 *pCurrentHandle = pCurrentThread->hThread;
391 /* We can now leave the critical section */
392 LeaveCriticalSection(&Thread_CritSect);
395 /* Now we can really do something */
398 /* This will now wait, until all the threads close */
399 WaitForMultipleObjects(iHandles, pThreadHandles, TRUE, INFINITE);
401 /* Free the memory we allocated for the handle array */
402 free(pThreadHandles);
405 /* No longer require the critical section, since all threads are dead */
406 DeleteCriticalSection(&Thread_CritSect);
410 int __stdcall event_loop_thread (IOCHAN iochan)
412 return event_loop (&iochan);
415 static void listener(IOCHAN h, int event)
417 COMSTACK line = (COMSTACK) iochan_getdata(h);
422 if (event == EVENT_INPUT)
424 if ((res = cs_listen(line, 0, 0)) < 0)
426 logf(LOG_FATAL, "cs_listen failed");
431 logf(LOG_DEBUG, "listen ok");
432 iochan_setevent(h, EVENT_OUTPUT);
433 iochan_setflags(h, EVENT_OUTPUT | EVENT_EXCEPT); /* set up for acpt */
435 else if (event == EVENT_OUTPUT)
442 if (!(new_line = cs_accept(line)))
444 logf(LOG_FATAL, "Accept failed.");
445 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
448 logf(LOG_DEBUG, "Accept ok");
450 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session,
453 logf(LOG_FATAL, "Failed to create iochan");
458 logf(LOG_DEBUG, "Creating association");
459 if (!(newas = create_association(new_chan, new_line)))
461 logf(LOG_FATAL, "Failed to create new assoc.");
465 logf(LOG_DEBUG, "Setting timeout %d", control_block.idle_timeout);
466 iochan_setdata(new_chan, newas);
467 iochan_settimeout(new_chan, control_block.idle_timeout * 60);
469 logf(LOG_DEBUG, "Determining client address");
470 a = cs_addrstr(new_line);
471 logf(LOG_LOG, "Accepted connection from %s", a ? a : "[Unknown]");
473 /* Now what we need todo is create a new thread with this iochan as
475 /* if (CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)event_loop_thread,
476 new_chan, 0, &ThreadId) == NULL) */
477 /* Somehow, somewhere we need to store this thread id, otherwise we
478 won't be able to close cleanly */
479 NewHandle = (HANDLE)_beginthreadex(NULL, 0, event_loop_thread,
480 new_chan, 0, &ThreadId);
481 if (NewHandle == (HANDLE)-1)
484 logf(LOG_FATAL|LOG_ERRNO, "Failed to create new thread.");
488 /* We successfully created the thread, so add it to the list */
489 statserv_add(NewHandle, new_chan);
491 logf(LOG_DEBUG, "Created new thread, iochan %p", new_chan);
492 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
496 logf(LOG_FATAL, "Bad event on listener.");
504 /* To save having an #ifdef in event_loop we need to define this empty function */
505 void statserv_remove(IOCHAN pIOChannel)
509 void statserv_closedown()
512 for (p = pListener; p; p = p->next)
516 static void listener(IOCHAN h, int event)
518 COMSTACK line = (COMSTACK) iochan_getdata(h);
521 static int child = 0;
524 if (event == EVENT_INPUT)
526 if (control_block.dynamic && !child)
532 logf(LOG_FATAL|LOG_ERRNO, "pipe");
536 if ((res = fork()) < 0)
538 logf(LOG_FATAL|LOG_ERRNO, "fork");
542 else if (res == 0) /* child */
549 for (pp = pListener; pp; pp = iochan_getnext(pp))
553 COMSTACK l = (COMSTACK)iochan_getdata(pp);
558 sprintf(nbuf, "%s(%d)", me, getpid());
559 log_init(control_block.loglevel, nbuf, 0);
564 /* wait for child to take the call */
570 if ((res = read(hand[0], dummy, 1)) < 0 && errno != EINTR)
572 logf(LOG_FATAL|LOG_ERRNO, "handshake read");
578 logf(LOG_DEBUG, "P: Child has taken the call");
583 if ((res = cs_listen_check(line, 0, 0, control_block.check_ip,
584 control_block.daemon_name)) < 0)
586 logf(LOG_WARN, "cs_listen failed");
591 logf(LOG_DEBUG, "listen ok");
592 iochan_setevent(h, EVENT_OUTPUT);
593 iochan_setflags(h, EVENT_OUTPUT | EVENT_EXCEPT); /* set up for acpt */
595 /* in dynamic mode, only the child ever comes down here */
596 else if (event == EVENT_OUTPUT)
602 if (!(new_line = cs_accept(line)))
604 logf(LOG_FATAL, "Accept failed.");
605 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
608 logf(LOG_DEBUG, "accept ok");
609 if (control_block.dynamic)
612 /* close our half of the listener socket */
613 for (pp = pListener; pp; pp = iochan_getnext(pp))
615 COMSTACK l = (COMSTACK)iochan_getdata(pp);
620 logf(LOG_DEBUG, "Releasing parent");
624 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
626 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session,
629 logf(LOG_FATAL, "Failed to create iochan");
633 new_chan->next = pListener;
634 pListener = new_chan;
635 if (!(newas = create_association(new_chan, new_line)))
637 logf(LOG_FATAL, "Failed to create new assoc.");
641 iochan_setdata(new_chan, newas);
642 iochan_settimeout(new_chan, control_block.idle_timeout * 60);
643 a = cs_addrstr(new_line);
644 logf(LOG_LOG, "Accepted connection from %s", a ? a : "[Unknown]");
648 logf(LOG_FATAL, "Bad event on listener.");
656 static void inetd_connection(int what)
663 if ((line = cs_createbysocket(0, tcpip_type, 0, what)))
665 if ((chan = iochan_create(cs_fileno(line), ir_session, EVENT_INPUT)))
667 if ((assoc = create_association(chan, line)))
669 iochan_setdata(chan, assoc);
670 iochan_settimeout(chan, control_block.idle_timeout * 60);
671 addr = cs_addrstr(line);
672 logf(LOG_LOG, "Inetd association from %s", addr ? addr : "[UNKNOWN]");
676 logf(LOG_FATAL, "Failed to create association structure");
678 chan->next = pListener;
683 logf(LOG_FATAL, "Failed to create iochan");
688 logf(LOG_ERRNO|LOG_FATAL, "Failed to create comstack on socket 0");
693 * Set up a listening endpoint, and give it to the event-handler.
695 static void add_listener(char *where, int what)
699 char mode[100], addr[100];
703 if (!where || sscanf(where, "%[^:]:%s", mode, addr) != 2)
705 logf (LOG_WARN, "%s: Address format: ('tcp'|'osi')':'<address>", me);
708 if (!strcmp(mode, "tcp"))
710 else if (!strcmp(mode, "osi"))
715 logf (LOG_WARN, "OSI Transport not allowed by configuration.");
721 logf (LOG_WARN, "You must specify either 'osi:' or 'tcp:'");
724 logf(LOG_LOG, "Adding %s %s listener on %s",
725 control_block.dynamic ? "dynamic" : "static",
726 what == PROTO_SR ? "SR" : "Z3950", where);
727 if (!(l = cs_create(type, 0, what)))
729 logf(LOG_FATAL|LOG_ERRNO, "Failed to create listener");
732 ap = cs_straddr (l, addr);
735 fprintf(stderr, "Address resolution failed.\n");
739 if (cs_bind(l, ap, CS_SERVER) < 0)
741 logf(LOG_FATAL|LOG_ERRNO, "Failed to bind to %s", where);
745 if (!(lst = iochan_create(cs_fileno(l), listener, EVENT_INPUT |
748 logf(LOG_FATAL|LOG_ERRNO, "Failed to create IOCHAN-type");
752 iochan_setdata(lst, l);
754 /* Ensure our listener chain is setup properly */
755 lst->next = pListener;
760 /* For windows we don't need to catch the signals */
761 static void catchchld(int num)
763 while (waitpid(-1, 0, WNOHANG) > 0)
765 signal(SIGCHLD, catchchld);
769 statserv_options_block *statserv_getcontrol(void)
771 static statserv_options_block cb;
773 memcpy(&cb, &control_block, sizeof(cb));
777 void statserv_setcontrol(statserv_options_block *block)
779 memcpy(&control_block, block, sizeof(*block));
782 int statserv_start(int argc, char **argv)
788 /* We need to initialize the thread list */
789 ThreadList_Initialize();
793 if ((me = strrchr (argv[0], '\\')))
800 if (control_block.options_func(argc, argv))
804 if (control_block.inetd)
805 inetd_connection(control_block.default_proto);
808 if (control_block.pre_init)
809 (*control_block.pre_init)(&control_block);
810 if (control_block.dynamic)
811 signal(SIGCHLD, catchchld);
813 if (*control_block.setuid)
817 if (!(pw = getpwnam(control_block.setuid)))
819 logf(LOG_FATAL, "%s: Unknown user", control_block.setuid);
822 if (setuid(pw->pw_uid) < 0)
824 logf(LOG_FATAL|LOG_ERRNO, "setuid");
830 if ((pListener == NULL) && *control_block.default_listen)
831 add_listener(control_block.default_listen,
832 control_block.default_proto);
834 if (pListener == NULL)
838 logf(LOG_LOG, "Entering event loop.");
839 ret = event_loop(&pListener);
845 int check_options(int argc, char **argv)
850 while ((ret = options("a:iszSl:v:u:c:w:t:k:d:", argv, argc, &arg)) != -2)
855 add_listener(arg, control_block.default_proto);
858 control_block.default_proto = PROTO_Z3950;
861 control_block.default_proto = PROTO_SR;
864 control_block.dynamic = 0;
867 strcpy(control_block.logfile, arg ? arg : "");
868 log_init(control_block.loglevel, me, control_block.logfile);
871 control_block.loglevel = log_mask_str(arg);
872 log_init(control_block.loglevel, me, control_block.logfile);
875 strcpy(control_block.apdufile, arg ? arg : "");
878 strcpy(control_block.setuid, arg ? arg : "");
881 strcpy(control_block.configname, arg ? arg : "");
884 strcpy(control_block.daemon_name, arg ? arg : "");
887 if (!arg || !(r = atoi(arg)))
889 fprintf(stderr, "%s: Specify positive timeout for -t.\n", me);
892 control_block.idle_timeout = r;
895 if (!arg || !(r = atoi(arg)))
897 fprintf(stderr, "%s: Specify positive size for -k.\n", me);
900 control_block.maxrecordsize = r * 1024;
903 control_block.inetd = 1;
913 fprintf(stderr, "Usage: %s [ -i -a <pdufile> -v <loglevel>"
914 " -l <logfile> -u <user> -c <config> -t <minutes>"
915 " -k <kilobytes> -d <daemon>"
916 " -zsS <listener-addr> -w <directory> ... ]\n", me);
930 static Args ArgDetails;
932 /* name of the executable */
933 #define SZAPPNAME "server"
935 /* list of service dependencies - "dep1\0dep2\0\0" */
936 #define SZDEPENDENCIES ""
938 int statserv_main(int argc, char **argv)
940 statserv_options_block *cb = statserv_getcontrol();
942 /* Lets setup the Arg structure */
943 ArgDetails.argc = argc;
944 ArgDetails.argv = argv;
946 /* Now setup the service with the service controller */
947 SetupService(argc, argv, &ArgDetails, SZAPPNAME,
948 cb->service_name, /* internal service name */
949 cb->service_name, /* displayed name of the service */
954 int StartAppService(void *pHandle, int argc, char **argv)
956 /* Initializes the App */
960 void RunAppService(void *pHandle)
962 Args *pArgs = (Args *)pHandle;
964 /* Starts the app running */
965 statserv_start(pArgs->argc, pArgs->argv);
968 void StopAppService(void *pHandle)
971 statserv_closedown();
974 int statserv_main(int argc, char **argv)
976 int ret = statserv_start (argc, argv);
977 statserv_closedown ();