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.47 1998-02-10 10:28:57 adam
11 * Added app_name, service_dependencies, service_display_name and
12 * options_func. options_func allows us to specify a different function
13 * to interogate the command line arguments. The other members allow us
14 * to pass the full service details accross to the service manager (CW).
17 * Revision 1.46 1998/01/30 15:24:57 adam
18 * Fixed bug in inetd code. The server listened on tcp:@:9999 even
19 * though it was started in inetd mode.
21 * Revision 1.45 1998/01/29 13:30:23 adam
22 * Better event handle system for NT/Unix.
24 * Revision 1.44 1997/11/07 13:31:52 adam
25 * Added NT Service name part of statserv_options_block. Moved NT
26 * service utility to server library.
28 * Revision 1.43 1997/10/31 12:20:09 adam
29 * Improved memory debugging for xmalloc/nmem.c. References to NMEM
30 * instead of ODR in n ESPEC-1 handling in source d1_espec.c.
31 * Bug fix: missing fclose in data1_read_espec1.
33 * Revision 1.42 1997/10/27 14:03:02 adam
34 * Added new member to statserver_options_block, pre_init, which
35 * specifies a callback to be invoked after command line parsing and
36 * before the server listens for the first time.
38 * Revision 1.41 1997/09/29 07:19:32 adam
39 * Server library uses nmem_init/nmem_exit. The log prefix no longer
40 * includes leading path on NT.
42 * Revision 1.40 1997/09/17 12:10:41 adam
45 * Revision 1.39 1997/09/09 10:10:19 adam
46 * Another MSV5.0 port. Changed projects to include proper
47 * library/include paths.
48 * Server starts server in test-mode when no options are given.
50 * Revision 1.38 1997/09/04 14:19:14 adam
53 * Revision 1.37 1997/09/01 08:53:01 adam
54 * New windows NT/95 port using MSV5.0. The test server 'ztest' was
55 * moved a separate directory. MSV5.0 project server.dsp created.
56 * As an option, the server can now operate as an NT service.
58 * Revision 1.36 1996/07/06 19:58:36 quinn
59 * System headerfiles gathered in yconfig
61 * Revision 1.35 1996/05/29 10:03:28 quinn
64 * Revision 1.34 1996/02/21 13:12:07 quinn
65 * *** empty log message ***
67 * Revision 1.33 1996/02/10 12:23:49 quinn
68 * Enable inetd operations fro TCP/IP stack
70 * Revision 1.32 1996/01/19 15:41:52 quinn
71 * *** empty log message ***
73 * Revision 1.31 1995/11/17 11:09:39 adam
74 * Added new option '-c' to specify configuration name in control block.
76 * Revision 1.30 1995/11/01 13:54:59 quinn
79 * Revision 1.29 1995/10/30 12:41:29 quinn
80 * Added hostname lookup for server.
82 * Revision 1.28 1995/09/29 17:12:30 quinn
85 * Revision 1.27 1995/09/27 15:03:02 quinn
86 * Modified function heads & prototypes.
88 * Revision 1.26 1995/08/29 14:44:51 quinn
91 * Revision 1.25 1995/08/29 11:18:02 quinn
92 * Added code to receive close
94 * Revision 1.24 1995/06/16 10:31:39 quinn
95 * Added session timeout.
97 * Revision 1.23 1995/06/15 12:30:48 quinn
100 * Revision 1.22 1995/06/15 07:45:17 quinn
103 * Revision 1.21 1995/06/06 08:15:40 quinn
106 * Revision 1.20 1995/05/29 08:12:09 quinn
109 * Revision 1.19 1995/05/16 09:37:27 quinn
112 * Revision 1.18 1995/05/16 08:51:09 quinn
113 * License, documentation, and memory fixes
115 * Revision 1.17 1995/05/15 11:56:42 quinn
116 * Asynchronous facilities. Restructuring of seshigh code.
118 * Revision 1.16 1995/04/10 10:23:40 quinn
119 * Some work to add scan and other things.
121 * Revision 1.15 1995/03/31 10:16:51 quinn
124 * Revision 1.14 1995/03/31 09:18:58 quinn
127 * Revision 1.13 1995/03/30 16:08:39 quinn
130 * Revision 1.12 1995/03/30 13:29:02 quinn
133 * Revision 1.11 1995/03/30 12:18:17 quinn
136 * Revision 1.10 1995/03/29 15:40:16 quinn
137 * Ongoing work. Statserv is now dynamic by default
139 * Revision 1.9 1995/03/27 08:34:30 quinn
140 * Added dynamic server functionality.
141 * Released bindings to session.c (is now redundant)
143 * Revision 1.8 1995/03/20 09:46:26 quinn
146 * Revision 1.7 1995/03/16 13:29:04 quinn
147 * Partitioned server.
149 * Revision 1.6 1995/03/15 15:18:52 quinn
150 * Little changes to better support nonblocking I/O
153 * Revision 1.5 1995/03/15 08:37:45 quinn
154 * Now we're pretty much set for nonblocking I/O.
156 * Revision 1.4 1995/03/14 16:59:48 quinn
159 * Revision 1.3 1995/03/14 11:30:15 quinn
162 * Revision 1.2 1995/03/14 10:28:03 quinn
163 * More work on demo server.
165 * Revision 1.1 1995/03/10 18:22:45 quinn
166 * The rudiments of an asynchronous server.
187 #include <comstack.h>
195 #include <statserv.h>
197 static IOCHAN pListener = NULL;
199 static char *me = "statserver";
203 int check_options(int argc, char **argv);
204 statserv_options_block control_block = {
205 1, /* dynamic mode */
206 LOG_DEFAULT_LEVEL, /* log level */
208 "", /* diagnostic output to stderr */
209 "tcp:@:9999", /* default listener port */
210 PROTO_Z3950, /* default application protocol */
211 60, /* idle timeout (minutes) */
212 1024*1024, /* maximum PDU size (approx.) to allow */
213 "default-config", /* configuration name to pass to backend */
214 "", /* set user id */
215 NULL, /* pre init handler */
216 check_options, /* Default routine, for checking the run-time arguments */
217 0 /* default value for inet deamon */
220 ,"Z39.50 Server", /* NT Service Name */
221 "Server", /* NT application Name */
222 "", /* NT Service Dependencies */
223 "Z39.50 Server" /* NT Service Display Name */
228 * handle incoming connect requests.
229 * The dynamic mode is a bit tricky mostly because we want to avoid
230 * doing all of the listening and accepting in the parent - it's
235 typedef struct _ThreadList ThreadList;
244 static ThreadList *pFirstThread;
245 static CRITICAL_SECTION Thread_CritSect;
246 static BOOL bInitialized = FALSE;
248 static void ThreadList_Initialize()
250 /* Initialize the critical Sections */
251 InitializeCriticalSection(&Thread_CritSect);
253 /* Set the first thraed */
256 /* we have been initialized */
260 static void statserv_add(HANDLE hThread, IOCHAN pIOChannel)
262 /* Only one thread can go through this section at a time */
263 EnterCriticalSection(&Thread_CritSect);
266 /* Lets create our new object */
267 ThreadList *pNewThread = (ThreadList *)malloc(sizeof(ThreadList));
268 pNewThread->hThread = hThread;
269 pNewThread->pIOChannel = pIOChannel;
270 pNewThread->pNext = pFirstThread;
271 pFirstThread = pNewThread;
273 /* Lets let somebody else create a new object now */
274 LeaveCriticalSection(&Thread_CritSect);
278 void statserv_remove(IOCHAN pIOChannel)
280 /* Only one thread can go through this section at a time */
281 EnterCriticalSection(&Thread_CritSect);
284 ThreadList *pCurrentThread = pFirstThread;
285 ThreadList *pNextThread;
286 ThreadList *pPrevThread =NULL;
288 /* Step through alll the threads */
289 for (; pCurrentThread != NULL; pCurrentThread = pNextThread)
291 /* We only need to compare on the IO Channel */
292 if (pCurrentThread->pIOChannel == pIOChannel)
294 /* We have found the thread we want to delete */
295 /* First of all reset the next pointers */
296 if (pPrevThread == NULL)
297 pFirstThread = pCurrentThread->pNext;
299 pPrevThread->pNext = pCurrentThread->pNext;
301 /* All we need todo now is delete the memory */
302 free(pCurrentThread);
304 /* No need to look at any more threads */
309 /* We need to look at another thread */
310 pNextThread = pCurrentThread->pNext;
314 /* Lets let somebody else remove an object now */
315 LeaveCriticalSection(&Thread_CritSect);
319 void statserv_closedown()
321 /* Shouldn't do anything if we are not initialized */
325 HANDLE *pThreadHandles = NULL;
327 /* We need to stop threads adding and removing while we */
328 /* start the closedown process */
329 EnterCriticalSection(&Thread_CritSect);
332 /* We have exclusive access to the thread stuff now */
333 /* Y didn't i use a semaphore - Oh well never mind */
334 ThreadList *pCurrentThread = pFirstThread;
336 /* Before we do anything else, we need to shutdown the listener */
337 if (pListener != NULL)
338 iochan_destroy(pListener);
340 for (; pCurrentThread != NULL; pCurrentThread = pCurrentThread->pNext)
342 /* Just destroy the IOCHAN, that should do the trick */
343 iochan_destroy(pCurrentThread->pIOChannel);
345 /* Keep a running count of our handles */
351 HANDLE *pCurrentHandle ;
353 /* Allocate the thread handle array */
354 pThreadHandles = (HANDLE *)malloc(sizeof(HANDLE) * iHandles);
355 pCurrentHandle = pThreadHandles;
357 for (pCurrentThread = pFirstThread;
358 pCurrentThread != NULL;
359 pCurrentThread = pCurrentThread->pNext, pCurrentHandle++)
361 /* Just the handle */
362 *pCurrentHandle = pCurrentThread->hThread;
366 /* We can now leave the critical section */
367 LeaveCriticalSection(&Thread_CritSect);
370 /* Now we can really do something */
373 /* This will now wait, until all the threads close */
374 WaitForMultipleObjects(iHandles, pThreadHandles, TRUE, INFINITE);
376 /* Free the memory we allocated for the handle array */
377 free(pThreadHandles);
380 /* No longer require the critical section, since all threads are dead */
381 DeleteCriticalSection(&Thread_CritSect);
385 int __stdcall event_loop_thread (IOCHAN iochan)
387 return event_loop (&iochan);
390 static void listener(IOCHAN h, int event)
392 COMSTACK line = (COMSTACK) iochan_getdata(h);
397 if (event == EVENT_INPUT)
399 if ((res = cs_listen(line, 0, 0)) < 0)
401 logf(LOG_FATAL, "cs_listen failed.");
406 logf(LOG_DEBUG, "listen ok");
407 iochan_setevent(h, EVENT_OUTPUT);
408 iochan_setflags(h, EVENT_OUTPUT | EVENT_EXCEPT); /* set up for acpt */
410 else if (event == EVENT_OUTPUT)
417 if (!(new_line = cs_accept(line)))
419 logf(LOG_FATAL, "Accept failed.");
420 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
423 logf(LOG_DEBUG, "Accept ok");
425 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session,
428 logf(LOG_FATAL, "Failed to create iochan");
433 logf(LOG_DEBUG, "Creating association");
434 if (!(newas = create_association(new_chan, new_line)))
436 logf(LOG_FATAL, "Failed to create new assoc.");
440 logf(LOG_DEBUG, "Setting timeout %d", control_block.idle_timeout);
441 iochan_setdata(new_chan, newas);
442 iochan_settimeout(new_chan, control_block.idle_timeout * 60);
444 logf(LOG_DEBUG, "Determining client address");
445 a = cs_addrstr(new_line);
446 logf(LOG_LOG, "Accepted connection from %s", a ? a : "[Unknown]");
448 /* Now what we need todo is create a new thread with this iochan as
450 /* if (CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)event_loop_thread,
451 new_chan, 0, &ThreadId) == NULL) */
452 /* Somehow, somewhere we need to store this thread id, otherwise we
453 won't be able to close cleanly */
454 NewHandle = (HANDLE)_beginthreadex(NULL, 0, event_loop_thread,
455 new_chan, 0, &ThreadId);
456 if (NewHandle == (HANDLE)-1)
459 logf(LOG_FATAL|LOG_ERRNO, "Failed to create new thread.");
463 /* We successfully created the thread, so add it to the list */
464 statserv_add(NewHandle, new_chan);
466 logf(LOG_DEBUG, "Created new thread, iochan %p", new_chan);
467 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
471 logf(LOG_FATAL, "Bad event on listener.");
479 /* To save having an #ifdef in event_loop we need to define this empty function */
480 void statserv_remove(IOCHAN pIOChannel)
484 void statserv_closedown()
487 for (p = pListener; p; p = p->next)
491 static void listener(IOCHAN h, int event)
493 COMSTACK line = (COMSTACK) iochan_getdata(h);
496 static int child = 0;
499 if (event == EVENT_INPUT)
501 if (control_block.dynamic && !child)
507 logf(LOG_FATAL|LOG_ERRNO, "pipe");
511 if ((res = fork()) < 0)
513 logf(LOG_FATAL|LOG_ERRNO, "fork");
517 else if (res == 0) /* child */
524 for (pp = pListener; pp; pp = iochan_getnext(pp))
528 COMSTACK l = iochan_getdata(pp);
533 sprintf(nbuf, "%s(%d)", me, getpid());
534 log_init(control_block.loglevel, nbuf, 0);
539 /* wait for child to take the call */
545 if ((res = read(hand[0], dummy, 1)) < 0 && errno != EINTR)
547 logf(LOG_FATAL|LOG_ERRNO, "handshake read");
553 logf(LOG_DEBUG, "P: Child has taken the call");
558 if ((res = cs_listen(line, 0, 0)) < 0)
560 logf(LOG_FATAL, "cs_listen failed.");
565 logf(LOG_DEBUG, "listen ok");
566 iochan_setevent(h, EVENT_OUTPUT);
567 iochan_setflags(h, EVENT_OUTPUT | EVENT_EXCEPT); /* set up for acpt */
569 /* in dynamic mode, only the child ever comes down here */
570 else if (event == EVENT_OUTPUT)
576 if (!(new_line = cs_accept(line)))
578 logf(LOG_FATAL, "Accept failed.");
579 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
582 logf(LOG_DEBUG, "accept ok");
583 if (control_block.dynamic)
586 /* close our half of the listener socket */
587 for (pp = pListener; pp; pp = iochan_getnext(pp))
589 COMSTACK l = iochan_getdata(pp);
594 logf(LOG_DEBUG, "Releasing parent");
598 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
600 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session,
603 logf(LOG_FATAL, "Failed to create iochan");
607 new_chan->next = pListener;
608 pListener = new_chan;
609 if (!(newas = create_association(new_chan, new_line)))
611 logf(LOG_FATAL, "Failed to create new assoc.");
615 iochan_setdata(new_chan, newas);
616 iochan_settimeout(new_chan, control_block.idle_timeout * 60);
617 a = cs_addrstr(new_line);
618 logf(LOG_LOG, "Accepted connection from %s", a ? a : "[Unknown]");
622 logf(LOG_FATAL, "Bad event on listener.");
630 static void inetd_connection(int what)
637 if ((line = cs_createbysocket(0, tcpip_type, 0, what)))
639 if ((chan = iochan_create(cs_fileno(line), ir_session, EVENT_INPUT)))
641 if ((assoc = create_association(chan, line)))
643 iochan_setdata(chan, assoc);
644 iochan_settimeout(chan, control_block.idle_timeout * 60);
645 addr = cs_addrstr(line);
646 logf(LOG_LOG, "Inetd association from %s", addr ? addr : "[UNKNOWN]");
650 logf(LOG_FATAL, "Failed to create association structure");
652 chan->next = pListener;
657 logf(LOG_FATAL, "Failed to create iochan");
662 logf(LOG_ERRNO|LOG_FATAL, "Failed to create comstack on socket 0");
667 * Set up a listening endpoint, and give it to the event-handler.
669 static void add_listener(char *where, int what)
673 char mode[100], addr[100];
677 if (!where || sscanf(where, "%[^:]:%s", mode, addr) != 2)
679 logf (LOG_WARN, "%s: Address format: ('tcp'|'osi')':'<address>", me);
682 if (!strcmp(mode, "tcp"))
684 else if (!strcmp(mode, "osi"))
689 logf (LOG_WARN, "OSI Transport not allowed by configuration.");
695 logf (LOG_WARN, "You must specify either 'osi:' or 'tcp:'");
698 logf(LOG_LOG, "Adding %s %s listener on %s",
699 control_block.dynamic ? "dynamic" : "static",
700 what == PROTO_SR ? "SR" : "Z3950", where);
701 if (!(l = cs_create(type, 0, what)))
703 logf(LOG_FATAL|LOG_ERRNO, "Failed to create listener");
705 ap = cs_straddr (l, addr);
708 fprintf(stderr, "Address resolution failed.\n");
712 if (cs_bind(l, ap, CS_SERVER) < 0)
714 logf(LOG_FATAL|LOG_ERRNO, "Failed to bind to %s", where);
716 if (!(lst = iochan_create(cs_fileno(l), listener, EVENT_INPUT |
719 logf(LOG_FATAL|LOG_ERRNO, "Failed to create IOCHAN-type");
721 iochan_setdata(lst, l);
723 /* Ensure our listener chain is setup properly */
724 lst->next = pListener;
729 /* For windows we don't need to catch the signals */
730 static void catchchld(int num)
732 while (waitpid(-1, 0, WNOHANG) > 0)
734 signal(SIGCHLD, catchchld);
738 statserv_options_block *statserv_getcontrol(void)
740 static statserv_options_block cb;
742 memcpy(&cb, &control_block, sizeof(cb));
746 void statserv_setcontrol(statserv_options_block *block)
748 memcpy(&control_block, block, sizeof(*block));
751 int statserv_start(int argc, char **argv)
757 /* We need to initialize the thread list */
758 ThreadList_Initialize();
762 if ((me = strrchr (argv[0], '\\')))
769 if (control_block.options_func(argc, argv))
773 if (control_block.inetd)
774 inetd_connection(control_block.default_proto);
777 if (control_block.pre_init)
778 (*control_block.pre_init)(&control_block);
779 if (control_block.dynamic)
780 signal(SIGCHLD, catchchld);
782 if (*control_block.setuid)
786 if (!(pw = getpwnam(control_block.setuid)))
788 logf(LOG_FATAL, "%s: Unknown user", control_block.setuid);
791 if (setuid(pw->pw_uid) < 0)
793 logf(LOG_FATAL|LOG_ERRNO, "setuid");
799 if ((pListener == NULL) && *control_block.default_listen)
800 add_listener(control_block.default_listen,
801 control_block.default_proto);
802 logf(LOG_LOG, "Entering event loop.");
804 if (pListener == NULL)
807 ret = event_loop(&pListener);
812 int check_options(int argc, char **argv)
817 while ((ret = options("a:iszSl:v:u:c:w:t:k:", argv, argc, &arg)) != -2)
822 add_listener(arg, control_block.default_proto);
825 control_block.default_proto = PROTO_Z3950;
828 control_block.default_proto = PROTO_SR;
831 control_block.dynamic = 0;
834 strcpy(control_block.logfile, arg ? arg : "");
835 log_init(control_block.loglevel, me, control_block.logfile);
838 control_block.loglevel = log_mask_str(arg);
839 log_init(control_block.loglevel, me, control_block.logfile);
842 strcpy(control_block.apdufile, arg ? arg : "");
845 strcpy(control_block.setuid, arg ? arg : "");
848 strcpy(control_block.configname, arg ? arg : "");
851 if (!arg || !(r = atoi(arg)))
853 fprintf(stderr, "%s: Specify positive timeout for -t.\n", me);
856 control_block.idle_timeout = r;
859 if (!arg || !(r = atoi(arg)))
861 fprintf(stderr, "%s: Specify positive timeout for -t.\n", me);
864 control_block.maxrecordsize = r * 1024;
867 control_block.inetd = 1;
877 fprintf(stderr, "Usage: %s [ -i -a <pdufile> -v <loglevel>"
878 " -l <logfile> -u <user> -c <config> -t <minutes>"
880 " -zsS <listener-addr> -w <directory> ... ]\n", me);
894 static Args ArgDetails;
896 /* name of the executable */
897 #define SZAPPNAME "server"
899 /* list of service dependencies - "dep1\0dep2\0\0" */
900 #define SZDEPENDENCIES ""
902 int statserv_main(int argc, char **argv)
904 statserv_options_block *cb = statserv_getcontrol();
906 /* Lets setup the Arg structure */
907 ArgDetails.argc = argc;
908 ArgDetails.argv = argv;
910 /* Now setup the service with the service controller */
911 SetupService(argc, argv, &ArgDetails, SZAPPNAME,
912 cb->service_name, /* internal service name */
913 cb->service_name, /* displayed name of the service */
918 int StartAppService(void *pHandle, int argc, char **argv)
920 /* Initializes the App */
924 void RunAppService(void *pHandle)
926 Args *pArgs = (Args *)pHandle;
928 /* Starts the app running */
929 statserv_start(pArgs->argc, pArgs->argv);
932 void StopAppService(void *pHandle)
935 statserv_closedown();
938 int statserv_main(int argc, char **argv)
940 int ret = statserv_start (argc, argv);
941 statserv_closedown ();