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.52 1998-08-21 14:13:34 adam
11 * Added GNU Configure script to build Makefiles.
13 * Revision 1.51 1998/07/07 15:51:03 adam
14 * Changed server so that it stops if bind fails - "address already in
15 * use" typically causes this.
17 * Revision 1.50 1998/06/22 11:32:39 adam
18 * Added 'conditional cs_listen' feature.
20 * Revision 1.49 1998/02/27 14:04:55 adam
21 * Fixed bug in statserv_remove.
23 * Revision 1.48 1998/02/11 11:53:36 adam
24 * Changed code so that it compiles as C++.
26 * Revision 1.47 1998/02/10 10:28:57 adam
27 * Added app_name, service_dependencies, service_display_name and
28 * options_func. options_func allows us to specify a different function
29 * to interogate the command line arguments. The other members allow us
30 * to pass the full service details accross to the service manager (CW).
33 * Revision 1.46 1998/01/30 15:24:57 adam
34 * Fixed bug in inetd code. The server listened on tcp:@:9999 even
35 * though it was started in inetd mode.
37 * Revision 1.45 1998/01/29 13:30:23 adam
38 * Better event handle system for NT/Unix.
40 * Revision 1.44 1997/11/07 13:31:52 adam
41 * Added NT Service name part of statserv_options_block. Moved NT
42 * service utility to server library.
44 * Revision 1.43 1997/10/31 12:20:09 adam
45 * Improved memory debugging for xmalloc/nmem.c. References to NMEM
46 * instead of ODR in n ESPEC-1 handling in source d1_espec.c.
47 * Bug fix: missing fclose in data1_read_espec1.
49 * Revision 1.42 1997/10/27 14:03:02 adam
50 * Added new member to statserver_options_block, pre_init, which
51 * specifies a callback to be invoked after command line parsing and
52 * before the server listens for the first time.
54 * Revision 1.41 1997/09/29 07:19:32 adam
55 * Server library uses nmem_init/nmem_exit. The log prefix no longer
56 * includes leading path on NT.
58 * Revision 1.40 1997/09/17 12:10:41 adam
61 * Revision 1.39 1997/09/09 10:10:19 adam
62 * Another MSV5.0 port. Changed projects to include proper
63 * library/include paths.
64 * Server starts server in test-mode when no options are given.
66 * Revision 1.38 1997/09/04 14:19:14 adam
69 * Revision 1.37 1997/09/01 08:53:01 adam
70 * New windows NT/95 port using MSV5.0. The test server 'ztest' was
71 * moved a separate directory. MSV5.0 project server.dsp created.
72 * As an option, the server can now operate as an NT service.
74 * Revision 1.36 1996/07/06 19:58:36 quinn
75 * System headerfiles gathered in yconfig
77 * Revision 1.35 1996/05/29 10:03:28 quinn
80 * Revision 1.34 1996/02/21 13:12:07 quinn
81 * *** empty log message ***
83 * Revision 1.33 1996/02/10 12:23:49 quinn
84 * Enable inetd operations fro TCP/IP stack
86 * Revision 1.32 1996/01/19 15:41:52 quinn
87 * *** empty log message ***
89 * Revision 1.31 1995/11/17 11:09:39 adam
90 * Added new option '-c' to specify configuration name in control block.
92 * Revision 1.30 1995/11/01 13:54:59 quinn
95 * Revision 1.29 1995/10/30 12:41:29 quinn
96 * Added hostname lookup for server.
98 * Revision 1.28 1995/09/29 17:12:30 quinn
101 * Revision 1.27 1995/09/27 15:03:02 quinn
102 * Modified function heads & prototypes.
104 * Revision 1.26 1995/08/29 14:44:51 quinn
107 * Revision 1.25 1995/08/29 11:18:02 quinn
108 * Added code to receive close
110 * Revision 1.24 1995/06/16 10:31:39 quinn
111 * Added session timeout.
113 * Revision 1.23 1995/06/15 12:30:48 quinn
116 * Revision 1.22 1995/06/15 07:45:17 quinn
119 * Revision 1.21 1995/06/06 08:15:40 quinn
122 * Revision 1.20 1995/05/29 08:12:09 quinn
125 * Revision 1.19 1995/05/16 09:37:27 quinn
128 * Revision 1.18 1995/05/16 08:51:09 quinn
129 * License, documentation, and memory fixes
131 * Revision 1.17 1995/05/15 11:56:42 quinn
132 * Asynchronous facilities. Restructuring of seshigh code.
134 * Revision 1.16 1995/04/10 10:23:40 quinn
135 * Some work to add scan and other things.
137 * Revision 1.15 1995/03/31 10:16:51 quinn
140 * Revision 1.14 1995/03/31 09:18:58 quinn
143 * Revision 1.13 1995/03/30 16:08:39 quinn
146 * Revision 1.12 1995/03/30 13:29:02 quinn
149 * Revision 1.11 1995/03/30 12:18:17 quinn
152 * Revision 1.10 1995/03/29 15:40:16 quinn
153 * Ongoing work. Statserv is now dynamic by default
155 * Revision 1.9 1995/03/27 08:34:30 quinn
156 * Added dynamic server functionality.
157 * Released bindings to session.c (is now redundant)
159 * Revision 1.8 1995/03/20 09:46:26 quinn
162 * Revision 1.7 1995/03/16 13:29:04 quinn
163 * Partitioned server.
165 * Revision 1.6 1995/03/15 15:18:52 quinn
166 * Little changes to better support nonblocking I/O
169 * Revision 1.5 1995/03/15 08:37:45 quinn
170 * Now we're pretty much set for nonblocking I/O.
172 * Revision 1.4 1995/03/14 16:59:48 quinn
175 * Revision 1.3 1995/03/14 11:30:15 quinn
178 * Revision 1.2 1995/03/14 10:28:03 quinn
179 * More work on demo server.
181 * Revision 1.1 1995/03/10 18:22:45 quinn
182 * The rudiments of an asynchronous server.
203 #include <comstack.h>
211 #include <statserv.h>
213 static IOCHAN pListener = NULL;
215 static char *me = "statserver";
219 int check_options(int argc, char **argv);
220 statserv_options_block control_block = {
221 1, /* dynamic mode */
222 LOG_DEFAULT_LEVEL, /* log level */
224 "", /* diagnostic output to stderr */
225 "tcp:@:9999", /* default listener port */
226 PROTO_Z3950, /* default application protocol */
227 60, /* idle timeout (minutes) */
228 1024*1024, /* maximum PDU size (approx.) to allow */
229 "default-config", /* configuration name to pass to backend */
230 "", /* set user id */
231 NULL, /* pre init handler */
232 check_options, /* Default routine, for checking the run-time arguments */
233 0 /* default value for inet deamon */
236 ,"Z39.50 Server", /* NT Service Name */
237 "Server", /* NT application Name */
238 "", /* NT Service Dependencies */
239 "Z39.50 Server" /* NT Service Display Name */
244 * handle incoming connect requests.
245 * The dynamic mode is a bit tricky mostly because we want to avoid
246 * doing all of the listening and accepting in the parent - it's
251 typedef struct _ThreadList ThreadList;
260 static ThreadList *pFirstThread;
261 static CRITICAL_SECTION Thread_CritSect;
262 static BOOL bInitialized = FALSE;
264 static void ThreadList_Initialize()
266 /* Initialize the critical Sections */
267 InitializeCriticalSection(&Thread_CritSect);
269 /* Set the first thraed */
272 /* we have been initialized */
276 static void statserv_add(HANDLE hThread, IOCHAN pIOChannel)
278 /* Only one thread can go through this section at a time */
279 EnterCriticalSection(&Thread_CritSect);
282 /* Lets create our new object */
283 ThreadList *pNewThread = (ThreadList *)malloc(sizeof(ThreadList));
284 pNewThread->hThread = hThread;
285 pNewThread->pIOChannel = pIOChannel;
286 pNewThread->pNext = pFirstThread;
287 pFirstThread = pNewThread;
289 /* Lets let somebody else create a new object now */
290 LeaveCriticalSection(&Thread_CritSect);
294 void statserv_remove(IOCHAN pIOChannel)
296 /* Only one thread can go through this section at a time */
297 EnterCriticalSection(&Thread_CritSect);
300 ThreadList *pCurrentThread = pFirstThread;
301 ThreadList *pNextThread;
302 ThreadList *pPrevThread =NULL;
304 /* Step through alll the threads */
305 for (; pCurrentThread != NULL; pCurrentThread = pNextThread)
307 /* We only need to compare on the IO Channel */
308 if (pCurrentThread->pIOChannel == pIOChannel)
310 /* We have found the thread we want to delete */
311 /* First of all reset the next pointers */
312 if (pPrevThread == NULL)
313 pFirstThread = pCurrentThread->pNext;
315 pPrevThread->pNext = pCurrentThread->pNext;
317 /* All we need todo now is delete the memory */
318 free(pCurrentThread);
320 /* No need to look at any more threads */
325 /* We need to look at another thread */
326 pNextThread = pCurrentThread->pNext;
327 pPrevThread = pCurrentThread;
331 /* Lets let somebody else remove an object now */
332 LeaveCriticalSection(&Thread_CritSect);
336 void statserv_closedown()
338 /* Shouldn't do anything if we are not initialized */
342 HANDLE *pThreadHandles = NULL;
344 /* We need to stop threads adding and removing while we */
345 /* start the closedown process */
346 EnterCriticalSection(&Thread_CritSect);
349 /* We have exclusive access to the thread stuff now */
350 /* Y didn't i use a semaphore - Oh well never mind */
351 ThreadList *pCurrentThread = pFirstThread;
353 /* Before we do anything else, we need to shutdown the listener */
354 if (pListener != NULL)
355 iochan_destroy(pListener);
357 for (; pCurrentThread != NULL; pCurrentThread = pCurrentThread->pNext)
359 /* Just destroy the IOCHAN, that should do the trick */
360 iochan_destroy(pCurrentThread->pIOChannel);
362 /* Keep a running count of our handles */
368 HANDLE *pCurrentHandle ;
370 /* Allocate the thread handle array */
371 pThreadHandles = (HANDLE *)malloc(sizeof(HANDLE) * iHandles);
372 pCurrentHandle = pThreadHandles;
374 for (pCurrentThread = pFirstThread;
375 pCurrentThread != NULL;
376 pCurrentThread = pCurrentThread->pNext, pCurrentHandle++)
378 /* Just the handle */
379 *pCurrentHandle = pCurrentThread->hThread;
383 /* We can now leave the critical section */
384 LeaveCriticalSection(&Thread_CritSect);
387 /* Now we can really do something */
390 /* This will now wait, until all the threads close */
391 WaitForMultipleObjects(iHandles, pThreadHandles, TRUE, INFINITE);
393 /* Free the memory we allocated for the handle array */
394 free(pThreadHandles);
397 /* No longer require the critical section, since all threads are dead */
398 DeleteCriticalSection(&Thread_CritSect);
402 int __stdcall event_loop_thread (IOCHAN iochan)
404 return event_loop (&iochan);
407 static void listener(IOCHAN h, int event)
409 COMSTACK line = (COMSTACK) iochan_getdata(h);
414 if (event == EVENT_INPUT)
416 if ((res = cs_listen(line, 0, 0)) < 0)
418 logf(LOG_FATAL, "cs_listen failed");
423 logf(LOG_DEBUG, "listen ok");
424 iochan_setevent(h, EVENT_OUTPUT);
425 iochan_setflags(h, EVENT_OUTPUT | EVENT_EXCEPT); /* set up for acpt */
427 else if (event == EVENT_OUTPUT)
434 if (!(new_line = cs_accept(line)))
436 logf(LOG_FATAL, "Accept failed.");
437 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
440 logf(LOG_DEBUG, "Accept ok");
442 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session,
445 logf(LOG_FATAL, "Failed to create iochan");
450 logf(LOG_DEBUG, "Creating association");
451 if (!(newas = create_association(new_chan, new_line)))
453 logf(LOG_FATAL, "Failed to create new assoc.");
457 logf(LOG_DEBUG, "Setting timeout %d", control_block.idle_timeout);
458 iochan_setdata(new_chan, newas);
459 iochan_settimeout(new_chan, control_block.idle_timeout * 60);
461 logf(LOG_DEBUG, "Determining client address");
462 a = cs_addrstr(new_line);
463 logf(LOG_LOG, "Accepted connection from %s", a ? a : "[Unknown]");
465 /* Now what we need todo is create a new thread with this iochan as
467 /* if (CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)event_loop_thread,
468 new_chan, 0, &ThreadId) == NULL) */
469 /* Somehow, somewhere we need to store this thread id, otherwise we
470 won't be able to close cleanly */
471 NewHandle = (HANDLE)_beginthreadex(NULL, 0, event_loop_thread,
472 new_chan, 0, &ThreadId);
473 if (NewHandle == (HANDLE)-1)
476 logf(LOG_FATAL|LOG_ERRNO, "Failed to create new thread.");
480 /* We successfully created the thread, so add it to the list */
481 statserv_add(NewHandle, new_chan);
483 logf(LOG_DEBUG, "Created new thread, iochan %p", new_chan);
484 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
488 logf(LOG_FATAL, "Bad event on listener.");
496 /* To save having an #ifdef in event_loop we need to define this empty function */
497 void statserv_remove(IOCHAN pIOChannel)
501 void statserv_closedown()
504 for (p = pListener; p; p = p->next)
508 static int check_ip(void *cd, const char *addr, int len, int type)
510 const unsigned char *ip = (const unsigned char *) addr;
514 sprintf (str, "%u", *ip);
515 for (i = 1; i<4; i++)
516 sprintf (str + strlen(str), ".%u", ip[i]);
517 logf (LOG_DEBUG, "ip %s", str);
521 static void listener(IOCHAN h, int event)
523 COMSTACK line = (COMSTACK) iochan_getdata(h);
526 static int child = 0;
529 if (event == EVENT_INPUT)
531 if (control_block.dynamic && !child)
537 logf(LOG_FATAL|LOG_ERRNO, "pipe");
541 if ((res = fork()) < 0)
543 logf(LOG_FATAL|LOG_ERRNO, "fork");
547 else if (res == 0) /* child */
554 for (pp = pListener; pp; pp = iochan_getnext(pp))
558 COMSTACK l = (COMSTACK)iochan_getdata(pp);
563 sprintf(nbuf, "%s(%d)", me, getpid());
564 log_init(control_block.loglevel, nbuf, 0);
569 /* wait for child to take the call */
575 if ((res = read(hand[0], dummy, 1)) < 0 && errno != EINTR)
577 logf(LOG_FATAL|LOG_ERRNO, "handshake read");
583 logf(LOG_DEBUG, "P: Child has taken the call");
588 if ((res = cs_listen_check(line, 0, 0, check_ip, 0)) < 0)
590 logf(LOG_WARN, "cs_listen failed");
595 logf(LOG_DEBUG, "listen ok");
596 iochan_setevent(h, EVENT_OUTPUT);
597 iochan_setflags(h, EVENT_OUTPUT | EVENT_EXCEPT); /* set up for acpt */
599 /* in dynamic mode, only the child ever comes down here */
600 else if (event == EVENT_OUTPUT)
606 if (!(new_line = cs_accept(line)))
608 logf(LOG_FATAL, "Accept failed.");
609 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
612 logf(LOG_DEBUG, "accept ok");
613 if (control_block.dynamic)
616 /* close our half of the listener socket */
617 for (pp = pListener; pp; pp = iochan_getnext(pp))
619 COMSTACK l = (COMSTACK)iochan_getdata(pp);
624 logf(LOG_DEBUG, "Releasing parent");
628 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
630 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session,
633 logf(LOG_FATAL, "Failed to create iochan");
637 new_chan->next = pListener;
638 pListener = new_chan;
639 if (!(newas = create_association(new_chan, new_line)))
641 logf(LOG_FATAL, "Failed to create new assoc.");
645 iochan_setdata(new_chan, newas);
646 iochan_settimeout(new_chan, control_block.idle_timeout * 60);
647 a = cs_addrstr(new_line);
648 logf(LOG_LOG, "Accepted connection from %s", a ? a : "[Unknown]");
652 logf(LOG_FATAL, "Bad event on listener.");
660 static void inetd_connection(int what)
667 if ((line = cs_createbysocket(0, tcpip_type, 0, what)))
669 if ((chan = iochan_create(cs_fileno(line), ir_session, EVENT_INPUT)))
671 if ((assoc = create_association(chan, line)))
673 iochan_setdata(chan, assoc);
674 iochan_settimeout(chan, control_block.idle_timeout * 60);
675 addr = cs_addrstr(line);
676 logf(LOG_LOG, "Inetd association from %s", addr ? addr : "[UNKNOWN]");
680 logf(LOG_FATAL, "Failed to create association structure");
682 chan->next = pListener;
687 logf(LOG_FATAL, "Failed to create iochan");
692 logf(LOG_ERRNO|LOG_FATAL, "Failed to create comstack on socket 0");
697 * Set up a listening endpoint, and give it to the event-handler.
699 static void add_listener(char *where, int what)
703 char mode[100], addr[100];
707 if (!where || sscanf(where, "%[^:]:%s", mode, addr) != 2)
709 logf (LOG_WARN, "%s: Address format: ('tcp'|'osi')':'<address>", me);
712 if (!strcmp(mode, "tcp"))
714 else if (!strcmp(mode, "osi"))
719 logf (LOG_WARN, "OSI Transport not allowed by configuration.");
725 logf (LOG_WARN, "You must specify either 'osi:' or 'tcp:'");
728 logf(LOG_LOG, "Adding %s %s listener on %s",
729 control_block.dynamic ? "dynamic" : "static",
730 what == PROTO_SR ? "SR" : "Z3950", where);
731 if (!(l = cs_create(type, 0, what)))
733 logf(LOG_FATAL|LOG_ERRNO, "Failed to create listener");
736 ap = cs_straddr (l, addr);
739 fprintf(stderr, "Address resolution failed.\n");
743 if (cs_bind(l, ap, CS_SERVER) < 0)
745 logf(LOG_FATAL|LOG_ERRNO, "Failed to bind to %s", where);
749 if (!(lst = iochan_create(cs_fileno(l), listener, EVENT_INPUT |
752 logf(LOG_FATAL|LOG_ERRNO, "Failed to create IOCHAN-type");
756 iochan_setdata(lst, l);
758 /* Ensure our listener chain is setup properly */
759 lst->next = pListener;
764 /* For windows we don't need to catch the signals */
765 static void catchchld(int num)
767 while (waitpid(-1, 0, WNOHANG) > 0)
769 signal(SIGCHLD, catchchld);
773 statserv_options_block *statserv_getcontrol(void)
775 static statserv_options_block cb;
777 memcpy(&cb, &control_block, sizeof(cb));
781 void statserv_setcontrol(statserv_options_block *block)
783 memcpy(&control_block, block, sizeof(*block));
786 int statserv_start(int argc, char **argv)
792 /* We need to initialize the thread list */
793 ThreadList_Initialize();
797 if ((me = strrchr (argv[0], '\\')))
804 if (control_block.options_func(argc, argv))
808 if (control_block.inetd)
809 inetd_connection(control_block.default_proto);
812 if (control_block.pre_init)
813 (*control_block.pre_init)(&control_block);
814 if (control_block.dynamic)
815 signal(SIGCHLD, catchchld);
817 if (*control_block.setuid)
821 if (!(pw = getpwnam(control_block.setuid)))
823 logf(LOG_FATAL, "%s: Unknown user", control_block.setuid);
826 if (setuid(pw->pw_uid) < 0)
828 logf(LOG_FATAL|LOG_ERRNO, "setuid");
834 if ((pListener == NULL) && *control_block.default_listen)
835 add_listener(control_block.default_listen,
836 control_block.default_proto);
838 if (pListener == NULL)
842 logf(LOG_LOG, "Entering event loop.");
843 ret = event_loop(&pListener);
849 int check_options(int argc, char **argv)
854 while ((ret = options("a:iszSl:v:u:c:w:t:k:", argv, argc, &arg)) != -2)
859 add_listener(arg, control_block.default_proto);
862 control_block.default_proto = PROTO_Z3950;
865 control_block.default_proto = PROTO_SR;
868 control_block.dynamic = 0;
871 strcpy(control_block.logfile, arg ? arg : "");
872 log_init(control_block.loglevel, me, control_block.logfile);
875 control_block.loglevel = log_mask_str(arg);
876 log_init(control_block.loglevel, me, control_block.logfile);
879 strcpy(control_block.apdufile, arg ? arg : "");
882 strcpy(control_block.setuid, arg ? arg : "");
885 strcpy(control_block.configname, arg ? arg : "");
888 if (!arg || !(r = atoi(arg)))
890 fprintf(stderr, "%s: Specify positive timeout for -t.\n", me);
893 control_block.idle_timeout = r;
896 if (!arg || !(r = atoi(arg)))
898 fprintf(stderr, "%s: Specify positive timeout for -t.\n", me);
901 control_block.maxrecordsize = r * 1024;
904 control_block.inetd = 1;
914 fprintf(stderr, "Usage: %s [ -i -a <pdufile> -v <loglevel>"
915 " -l <logfile> -u <user> -c <config> -t <minutes>"
917 " -zsS <listener-addr> -w <directory> ... ]\n", me);
931 static Args ArgDetails;
933 /* name of the executable */
934 #define SZAPPNAME "server"
936 /* list of service dependencies - "dep1\0dep2\0\0" */
937 #define SZDEPENDENCIES ""
939 int statserv_main(int argc, char **argv)
941 statserv_options_block *cb = statserv_getcontrol();
943 /* Lets setup the Arg structure */
944 ArgDetails.argc = argc;
945 ArgDetails.argv = argv;
947 /* Now setup the service with the service controller */
948 SetupService(argc, argv, &ArgDetails, SZAPPNAME,
949 cb->service_name, /* internal service name */
950 cb->service_name, /* displayed name of the service */
955 int StartAppService(void *pHandle, int argc, char **argv)
957 /* Initializes the App */
961 void RunAppService(void *pHandle)
963 Args *pArgs = (Args *)pHandle;
965 /* Starts the app running */
966 statserv_start(pArgs->argc, pArgs->argv);
969 void StopAppService(void *pHandle)
972 statserv_closedown();
975 int statserv_main(int argc, char **argv)
977 int ret = statserv_start (argc, argv);
978 statserv_closedown ();