2 * Copyright (c) 1995-1999, 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.55 1999-06-10 09:18:54 adam
11 * Modified so that pre_init is called when service/server is started.
13 * Revision 1.54 1999/04/16 14:45:55 adam
14 * Added interface for tcpd wrapper for access control.
16 * Revision 1.53 1999/02/02 13:57:39 adam
17 * Uses preprocessor define WIN32 instead of WINDOWS to build code
18 * for Microsoft WIN32.
20 * Revision 1.52 1998/08/21 14:13:34 adam
21 * Added GNU Configure script to build Makefiles.
23 * Revision 1.51 1998/07/07 15:51:03 adam
24 * Changed server so that it stops if bind fails - "address already in
25 * use" typically causes this.
27 * Revision 1.50 1998/06/22 11:32:39 adam
28 * Added 'conditional cs_listen' feature.
30 * Revision 1.49 1998/02/27 14:04:55 adam
31 * Fixed bug in statserv_remove.
33 * Revision 1.48 1998/02/11 11:53:36 adam
34 * Changed code so that it compiles as C++.
36 * Revision 1.47 1998/02/10 10:28:57 adam
37 * Added app_name, service_dependencies, service_display_name and
38 * options_func. options_func allows us to specify a different function
39 * to interogate the command line arguments. The other members allow us
40 * to pass the full service details accross to the service manager (CW).
43 * Revision 1.46 1998/01/30 15:24:57 adam
44 * Fixed bug in inetd code. The server listened on tcp:@:9999 even
45 * though it was started in inetd mode.
47 * Revision 1.45 1998/01/29 13:30:23 adam
48 * Better event handle system for NT/Unix.
50 * Revision 1.44 1997/11/07 13:31:52 adam
51 * Added NT Service name part of statserv_options_block. Moved NT
52 * service utility to server library.
54 * Revision 1.43 1997/10/31 12:20:09 adam
55 * Improved memory debugging for xmalloc/nmem.c. References to NMEM
56 * instead of ODR in n ESPEC-1 handling in source d1_espec.c.
57 * Bug fix: missing fclose in data1_read_espec1.
59 * Revision 1.42 1997/10/27 14:03:02 adam
60 * Added new member to statserver_options_block, pre_init, which
61 * specifies a callback to be invoked after command line parsing and
62 * before the server listens for the first time.
64 * Revision 1.41 1997/09/29 07:19:32 adam
65 * Server library uses nmem_init/nmem_exit. The log prefix no longer
66 * includes leading path on NT.
68 * Revision 1.40 1997/09/17 12:10:41 adam
71 * Revision 1.39 1997/09/09 10:10:19 adam
72 * Another MSV5.0 port. Changed projects to include proper
73 * library/include paths.
74 * Server starts server in test-mode when no options are given.
76 * Revision 1.38 1997/09/04 14:19:14 adam
79 * Revision 1.37 1997/09/01 08:53:01 adam
80 * New windows NT/95 port using MSV5.0. The test server 'ztest' was
81 * moved a separate directory. MSV5.0 project server.dsp created.
82 * As an option, the server can now operate as an NT service.
84 * Revision 1.36 1996/07/06 19:58:36 quinn
85 * System headerfiles gathered in yconfig
87 * Revision 1.35 1996/05/29 10:03:28 quinn
90 * Revision 1.34 1996/02/21 13:12:07 quinn
91 * *** empty log message ***
93 * Revision 1.33 1996/02/10 12:23:49 quinn
94 * Enable inetd operations fro TCP/IP stack
96 * Revision 1.32 1996/01/19 15:41:52 quinn
97 * *** empty log message ***
99 * Revision 1.31 1995/11/17 11:09:39 adam
100 * Added new option '-c' to specify configuration name in control block.
102 * Revision 1.30 1995/11/01 13:54:59 quinn
105 * Revision 1.29 1995/10/30 12:41:29 quinn
106 * Added hostname lookup for server.
108 * Revision 1.28 1995/09/29 17:12:30 quinn
111 * Revision 1.27 1995/09/27 15:03:02 quinn
112 * Modified function heads & prototypes.
114 * Revision 1.26 1995/08/29 14:44:51 quinn
117 * Revision 1.25 1995/08/29 11:18:02 quinn
118 * Added code to receive close
120 * Revision 1.24 1995/06/16 10:31:39 quinn
121 * Added session timeout.
123 * Revision 1.23 1995/06/15 12:30:48 quinn
126 * Revision 1.22 1995/06/15 07:45:17 quinn
129 * Revision 1.21 1995/06/06 08:15:40 quinn
132 * Revision 1.20 1995/05/29 08:12:09 quinn
135 * Revision 1.19 1995/05/16 09:37:27 quinn
138 * Revision 1.18 1995/05/16 08:51:09 quinn
139 * License, documentation, and memory fixes
141 * Revision 1.17 1995/05/15 11:56:42 quinn
142 * Asynchronous facilities. Restructuring of seshigh code.
144 * Revision 1.16 1995/04/10 10:23:40 quinn
145 * Some work to add scan and other things.
147 * Revision 1.15 1995/03/31 10:16:51 quinn
150 * Revision 1.14 1995/03/31 09:18:58 quinn
153 * Revision 1.13 1995/03/30 16:08:39 quinn
156 * Revision 1.12 1995/03/30 13:29:02 quinn
159 * Revision 1.11 1995/03/30 12:18:17 quinn
162 * Revision 1.10 1995/03/29 15:40:16 quinn
163 * Ongoing work. Statserv is now dynamic by default
165 * Revision 1.9 1995/03/27 08:34:30 quinn
166 * Added dynamic server functionality.
167 * Released bindings to session.c (is now redundant)
169 * Revision 1.8 1995/03/20 09:46:26 quinn
172 * Revision 1.7 1995/03/16 13:29:04 quinn
173 * Partitioned server.
175 * Revision 1.6 1995/03/15 15:18:52 quinn
176 * Little changes to better support nonblocking I/O
179 * Revision 1.5 1995/03/15 08:37:45 quinn
180 * Now we're pretty much set for nonblocking I/O.
182 * Revision 1.4 1995/03/14 16:59:48 quinn
185 * Revision 1.3 1995/03/14 11:30:15 quinn
188 * Revision 1.2 1995/03/14 10:28:03 quinn
189 * More work on demo server.
191 * Revision 1.1 1995/03/10 18:22:45 quinn
192 * The rudiments of an asynchronous server.
211 #include <comstack.h>
220 #include <statserv.h>
222 static IOCHAN pListener = NULL;
224 static char *me = "statserver";
228 int check_options(int argc, char **argv);
229 statserv_options_block control_block = {
230 1, /* dynamic mode */
231 LOG_DEFAULT_LEVEL, /* log level */
233 "", /* diagnostic output to stderr */
234 "tcp:@:9999", /* default listener port */
235 PROTO_Z3950, /* default application protocol */
236 60, /* idle timeout (minutes) */
237 1024*1024, /* maximum PDU size (approx.) to allow */
238 "default-config", /* configuration name to pass to backend */
239 "", /* set user id */
240 NULL, /* pre init handler */
241 check_options, /* Default routine, for checking the run-time arguments */
244 0 /* default value for inet deamon */
247 ,"Z39.50 Server", /* NT Service Name */
248 "Server", /* NT application Name */
249 "", /* NT Service Dependencies */
250 "Z39.50 Server" /* NT Service Display Name */
255 * handle incoming connect requests.
256 * The dynamic mode is a bit tricky mostly because we want to avoid
257 * doing all of the listening and accepting in the parent - it's
262 typedef struct _ThreadList ThreadList;
271 static ThreadList *pFirstThread;
272 static CRITICAL_SECTION Thread_CritSect;
273 static BOOL bInitialized = FALSE;
275 static void ThreadList_Initialize()
277 /* Initialize the critical Sections */
278 InitializeCriticalSection(&Thread_CritSect);
280 /* Set the first thraed */
283 /* we have been initialized */
287 static void statserv_add(HANDLE hThread, IOCHAN pIOChannel)
289 /* Only one thread can go through this section at a time */
290 EnterCriticalSection(&Thread_CritSect);
293 /* Lets create our new object */
294 ThreadList *pNewThread = (ThreadList *)malloc(sizeof(ThreadList));
295 pNewThread->hThread = hThread;
296 pNewThread->pIOChannel = pIOChannel;
297 pNewThread->pNext = pFirstThread;
298 pFirstThread = pNewThread;
300 /* Lets let somebody else create a new object now */
301 LeaveCriticalSection(&Thread_CritSect);
305 void statserv_remove(IOCHAN pIOChannel)
307 /* Only one thread can go through this section at a time */
308 EnterCriticalSection(&Thread_CritSect);
311 ThreadList *pCurrentThread = pFirstThread;
312 ThreadList *pNextThread;
313 ThreadList *pPrevThread =NULL;
315 /* Step through alll the threads */
316 for (; pCurrentThread != NULL; pCurrentThread = pNextThread)
318 /* We only need to compare on the IO Channel */
319 if (pCurrentThread->pIOChannel == pIOChannel)
321 /* We have found the thread we want to delete */
322 /* First of all reset the next pointers */
323 if (pPrevThread == NULL)
324 pFirstThread = pCurrentThread->pNext;
326 pPrevThread->pNext = pCurrentThread->pNext;
328 /* All we need todo now is delete the memory */
329 free(pCurrentThread);
331 /* No need to look at any more threads */
336 /* We need to look at another thread */
337 pNextThread = pCurrentThread->pNext;
338 pPrevThread = pCurrentThread;
342 /* Lets let somebody else remove an object now */
343 LeaveCriticalSection(&Thread_CritSect);
347 void statserv_closedown()
349 /* Shouldn't do anything if we are not initialized */
353 HANDLE *pThreadHandles = NULL;
355 /* We need to stop threads adding and removing while we */
356 /* start the closedown process */
357 EnterCriticalSection(&Thread_CritSect);
360 /* We have exclusive access to the thread stuff now */
361 /* Y didn't i use a semaphore - Oh well never mind */
362 ThreadList *pCurrentThread = pFirstThread;
364 /* Before we do anything else, we need to shutdown the listener */
365 if (pListener != NULL)
366 iochan_destroy(pListener);
368 for (; pCurrentThread != NULL; pCurrentThread = pCurrentThread->pNext)
370 /* Just destroy the IOCHAN, that should do the trick */
371 iochan_destroy(pCurrentThread->pIOChannel);
373 /* Keep a running count of our handles */
379 HANDLE *pCurrentHandle ;
381 /* Allocate the thread handle array */
382 pThreadHandles = (HANDLE *)malloc(sizeof(HANDLE) * iHandles);
383 pCurrentHandle = pThreadHandles;
385 for (pCurrentThread = pFirstThread;
386 pCurrentThread != NULL;
387 pCurrentThread = pCurrentThread->pNext, pCurrentHandle++)
389 /* Just the handle */
390 *pCurrentHandle = pCurrentThread->hThread;
394 /* We can now leave the critical section */
395 LeaveCriticalSection(&Thread_CritSect);
398 /* Now we can really do something */
401 /* This will now wait, until all the threads close */
402 WaitForMultipleObjects(iHandles, pThreadHandles, TRUE, INFINITE);
404 /* Free the memory we allocated for the handle array */
405 free(pThreadHandles);
408 /* No longer require the critical section, since all threads are dead */
409 DeleteCriticalSection(&Thread_CritSect);
413 int __stdcall event_loop_thread (IOCHAN iochan)
415 return event_loop (&iochan);
418 static void listener(IOCHAN h, int event)
420 COMSTACK line = (COMSTACK) iochan_getdata(h);
425 if (event == EVENT_INPUT)
427 if ((res = cs_listen(line, 0, 0)) < 0)
429 logf(LOG_FATAL, "cs_listen failed");
434 logf(LOG_DEBUG, "listen ok");
435 iochan_setevent(h, EVENT_OUTPUT);
436 iochan_setflags(h, EVENT_OUTPUT | EVENT_EXCEPT); /* set up for acpt */
438 else if (event == EVENT_OUTPUT)
445 if (!(new_line = cs_accept(line)))
447 logf(LOG_FATAL, "Accept failed.");
448 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
451 logf(LOG_DEBUG, "Accept ok");
453 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session,
456 logf(LOG_FATAL, "Failed to create iochan");
461 logf(LOG_DEBUG, "Creating association");
462 if (!(newas = create_association(new_chan, new_line)))
464 logf(LOG_FATAL, "Failed to create new assoc.");
468 logf(LOG_DEBUG, "Setting timeout %d", control_block.idle_timeout);
469 iochan_setdata(new_chan, newas);
470 iochan_settimeout(new_chan, control_block.idle_timeout * 60);
472 logf(LOG_DEBUG, "Determining client address");
473 a = cs_addrstr(new_line);
474 logf(LOG_LOG, "Accepted connection from %s", a ? a : "[Unknown]");
476 /* Now what we need todo is create a new thread with this iochan as
478 /* if (CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)event_loop_thread,
479 new_chan, 0, &ThreadId) == NULL) */
480 /* Somehow, somewhere we need to store this thread id, otherwise we
481 won't be able to close cleanly */
482 NewHandle = (HANDLE)_beginthreadex(NULL, 0, event_loop_thread,
483 new_chan, 0, &ThreadId);
484 if (NewHandle == (HANDLE)-1)
487 logf(LOG_FATAL|LOG_ERRNO, "Failed to create new thread.");
491 /* We successfully created the thread, so add it to the list */
492 statserv_add(NewHandle, new_chan);
494 logf(LOG_DEBUG, "Created new thread, iochan %p", new_chan);
495 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
499 logf(LOG_FATAL, "Bad event on listener.");
507 /* To save having an #ifdef in event_loop we need to define this empty function */
508 void statserv_remove(IOCHAN pIOChannel)
512 void statserv_closedown()
515 for (p = pListener; p; p = p->next)
519 static void listener(IOCHAN h, int event)
521 COMSTACK line = (COMSTACK) iochan_getdata(h);
524 static int child = 0;
527 if (event == EVENT_INPUT)
529 if (control_block.dynamic && !child)
535 logf(LOG_FATAL|LOG_ERRNO, "pipe");
539 if ((res = fork()) < 0)
541 logf(LOG_FATAL|LOG_ERRNO, "fork");
545 else if (res == 0) /* child */
552 for (pp = pListener; pp; pp = iochan_getnext(pp))
556 COMSTACK l = (COMSTACK)iochan_getdata(pp);
561 sprintf(nbuf, "%s(%d)", me, getpid());
562 log_init(control_block.loglevel, nbuf, 0);
567 /* wait for child to take the call */
573 if ((res = read(hand[0], dummy, 1)) < 0 && errno != EINTR)
575 logf(LOG_FATAL|LOG_ERRNO, "handshake read");
581 logf(LOG_DEBUG, "P: Child has taken the call");
586 if ((res = cs_listen_check(line, 0, 0, control_block.check_ip,
587 control_block.daemon_name)) < 0)
589 logf(LOG_WARN, "cs_listen failed");
594 logf(LOG_DEBUG, "listen ok");
595 iochan_setevent(h, EVENT_OUTPUT);
596 iochan_setflags(h, EVENT_OUTPUT | EVENT_EXCEPT); /* set up for acpt */
598 /* in dynamic mode, only the child ever comes down here */
599 else if (event == EVENT_OUTPUT)
605 if (!(new_line = cs_accept(line)))
607 logf(LOG_FATAL, "Accept failed.");
608 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
611 logf(LOG_DEBUG, "accept ok");
612 if (control_block.dynamic)
615 /* close our half of the listener socket */
616 for (pp = pListener; pp; pp = iochan_getnext(pp))
618 COMSTACK l = (COMSTACK)iochan_getdata(pp);
623 logf(LOG_DEBUG, "Releasing parent");
627 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
629 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session,
632 logf(LOG_FATAL, "Failed to create iochan");
636 new_chan->next = pListener;
637 pListener = new_chan;
638 if (!(newas = create_association(new_chan, new_line)))
640 logf(LOG_FATAL, "Failed to create new assoc.");
644 iochan_setdata(new_chan, newas);
645 iochan_settimeout(new_chan, control_block.idle_timeout * 60);
646 a = cs_addrstr(new_line);
647 logf(LOG_LOG, "Accepted connection from %s", a ? a : "[Unknown]");
651 logf(LOG_FATAL, "Bad event on listener.");
659 static void inetd_connection(int what)
666 if ((line = cs_createbysocket(0, tcpip_type, 0, what)))
668 if ((chan = iochan_create(cs_fileno(line), ir_session, EVENT_INPUT)))
670 if ((assoc = create_association(chan, line)))
672 iochan_setdata(chan, assoc);
673 iochan_settimeout(chan, control_block.idle_timeout * 60);
674 addr = cs_addrstr(line);
675 logf(LOG_LOG, "Inetd association from %s", addr ? addr : "[UNKNOWN]");
679 logf(LOG_FATAL, "Failed to create association structure");
681 chan->next = pListener;
686 logf(LOG_FATAL, "Failed to create iochan");
691 logf(LOG_ERRNO|LOG_FATAL, "Failed to create comstack on socket 0");
696 * Set up a listening endpoint, and give it to the event-handler.
698 static void add_listener(char *where, int what)
702 char mode[100], addr[100];
706 if (!where || sscanf(where, "%[^:]:%s", mode, addr) != 2)
708 logf (LOG_WARN, "%s: Address format: ('tcp'|'osi')':'<address>", me);
711 if (!strcmp(mode, "tcp"))
713 else if (!strcmp(mode, "osi"))
718 logf (LOG_WARN, "OSI Transport not allowed by configuration.");
724 logf (LOG_WARN, "You must specify either 'osi:' or 'tcp:'");
727 logf(LOG_LOG, "Adding %s %s listener on %s",
728 control_block.dynamic ? "dynamic" : "static",
729 what == PROTO_SR ? "SR" : "Z3950", where);
730 if (!(l = cs_create(type, 0, what)))
732 logf(LOG_FATAL|LOG_ERRNO, "Failed to create listener");
735 ap = cs_straddr (l, addr);
738 fprintf(stderr, "Address resolution failed.\n");
742 if (cs_bind(l, ap, CS_SERVER) < 0)
744 logf(LOG_FATAL|LOG_ERRNO, "Failed to bind to %s", where);
748 if (!(lst = iochan_create(cs_fileno(l), listener, EVENT_INPUT |
751 logf(LOG_FATAL|LOG_ERRNO, "Failed to create IOCHAN-type");
755 iochan_setdata(lst, l);
757 /* Ensure our listener chain is setup properly */
758 lst->next = pListener;
763 /* For windows we don't need to catch the signals */
764 static void catchchld(int num)
766 while (waitpid(-1, 0, WNOHANG) > 0)
768 signal(SIGCHLD, catchchld);
772 statserv_options_block *statserv_getcontrol(void)
774 static statserv_options_block cb;
776 memcpy(&cb, &control_block, sizeof(cb));
780 void statserv_setcontrol(statserv_options_block *block)
782 memcpy(&control_block, block, sizeof(*block));
785 int statserv_start(int argc, char **argv)
791 /* We need to initialize the thread list */
792 ThreadList_Initialize();
796 if ((me = strrchr (argv[0], '\\')))
803 if (control_block.options_func(argc, argv))
806 if (control_block.pre_init)
807 (*control_block.pre_init)(&control_block);
809 if (control_block.inetd)
810 inetd_connection(control_block.default_proto);
813 if (control_block.dynamic)
814 signal(SIGCHLD, catchchld);
816 if (*control_block.setuid)
820 if (!(pw = getpwnam(control_block.setuid)))
822 logf(LOG_FATAL, "%s: Unknown user", control_block.setuid);
825 if (setuid(pw->pw_uid) < 0)
827 logf(LOG_FATAL|LOG_ERRNO, "setuid");
833 if ((pListener == NULL) && *control_block.default_listen)
834 add_listener(control_block.default_listen,
835 control_block.default_proto);
837 if (pListener == NULL)
841 logf(LOG_LOG, "Entering event loop.");
842 ret = event_loop(&pListener);
848 int check_options(int argc, char **argv)
853 while ((ret = options("a:iszSl:v:u:c:w:t:k:d:", argv, argc, &arg)) != -2)
858 add_listener(arg, control_block.default_proto);
861 control_block.default_proto = PROTO_Z3950;
864 control_block.default_proto = PROTO_SR;
867 control_block.dynamic = 0;
870 strcpy(control_block.logfile, arg ? arg : "");
871 log_init(control_block.loglevel, me, control_block.logfile);
874 control_block.loglevel = log_mask_str(arg);
875 log_init(control_block.loglevel, me, control_block.logfile);
878 strcpy(control_block.apdufile, arg ? arg : "");
881 strcpy(control_block.setuid, arg ? arg : "");
884 strcpy(control_block.configname, arg ? arg : "");
887 strcpy(control_block.daemon_name, arg ? arg : "");
890 if (!arg || !(r = atoi(arg)))
892 fprintf(stderr, "%s: Specify positive timeout for -t.\n", me);
895 control_block.idle_timeout = r;
898 if (!arg || !(r = atoi(arg)))
900 fprintf(stderr, "%s: Specify positive size for -k.\n", me);
903 control_block.maxrecordsize = r * 1024;
906 control_block.inetd = 1;
916 fprintf(stderr, "Usage: %s [ -i -a <pdufile> -v <loglevel>"
917 " -l <logfile> -u <user> -c <config> -t <minutes>"
918 " -k <kilobytes> -d <daemon>"
919 " -zsS <listener-addr> -w <directory> ... ]\n", me);
933 static Args ArgDetails;
935 /* name of the executable */
936 #define SZAPPNAME "server"
938 /* list of service dependencies - "dep1\0dep2\0\0" */
939 #define SZDEPENDENCIES ""
941 int statserv_main(int argc, char **argv)
943 statserv_options_block *cb = statserv_getcontrol();
945 /* Lets setup the Arg structure */
946 ArgDetails.argc = argc;
947 ArgDetails.argv = argv;
949 /* Now setup the service with the service controller */
950 SetupService(argc, argv, &ArgDetails, SZAPPNAME,
951 cb->service_name, /* internal service name */
952 cb->service_name, /* displayed name of the service */
957 int StartAppService(void *pHandle, int argc, char **argv)
959 /* Initializes the App */
963 void RunAppService(void *pHandle)
965 Args *pArgs = (Args *)pHandle;
967 /* Starts the app running */
968 statserv_start(pArgs->argc, pArgs->argv);
971 void StopAppService(void *pHandle)
974 statserv_closedown();
977 int statserv_main(int argc, char **argv)
979 int ret = statserv_start (argc, argv);
980 statserv_closedown ();