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.49 1998-02-27 14:04:55 adam
11 * Fixed bug in statserv_remove.
13 * Revision 1.48 1998/02/11 11:53:36 adam
14 * Changed code so that it compiles as C++.
16 * Revision 1.47 1998/02/10 10:28:57 adam
17 * Added app_name, service_dependencies, service_display_name and
18 * options_func. options_func allows us to specify a different function
19 * to interogate the command line arguments. The other members allow us
20 * to pass the full service details accross to the service manager (CW).
23 * Revision 1.46 1998/01/30 15:24:57 adam
24 * Fixed bug in inetd code. The server listened on tcp:@:9999 even
25 * though it was started in inetd mode.
27 * Revision 1.45 1998/01/29 13:30:23 adam
28 * Better event handle system for NT/Unix.
30 * Revision 1.44 1997/11/07 13:31:52 adam
31 * Added NT Service name part of statserv_options_block. Moved NT
32 * service utility to server library.
34 * Revision 1.43 1997/10/31 12:20:09 adam
35 * Improved memory debugging for xmalloc/nmem.c. References to NMEM
36 * instead of ODR in n ESPEC-1 handling in source d1_espec.c.
37 * Bug fix: missing fclose in data1_read_espec1.
39 * Revision 1.42 1997/10/27 14:03:02 adam
40 * Added new member to statserver_options_block, pre_init, which
41 * specifies a callback to be invoked after command line parsing and
42 * before the server listens for the first time.
44 * Revision 1.41 1997/09/29 07:19:32 adam
45 * Server library uses nmem_init/nmem_exit. The log prefix no longer
46 * includes leading path on NT.
48 * Revision 1.40 1997/09/17 12:10:41 adam
51 * Revision 1.39 1997/09/09 10:10:19 adam
52 * Another MSV5.0 port. Changed projects to include proper
53 * library/include paths.
54 * Server starts server in test-mode when no options are given.
56 * Revision 1.38 1997/09/04 14:19:14 adam
59 * Revision 1.37 1997/09/01 08:53:01 adam
60 * New windows NT/95 port using MSV5.0. The test server 'ztest' was
61 * moved a separate directory. MSV5.0 project server.dsp created.
62 * As an option, the server can now operate as an NT service.
64 * Revision 1.36 1996/07/06 19:58:36 quinn
65 * System headerfiles gathered in yconfig
67 * Revision 1.35 1996/05/29 10:03:28 quinn
70 * Revision 1.34 1996/02/21 13:12:07 quinn
71 * *** empty log message ***
73 * Revision 1.33 1996/02/10 12:23:49 quinn
74 * Enable inetd operations fro TCP/IP stack
76 * Revision 1.32 1996/01/19 15:41:52 quinn
77 * *** empty log message ***
79 * Revision 1.31 1995/11/17 11:09:39 adam
80 * Added new option '-c' to specify configuration name in control block.
82 * Revision 1.30 1995/11/01 13:54:59 quinn
85 * Revision 1.29 1995/10/30 12:41:29 quinn
86 * Added hostname lookup for server.
88 * Revision 1.28 1995/09/29 17:12:30 quinn
91 * Revision 1.27 1995/09/27 15:03:02 quinn
92 * Modified function heads & prototypes.
94 * Revision 1.26 1995/08/29 14:44:51 quinn
97 * Revision 1.25 1995/08/29 11:18:02 quinn
98 * Added code to receive close
100 * Revision 1.24 1995/06/16 10:31:39 quinn
101 * Added session timeout.
103 * Revision 1.23 1995/06/15 12:30:48 quinn
106 * Revision 1.22 1995/06/15 07:45:17 quinn
109 * Revision 1.21 1995/06/06 08:15:40 quinn
112 * Revision 1.20 1995/05/29 08:12:09 quinn
115 * Revision 1.19 1995/05/16 09:37:27 quinn
118 * Revision 1.18 1995/05/16 08:51:09 quinn
119 * License, documentation, and memory fixes
121 * Revision 1.17 1995/05/15 11:56:42 quinn
122 * Asynchronous facilities. Restructuring of seshigh code.
124 * Revision 1.16 1995/04/10 10:23:40 quinn
125 * Some work to add scan and other things.
127 * Revision 1.15 1995/03/31 10:16:51 quinn
130 * Revision 1.14 1995/03/31 09:18:58 quinn
133 * Revision 1.13 1995/03/30 16:08:39 quinn
136 * Revision 1.12 1995/03/30 13:29:02 quinn
139 * Revision 1.11 1995/03/30 12:18:17 quinn
142 * Revision 1.10 1995/03/29 15:40:16 quinn
143 * Ongoing work. Statserv is now dynamic by default
145 * Revision 1.9 1995/03/27 08:34:30 quinn
146 * Added dynamic server functionality.
147 * Released bindings to session.c (is now redundant)
149 * Revision 1.8 1995/03/20 09:46:26 quinn
152 * Revision 1.7 1995/03/16 13:29:04 quinn
153 * Partitioned server.
155 * Revision 1.6 1995/03/15 15:18:52 quinn
156 * Little changes to better support nonblocking I/O
159 * Revision 1.5 1995/03/15 08:37:45 quinn
160 * Now we're pretty much set for nonblocking I/O.
162 * Revision 1.4 1995/03/14 16:59:48 quinn
165 * Revision 1.3 1995/03/14 11:30:15 quinn
168 * Revision 1.2 1995/03/14 10:28:03 quinn
169 * More work on demo server.
171 * Revision 1.1 1995/03/10 18:22:45 quinn
172 * The rudiments of an asynchronous server.
193 #include <comstack.h>
201 #include <statserv.h>
203 static IOCHAN pListener = NULL;
205 static char *me = "statserver";
209 int check_options(int argc, char **argv);
210 statserv_options_block control_block = {
211 1, /* dynamic mode */
212 LOG_DEFAULT_LEVEL, /* log level */
214 "", /* diagnostic output to stderr */
215 "tcp:@:9999", /* default listener port */
216 PROTO_Z3950, /* default application protocol */
217 60, /* idle timeout (minutes) */
218 1024*1024, /* maximum PDU size (approx.) to allow */
219 "default-config", /* configuration name to pass to backend */
220 "", /* set user id */
221 NULL, /* pre init handler */
222 check_options, /* Default routine, for checking the run-time arguments */
223 0 /* default value for inet deamon */
226 ,"Z39.50 Server", /* NT Service Name */
227 "Server", /* NT application Name */
228 "", /* NT Service Dependencies */
229 "Z39.50 Server" /* NT Service Display Name */
234 * handle incoming connect requests.
235 * The dynamic mode is a bit tricky mostly because we want to avoid
236 * doing all of the listening and accepting in the parent - it's
241 typedef struct _ThreadList ThreadList;
250 static ThreadList *pFirstThread;
251 static CRITICAL_SECTION Thread_CritSect;
252 static BOOL bInitialized = FALSE;
254 static void ThreadList_Initialize()
256 /* Initialize the critical Sections */
257 InitializeCriticalSection(&Thread_CritSect);
259 /* Set the first thraed */
262 /* we have been initialized */
266 static void statserv_add(HANDLE hThread, IOCHAN pIOChannel)
268 /* Only one thread can go through this section at a time */
269 EnterCriticalSection(&Thread_CritSect);
272 /* Lets create our new object */
273 ThreadList *pNewThread = (ThreadList *)malloc(sizeof(ThreadList));
274 pNewThread->hThread = hThread;
275 pNewThread->pIOChannel = pIOChannel;
276 pNewThread->pNext = pFirstThread;
277 pFirstThread = pNewThread;
279 /* Lets let somebody else create a new object now */
280 LeaveCriticalSection(&Thread_CritSect);
284 void statserv_remove(IOCHAN pIOChannel)
286 /* Only one thread can go through this section at a time */
287 EnterCriticalSection(&Thread_CritSect);
290 ThreadList *pCurrentThread = pFirstThread;
291 ThreadList *pNextThread;
292 ThreadList *pPrevThread =NULL;
294 /* Step through alll the threads */
295 for (; pCurrentThread != NULL; pCurrentThread = pNextThread)
297 /* We only need to compare on the IO Channel */
298 if (pCurrentThread->pIOChannel == pIOChannel)
300 /* We have found the thread we want to delete */
301 /* First of all reset the next pointers */
302 if (pPrevThread == NULL)
303 pFirstThread = pCurrentThread->pNext;
305 pPrevThread->pNext = pCurrentThread->pNext;
307 /* All we need todo now is delete the memory */
308 free(pCurrentThread);
310 /* No need to look at any more threads */
315 /* We need to look at another thread */
316 pNextThread = pCurrentThread->pNext;
317 pPrevThread = pCurrentThread;
321 /* Lets let somebody else remove an object now */
322 LeaveCriticalSection(&Thread_CritSect);
326 void statserv_closedown()
328 /* Shouldn't do anything if we are not initialized */
332 HANDLE *pThreadHandles = NULL;
334 /* We need to stop threads adding and removing while we */
335 /* start the closedown process */
336 EnterCriticalSection(&Thread_CritSect);
339 /* We have exclusive access to the thread stuff now */
340 /* Y didn't i use a semaphore - Oh well never mind */
341 ThreadList *pCurrentThread = pFirstThread;
343 /* Before we do anything else, we need to shutdown the listener */
344 if (pListener != NULL)
345 iochan_destroy(pListener);
347 for (; pCurrentThread != NULL; pCurrentThread = pCurrentThread->pNext)
349 /* Just destroy the IOCHAN, that should do the trick */
350 iochan_destroy(pCurrentThread->pIOChannel);
352 /* Keep a running count of our handles */
358 HANDLE *pCurrentHandle ;
360 /* Allocate the thread handle array */
361 pThreadHandles = (HANDLE *)malloc(sizeof(HANDLE) * iHandles);
362 pCurrentHandle = pThreadHandles;
364 for (pCurrentThread = pFirstThread;
365 pCurrentThread != NULL;
366 pCurrentThread = pCurrentThread->pNext, pCurrentHandle++)
368 /* Just the handle */
369 *pCurrentHandle = pCurrentThread->hThread;
373 /* We can now leave the critical section */
374 LeaveCriticalSection(&Thread_CritSect);
377 /* Now we can really do something */
380 /* This will now wait, until all the threads close */
381 WaitForMultipleObjects(iHandles, pThreadHandles, TRUE, INFINITE);
383 /* Free the memory we allocated for the handle array */
384 free(pThreadHandles);
387 /* No longer require the critical section, since all threads are dead */
388 DeleteCriticalSection(&Thread_CritSect);
392 int __stdcall event_loop_thread (IOCHAN iochan)
394 return event_loop (&iochan);
397 static void listener(IOCHAN h, int event)
399 COMSTACK line = (COMSTACK) iochan_getdata(h);
404 if (event == EVENT_INPUT)
406 if ((res = cs_listen(line, 0, 0)) < 0)
408 logf(LOG_FATAL, "cs_listen failed.");
413 logf(LOG_DEBUG, "listen ok");
414 iochan_setevent(h, EVENT_OUTPUT);
415 iochan_setflags(h, EVENT_OUTPUT | EVENT_EXCEPT); /* set up for acpt */
417 else if (event == EVENT_OUTPUT)
424 if (!(new_line = cs_accept(line)))
426 logf(LOG_FATAL, "Accept failed.");
427 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
430 logf(LOG_DEBUG, "Accept ok");
432 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session,
435 logf(LOG_FATAL, "Failed to create iochan");
440 logf(LOG_DEBUG, "Creating association");
441 if (!(newas = create_association(new_chan, new_line)))
443 logf(LOG_FATAL, "Failed to create new assoc.");
447 logf(LOG_DEBUG, "Setting timeout %d", control_block.idle_timeout);
448 iochan_setdata(new_chan, newas);
449 iochan_settimeout(new_chan, control_block.idle_timeout * 60);
451 logf(LOG_DEBUG, "Determining client address");
452 a = cs_addrstr(new_line);
453 logf(LOG_LOG, "Accepted connection from %s", a ? a : "[Unknown]");
455 /* Now what we need todo is create a new thread with this iochan as
457 /* if (CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)event_loop_thread,
458 new_chan, 0, &ThreadId) == NULL) */
459 /* Somehow, somewhere we need to store this thread id, otherwise we
460 won't be able to close cleanly */
461 NewHandle = (HANDLE)_beginthreadex(NULL, 0, event_loop_thread,
462 new_chan, 0, &ThreadId);
463 if (NewHandle == (HANDLE)-1)
466 logf(LOG_FATAL|LOG_ERRNO, "Failed to create new thread.");
470 /* We successfully created the thread, so add it to the list */
471 statserv_add(NewHandle, new_chan);
473 logf(LOG_DEBUG, "Created new thread, iochan %p", new_chan);
474 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
478 logf(LOG_FATAL, "Bad event on listener.");
486 /* To save having an #ifdef in event_loop we need to define this empty function */
487 void statserv_remove(IOCHAN pIOChannel)
491 void statserv_closedown()
494 for (p = pListener; p; p = p->next)
498 static void listener(IOCHAN h, int event)
500 COMSTACK line = (COMSTACK) iochan_getdata(h);
503 static int child = 0;
506 if (event == EVENT_INPUT)
508 if (control_block.dynamic && !child)
514 logf(LOG_FATAL|LOG_ERRNO, "pipe");
518 if ((res = fork()) < 0)
520 logf(LOG_FATAL|LOG_ERRNO, "fork");
524 else if (res == 0) /* child */
531 for (pp = pListener; pp; pp = iochan_getnext(pp))
535 COMSTACK l = (COMSTACK)iochan_getdata(pp);
540 sprintf(nbuf, "%s(%d)", me, getpid());
541 log_init(control_block.loglevel, nbuf, 0);
546 /* wait for child to take the call */
552 if ((res = read(hand[0], dummy, 1)) < 0 && errno != EINTR)
554 logf(LOG_FATAL|LOG_ERRNO, "handshake read");
560 logf(LOG_DEBUG, "P: Child has taken the call");
565 if ((res = cs_listen(line, 0, 0)) < 0)
567 logf(LOG_FATAL, "cs_listen failed.");
572 logf(LOG_DEBUG, "listen ok");
573 iochan_setevent(h, EVENT_OUTPUT);
574 iochan_setflags(h, EVENT_OUTPUT | EVENT_EXCEPT); /* set up for acpt */
576 /* in dynamic mode, only the child ever comes down here */
577 else if (event == EVENT_OUTPUT)
583 if (!(new_line = cs_accept(line)))
585 logf(LOG_FATAL, "Accept failed.");
586 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
589 logf(LOG_DEBUG, "accept ok");
590 if (control_block.dynamic)
593 /* close our half of the listener socket */
594 for (pp = pListener; pp; pp = iochan_getnext(pp))
596 COMSTACK l = (COMSTACK)iochan_getdata(pp);
601 logf(LOG_DEBUG, "Releasing parent");
605 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
607 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session,
610 logf(LOG_FATAL, "Failed to create iochan");
614 new_chan->next = pListener;
615 pListener = new_chan;
616 if (!(newas = create_association(new_chan, new_line)))
618 logf(LOG_FATAL, "Failed to create new assoc.");
622 iochan_setdata(new_chan, newas);
623 iochan_settimeout(new_chan, control_block.idle_timeout * 60);
624 a = cs_addrstr(new_line);
625 logf(LOG_LOG, "Accepted connection from %s", a ? a : "[Unknown]");
629 logf(LOG_FATAL, "Bad event on listener.");
637 static void inetd_connection(int what)
644 if ((line = cs_createbysocket(0, tcpip_type, 0, what)))
646 if ((chan = iochan_create(cs_fileno(line), ir_session, EVENT_INPUT)))
648 if ((assoc = create_association(chan, line)))
650 iochan_setdata(chan, assoc);
651 iochan_settimeout(chan, control_block.idle_timeout * 60);
652 addr = cs_addrstr(line);
653 logf(LOG_LOG, "Inetd association from %s", addr ? addr : "[UNKNOWN]");
657 logf(LOG_FATAL, "Failed to create association structure");
659 chan->next = pListener;
664 logf(LOG_FATAL, "Failed to create iochan");
669 logf(LOG_ERRNO|LOG_FATAL, "Failed to create comstack on socket 0");
674 * Set up a listening endpoint, and give it to the event-handler.
676 static void add_listener(char *where, int what)
680 char mode[100], addr[100];
684 if (!where || sscanf(where, "%[^:]:%s", mode, addr) != 2)
686 logf (LOG_WARN, "%s: Address format: ('tcp'|'osi')':'<address>", me);
689 if (!strcmp(mode, "tcp"))
691 else if (!strcmp(mode, "osi"))
696 logf (LOG_WARN, "OSI Transport not allowed by configuration.");
702 logf (LOG_WARN, "You must specify either 'osi:' or 'tcp:'");
705 logf(LOG_LOG, "Adding %s %s listener on %s",
706 control_block.dynamic ? "dynamic" : "static",
707 what == PROTO_SR ? "SR" : "Z3950", where);
708 if (!(l = cs_create(type, 0, what)))
710 logf(LOG_FATAL|LOG_ERRNO, "Failed to create listener");
712 ap = cs_straddr (l, addr);
715 fprintf(stderr, "Address resolution failed.\n");
719 if (cs_bind(l, ap, CS_SERVER) < 0)
721 logf(LOG_FATAL|LOG_ERRNO, "Failed to bind to %s", where);
723 if (!(lst = iochan_create(cs_fileno(l), listener, EVENT_INPUT |
726 logf(LOG_FATAL|LOG_ERRNO, "Failed to create IOCHAN-type");
728 iochan_setdata(lst, l);
730 /* Ensure our listener chain is setup properly */
731 lst->next = pListener;
736 /* For windows we don't need to catch the signals */
737 static void catchchld(int num)
739 while (waitpid(-1, 0, WNOHANG) > 0)
741 signal(SIGCHLD, catchchld);
745 statserv_options_block *statserv_getcontrol(void)
747 static statserv_options_block cb;
749 memcpy(&cb, &control_block, sizeof(cb));
753 void statserv_setcontrol(statserv_options_block *block)
755 memcpy(&control_block, block, sizeof(*block));
758 int statserv_start(int argc, char **argv)
764 /* We need to initialize the thread list */
765 ThreadList_Initialize();
769 if ((me = strrchr (argv[0], '\\')))
776 if (control_block.options_func(argc, argv))
780 if (control_block.inetd)
781 inetd_connection(control_block.default_proto);
784 if (control_block.pre_init)
785 (*control_block.pre_init)(&control_block);
786 if (control_block.dynamic)
787 signal(SIGCHLD, catchchld);
789 if (*control_block.setuid)
793 if (!(pw = getpwnam(control_block.setuid)))
795 logf(LOG_FATAL, "%s: Unknown user", control_block.setuid);
798 if (setuid(pw->pw_uid) < 0)
800 logf(LOG_FATAL|LOG_ERRNO, "setuid");
806 if ((pListener == NULL) && *control_block.default_listen)
807 add_listener(control_block.default_listen,
808 control_block.default_proto);
809 logf(LOG_LOG, "Entering event loop.");
811 if (pListener == NULL)
814 ret = event_loop(&pListener);
819 int check_options(int argc, char **argv)
824 while ((ret = options("a:iszSl:v:u:c:w:t:k:", argv, argc, &arg)) != -2)
829 add_listener(arg, control_block.default_proto);
832 control_block.default_proto = PROTO_Z3950;
835 control_block.default_proto = PROTO_SR;
838 control_block.dynamic = 0;
841 strcpy(control_block.logfile, arg ? arg : "");
842 log_init(control_block.loglevel, me, control_block.logfile);
845 control_block.loglevel = log_mask_str(arg);
846 log_init(control_block.loglevel, me, control_block.logfile);
849 strcpy(control_block.apdufile, arg ? arg : "");
852 strcpy(control_block.setuid, arg ? arg : "");
855 strcpy(control_block.configname, arg ? arg : "");
858 if (!arg || !(r = atoi(arg)))
860 fprintf(stderr, "%s: Specify positive timeout for -t.\n", me);
863 control_block.idle_timeout = r;
866 if (!arg || !(r = atoi(arg)))
868 fprintf(stderr, "%s: Specify positive timeout for -t.\n", me);
871 control_block.maxrecordsize = r * 1024;
874 control_block.inetd = 1;
884 fprintf(stderr, "Usage: %s [ -i -a <pdufile> -v <loglevel>"
885 " -l <logfile> -u <user> -c <config> -t <minutes>"
887 " -zsS <listener-addr> -w <directory> ... ]\n", me);
901 static Args ArgDetails;
903 /* name of the executable */
904 #define SZAPPNAME "server"
906 /* list of service dependencies - "dep1\0dep2\0\0" */
907 #define SZDEPENDENCIES ""
909 int statserv_main(int argc, char **argv)
911 statserv_options_block *cb = statserv_getcontrol();
913 /* Lets setup the Arg structure */
914 ArgDetails.argc = argc;
915 ArgDetails.argv = argv;
917 /* Now setup the service with the service controller */
918 SetupService(argc, argv, &ArgDetails, SZAPPNAME,
919 cb->service_name, /* internal service name */
920 cb->service_name, /* displayed name of the service */
925 int StartAppService(void *pHandle, int argc, char **argv)
927 /* Initializes the App */
931 void RunAppService(void *pHandle)
933 Args *pArgs = (Args *)pHandle;
935 /* Starts the app running */
936 statserv_start(pArgs->argc, pArgs->argv);
939 void StopAppService(void *pHandle)
942 statserv_closedown();
945 int statserv_main(int argc, char **argv)
947 int ret = statserv_start (argc, argv);
948 statserv_closedown ();