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.56 1999-06-10 11:45:30 adam
11 * Added bend_start, bend_stop handlers and removed pre_init.
12 * Handlers bend_start/bend_stop are called when service/daemon is
15 * Revision 1.55 1999/06/10 09:18:54 adam
16 * Modified so that pre_init is called when service/server is started.
18 * Revision 1.54 1999/04/16 14:45:55 adam
19 * Added interface for tcpd wrapper for access control.
21 * Revision 1.53 1999/02/02 13:57:39 adam
22 * Uses preprocessor define WIN32 instead of WINDOWS to build code
23 * for Microsoft WIN32.
25 * Revision 1.52 1998/08/21 14:13:34 adam
26 * Added GNU Configure script to build Makefiles.
28 * Revision 1.51 1998/07/07 15:51:03 adam
29 * Changed server so that it stops if bind fails - "address already in
30 * use" typically causes this.
32 * Revision 1.50 1998/06/22 11:32:39 adam
33 * Added 'conditional cs_listen' feature.
35 * Revision 1.49 1998/02/27 14:04:55 adam
36 * Fixed bug in statserv_remove.
38 * Revision 1.48 1998/02/11 11:53:36 adam
39 * Changed code so that it compiles as C++.
41 * Revision 1.47 1998/02/10 10:28:57 adam
42 * Added app_name, service_dependencies, service_display_name and
43 * options_func. options_func allows us to specify a different function
44 * to interogate the command line arguments. The other members allow us
45 * to pass the full service details accross to the service manager (CW).
48 * Revision 1.46 1998/01/30 15:24:57 adam
49 * Fixed bug in inetd code. The server listened on tcp:@:9999 even
50 * though it was started in inetd mode.
52 * Revision 1.45 1998/01/29 13:30:23 adam
53 * Better event handle system for NT/Unix.
55 * Revision 1.44 1997/11/07 13:31:52 adam
56 * Added NT Service name part of statserv_options_block. Moved NT
57 * service utility to server library.
59 * Revision 1.43 1997/10/31 12:20:09 adam
60 * Improved memory debugging for xmalloc/nmem.c. References to NMEM
61 * instead of ODR in n ESPEC-1 handling in source d1_espec.c.
62 * Bug fix: missing fclose in data1_read_espec1.
64 * Revision 1.42 1997/10/27 14:03:02 adam
65 * Added new member to statserver_options_block, pre_init, which
66 * specifies a callback to be invoked after command line parsing and
67 * before the server listens for the first time.
69 * Revision 1.41 1997/09/29 07:19:32 adam
70 * Server library uses nmem_init/nmem_exit. The log prefix no longer
71 * includes leading path on NT.
73 * Revision 1.40 1997/09/17 12:10:41 adam
76 * Revision 1.39 1997/09/09 10:10:19 adam
77 * Another MSV5.0 port. Changed projects to include proper
78 * library/include paths.
79 * Server starts server in test-mode when no options are given.
81 * Revision 1.38 1997/09/04 14:19:14 adam
84 * Revision 1.37 1997/09/01 08:53:01 adam
85 * New windows NT/95 port using MSV5.0. The test server 'ztest' was
86 * moved a separate directory. MSV5.0 project server.dsp created.
87 * As an option, the server can now operate as an NT service.
89 * Revision 1.36 1996/07/06 19:58:36 quinn
90 * System headerfiles gathered in yconfig
92 * Revision 1.35 1996/05/29 10:03:28 quinn
95 * Revision 1.34 1996/02/21 13:12:07 quinn
96 * *** empty log message ***
98 * Revision 1.33 1996/02/10 12:23:49 quinn
99 * Enable inetd operations fro TCP/IP stack
101 * Revision 1.32 1996/01/19 15:41:52 quinn
102 * *** empty log message ***
104 * Revision 1.31 1995/11/17 11:09:39 adam
105 * Added new option '-c' to specify configuration name in control block.
107 * Revision 1.30 1995/11/01 13:54:59 quinn
110 * Revision 1.29 1995/10/30 12:41:29 quinn
111 * Added hostname lookup for server.
113 * Revision 1.28 1995/09/29 17:12:30 quinn
116 * Revision 1.27 1995/09/27 15:03:02 quinn
117 * Modified function heads & prototypes.
119 * Revision 1.26 1995/08/29 14:44:51 quinn
122 * Revision 1.25 1995/08/29 11:18:02 quinn
123 * Added code to receive close
125 * Revision 1.24 1995/06/16 10:31:39 quinn
126 * Added session timeout.
128 * Revision 1.23 1995/06/15 12:30:48 quinn
131 * Revision 1.22 1995/06/15 07:45:17 quinn
134 * Revision 1.21 1995/06/06 08:15:40 quinn
137 * Revision 1.20 1995/05/29 08:12:09 quinn
140 * Revision 1.19 1995/05/16 09:37:27 quinn
143 * Revision 1.18 1995/05/16 08:51:09 quinn
144 * License, documentation, and memory fixes
146 * Revision 1.17 1995/05/15 11:56:42 quinn
147 * Asynchronous facilities. Restructuring of seshigh code.
149 * Revision 1.16 1995/04/10 10:23:40 quinn
150 * Some work to add scan and other things.
152 * Revision 1.15 1995/03/31 10:16:51 quinn
155 * Revision 1.14 1995/03/31 09:18:58 quinn
158 * Revision 1.13 1995/03/30 16:08:39 quinn
161 * Revision 1.12 1995/03/30 13:29:02 quinn
164 * Revision 1.11 1995/03/30 12:18:17 quinn
167 * Revision 1.10 1995/03/29 15:40:16 quinn
168 * Ongoing work. Statserv is now dynamic by default
170 * Revision 1.9 1995/03/27 08:34:30 quinn
171 * Added dynamic server functionality.
172 * Released bindings to session.c (is now redundant)
174 * Revision 1.8 1995/03/20 09:46:26 quinn
177 * Revision 1.7 1995/03/16 13:29:04 quinn
178 * Partitioned server.
180 * Revision 1.6 1995/03/15 15:18:52 quinn
181 * Little changes to better support nonblocking I/O
184 * Revision 1.5 1995/03/15 08:37:45 quinn
185 * Now we're pretty much set for nonblocking I/O.
187 * Revision 1.4 1995/03/14 16:59:48 quinn
190 * Revision 1.3 1995/03/14 11:30:15 quinn
193 * Revision 1.2 1995/03/14 10:28:03 quinn
194 * More work on demo server.
196 * Revision 1.1 1995/03/10 18:22:45 quinn
197 * The rudiments of an asynchronous server.
216 #include <comstack.h>
225 #include <statserv.h>
227 static IOCHAN pListener = NULL;
229 static char *me = "statserver";
233 int check_options(int argc, char **argv);
234 statserv_options_block control_block = {
235 1, /* dynamic mode */
236 LOG_DEFAULT_LEVEL, /* log level */
238 "", /* diagnostic output to stderr */
239 "tcp:@:9999", /* default listener port */
240 PROTO_Z3950, /* default application protocol */
241 60, /* idle timeout (minutes) */
242 1024*1024, /* maximum PDU size (approx.) to allow */
243 "default-config", /* configuration name to pass to backend */
244 "", /* set user id */
245 0, /* bend_start handler */
246 0, /* bend_stop handler */
247 check_options, /* Default routine, for checking the run-time arguments */
250 0 /* default value for inet deamon */
253 ,"Z39.50 Server", /* NT Service Name */
254 "Server", /* NT application Name */
255 "", /* NT Service Dependencies */
256 "Z39.50 Server" /* NT Service Display Name */
261 * handle incoming connect requests.
262 * The dynamic mode is a bit tricky mostly because we want to avoid
263 * doing all of the listening and accepting in the parent - it's
268 typedef struct _ThreadList ThreadList;
277 static ThreadList *pFirstThread;
278 static CRITICAL_SECTION Thread_CritSect;
279 static BOOL bInitialized = FALSE;
281 static void ThreadList_Initialize()
283 /* Initialize the critical Sections */
284 InitializeCriticalSection(&Thread_CritSect);
286 /* Set the first thraed */
289 /* we have been initialized */
293 static void statserv_add(HANDLE hThread, IOCHAN pIOChannel)
295 /* Only one thread can go through this section at a time */
296 EnterCriticalSection(&Thread_CritSect);
299 /* Lets create our new object */
300 ThreadList *pNewThread = (ThreadList *)malloc(sizeof(ThreadList));
301 pNewThread->hThread = hThread;
302 pNewThread->pIOChannel = pIOChannel;
303 pNewThread->pNext = pFirstThread;
304 pFirstThread = pNewThread;
306 /* Lets let somebody else create a new object now */
307 LeaveCriticalSection(&Thread_CritSect);
311 void statserv_remove(IOCHAN pIOChannel)
313 /* Only one thread can go through this section at a time */
314 EnterCriticalSection(&Thread_CritSect);
317 ThreadList *pCurrentThread = pFirstThread;
318 ThreadList *pNextThread;
319 ThreadList *pPrevThread =NULL;
321 /* Step through alll the threads */
322 for (; pCurrentThread != NULL; pCurrentThread = pNextThread)
324 /* We only need to compare on the IO Channel */
325 if (pCurrentThread->pIOChannel == pIOChannel)
327 /* We have found the thread we want to delete */
328 /* First of all reset the next pointers */
329 if (pPrevThread == NULL)
330 pFirstThread = pCurrentThread->pNext;
332 pPrevThread->pNext = pCurrentThread->pNext;
334 /* All we need todo now is delete the memory */
335 free(pCurrentThread);
337 /* No need to look at any more threads */
342 /* We need to look at another thread */
343 pNextThread = pCurrentThread->pNext;
344 pPrevThread = pCurrentThread;
348 /* Lets let somebody else remove an object now */
349 LeaveCriticalSection(&Thread_CritSect);
353 void statserv_closedown()
355 /* Shouldn't do anything if we are not initialized */
359 HANDLE *pThreadHandles = NULL;
361 /* We need to stop threads adding and removing while we */
362 /* start the closedown process */
363 EnterCriticalSection(&Thread_CritSect);
366 /* We have exclusive access to the thread stuff now */
367 /* Y didn't i use a semaphore - Oh well never mind */
368 ThreadList *pCurrentThread = pFirstThread;
370 /* Before we do anything else, we need to shutdown the listener */
371 if (pListener != NULL)
372 iochan_destroy(pListener);
374 for (; pCurrentThread != NULL; pCurrentThread = pCurrentThread->pNext)
376 /* Just destroy the IOCHAN, that should do the trick */
377 iochan_destroy(pCurrentThread->pIOChannel);
379 /* Keep a running count of our handles */
385 HANDLE *pCurrentHandle ;
387 /* Allocate the thread handle array */
388 pThreadHandles = (HANDLE *)malloc(sizeof(HANDLE) * iHandles);
389 pCurrentHandle = pThreadHandles;
391 for (pCurrentThread = pFirstThread;
392 pCurrentThread != NULL;
393 pCurrentThread = pCurrentThread->pNext, pCurrentHandle++)
395 /* Just the handle */
396 *pCurrentHandle = pCurrentThread->hThread;
400 /* We can now leave the critical section */
401 LeaveCriticalSection(&Thread_CritSect);
404 /* Now we can really do something */
407 /* This will now wait, until all the threads close */
408 WaitForMultipleObjects(iHandles, pThreadHandles, TRUE, INFINITE);
410 /* Free the memory we allocated for the handle array */
411 free(pThreadHandles);
414 if (control_block.bend_stop)
415 (*control_block.bend_stop)(&control_block);
416 /* No longer require the critical section, since all threads are dead */
417 DeleteCriticalSection(&Thread_CritSect);
421 int __stdcall event_loop_thread (IOCHAN iochan)
423 return event_loop (&iochan);
426 static void listener(IOCHAN h, int event)
428 COMSTACK line = (COMSTACK) iochan_getdata(h);
433 if (event == EVENT_INPUT)
435 if ((res = cs_listen(line, 0, 0)) < 0)
437 logf(LOG_FATAL, "cs_listen failed");
442 logf(LOG_DEBUG, "listen ok");
443 iochan_setevent(h, EVENT_OUTPUT);
444 iochan_setflags(h, EVENT_OUTPUT | EVENT_EXCEPT); /* set up for acpt */
446 else if (event == EVENT_OUTPUT)
453 if (!(new_line = cs_accept(line)))
455 logf(LOG_FATAL, "Accept failed.");
456 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
459 logf(LOG_DEBUG, "Accept ok");
461 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session,
464 logf(LOG_FATAL, "Failed to create iochan");
469 logf(LOG_DEBUG, "Creating association");
470 if (!(newas = create_association(new_chan, new_line)))
472 logf(LOG_FATAL, "Failed to create new assoc.");
476 logf(LOG_DEBUG, "Setting timeout %d", control_block.idle_timeout);
477 iochan_setdata(new_chan, newas);
478 iochan_settimeout(new_chan, control_block.idle_timeout * 60);
480 logf(LOG_DEBUG, "Determining client address");
481 a = cs_addrstr(new_line);
482 logf(LOG_LOG, "Accepted connection from %s", a ? a : "[Unknown]");
484 /* Now what we need todo is create a new thread with this iochan as
486 /* if (CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)event_loop_thread,
487 new_chan, 0, &ThreadId) == NULL) */
488 /* Somehow, somewhere we need to store this thread id, otherwise we
489 won't be able to close cleanly */
490 NewHandle = (HANDLE)_beginthreadex(NULL, 0, event_loop_thread,
491 new_chan, 0, &ThreadId);
492 if (NewHandle == (HANDLE)-1)
495 logf(LOG_FATAL|LOG_ERRNO, "Failed to create new thread.");
499 /* We successfully created the thread, so add it to the list */
500 statserv_add(NewHandle, new_chan);
502 logf(LOG_DEBUG, "Created new thread, iochan %p", new_chan);
503 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
507 logf(LOG_FATAL, "Bad event on listener.");
515 /* To save having an #ifdef in event_loop we need to define this empty function */
516 void statserv_remove(IOCHAN pIOChannel)
520 void statserv_closedown()
523 for (p = pListener; p; p = p->next)
527 static void listener(IOCHAN h, int event)
529 COMSTACK line = (COMSTACK) iochan_getdata(h);
532 static int child = 0;
535 if (event == EVENT_INPUT)
537 if (control_block.dynamic && !child)
543 logf(LOG_FATAL|LOG_ERRNO, "pipe");
547 if ((res = fork()) < 0)
549 logf(LOG_FATAL|LOG_ERRNO, "fork");
553 else if (res == 0) /* child */
560 for (pp = pListener; pp; pp = iochan_getnext(pp))
564 COMSTACK l = (COMSTACK)iochan_getdata(pp);
569 sprintf(nbuf, "%s(%d)", me, getpid());
570 log_init(control_block.loglevel, nbuf, 0);
575 /* wait for child to take the call */
581 if ((res = read(hand[0], dummy, 1)) < 0 && errno != EINTR)
583 logf(LOG_FATAL|LOG_ERRNO, "handshake read");
589 logf(LOG_DEBUG, "P: Child has taken the call");
594 if ((res = cs_listen_check(line, 0, 0, control_block.check_ip,
595 control_block.daemon_name)) < 0)
597 logf(LOG_WARN, "cs_listen failed");
602 logf(LOG_DEBUG, "listen ok");
603 iochan_setevent(h, EVENT_OUTPUT);
604 iochan_setflags(h, EVENT_OUTPUT | EVENT_EXCEPT); /* set up for acpt */
606 /* in dynamic mode, only the child ever comes down here */
607 else if (event == EVENT_OUTPUT)
613 if (!(new_line = cs_accept(line)))
615 logf(LOG_FATAL, "Accept failed.");
616 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
619 logf(LOG_DEBUG, "accept ok");
620 if (control_block.dynamic)
623 /* close our half of the listener socket */
624 for (pp = pListener; pp; pp = iochan_getnext(pp))
626 COMSTACK l = (COMSTACK)iochan_getdata(pp);
631 logf(LOG_DEBUG, "Releasing parent");
635 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
637 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session,
640 logf(LOG_FATAL, "Failed to create iochan");
644 new_chan->next = pListener;
645 pListener = new_chan;
646 if (!(newas = create_association(new_chan, new_line)))
648 logf(LOG_FATAL, "Failed to create new assoc.");
652 iochan_setdata(new_chan, newas);
653 iochan_settimeout(new_chan, control_block.idle_timeout * 60);
654 a = cs_addrstr(new_line);
655 logf(LOG_LOG, "Accepted connection from %s", a ? a : "[Unknown]");
659 logf(LOG_FATAL, "Bad event on listener.");
667 static void inetd_connection(int what)
674 if ((line = cs_createbysocket(0, tcpip_type, 0, what)))
676 if ((chan = iochan_create(cs_fileno(line), ir_session, EVENT_INPUT)))
678 if ((assoc = create_association(chan, line)))
680 iochan_setdata(chan, assoc);
681 iochan_settimeout(chan, control_block.idle_timeout * 60);
682 addr = cs_addrstr(line);
683 logf(LOG_LOG, "Inetd association from %s", addr ? addr : "[UNKNOWN]");
687 logf(LOG_FATAL, "Failed to create association structure");
689 chan->next = pListener;
694 logf(LOG_FATAL, "Failed to create iochan");
699 logf(LOG_ERRNO|LOG_FATAL, "Failed to create comstack on socket 0");
704 * Set up a listening endpoint, and give it to the event-handler.
706 static void add_listener(char *where, int what)
710 char mode[100], addr[100];
714 if (!where || sscanf(where, "%[^:]:%s", mode, addr) != 2)
716 logf (LOG_WARN, "%s: Address format: ('tcp'|'osi')':'<address>", me);
719 if (!strcmp(mode, "tcp"))
721 else if (!strcmp(mode, "osi"))
726 logf (LOG_WARN, "OSI Transport not allowed by configuration.");
732 logf (LOG_WARN, "You must specify either 'osi:' or 'tcp:'");
735 logf(LOG_LOG, "Adding %s %s listener on %s",
736 control_block.dynamic ? "dynamic" : "static",
737 what == PROTO_SR ? "SR" : "Z3950", where);
738 if (!(l = cs_create(type, 0, what)))
740 logf(LOG_FATAL|LOG_ERRNO, "Failed to create listener");
743 ap = cs_straddr (l, addr);
746 fprintf(stderr, "Address resolution failed.\n");
750 if (cs_bind(l, ap, CS_SERVER) < 0)
752 logf(LOG_FATAL|LOG_ERRNO, "Failed to bind to %s", where);
756 if (!(lst = iochan_create(cs_fileno(l), listener, EVENT_INPUT |
759 logf(LOG_FATAL|LOG_ERRNO, "Failed to create IOCHAN-type");
763 iochan_setdata(lst, l);
765 /* Ensure our listener chain is setup properly */
766 lst->next = pListener;
771 /* For windows we don't need to catch the signals */
772 static void catchchld(int num)
774 while (waitpid(-1, 0, WNOHANG) > 0)
776 signal(SIGCHLD, catchchld);
780 statserv_options_block *statserv_getcontrol(void)
782 static statserv_options_block cb;
784 memcpy(&cb, &control_block, sizeof(cb));
788 void statserv_setcontrol(statserv_options_block *block)
790 memcpy(&control_block, block, sizeof(*block));
793 int statserv_start(int argc, char **argv)
799 /* We need to initialize the thread list */
800 ThreadList_Initialize();
804 if ((me = strrchr (argv[0], '\\')))
811 if (control_block.options_func(argc, argv))
814 if (control_block.bend_start)
815 (*control_block.bend_start)(&control_block);
817 if (control_block.inetd)
818 inetd_connection(control_block.default_proto);
821 if (control_block.dynamic)
822 signal(SIGCHLD, catchchld);
824 if (*control_block.setuid)
828 if (!(pw = getpwnam(control_block.setuid)))
830 logf(LOG_FATAL, "%s: Unknown user", control_block.setuid);
833 if (setuid(pw->pw_uid) < 0)
835 logf(LOG_FATAL|LOG_ERRNO, "setuid");
841 if ((pListener == NULL) && *control_block.default_listen)
842 add_listener(control_block.default_listen,
843 control_block.default_proto);
845 if (pListener == NULL)
849 logf(LOG_LOG, "Entering event loop.");
850 ret = event_loop(&pListener);
856 int check_options(int argc, char **argv)
861 while ((ret = options("a:iszSl:v:u:c:w:t:k:d:", argv, argc, &arg)) != -2)
866 add_listener(arg, control_block.default_proto);
869 control_block.default_proto = PROTO_Z3950;
872 control_block.default_proto = PROTO_SR;
875 control_block.dynamic = 0;
878 strcpy(control_block.logfile, arg ? arg : "");
879 log_init(control_block.loglevel, me, control_block.logfile);
882 control_block.loglevel = log_mask_str(arg);
883 log_init(control_block.loglevel, me, control_block.logfile);
886 strcpy(control_block.apdufile, arg ? arg : "");
889 strcpy(control_block.setuid, arg ? arg : "");
892 strcpy(control_block.configname, arg ? arg : "");
895 strcpy(control_block.daemon_name, arg ? arg : "");
898 if (!arg || !(r = atoi(arg)))
900 fprintf(stderr, "%s: Specify positive timeout for -t.\n", me);
903 control_block.idle_timeout = r;
906 if (!arg || !(r = atoi(arg)))
908 fprintf(stderr, "%s: Specify positive size for -k.\n", me);
911 control_block.maxrecordsize = r * 1024;
914 control_block.inetd = 1;
924 fprintf(stderr, "Usage: %s [ -i -a <pdufile> -v <loglevel>"
925 " -l <logfile> -u <user> -c <config> -t <minutes>"
926 " -k <kilobytes> -d <daemon>"
927 " -zsS <listener-addr> -w <directory> ... ]\n", me);
941 static Args ArgDetails;
943 /* name of the executable */
944 #define SZAPPNAME "server"
946 /* list of service dependencies - "dep1\0dep2\0\0" */
947 #define SZDEPENDENCIES ""
949 int statserv_main(int argc, char **argv)
951 statserv_options_block *cb = statserv_getcontrol();
953 /* Lets setup the Arg structure */
954 ArgDetails.argc = argc;
955 ArgDetails.argv = argv;
957 /* Now setup the service with the service controller */
958 SetupService(argc, argv, &ArgDetails, SZAPPNAME,
959 cb->service_name, /* internal service name */
960 cb->service_name, /* displayed name of the service */
965 int StartAppService(void *pHandle, int argc, char **argv)
967 /* Initializes the App */
971 void RunAppService(void *pHandle)
973 Args *pArgs = (Args *)pHandle;
975 /* Starts the app running */
976 statserv_start(pArgs->argc, pArgs->argv);
979 void StopAppService(void *pHandle)
982 statserv_closedown();
985 int statserv_main(int argc, char **argv)
987 int ret = statserv_start (argc, argv);
988 statserv_closedown ();