2 * Copyright (c) 1995-1998, 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.50 1998-06-22 11:32:39 adam
11 * Added 'conditional cs_listen' feature.
13 * Revision 1.49 1998/02/27 14:04:55 adam
14 * Fixed bug in statserv_remove.
16 * Revision 1.48 1998/02/11 11:53:36 adam
17 * Changed code so that it compiles as C++.
19 * Revision 1.47 1998/02/10 10:28:57 adam
20 * Added app_name, service_dependencies, service_display_name and
21 * options_func. options_func allows us to specify a different function
22 * to interogate the command line arguments. The other members allow us
23 * to pass the full service details accross to the service manager (CW).
26 * Revision 1.46 1998/01/30 15:24:57 adam
27 * Fixed bug in inetd code. The server listened on tcp:@:9999 even
28 * though it was started in inetd mode.
30 * Revision 1.45 1998/01/29 13:30:23 adam
31 * Better event handle system for NT/Unix.
33 * Revision 1.44 1997/11/07 13:31:52 adam
34 * Added NT Service name part of statserv_options_block. Moved NT
35 * service utility to server library.
37 * Revision 1.43 1997/10/31 12:20:09 adam
38 * Improved memory debugging for xmalloc/nmem.c. References to NMEM
39 * instead of ODR in n ESPEC-1 handling in source d1_espec.c.
40 * Bug fix: missing fclose in data1_read_espec1.
42 * Revision 1.42 1997/10/27 14:03:02 adam
43 * Added new member to statserver_options_block, pre_init, which
44 * specifies a callback to be invoked after command line parsing and
45 * before the server listens for the first time.
47 * Revision 1.41 1997/09/29 07:19:32 adam
48 * Server library uses nmem_init/nmem_exit. The log prefix no longer
49 * includes leading path on NT.
51 * Revision 1.40 1997/09/17 12:10:41 adam
54 * Revision 1.39 1997/09/09 10:10:19 adam
55 * Another MSV5.0 port. Changed projects to include proper
56 * library/include paths.
57 * Server starts server in test-mode when no options are given.
59 * Revision 1.38 1997/09/04 14:19:14 adam
62 * Revision 1.37 1997/09/01 08:53:01 adam
63 * New windows NT/95 port using MSV5.0. The test server 'ztest' was
64 * moved a separate directory. MSV5.0 project server.dsp created.
65 * As an option, the server can now operate as an NT service.
67 * Revision 1.36 1996/07/06 19:58:36 quinn
68 * System headerfiles gathered in yconfig
70 * Revision 1.35 1996/05/29 10:03:28 quinn
73 * Revision 1.34 1996/02/21 13:12:07 quinn
74 * *** empty log message ***
76 * Revision 1.33 1996/02/10 12:23:49 quinn
77 * Enable inetd operations fro TCP/IP stack
79 * Revision 1.32 1996/01/19 15:41:52 quinn
80 * *** empty log message ***
82 * Revision 1.31 1995/11/17 11:09:39 adam
83 * Added new option '-c' to specify configuration name in control block.
85 * Revision 1.30 1995/11/01 13:54:59 quinn
88 * Revision 1.29 1995/10/30 12:41:29 quinn
89 * Added hostname lookup for server.
91 * Revision 1.28 1995/09/29 17:12:30 quinn
94 * Revision 1.27 1995/09/27 15:03:02 quinn
95 * Modified function heads & prototypes.
97 * Revision 1.26 1995/08/29 14:44:51 quinn
100 * Revision 1.25 1995/08/29 11:18:02 quinn
101 * Added code to receive close
103 * Revision 1.24 1995/06/16 10:31:39 quinn
104 * Added session timeout.
106 * Revision 1.23 1995/06/15 12:30:48 quinn
109 * Revision 1.22 1995/06/15 07:45:17 quinn
112 * Revision 1.21 1995/06/06 08:15:40 quinn
115 * Revision 1.20 1995/05/29 08:12:09 quinn
118 * Revision 1.19 1995/05/16 09:37:27 quinn
121 * Revision 1.18 1995/05/16 08:51:09 quinn
122 * License, documentation, and memory fixes
124 * Revision 1.17 1995/05/15 11:56:42 quinn
125 * Asynchronous facilities. Restructuring of seshigh code.
127 * Revision 1.16 1995/04/10 10:23:40 quinn
128 * Some work to add scan and other things.
130 * Revision 1.15 1995/03/31 10:16:51 quinn
133 * Revision 1.14 1995/03/31 09:18:58 quinn
136 * Revision 1.13 1995/03/30 16:08:39 quinn
139 * Revision 1.12 1995/03/30 13:29:02 quinn
142 * Revision 1.11 1995/03/30 12:18:17 quinn
145 * Revision 1.10 1995/03/29 15:40:16 quinn
146 * Ongoing work. Statserv is now dynamic by default
148 * Revision 1.9 1995/03/27 08:34:30 quinn
149 * Added dynamic server functionality.
150 * Released bindings to session.c (is now redundant)
152 * Revision 1.8 1995/03/20 09:46:26 quinn
155 * Revision 1.7 1995/03/16 13:29:04 quinn
156 * Partitioned server.
158 * Revision 1.6 1995/03/15 15:18:52 quinn
159 * Little changes to better support nonblocking I/O
162 * Revision 1.5 1995/03/15 08:37:45 quinn
163 * Now we're pretty much set for nonblocking I/O.
165 * Revision 1.4 1995/03/14 16:59:48 quinn
168 * Revision 1.3 1995/03/14 11:30:15 quinn
171 * Revision 1.2 1995/03/14 10:28:03 quinn
172 * More work on demo server.
174 * Revision 1.1 1995/03/10 18:22:45 quinn
175 * The rudiments of an asynchronous server.
196 #include <comstack.h>
204 #include <statserv.h>
206 static IOCHAN pListener = NULL;
208 static char *me = "statserver";
212 int check_options(int argc, char **argv);
213 statserv_options_block control_block = {
214 1, /* dynamic mode */
215 LOG_DEFAULT_LEVEL, /* log level */
217 "", /* diagnostic output to stderr */
218 "tcp:@:9999", /* default listener port */
219 PROTO_Z3950, /* default application protocol */
220 60, /* idle timeout (minutes) */
221 1024*1024, /* maximum PDU size (approx.) to allow */
222 "default-config", /* configuration name to pass to backend */
223 "", /* set user id */
224 NULL, /* pre init handler */
225 check_options, /* Default routine, for checking the run-time arguments */
226 0 /* default value for inet deamon */
229 ,"Z39.50 Server", /* NT Service Name */
230 "Server", /* NT application Name */
231 "", /* NT Service Dependencies */
232 "Z39.50 Server" /* NT Service Display Name */
237 * handle incoming connect requests.
238 * The dynamic mode is a bit tricky mostly because we want to avoid
239 * doing all of the listening and accepting in the parent - it's
244 typedef struct _ThreadList ThreadList;
253 static ThreadList *pFirstThread;
254 static CRITICAL_SECTION Thread_CritSect;
255 static BOOL bInitialized = FALSE;
257 static void ThreadList_Initialize()
259 /* Initialize the critical Sections */
260 InitializeCriticalSection(&Thread_CritSect);
262 /* Set the first thraed */
265 /* we have been initialized */
269 static void statserv_add(HANDLE hThread, IOCHAN pIOChannel)
271 /* Only one thread can go through this section at a time */
272 EnterCriticalSection(&Thread_CritSect);
275 /* Lets create our new object */
276 ThreadList *pNewThread = (ThreadList *)malloc(sizeof(ThreadList));
277 pNewThread->hThread = hThread;
278 pNewThread->pIOChannel = pIOChannel;
279 pNewThread->pNext = pFirstThread;
280 pFirstThread = pNewThread;
282 /* Lets let somebody else create a new object now */
283 LeaveCriticalSection(&Thread_CritSect);
287 void statserv_remove(IOCHAN pIOChannel)
289 /* Only one thread can go through this section at a time */
290 EnterCriticalSection(&Thread_CritSect);
293 ThreadList *pCurrentThread = pFirstThread;
294 ThreadList *pNextThread;
295 ThreadList *pPrevThread =NULL;
297 /* Step through alll the threads */
298 for (; pCurrentThread != NULL; pCurrentThread = pNextThread)
300 /* We only need to compare on the IO Channel */
301 if (pCurrentThread->pIOChannel == pIOChannel)
303 /* We have found the thread we want to delete */
304 /* First of all reset the next pointers */
305 if (pPrevThread == NULL)
306 pFirstThread = pCurrentThread->pNext;
308 pPrevThread->pNext = pCurrentThread->pNext;
310 /* All we need todo now is delete the memory */
311 free(pCurrentThread);
313 /* No need to look at any more threads */
318 /* We need to look at another thread */
319 pNextThread = pCurrentThread->pNext;
320 pPrevThread = pCurrentThread;
324 /* Lets let somebody else remove an object now */
325 LeaveCriticalSection(&Thread_CritSect);
329 void statserv_closedown()
331 /* Shouldn't do anything if we are not initialized */
335 HANDLE *pThreadHandles = NULL;
337 /* We need to stop threads adding and removing while we */
338 /* start the closedown process */
339 EnterCriticalSection(&Thread_CritSect);
342 /* We have exclusive access to the thread stuff now */
343 /* Y didn't i use a semaphore - Oh well never mind */
344 ThreadList *pCurrentThread = pFirstThread;
346 /* Before we do anything else, we need to shutdown the listener */
347 if (pListener != NULL)
348 iochan_destroy(pListener);
350 for (; pCurrentThread != NULL; pCurrentThread = pCurrentThread->pNext)
352 /* Just destroy the IOCHAN, that should do the trick */
353 iochan_destroy(pCurrentThread->pIOChannel);
355 /* Keep a running count of our handles */
361 HANDLE *pCurrentHandle ;
363 /* Allocate the thread handle array */
364 pThreadHandles = (HANDLE *)malloc(sizeof(HANDLE) * iHandles);
365 pCurrentHandle = pThreadHandles;
367 for (pCurrentThread = pFirstThread;
368 pCurrentThread != NULL;
369 pCurrentThread = pCurrentThread->pNext, pCurrentHandle++)
371 /* Just the handle */
372 *pCurrentHandle = pCurrentThread->hThread;
376 /* We can now leave the critical section */
377 LeaveCriticalSection(&Thread_CritSect);
380 /* Now we can really do something */
383 /* This will now wait, until all the threads close */
384 WaitForMultipleObjects(iHandles, pThreadHandles, TRUE, INFINITE);
386 /* Free the memory we allocated for the handle array */
387 free(pThreadHandles);
390 /* No longer require the critical section, since all threads are dead */
391 DeleteCriticalSection(&Thread_CritSect);
395 int __stdcall event_loop_thread (IOCHAN iochan)
397 return event_loop (&iochan);
400 static void listener(IOCHAN h, int event)
402 COMSTACK line = (COMSTACK) iochan_getdata(h);
407 if (event == EVENT_INPUT)
409 if ((res = cs_listen(line, 0, 0)) < 0)
411 logf(LOG_FATAL, "cs_listen failed");
416 logf(LOG_DEBUG, "listen ok");
417 iochan_setevent(h, EVENT_OUTPUT);
418 iochan_setflags(h, EVENT_OUTPUT | EVENT_EXCEPT); /* set up for acpt */
420 else if (event == EVENT_OUTPUT)
427 if (!(new_line = cs_accept(line)))
429 logf(LOG_FATAL, "Accept failed.");
430 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
433 logf(LOG_DEBUG, "Accept ok");
435 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session,
438 logf(LOG_FATAL, "Failed to create iochan");
443 logf(LOG_DEBUG, "Creating association");
444 if (!(newas = create_association(new_chan, new_line)))
446 logf(LOG_FATAL, "Failed to create new assoc.");
450 logf(LOG_DEBUG, "Setting timeout %d", control_block.idle_timeout);
451 iochan_setdata(new_chan, newas);
452 iochan_settimeout(new_chan, control_block.idle_timeout * 60);
454 logf(LOG_DEBUG, "Determining client address");
455 a = cs_addrstr(new_line);
456 logf(LOG_LOG, "Accepted connection from %s", a ? a : "[Unknown]");
458 /* Now what we need todo is create a new thread with this iochan as
460 /* if (CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)event_loop_thread,
461 new_chan, 0, &ThreadId) == NULL) */
462 /* Somehow, somewhere we need to store this thread id, otherwise we
463 won't be able to close cleanly */
464 NewHandle = (HANDLE)_beginthreadex(NULL, 0, event_loop_thread,
465 new_chan, 0, &ThreadId);
466 if (NewHandle == (HANDLE)-1)
469 logf(LOG_FATAL|LOG_ERRNO, "Failed to create new thread.");
473 /* We successfully created the thread, so add it to the list */
474 statserv_add(NewHandle, new_chan);
476 logf(LOG_DEBUG, "Created new thread, iochan %p", new_chan);
477 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
481 logf(LOG_FATAL, "Bad event on listener.");
489 /* To save having an #ifdef in event_loop we need to define this empty function */
490 void statserv_remove(IOCHAN pIOChannel)
494 void statserv_closedown()
497 for (p = pListener; p; p = p->next)
501 static int check_ip(void *cd, const char *addr, int len, int type)
503 const unsigned char *ip = (const unsigned char *) addr;
507 sprintf (str, "%u", *ip);
508 for (i = 1; i<4; i++)
509 sprintf (str + strlen(str), ".%u", ip[i]);
510 logf (LOG_DEBUG, "ip %s", str);
514 static void listener(IOCHAN h, int event)
516 COMSTACK line = (COMSTACK) iochan_getdata(h);
519 static int child = 0;
522 if (event == EVENT_INPUT)
524 if (control_block.dynamic && !child)
530 logf(LOG_FATAL|LOG_ERRNO, "pipe");
534 if ((res = fork()) < 0)
536 logf(LOG_FATAL|LOG_ERRNO, "fork");
540 else if (res == 0) /* child */
547 for (pp = pListener; pp; pp = iochan_getnext(pp))
551 COMSTACK l = (COMSTACK)iochan_getdata(pp);
556 sprintf(nbuf, "%s(%d)", me, getpid());
557 log_init(control_block.loglevel, nbuf, 0);
562 /* wait for child to take the call */
568 if ((res = read(hand[0], dummy, 1)) < 0 && errno != EINTR)
570 logf(LOG_FATAL|LOG_ERRNO, "handshake read");
576 logf(LOG_DEBUG, "P: Child has taken the call");
581 if ((res = cs_listen_check(line, 0, 0, check_ip, 0)) < 0)
583 logf(LOG_WARN, "cs_listen failed");
588 logf(LOG_DEBUG, "listen ok");
589 iochan_setevent(h, EVENT_OUTPUT);
590 iochan_setflags(h, EVENT_OUTPUT | EVENT_EXCEPT); /* set up for acpt */
592 /* in dynamic mode, only the child ever comes down here */
593 else if (event == EVENT_OUTPUT)
599 if (!(new_line = cs_accept(line)))
601 logf(LOG_FATAL, "Accept failed.");
602 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
605 logf(LOG_DEBUG, "accept ok");
606 if (control_block.dynamic)
609 /* close our half of the listener socket */
610 for (pp = pListener; pp; pp = iochan_getnext(pp))
612 COMSTACK l = (COMSTACK)iochan_getdata(pp);
617 logf(LOG_DEBUG, "Releasing parent");
621 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
623 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session,
626 logf(LOG_FATAL, "Failed to create iochan");
630 new_chan->next = pListener;
631 pListener = new_chan;
632 if (!(newas = create_association(new_chan, new_line)))
634 logf(LOG_FATAL, "Failed to create new assoc.");
638 iochan_setdata(new_chan, newas);
639 iochan_settimeout(new_chan, control_block.idle_timeout * 60);
640 a = cs_addrstr(new_line);
641 logf(LOG_LOG, "Accepted connection from %s", a ? a : "[Unknown]");
645 logf(LOG_FATAL, "Bad event on listener.");
653 static void inetd_connection(int what)
660 if ((line = cs_createbysocket(0, tcpip_type, 0, what)))
662 if ((chan = iochan_create(cs_fileno(line), ir_session, EVENT_INPUT)))
664 if ((assoc = create_association(chan, line)))
666 iochan_setdata(chan, assoc);
667 iochan_settimeout(chan, control_block.idle_timeout * 60);
668 addr = cs_addrstr(line);
669 logf(LOG_LOG, "Inetd association from %s", addr ? addr : "[UNKNOWN]");
673 logf(LOG_FATAL, "Failed to create association structure");
675 chan->next = pListener;
680 logf(LOG_FATAL, "Failed to create iochan");
685 logf(LOG_ERRNO|LOG_FATAL, "Failed to create comstack on socket 0");
690 * Set up a listening endpoint, and give it to the event-handler.
692 static void add_listener(char *where, int what)
696 char mode[100], addr[100];
700 if (!where || sscanf(where, "%[^:]:%s", mode, addr) != 2)
702 logf (LOG_WARN, "%s: Address format: ('tcp'|'osi')':'<address>", me);
705 if (!strcmp(mode, "tcp"))
707 else if (!strcmp(mode, "osi"))
712 logf (LOG_WARN, "OSI Transport not allowed by configuration.");
718 logf (LOG_WARN, "You must specify either 'osi:' or 'tcp:'");
721 logf(LOG_LOG, "Adding %s %s listener on %s",
722 control_block.dynamic ? "dynamic" : "static",
723 what == PROTO_SR ? "SR" : "Z3950", where);
724 if (!(l = cs_create(type, 0, what)))
726 logf(LOG_FATAL|LOG_ERRNO, "Failed to create listener");
728 ap = cs_straddr (l, addr);
731 fprintf(stderr, "Address resolution failed.\n");
735 if (cs_bind(l, ap, CS_SERVER) < 0)
737 logf(LOG_FATAL|LOG_ERRNO, "Failed to bind to %s", where);
739 if (!(lst = iochan_create(cs_fileno(l), listener, EVENT_INPUT |
742 logf(LOG_FATAL|LOG_ERRNO, "Failed to create IOCHAN-type");
744 iochan_setdata(lst, l);
746 /* Ensure our listener chain is setup properly */
747 lst->next = pListener;
752 /* For windows we don't need to catch the signals */
753 static void catchchld(int num)
755 while (waitpid(-1, 0, WNOHANG) > 0)
757 signal(SIGCHLD, catchchld);
761 statserv_options_block *statserv_getcontrol(void)
763 static statserv_options_block cb;
765 memcpy(&cb, &control_block, sizeof(cb));
769 void statserv_setcontrol(statserv_options_block *block)
771 memcpy(&control_block, block, sizeof(*block));
774 int statserv_start(int argc, char **argv)
780 /* We need to initialize the thread list */
781 ThreadList_Initialize();
785 if ((me = strrchr (argv[0], '\\')))
792 if (control_block.options_func(argc, argv))
796 if (control_block.inetd)
797 inetd_connection(control_block.default_proto);
800 if (control_block.pre_init)
801 (*control_block.pre_init)(&control_block);
802 if (control_block.dynamic)
803 signal(SIGCHLD, catchchld);
805 if (*control_block.setuid)
809 if (!(pw = getpwnam(control_block.setuid)))
811 logf(LOG_FATAL, "%s: Unknown user", control_block.setuid);
814 if (setuid(pw->pw_uid) < 0)
816 logf(LOG_FATAL|LOG_ERRNO, "setuid");
822 if ((pListener == NULL) && *control_block.default_listen)
823 add_listener(control_block.default_listen,
824 control_block.default_proto);
825 logf(LOG_LOG, "Entering event loop.");
827 if (pListener == NULL)
830 ret = event_loop(&pListener);
835 int check_options(int argc, char **argv)
840 while ((ret = options("a:iszSl:v:u:c:w:t:k:", argv, argc, &arg)) != -2)
845 add_listener(arg, control_block.default_proto);
848 control_block.default_proto = PROTO_Z3950;
851 control_block.default_proto = PROTO_SR;
854 control_block.dynamic = 0;
857 strcpy(control_block.logfile, arg ? arg : "");
858 log_init(control_block.loglevel, me, control_block.logfile);
861 control_block.loglevel = log_mask_str(arg);
862 log_init(control_block.loglevel, me, control_block.logfile);
865 strcpy(control_block.apdufile, arg ? arg : "");
868 strcpy(control_block.setuid, arg ? arg : "");
871 strcpy(control_block.configname, arg ? arg : "");
874 if (!arg || !(r = atoi(arg)))
876 fprintf(stderr, "%s: Specify positive timeout for -t.\n", me);
879 control_block.idle_timeout = r;
882 if (!arg || !(r = atoi(arg)))
884 fprintf(stderr, "%s: Specify positive timeout for -t.\n", me);
887 control_block.maxrecordsize = r * 1024;
890 control_block.inetd = 1;
900 fprintf(stderr, "Usage: %s [ -i -a <pdufile> -v <loglevel>"
901 " -l <logfile> -u <user> -c <config> -t <minutes>"
903 " -zsS <listener-addr> -w <directory> ... ]\n", me);
917 static Args ArgDetails;
919 /* name of the executable */
920 #define SZAPPNAME "server"
922 /* list of service dependencies - "dep1\0dep2\0\0" */
923 #define SZDEPENDENCIES ""
925 int statserv_main(int argc, char **argv)
927 statserv_options_block *cb = statserv_getcontrol();
929 /* Lets setup the Arg structure */
930 ArgDetails.argc = argc;
931 ArgDetails.argv = argv;
933 /* Now setup the service with the service controller */
934 SetupService(argc, argv, &ArgDetails, SZAPPNAME,
935 cb->service_name, /* internal service name */
936 cb->service_name, /* displayed name of the service */
941 int StartAppService(void *pHandle, int argc, char **argv)
943 /* Initializes the App */
947 void RunAppService(void *pHandle)
949 Args *pArgs = (Args *)pHandle;
951 /* Starts the app running */
952 statserv_start(pArgs->argc, pArgs->argv);
955 void StopAppService(void *pHandle)
958 statserv_closedown();
961 int statserv_main(int argc, char **argv)
963 int ret = statserv_start (argc, argv);
964 statserv_closedown ();