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.48 1998-02-11 11:53:36 adam
11 * Changed code so that it compiles as C++.
13 * Revision 1.47 1998/02/10 10:28:57 adam
14 * Added app_name, service_dependencies, service_display_name and
15 * options_func. options_func allows us to specify a different function
16 * to interogate the command line arguments. The other members allow us
17 * to pass the full service details accross to the service manager (CW).
20 * Revision 1.46 1998/01/30 15:24:57 adam
21 * Fixed bug in inetd code. The server listened on tcp:@:9999 even
22 * though it was started in inetd mode.
24 * Revision 1.45 1998/01/29 13:30:23 adam
25 * Better event handle system for NT/Unix.
27 * Revision 1.44 1997/11/07 13:31:52 adam
28 * Added NT Service name part of statserv_options_block. Moved NT
29 * service utility to server library.
31 * Revision 1.43 1997/10/31 12:20:09 adam
32 * Improved memory debugging for xmalloc/nmem.c. References to NMEM
33 * instead of ODR in n ESPEC-1 handling in source d1_espec.c.
34 * Bug fix: missing fclose in data1_read_espec1.
36 * Revision 1.42 1997/10/27 14:03:02 adam
37 * Added new member to statserver_options_block, pre_init, which
38 * specifies a callback to be invoked after command line parsing and
39 * before the server listens for the first time.
41 * Revision 1.41 1997/09/29 07:19:32 adam
42 * Server library uses nmem_init/nmem_exit. The log prefix no longer
43 * includes leading path on NT.
45 * Revision 1.40 1997/09/17 12:10:41 adam
48 * Revision 1.39 1997/09/09 10:10:19 adam
49 * Another MSV5.0 port. Changed projects to include proper
50 * library/include paths.
51 * Server starts server in test-mode when no options are given.
53 * Revision 1.38 1997/09/04 14:19:14 adam
56 * Revision 1.37 1997/09/01 08:53:01 adam
57 * New windows NT/95 port using MSV5.0. The test server 'ztest' was
58 * moved a separate directory. MSV5.0 project server.dsp created.
59 * As an option, the server can now operate as an NT service.
61 * Revision 1.36 1996/07/06 19:58:36 quinn
62 * System headerfiles gathered in yconfig
64 * Revision 1.35 1996/05/29 10:03:28 quinn
67 * Revision 1.34 1996/02/21 13:12:07 quinn
68 * *** empty log message ***
70 * Revision 1.33 1996/02/10 12:23:49 quinn
71 * Enable inetd operations fro TCP/IP stack
73 * Revision 1.32 1996/01/19 15:41:52 quinn
74 * *** empty log message ***
76 * Revision 1.31 1995/11/17 11:09:39 adam
77 * Added new option '-c' to specify configuration name in control block.
79 * Revision 1.30 1995/11/01 13:54:59 quinn
82 * Revision 1.29 1995/10/30 12:41:29 quinn
83 * Added hostname lookup for server.
85 * Revision 1.28 1995/09/29 17:12:30 quinn
88 * Revision 1.27 1995/09/27 15:03:02 quinn
89 * Modified function heads & prototypes.
91 * Revision 1.26 1995/08/29 14:44:51 quinn
94 * Revision 1.25 1995/08/29 11:18:02 quinn
95 * Added code to receive close
97 * Revision 1.24 1995/06/16 10:31:39 quinn
98 * Added session timeout.
100 * Revision 1.23 1995/06/15 12:30:48 quinn
103 * Revision 1.22 1995/06/15 07:45:17 quinn
106 * Revision 1.21 1995/06/06 08:15:40 quinn
109 * Revision 1.20 1995/05/29 08:12:09 quinn
112 * Revision 1.19 1995/05/16 09:37:27 quinn
115 * Revision 1.18 1995/05/16 08:51:09 quinn
116 * License, documentation, and memory fixes
118 * Revision 1.17 1995/05/15 11:56:42 quinn
119 * Asynchronous facilities. Restructuring of seshigh code.
121 * Revision 1.16 1995/04/10 10:23:40 quinn
122 * Some work to add scan and other things.
124 * Revision 1.15 1995/03/31 10:16:51 quinn
127 * Revision 1.14 1995/03/31 09:18:58 quinn
130 * Revision 1.13 1995/03/30 16:08:39 quinn
133 * Revision 1.12 1995/03/30 13:29:02 quinn
136 * Revision 1.11 1995/03/30 12:18:17 quinn
139 * Revision 1.10 1995/03/29 15:40:16 quinn
140 * Ongoing work. Statserv is now dynamic by default
142 * Revision 1.9 1995/03/27 08:34:30 quinn
143 * Added dynamic server functionality.
144 * Released bindings to session.c (is now redundant)
146 * Revision 1.8 1995/03/20 09:46:26 quinn
149 * Revision 1.7 1995/03/16 13:29:04 quinn
150 * Partitioned server.
152 * Revision 1.6 1995/03/15 15:18:52 quinn
153 * Little changes to better support nonblocking I/O
156 * Revision 1.5 1995/03/15 08:37:45 quinn
157 * Now we're pretty much set for nonblocking I/O.
159 * Revision 1.4 1995/03/14 16:59:48 quinn
162 * Revision 1.3 1995/03/14 11:30:15 quinn
165 * Revision 1.2 1995/03/14 10:28:03 quinn
166 * More work on demo server.
168 * Revision 1.1 1995/03/10 18:22:45 quinn
169 * The rudiments of an asynchronous server.
190 #include <comstack.h>
198 #include <statserv.h>
200 static IOCHAN pListener = NULL;
202 static char *me = "statserver";
206 int check_options(int argc, char **argv);
207 statserv_options_block control_block = {
208 1, /* dynamic mode */
209 LOG_DEFAULT_LEVEL, /* log level */
211 "", /* diagnostic output to stderr */
212 "tcp:@:9999", /* default listener port */
213 PROTO_Z3950, /* default application protocol */
214 60, /* idle timeout (minutes) */
215 1024*1024, /* maximum PDU size (approx.) to allow */
216 "default-config", /* configuration name to pass to backend */
217 "", /* set user id */
218 NULL, /* pre init handler */
219 check_options, /* Default routine, for checking the run-time arguments */
220 0 /* default value for inet deamon */
223 ,"Z39.50 Server", /* NT Service Name */
224 "Server", /* NT application Name */
225 "", /* NT Service Dependencies */
226 "Z39.50 Server" /* NT Service Display Name */
231 * handle incoming connect requests.
232 * The dynamic mode is a bit tricky mostly because we want to avoid
233 * doing all of the listening and accepting in the parent - it's
238 typedef struct _ThreadList ThreadList;
247 static ThreadList *pFirstThread;
248 static CRITICAL_SECTION Thread_CritSect;
249 static BOOL bInitialized = FALSE;
251 static void ThreadList_Initialize()
253 /* Initialize the critical Sections */
254 InitializeCriticalSection(&Thread_CritSect);
256 /* Set the first thraed */
259 /* we have been initialized */
263 static void statserv_add(HANDLE hThread, IOCHAN pIOChannel)
265 /* Only one thread can go through this section at a time */
266 EnterCriticalSection(&Thread_CritSect);
269 /* Lets create our new object */
270 ThreadList *pNewThread = (ThreadList *)malloc(sizeof(ThreadList));
271 pNewThread->hThread = hThread;
272 pNewThread->pIOChannel = pIOChannel;
273 pNewThread->pNext = pFirstThread;
274 pFirstThread = pNewThread;
276 /* Lets let somebody else create a new object now */
277 LeaveCriticalSection(&Thread_CritSect);
281 void statserv_remove(IOCHAN pIOChannel)
283 /* Only one thread can go through this section at a time */
284 EnterCriticalSection(&Thread_CritSect);
287 ThreadList *pCurrentThread = pFirstThread;
288 ThreadList *pNextThread;
289 ThreadList *pPrevThread =NULL;
291 /* Step through alll the threads */
292 for (; pCurrentThread != NULL; pCurrentThread = pNextThread)
294 /* We only need to compare on the IO Channel */
295 if (pCurrentThread->pIOChannel == pIOChannel)
297 /* We have found the thread we want to delete */
298 /* First of all reset the next pointers */
299 if (pPrevThread == NULL)
300 pFirstThread = pCurrentThread->pNext;
302 pPrevThread->pNext = pCurrentThread->pNext;
304 /* All we need todo now is delete the memory */
305 free(pCurrentThread);
307 /* No need to look at any more threads */
312 /* We need to look at another thread */
313 pNextThread = pCurrentThread->pNext;
317 /* Lets let somebody else remove an object now */
318 LeaveCriticalSection(&Thread_CritSect);
322 void statserv_closedown()
324 /* Shouldn't do anything if we are not initialized */
328 HANDLE *pThreadHandles = NULL;
330 /* We need to stop threads adding and removing while we */
331 /* start the closedown process */
332 EnterCriticalSection(&Thread_CritSect);
335 /* We have exclusive access to the thread stuff now */
336 /* Y didn't i use a semaphore - Oh well never mind */
337 ThreadList *pCurrentThread = pFirstThread;
339 /* Before we do anything else, we need to shutdown the listener */
340 if (pListener != NULL)
341 iochan_destroy(pListener);
343 for (; pCurrentThread != NULL; pCurrentThread = pCurrentThread->pNext)
345 /* Just destroy the IOCHAN, that should do the trick */
346 iochan_destroy(pCurrentThread->pIOChannel);
348 /* Keep a running count of our handles */
354 HANDLE *pCurrentHandle ;
356 /* Allocate the thread handle array */
357 pThreadHandles = (HANDLE *)malloc(sizeof(HANDLE) * iHandles);
358 pCurrentHandle = pThreadHandles;
360 for (pCurrentThread = pFirstThread;
361 pCurrentThread != NULL;
362 pCurrentThread = pCurrentThread->pNext, pCurrentHandle++)
364 /* Just the handle */
365 *pCurrentHandle = pCurrentThread->hThread;
369 /* We can now leave the critical section */
370 LeaveCriticalSection(&Thread_CritSect);
373 /* Now we can really do something */
376 /* This will now wait, until all the threads close */
377 WaitForMultipleObjects(iHandles, pThreadHandles, TRUE, INFINITE);
379 /* Free the memory we allocated for the handle array */
380 free(pThreadHandles);
383 /* No longer require the critical section, since all threads are dead */
384 DeleteCriticalSection(&Thread_CritSect);
388 int __stdcall event_loop_thread (IOCHAN iochan)
390 return event_loop (&iochan);
393 static void listener(IOCHAN h, int event)
395 COMSTACK line = (COMSTACK) iochan_getdata(h);
400 if (event == EVENT_INPUT)
402 if ((res = cs_listen(line, 0, 0)) < 0)
404 logf(LOG_FATAL, "cs_listen failed.");
409 logf(LOG_DEBUG, "listen ok");
410 iochan_setevent(h, EVENT_OUTPUT);
411 iochan_setflags(h, EVENT_OUTPUT | EVENT_EXCEPT); /* set up for acpt */
413 else if (event == EVENT_OUTPUT)
420 if (!(new_line = cs_accept(line)))
422 logf(LOG_FATAL, "Accept failed.");
423 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
426 logf(LOG_DEBUG, "Accept ok");
428 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session,
431 logf(LOG_FATAL, "Failed to create iochan");
436 logf(LOG_DEBUG, "Creating association");
437 if (!(newas = create_association(new_chan, new_line)))
439 logf(LOG_FATAL, "Failed to create new assoc.");
443 logf(LOG_DEBUG, "Setting timeout %d", control_block.idle_timeout);
444 iochan_setdata(new_chan, newas);
445 iochan_settimeout(new_chan, control_block.idle_timeout * 60);
447 logf(LOG_DEBUG, "Determining client address");
448 a = cs_addrstr(new_line);
449 logf(LOG_LOG, "Accepted connection from %s", a ? a : "[Unknown]");
451 /* Now what we need todo is create a new thread with this iochan as
453 /* if (CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)event_loop_thread,
454 new_chan, 0, &ThreadId) == NULL) */
455 /* Somehow, somewhere we need to store this thread id, otherwise we
456 won't be able to close cleanly */
457 NewHandle = (HANDLE)_beginthreadex(NULL, 0, event_loop_thread,
458 new_chan, 0, &ThreadId);
459 if (NewHandle == (HANDLE)-1)
462 logf(LOG_FATAL|LOG_ERRNO, "Failed to create new thread.");
466 /* We successfully created the thread, so add it to the list */
467 statserv_add(NewHandle, new_chan);
469 logf(LOG_DEBUG, "Created new thread, iochan %p", new_chan);
470 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
474 logf(LOG_FATAL, "Bad event on listener.");
482 /* To save having an #ifdef in event_loop we need to define this empty function */
483 void statserv_remove(IOCHAN pIOChannel)
487 void statserv_closedown()
490 for (p = pListener; p; p = p->next)
494 static void listener(IOCHAN h, int event)
496 COMSTACK line = (COMSTACK) iochan_getdata(h);
499 static int child = 0;
502 if (event == EVENT_INPUT)
504 if (control_block.dynamic && !child)
510 logf(LOG_FATAL|LOG_ERRNO, "pipe");
514 if ((res = fork()) < 0)
516 logf(LOG_FATAL|LOG_ERRNO, "fork");
520 else if (res == 0) /* child */
527 for (pp = pListener; pp; pp = iochan_getnext(pp))
531 COMSTACK l = (COMSTACK)iochan_getdata(pp);
536 sprintf(nbuf, "%s(%d)", me, getpid());
537 log_init(control_block.loglevel, nbuf, 0);
542 /* wait for child to take the call */
548 if ((res = read(hand[0], dummy, 1)) < 0 && errno != EINTR)
550 logf(LOG_FATAL|LOG_ERRNO, "handshake read");
556 logf(LOG_DEBUG, "P: Child has taken the call");
561 if ((res = cs_listen(line, 0, 0)) < 0)
563 logf(LOG_FATAL, "cs_listen failed.");
568 logf(LOG_DEBUG, "listen ok");
569 iochan_setevent(h, EVENT_OUTPUT);
570 iochan_setflags(h, EVENT_OUTPUT | EVENT_EXCEPT); /* set up for acpt */
572 /* in dynamic mode, only the child ever comes down here */
573 else if (event == EVENT_OUTPUT)
579 if (!(new_line = cs_accept(line)))
581 logf(LOG_FATAL, "Accept failed.");
582 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
585 logf(LOG_DEBUG, "accept ok");
586 if (control_block.dynamic)
589 /* close our half of the listener socket */
590 for (pp = pListener; pp; pp = iochan_getnext(pp))
592 COMSTACK l = (COMSTACK)iochan_getdata(pp);
597 logf(LOG_DEBUG, "Releasing parent");
601 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
603 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session,
606 logf(LOG_FATAL, "Failed to create iochan");
610 new_chan->next = pListener;
611 pListener = new_chan;
612 if (!(newas = create_association(new_chan, new_line)))
614 logf(LOG_FATAL, "Failed to create new assoc.");
618 iochan_setdata(new_chan, newas);
619 iochan_settimeout(new_chan, control_block.idle_timeout * 60);
620 a = cs_addrstr(new_line);
621 logf(LOG_LOG, "Accepted connection from %s", a ? a : "[Unknown]");
625 logf(LOG_FATAL, "Bad event on listener.");
633 static void inetd_connection(int what)
640 if ((line = cs_createbysocket(0, tcpip_type, 0, what)))
642 if ((chan = iochan_create(cs_fileno(line), ir_session, EVENT_INPUT)))
644 if ((assoc = create_association(chan, line)))
646 iochan_setdata(chan, assoc);
647 iochan_settimeout(chan, control_block.idle_timeout * 60);
648 addr = cs_addrstr(line);
649 logf(LOG_LOG, "Inetd association from %s", addr ? addr : "[UNKNOWN]");
653 logf(LOG_FATAL, "Failed to create association structure");
655 chan->next = pListener;
660 logf(LOG_FATAL, "Failed to create iochan");
665 logf(LOG_ERRNO|LOG_FATAL, "Failed to create comstack on socket 0");
670 * Set up a listening endpoint, and give it to the event-handler.
672 static void add_listener(char *where, int what)
676 char mode[100], addr[100];
680 if (!where || sscanf(where, "%[^:]:%s", mode, addr) != 2)
682 logf (LOG_WARN, "%s: Address format: ('tcp'|'osi')':'<address>", me);
685 if (!strcmp(mode, "tcp"))
687 else if (!strcmp(mode, "osi"))
692 logf (LOG_WARN, "OSI Transport not allowed by configuration.");
698 logf (LOG_WARN, "You must specify either 'osi:' or 'tcp:'");
701 logf(LOG_LOG, "Adding %s %s listener on %s",
702 control_block.dynamic ? "dynamic" : "static",
703 what == PROTO_SR ? "SR" : "Z3950", where);
704 if (!(l = cs_create(type, 0, what)))
706 logf(LOG_FATAL|LOG_ERRNO, "Failed to create listener");
708 ap = cs_straddr (l, addr);
711 fprintf(stderr, "Address resolution failed.\n");
715 if (cs_bind(l, ap, CS_SERVER) < 0)
717 logf(LOG_FATAL|LOG_ERRNO, "Failed to bind to %s", where);
719 if (!(lst = iochan_create(cs_fileno(l), listener, EVENT_INPUT |
722 logf(LOG_FATAL|LOG_ERRNO, "Failed to create IOCHAN-type");
724 iochan_setdata(lst, l);
726 /* Ensure our listener chain is setup properly */
727 lst->next = pListener;
732 /* For windows we don't need to catch the signals */
733 static void catchchld(int num)
735 while (waitpid(-1, 0, WNOHANG) > 0)
737 signal(SIGCHLD, catchchld);
741 statserv_options_block *statserv_getcontrol(void)
743 static statserv_options_block cb;
745 memcpy(&cb, &control_block, sizeof(cb));
749 void statserv_setcontrol(statserv_options_block *block)
751 memcpy(&control_block, block, sizeof(*block));
754 int statserv_start(int argc, char **argv)
760 /* We need to initialize the thread list */
761 ThreadList_Initialize();
765 if ((me = strrchr (argv[0], '\\')))
772 if (control_block.options_func(argc, argv))
776 if (control_block.inetd)
777 inetd_connection(control_block.default_proto);
780 if (control_block.pre_init)
781 (*control_block.pre_init)(&control_block);
782 if (control_block.dynamic)
783 signal(SIGCHLD, catchchld);
785 if (*control_block.setuid)
789 if (!(pw = getpwnam(control_block.setuid)))
791 logf(LOG_FATAL, "%s: Unknown user", control_block.setuid);
794 if (setuid(pw->pw_uid) < 0)
796 logf(LOG_FATAL|LOG_ERRNO, "setuid");
802 if ((pListener == NULL) && *control_block.default_listen)
803 add_listener(control_block.default_listen,
804 control_block.default_proto);
805 logf(LOG_LOG, "Entering event loop.");
807 if (pListener == NULL)
810 ret = event_loop(&pListener);
815 int check_options(int argc, char **argv)
820 while ((ret = options("a:iszSl:v:u:c:w:t:k:", argv, argc, &arg)) != -2)
825 add_listener(arg, control_block.default_proto);
828 control_block.default_proto = PROTO_Z3950;
831 control_block.default_proto = PROTO_SR;
834 control_block.dynamic = 0;
837 strcpy(control_block.logfile, arg ? arg : "");
838 log_init(control_block.loglevel, me, control_block.logfile);
841 control_block.loglevel = log_mask_str(arg);
842 log_init(control_block.loglevel, me, control_block.logfile);
845 strcpy(control_block.apdufile, arg ? arg : "");
848 strcpy(control_block.setuid, arg ? arg : "");
851 strcpy(control_block.configname, arg ? arg : "");
854 if (!arg || !(r = atoi(arg)))
856 fprintf(stderr, "%s: Specify positive timeout for -t.\n", me);
859 control_block.idle_timeout = r;
862 if (!arg || !(r = atoi(arg)))
864 fprintf(stderr, "%s: Specify positive timeout for -t.\n", me);
867 control_block.maxrecordsize = r * 1024;
870 control_block.inetd = 1;
880 fprintf(stderr, "Usage: %s [ -i -a <pdufile> -v <loglevel>"
881 " -l <logfile> -u <user> -c <config> -t <minutes>"
883 " -zsS <listener-addr> -w <directory> ... ]\n", me);
897 static Args ArgDetails;
899 /* name of the executable */
900 #define SZAPPNAME "server"
902 /* list of service dependencies - "dep1\0dep2\0\0" */
903 #define SZDEPENDENCIES ""
905 int statserv_main(int argc, char **argv)
907 statserv_options_block *cb = statserv_getcontrol();
909 /* Lets setup the Arg structure */
910 ArgDetails.argc = argc;
911 ArgDetails.argv = argv;
913 /* Now setup the service with the service controller */
914 SetupService(argc, argv, &ArgDetails, SZAPPNAME,
915 cb->service_name, /* internal service name */
916 cb->service_name, /* displayed name of the service */
921 int StartAppService(void *pHandle, int argc, char **argv)
923 /* Initializes the App */
927 void RunAppService(void *pHandle)
929 Args *pArgs = (Args *)pHandle;
931 /* Starts the app running */
932 statserv_start(pArgs->argc, pArgs->argv);
935 void StopAppService(void *pHandle)
938 statserv_closedown();
941 int statserv_main(int argc, char **argv)
943 int ret = statserv_start (argc, argv);
944 statserv_closedown ();