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.57 1999-07-06 12:17:15 adam
11 * Added option -1 that runs server once (for profiling purposes).
13 * Revision 1.56 1999/06/10 11:45:30 adam
14 * Added bend_start, bend_stop handlers and removed pre_init.
15 * Handlers bend_start/bend_stop are called when service/daemon is
18 * Revision 1.55 1999/06/10 09:18:54 adam
19 * Modified so that pre_init is called when service/server is started.
21 * Revision 1.54 1999/04/16 14:45:55 adam
22 * Added interface for tcpd wrapper for access control.
24 * Revision 1.53 1999/02/02 13:57:39 adam
25 * Uses preprocessor define WIN32 instead of WINDOWS to build code
26 * for Microsoft WIN32.
28 * Revision 1.52 1998/08/21 14:13:34 adam
29 * Added GNU Configure script to build Makefiles.
31 * Revision 1.51 1998/07/07 15:51:03 adam
32 * Changed server so that it stops if bind fails - "address already in
33 * use" typically causes this.
35 * Revision 1.50 1998/06/22 11:32:39 adam
36 * Added 'conditional cs_listen' feature.
38 * Revision 1.49 1998/02/27 14:04:55 adam
39 * Fixed bug in statserv_remove.
41 * Revision 1.48 1998/02/11 11:53:36 adam
42 * Changed code so that it compiles as C++.
44 * Revision 1.47 1998/02/10 10:28:57 adam
45 * Added app_name, service_dependencies, service_display_name and
46 * options_func. options_func allows us to specify a different function
47 * to interogate the command line arguments. The other members allow us
48 * to pass the full service details accross to the service manager (CW).
51 * Revision 1.46 1998/01/30 15:24:57 adam
52 * Fixed bug in inetd code. The server listened on tcp:@:9999 even
53 * though it was started in inetd mode.
55 * Revision 1.45 1998/01/29 13:30:23 adam
56 * Better event handle system for NT/Unix.
58 * Revision 1.44 1997/11/07 13:31:52 adam
59 * Added NT Service name part of statserv_options_block. Moved NT
60 * service utility to server library.
62 * Revision 1.43 1997/10/31 12:20:09 adam
63 * Improved memory debugging for xmalloc/nmem.c. References to NMEM
64 * instead of ODR in n ESPEC-1 handling in source d1_espec.c.
65 * Bug fix: missing fclose in data1_read_espec1.
67 * Revision 1.42 1997/10/27 14:03:02 adam
68 * Added new member to statserver_options_block, pre_init, which
69 * specifies a callback to be invoked after command line parsing and
70 * before the server listens for the first time.
72 * Revision 1.41 1997/09/29 07:19:32 adam
73 * Server library uses nmem_init/nmem_exit. The log prefix no longer
74 * includes leading path on NT.
76 * Revision 1.40 1997/09/17 12:10:41 adam
79 * Revision 1.39 1997/09/09 10:10:19 adam
80 * Another MSV5.0 port. Changed projects to include proper
81 * library/include paths.
82 * Server starts server in test-mode when no options are given.
84 * Revision 1.38 1997/09/04 14:19:14 adam
87 * Revision 1.37 1997/09/01 08:53:01 adam
88 * New windows NT/95 port using MSV5.0. The test server 'ztest' was
89 * moved a separate directory. MSV5.0 project server.dsp created.
90 * As an option, the server can now operate as an NT service.
92 * Revision 1.36 1996/07/06 19:58:36 quinn
93 * System headerfiles gathered in yconfig
95 * Revision 1.35 1996/05/29 10:03:28 quinn
98 * Revision 1.34 1996/02/21 13:12:07 quinn
99 * *** empty log message ***
101 * Revision 1.33 1996/02/10 12:23:49 quinn
102 * Enable inetd operations fro TCP/IP stack
104 * Revision 1.32 1996/01/19 15:41:52 quinn
105 * *** empty log message ***
107 * Revision 1.31 1995/11/17 11:09:39 adam
108 * Added new option '-c' to specify configuration name in control block.
110 * Revision 1.30 1995/11/01 13:54:59 quinn
113 * Revision 1.29 1995/10/30 12:41:29 quinn
114 * Added hostname lookup for server.
116 * Revision 1.28 1995/09/29 17:12:30 quinn
119 * Revision 1.27 1995/09/27 15:03:02 quinn
120 * Modified function heads & prototypes.
122 * Revision 1.26 1995/08/29 14:44:51 quinn
125 * Revision 1.25 1995/08/29 11:18:02 quinn
126 * Added code to receive close
128 * Revision 1.24 1995/06/16 10:31:39 quinn
129 * Added session timeout.
131 * Revision 1.23 1995/06/15 12:30:48 quinn
134 * Revision 1.22 1995/06/15 07:45:17 quinn
137 * Revision 1.21 1995/06/06 08:15:40 quinn
140 * Revision 1.20 1995/05/29 08:12:09 quinn
143 * Revision 1.19 1995/05/16 09:37:27 quinn
146 * Revision 1.18 1995/05/16 08:51:09 quinn
147 * License, documentation, and memory fixes
149 * Revision 1.17 1995/05/15 11:56:42 quinn
150 * Asynchronous facilities. Restructuring of seshigh code.
152 * Revision 1.16 1995/04/10 10:23:40 quinn
153 * Some work to add scan and other things.
155 * Revision 1.15 1995/03/31 10:16:51 quinn
158 * Revision 1.14 1995/03/31 09:18:58 quinn
161 * Revision 1.13 1995/03/30 16:08:39 quinn
164 * Revision 1.12 1995/03/30 13:29:02 quinn
167 * Revision 1.11 1995/03/30 12:18:17 quinn
170 * Revision 1.10 1995/03/29 15:40:16 quinn
171 * Ongoing work. Statserv is now dynamic by default
173 * Revision 1.9 1995/03/27 08:34:30 quinn
174 * Added dynamic server functionality.
175 * Released bindings to session.c (is now redundant)
177 * Revision 1.8 1995/03/20 09:46:26 quinn
180 * Revision 1.7 1995/03/16 13:29:04 quinn
181 * Partitioned server.
183 * Revision 1.6 1995/03/15 15:18:52 quinn
184 * Little changes to better support nonblocking I/O
187 * Revision 1.5 1995/03/15 08:37:45 quinn
188 * Now we're pretty much set for nonblocking I/O.
190 * Revision 1.4 1995/03/14 16:59:48 quinn
193 * Revision 1.3 1995/03/14 11:30:15 quinn
196 * Revision 1.2 1995/03/14 10:28:03 quinn
197 * More work on demo server.
199 * Revision 1.1 1995/03/10 18:22:45 quinn
200 * The rudiments of an asynchronous server.
219 #include <comstack.h>
228 #include <statserv.h>
230 static IOCHAN pListener = NULL;
232 static char *me = "statserver";
236 int check_options(int argc, char **argv);
237 statserv_options_block control_block = {
238 1, /* dynamic mode */
239 0, /* one shot (single session) */
240 LOG_DEFAULT_LEVEL, /* log level */
242 "", /* diagnostic output to stderr */
243 "tcp:@:9999", /* default listener port */
244 PROTO_Z3950, /* default application protocol */
245 60, /* idle timeout (minutes) */
246 1024*1024, /* maximum PDU size (approx.) to allow */
247 "default-config", /* configuration name to pass to backend */
248 "", /* set user id */
249 0, /* bend_start handler */
250 0, /* bend_stop handler */
251 check_options, /* Default routine, for checking the run-time arguments */
254 0 /* default value for inet deamon */
257 ,"Z39.50 Server", /* NT Service Name */
258 "Server", /* NT application Name */
259 "", /* NT Service Dependencies */
260 "Z39.50 Server" /* NT Service Display Name */
265 * handle incoming connect requests.
266 * The dynamic mode is a bit tricky mostly because we want to avoid
267 * doing all of the listening and accepting in the parent - it's
272 typedef struct _ThreadList ThreadList;
281 static ThreadList *pFirstThread;
282 static CRITICAL_SECTION Thread_CritSect;
283 static BOOL bInitialized = FALSE;
285 static void ThreadList_Initialize()
287 /* Initialize the critical Sections */
288 InitializeCriticalSection(&Thread_CritSect);
290 /* Set the first thraed */
293 /* we have been initialized */
297 static void statserv_add(HANDLE hThread, IOCHAN pIOChannel)
299 /* Only one thread can go through this section at a time */
300 EnterCriticalSection(&Thread_CritSect);
303 /* Lets create our new object */
304 ThreadList *pNewThread = (ThreadList *)malloc(sizeof(ThreadList));
305 pNewThread->hThread = hThread;
306 pNewThread->pIOChannel = pIOChannel;
307 pNewThread->pNext = pFirstThread;
308 pFirstThread = pNewThread;
310 /* Lets let somebody else create a new object now */
311 LeaveCriticalSection(&Thread_CritSect);
315 void statserv_remove(IOCHAN pIOChannel)
317 /* Only one thread can go through this section at a time */
318 EnterCriticalSection(&Thread_CritSect);
321 ThreadList *pCurrentThread = pFirstThread;
322 ThreadList *pNextThread;
323 ThreadList *pPrevThread =NULL;
325 /* Step through alll the threads */
326 for (; pCurrentThread != NULL; pCurrentThread = pNextThread)
328 /* We only need to compare on the IO Channel */
329 if (pCurrentThread->pIOChannel == pIOChannel)
331 /* We have found the thread we want to delete */
332 /* First of all reset the next pointers */
333 if (pPrevThread == NULL)
334 pFirstThread = pCurrentThread->pNext;
336 pPrevThread->pNext = pCurrentThread->pNext;
338 /* All we need todo now is delete the memory */
339 free(pCurrentThread);
341 /* No need to look at any more threads */
346 /* We need to look at another thread */
347 pNextThread = pCurrentThread->pNext;
348 pPrevThread = pCurrentThread;
352 /* Lets let somebody else remove an object now */
353 LeaveCriticalSection(&Thread_CritSect);
357 void statserv_closedown()
359 /* Shouldn't do anything if we are not initialized */
363 HANDLE *pThreadHandles = NULL;
365 /* We need to stop threads adding and removing while we */
366 /* start the closedown process */
367 EnterCriticalSection(&Thread_CritSect);
370 /* We have exclusive access to the thread stuff now */
371 /* Y didn't i use a semaphore - Oh well never mind */
372 ThreadList *pCurrentThread = pFirstThread;
374 /* Before we do anything else, we need to shutdown the listener */
375 if (pListener != NULL)
376 iochan_destroy(pListener);
378 for (; pCurrentThread != NULL; pCurrentThread = pCurrentThread->pNext)
380 /* Just destroy the IOCHAN, that should do the trick */
381 iochan_destroy(pCurrentThread->pIOChannel);
383 /* Keep a running count of our handles */
389 HANDLE *pCurrentHandle ;
391 /* Allocate the thread handle array */
392 pThreadHandles = (HANDLE *)malloc(sizeof(HANDLE) * iHandles);
393 pCurrentHandle = pThreadHandles;
395 for (pCurrentThread = pFirstThread;
396 pCurrentThread != NULL;
397 pCurrentThread = pCurrentThread->pNext, pCurrentHandle++)
399 /* Just the handle */
400 *pCurrentHandle = pCurrentThread->hThread;
404 /* We can now leave the critical section */
405 LeaveCriticalSection(&Thread_CritSect);
408 /* Now we can really do something */
411 /* This will now wait, until all the threads close */
412 WaitForMultipleObjects(iHandles, pThreadHandles, TRUE, INFINITE);
414 /* Free the memory we allocated for the handle array */
415 free(pThreadHandles);
418 if (control_block.bend_stop)
419 (*control_block.bend_stop)(&control_block);
420 /* No longer require the critical section, since all threads are dead */
421 DeleteCriticalSection(&Thread_CritSect);
425 int __stdcall event_loop_thread (IOCHAN iochan)
427 return event_loop (&iochan);
430 static void listener(IOCHAN h, int event)
432 COMSTACK line = (COMSTACK) iochan_getdata(h);
437 if (event == EVENT_INPUT)
439 if ((res = cs_listen(line, 0, 0)) < 0)
441 logf(LOG_FATAL, "cs_listen failed");
446 logf(LOG_DEBUG, "listen ok");
447 iochan_setevent(h, EVENT_OUTPUT);
448 iochan_setflags(h, EVENT_OUTPUT | EVENT_EXCEPT); /* set up for acpt */
450 else if (event == EVENT_OUTPUT)
457 if (!(new_line = cs_accept(line)))
459 logf(LOG_FATAL, "Accept failed.");
460 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
463 logf(LOG_DEBUG, "Accept ok");
465 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session,
468 logf(LOG_FATAL, "Failed to create iochan");
473 logf(LOG_DEBUG, "Creating association");
474 if (!(newas = create_association(new_chan, new_line)))
476 logf(LOG_FATAL, "Failed to create new assoc.");
480 logf(LOG_DEBUG, "Setting timeout %d", control_block.idle_timeout);
481 iochan_setdata(new_chan, newas);
482 iochan_settimeout(new_chan, control_block.idle_timeout * 60);
484 logf(LOG_DEBUG, "Determining client address");
485 a = cs_addrstr(new_line);
486 logf(LOG_LOG, "Accepted connection from %s", a ? a : "[Unknown]");
488 /* Now what we need todo is create a new thread with this iochan as
490 /* if (CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)event_loop_thread,
491 new_chan, 0, &ThreadId) == NULL) */
492 /* Somehow, somewhere we need to store this thread id, otherwise we
493 won't be able to close cleanly */
494 NewHandle = (HANDLE)_beginthreadex(NULL, 0, event_loop_thread,
495 new_chan, 0, &ThreadId);
496 if (NewHandle == (HANDLE)-1)
499 logf(LOG_FATAL|LOG_ERRNO, "Failed to create new thread.");
503 /* We successfully created the thread, so add it to the list */
504 statserv_add(NewHandle, new_chan);
506 logf(LOG_DEBUG, "Created new thread, iochan %p", new_chan);
507 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
511 logf(LOG_FATAL, "Bad event on listener.");
519 /* To save having an #ifdef in event_loop we need to define this empty function */
520 void statserv_remove(IOCHAN pIOChannel)
524 void statserv_closedown()
527 for (p = pListener; p; p = p->next)
531 static void listener(IOCHAN h, int event)
533 COMSTACK line = (COMSTACK) iochan_getdata(h);
536 static int child = 0;
539 if (event == EVENT_INPUT)
541 if (control_block.dynamic && !child)
547 logf(LOG_FATAL|LOG_ERRNO, "pipe");
551 if ((res = fork()) < 0)
553 logf(LOG_FATAL|LOG_ERRNO, "fork");
557 else if (res == 0) /* child */
564 for (pp = pListener; pp; pp = iochan_getnext(pp))
568 COMSTACK l = (COMSTACK)iochan_getdata(pp);
573 sprintf(nbuf, "%s(%d)", me, getpid());
574 log_init(control_block.loglevel, nbuf, 0);
579 /* wait for child to take the call */
585 if ((res = read(hand[0], dummy, 1)) < 0 && errno != EINTR)
587 logf(LOG_FATAL|LOG_ERRNO, "handshake read");
593 logf(LOG_DEBUG, "P: Child has taken the call");
598 if ((res = cs_listen_check(line, 0, 0, control_block.check_ip,
599 control_block.daemon_name)) < 0)
601 logf(LOG_WARN, "cs_listen failed");
606 logf(LOG_DEBUG, "listen ok");
607 iochan_setevent(h, EVENT_OUTPUT);
608 iochan_setflags(h, EVENT_OUTPUT | EVENT_EXCEPT); /* set up for acpt */
610 /* in dynamic mode, only the child ever comes down here */
611 else if (event == EVENT_OUTPUT)
617 if (!(new_line = cs_accept(line)))
619 logf(LOG_FATAL, "Accept failed.");
620 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
623 logf(LOG_DEBUG, "accept ok");
624 if (control_block.dynamic)
627 /* close our half of the listener socket */
628 for (pp = pListener; pp; pp = iochan_getnext(pp))
630 COMSTACK l = (COMSTACK)iochan_getdata(pp);
635 logf(LOG_DEBUG, "Releasing parent");
639 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
641 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session,
644 logf(LOG_FATAL, "Failed to create iochan");
648 new_chan->next = pListener;
649 pListener = new_chan;
650 if (!(newas = create_association(new_chan, new_line)))
652 logf(LOG_FATAL, "Failed to create new assoc.");
656 iochan_setdata(new_chan, newas);
657 iochan_settimeout(new_chan, control_block.idle_timeout * 60);
658 a = cs_addrstr(new_line);
659 logf(LOG_LOG, "Accepted connection from %s", a ? a : "[Unknown]");
663 logf(LOG_FATAL, "Bad event on listener.");
671 static void inetd_connection(int what)
678 if ((line = cs_createbysocket(0, tcpip_type, 0, what)))
680 if ((chan = iochan_create(cs_fileno(line), ir_session, EVENT_INPUT)))
682 if ((assoc = create_association(chan, line)))
684 iochan_setdata(chan, assoc);
685 iochan_settimeout(chan, control_block.idle_timeout * 60);
686 addr = cs_addrstr(line);
687 logf(LOG_LOG, "Inetd association from %s", addr ? addr : "[UNKNOWN]");
691 logf(LOG_FATAL, "Failed to create association structure");
693 chan->next = pListener;
698 logf(LOG_FATAL, "Failed to create iochan");
703 logf(LOG_ERRNO|LOG_FATAL, "Failed to create comstack on socket 0");
708 * Set up a listening endpoint, and give it to the event-handler.
710 static void add_listener(char *where, int what)
714 char mode[100], addr[100];
718 if (!where || sscanf(where, "%[^:]:%s", mode, addr) != 2)
720 logf (LOG_WARN, "%s: Address format: ('tcp'|'osi')':'<address>", me);
723 if (!strcmp(mode, "tcp"))
725 else if (!strcmp(mode, "osi"))
730 logf (LOG_WARN, "OSI Transport not allowed by configuration.");
736 logf (LOG_WARN, "You must specify either 'osi:' or 'tcp:'");
739 logf(LOG_LOG, "Adding %s %s listener on %s",
740 control_block.dynamic ? "dynamic" : "static",
741 what == PROTO_SR ? "SR" : "Z3950", where);
742 if (!(l = cs_create(type, 0, what)))
744 logf(LOG_FATAL|LOG_ERRNO, "Failed to create listener");
747 ap = cs_straddr (l, addr);
750 fprintf(stderr, "Address resolution failed.\n");
754 if (cs_bind(l, ap, CS_SERVER) < 0)
756 logf(LOG_FATAL|LOG_ERRNO, "Failed to bind to %s", where);
760 if (!(lst = iochan_create(cs_fileno(l), listener, EVENT_INPUT |
763 logf(LOG_FATAL|LOG_ERRNO, "Failed to create IOCHAN-type");
767 iochan_setdata(lst, l);
769 /* Ensure our listener chain is setup properly */
770 lst->next = pListener;
775 /* For windows we don't need to catch the signals */
776 static void catchchld(int num)
778 while (waitpid(-1, 0, WNOHANG) > 0)
780 signal(SIGCHLD, catchchld);
784 statserv_options_block *statserv_getcontrol(void)
786 static statserv_options_block cb;
788 memcpy(&cb, &control_block, sizeof(cb));
792 void statserv_setcontrol(statserv_options_block *block)
794 memcpy(&control_block, block, sizeof(*block));
797 int statserv_start(int argc, char **argv)
803 /* We need to initialize the thread list */
804 ThreadList_Initialize();
808 if ((me = strrchr (argv[0], '\\')))
815 if (control_block.options_func(argc, argv))
818 if (control_block.bend_start)
819 (*control_block.bend_start)(&control_block);
821 if (control_block.inetd)
822 inetd_connection(control_block.default_proto);
825 if (control_block.dynamic)
826 signal(SIGCHLD, catchchld);
828 if (*control_block.setuid)
832 if (!(pw = getpwnam(control_block.setuid)))
834 logf(LOG_FATAL, "%s: Unknown user", control_block.setuid);
837 if (setuid(pw->pw_uid) < 0)
839 logf(LOG_FATAL|LOG_ERRNO, "setuid");
845 if ((pListener == NULL) && *control_block.default_listen)
846 add_listener(control_block.default_listen,
847 control_block.default_proto);
849 if (pListener == NULL)
853 logf(LOG_LOG, "Entering event loop.");
854 ret = event_loop(&pListener);
860 int check_options(int argc, char **argv)
865 while ((ret = options("1a:iszSl:v:u:c:w:t:k:d:", argv, argc, &arg)) != -2)
870 add_listener(arg, control_block.default_proto);
873 control_block.one_shot = 1;
874 control_block.dynamic = 0;
877 control_block.default_proto = PROTO_Z3950;
880 control_block.default_proto = PROTO_SR;
883 control_block.dynamic = 0;
886 strcpy(control_block.logfile, arg ? arg : "");
887 log_init(control_block.loglevel, me, control_block.logfile);
890 control_block.loglevel = log_mask_str(arg);
891 log_init(control_block.loglevel, me, control_block.logfile);
894 strcpy(control_block.apdufile, arg ? arg : "");
897 strcpy(control_block.setuid, arg ? arg : "");
900 strcpy(control_block.configname, arg ? arg : "");
903 strcpy(control_block.daemon_name, arg ? arg : "");
906 if (!arg || !(r = atoi(arg)))
908 fprintf(stderr, "%s: Specify positive timeout for -t.\n", me);
911 control_block.idle_timeout = r;
914 if (!arg || !(r = atoi(arg)))
916 fprintf(stderr, "%s: Specify positive size for -k.\n", me);
919 control_block.maxrecordsize = r * 1024;
922 control_block.inetd = 1;
932 fprintf(stderr, "Usage: %s [ -i -a <pdufile> -v <loglevel>"
933 " -l <logfile> -u <user> -c <config> -t <minutes>"
934 " -k <kilobytes> -d <daemon>"
935 " -zsS <listener-addr> -w <directory> ... ]\n", me);
949 static Args ArgDetails;
951 /* name of the executable */
952 #define SZAPPNAME "server"
954 /* list of service dependencies - "dep1\0dep2\0\0" */
955 #define SZDEPENDENCIES ""
957 int statserv_main(int argc, char **argv)
959 statserv_options_block *cb = statserv_getcontrol();
961 /* Lets setup the Arg structure */
962 ArgDetails.argc = argc;
963 ArgDetails.argv = argv;
965 /* Now setup the service with the service controller */
966 SetupService(argc, argv, &ArgDetails, SZAPPNAME,
967 cb->service_name, /* internal service name */
968 cb->service_name, /* displayed name of the service */
973 int StartAppService(void *pHandle, int argc, char **argv)
975 /* Initializes the App */
979 void RunAppService(void *pHandle)
981 Args *pArgs = (Args *)pHandle;
983 /* Starts the app running */
984 statserv_start(pArgs->argc, pArgs->argv);
987 void StopAppService(void *pHandle)
990 statserv_closedown();
993 int statserv_main(int argc, char **argv)
995 int ret = statserv_start (argc, argv);
996 statserv_closedown ();