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 Datasystem.
10 * Revision 1.45 1998-01-29 13:30:23 adam
11 * Better event handle system for NT/Unix.
13 * Revision 1.44 1997/11/07 13:31:52 adam
14 * Added NT Service name part of statserv_options_block. Moved NT
15 * service utility to server library.
17 * Revision 1.43 1997/10/31 12:20:09 adam
18 * Improved memory debugging for xmalloc/nmem.c. References to NMEM
19 * instead of ODR in n ESPEC-1 handling in source d1_espec.c.
20 * Bug fix: missing fclose in data1_read_espec1.
22 * Revision 1.42 1997/10/27 14:03:02 adam
23 * Added new member to statserver_options_block, pre_init, which
24 * specifies a callback to be invoked after command line parsing and
25 * before the server listens for the first time.
27 * Revision 1.41 1997/09/29 07:19:32 adam
28 * Server library uses nmem_init/nmem_exit. The log prefix no longer
29 * includes leading path on NT.
31 * Revision 1.40 1997/09/17 12:10:41 adam
34 * Revision 1.39 1997/09/09 10:10:19 adam
35 * Another MSV5.0 port. Changed projects to include proper
36 * library/include paths.
37 * Server starts server in test-mode when no options are given.
39 * Revision 1.38 1997/09/04 14:19:14 adam
42 * Revision 1.37 1997/09/01 08:53:01 adam
43 * New windows NT/95 port using MSV5.0. The test server 'ztest' was
44 * moved a separate directory. MSV5.0 project server.dsp created.
45 * As an option, the server can now operate as an NT service.
47 * Revision 1.36 1996/07/06 19:58:36 quinn
48 * System headerfiles gathered in yconfig
50 * Revision 1.35 1996/05/29 10:03:28 quinn
53 * Revision 1.34 1996/02/21 13:12:07 quinn
54 * *** empty log message ***
56 * Revision 1.33 1996/02/10 12:23:49 quinn
57 * Enable inetd operations fro TCP/IP stack
59 * Revision 1.32 1996/01/19 15:41:52 quinn
60 * *** empty log message ***
62 * Revision 1.31 1995/11/17 11:09:39 adam
63 * Added new option '-c' to specify configuration name in control block.
65 * Revision 1.30 1995/11/01 13:54:59 quinn
68 * Revision 1.29 1995/10/30 12:41:29 quinn
69 * Added hostname lookup for server.
71 * Revision 1.28 1995/09/29 17:12:30 quinn
74 * Revision 1.27 1995/09/27 15:03:02 quinn
75 * Modified function heads & prototypes.
77 * Revision 1.26 1995/08/29 14:44:51 quinn
80 * Revision 1.25 1995/08/29 11:18:02 quinn
81 * Added code to receive close
83 * Revision 1.24 1995/06/16 10:31:39 quinn
84 * Added session timeout.
86 * Revision 1.23 1995/06/15 12:30:48 quinn
89 * Revision 1.22 1995/06/15 07:45:17 quinn
92 * Revision 1.21 1995/06/06 08:15:40 quinn
95 * Revision 1.20 1995/05/29 08:12:09 quinn
98 * Revision 1.19 1995/05/16 09:37:27 quinn
101 * Revision 1.18 1995/05/16 08:51:09 quinn
102 * License, documentation, and memory fixes
104 * Revision 1.17 1995/05/15 11:56:42 quinn
105 * Asynchronous facilities. Restructuring of seshigh code.
107 * Revision 1.16 1995/04/10 10:23:40 quinn
108 * Some work to add scan and other things.
110 * Revision 1.15 1995/03/31 10:16:51 quinn
113 * Revision 1.14 1995/03/31 09:18:58 quinn
116 * Revision 1.13 1995/03/30 16:08:39 quinn
119 * Revision 1.12 1995/03/30 13:29:02 quinn
122 * Revision 1.11 1995/03/30 12:18:17 quinn
125 * Revision 1.10 1995/03/29 15:40:16 quinn
126 * Ongoing work. Statserv is now dynamic by default
128 * Revision 1.9 1995/03/27 08:34:30 quinn
129 * Added dynamic server functionality.
130 * Released bindings to session.c (is now redundant)
132 * Revision 1.8 1995/03/20 09:46:26 quinn
135 * Revision 1.7 1995/03/16 13:29:04 quinn
136 * Partitioned server.
138 * Revision 1.6 1995/03/15 15:18:52 quinn
139 * Little changes to better support nonblocking I/O
142 * Revision 1.5 1995/03/15 08:37:45 quinn
143 * Now we're pretty much set for nonblocking I/O.
145 * Revision 1.4 1995/03/14 16:59:48 quinn
148 * Revision 1.3 1995/03/14 11:30:15 quinn
151 * Revision 1.2 1995/03/14 10:28:03 quinn
152 * More work on demo server.
154 * Revision 1.1 1995/03/10 18:22:45 quinn
155 * The rudiments of an asynchronous server.
176 #include <comstack.h>
184 #include <statserv.h>
186 static IOCHAN pListener = NULL;
188 static char *me = "statserver";
192 static statserv_options_block control_block = {
193 1, /* dynamic mode */
194 LOG_DEFAULT_LEVEL, /* log level */
196 "", /* diagnostic output to stderr */
197 "tcp:@:9999", /* default listener port */
198 PROTO_Z3950, /* default application protocol */
199 60, /* idle timeout (minutes) */
200 1024*1024, /* maximum PDU size (approx.) to allow */
201 "default-config", /* configuration name to pass to backend */
202 "", /* set user id */
203 NULL, /* pre init handler */
204 "Z39.50 Server" /* NT Service Name */
208 * handle incoming connect requests.
209 * The dynamic mode is a bit tricky mostly because we want to avoid
210 * doing all of the listening and accepting in the parent - it's
215 typedef struct _ThreadList ThreadList;
224 static ThreadList *pFirstThread;
225 static CRITICAL_SECTION Thread_CritSect;
226 static BOOL bInitialized = FALSE;
228 static void ThreadList_Initialize()
230 /* Initialize the critical Sections */
231 InitializeCriticalSection(&Thread_CritSect);
233 /* Set the first thraed */
236 /* we have been initialized */
240 static void statserv_add(HANDLE hThread, IOCHAN pIOChannel)
242 /* Only one thread can go through this section at a time */
243 EnterCriticalSection(&Thread_CritSect);
246 /* Lets create our new object */
247 ThreadList *pNewThread = (ThreadList *)malloc(sizeof(ThreadList));
248 pNewThread->hThread = hThread;
249 pNewThread->pIOChannel = pIOChannel;
250 pNewThread->pNext = pFirstThread;
251 pFirstThread = pNewThread;
253 /* Lets let somebody else create a new object now */
254 LeaveCriticalSection(&Thread_CritSect);
258 void statserv_remove(IOCHAN pIOChannel)
260 /* Only one thread can go through this section at a time */
261 EnterCriticalSection(&Thread_CritSect);
264 ThreadList *pCurrentThread = pFirstThread;
265 ThreadList *pNextThread;
266 ThreadList *pPrevThread =NULL;
268 /* Step through alll the threads */
269 for (; pCurrentThread != NULL; pCurrentThread = pNextThread)
271 /* We only need to compare on the IO Channel */
272 if (pCurrentThread->pIOChannel == pIOChannel)
274 /* We have found the thread we want to delete */
275 /* First of all reset the next pointers */
276 if (pPrevThread == NULL)
277 pFirstThread = pCurrentThread->pNext;
279 pPrevThread->pNext = pCurrentThread->pNext;
281 /* All we need todo now is delete the memory */
282 free(pCurrentThread);
284 /* No need to look at any more threads */
289 /* We need to look at another thread */
290 pNextThread = pCurrentThread->pNext;
294 /* Lets let somebody else remove an object now */
295 LeaveCriticalSection(&Thread_CritSect);
299 void statserv_closedown()
301 /* Shouldn't do anything if we are not initialized */
305 HANDLE *pThreadHandles = NULL;
307 /* We need to stop threads adding and removing while we */
308 /* start the closedown process */
309 EnterCriticalSection(&Thread_CritSect);
312 /* We have exclusive access to the thread stuff now */
313 /* Y didn't i use a semaphore - Oh well never mind */
314 ThreadList *pCurrentThread = pFirstThread;
316 /* Before we do anything else, we need to shutdown the listener */
317 if (pListener != NULL)
318 iochan_destroy(pListener);
320 for (; pCurrentThread != NULL; pCurrentThread = pCurrentThread->pNext)
322 /* Just destroy the IOCHAN, that should do the trick */
323 iochan_destroy(pCurrentThread->pIOChannel);
325 /* Keep a running count of our handles */
331 HANDLE *pCurrentHandle ;
333 /* Allocate the thread handle array */
334 pThreadHandles = (HANDLE *)malloc(sizeof(HANDLE) * iHandles);
335 pCurrentHandle = pThreadHandles;
337 for (pCurrentThread = pFirstThread;
338 pCurrentThread != NULL;
339 pCurrentThread = pCurrentThread->pNext, pCurrentHandle++)
341 /* Just the handle */
342 *pCurrentHandle = pCurrentThread->hThread;
346 /* We can now leave the critical section */
347 LeaveCriticalSection(&Thread_CritSect);
350 /* Now we can really do something */
353 /* This will now wait, until all the threads close */
354 WaitForMultipleObjects(iHandles, pThreadHandles, TRUE, INFINITE);
356 /* Free the memory we allocated for the handle array */
357 free(pThreadHandles);
360 /* No longer require the critical section, since all threads are dead */
361 DeleteCriticalSection(&Thread_CritSect);
365 int __stdcall event_loop_thread (IOCHAN iochan)
367 return event_loop (&iochan);
370 static void listener(IOCHAN h, int event)
372 COMSTACK line = (COMSTACK) iochan_getdata(h);
377 if (event == EVENT_INPUT)
379 if ((res = cs_listen(line, 0, 0)) < 0)
381 logf(LOG_FATAL, "cs_listen failed.");
386 logf(LOG_DEBUG, "listen ok");
387 iochan_setevent(h, EVENT_OUTPUT);
388 iochan_setflags(h, EVENT_OUTPUT | EVENT_EXCEPT); /* set up for acpt */
390 else if (event == EVENT_OUTPUT)
397 if (!(new_line = cs_accept(line)))
399 logf(LOG_FATAL, "Accept failed.");
400 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
403 logf(LOG_DEBUG, "Accept ok");
405 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session, EVENT_INPUT)))
407 logf(LOG_FATAL, "Failed to create iochan");
412 logf(LOG_DEBUG, "Creating association");
413 if (!(newas = create_association(new_chan, new_line)))
415 logf(LOG_FATAL, "Failed to create new assoc.");
419 logf(LOG_DEBUG, "Setting timeout %d", control_block.idle_timeout);
420 iochan_setdata(new_chan, newas);
421 iochan_settimeout(new_chan, control_block.idle_timeout * 60);
423 logf(LOG_DEBUG, "Determining client address");
424 a = cs_addrstr(new_line);
425 logf(LOG_LOG, "Accepted connection from %s", a ? a : "[Unknown]");
427 /* Now what we need todo is create a new thread with this iochan as
429 /* if (CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)event_loop_thread,
430 new_chan, 0, &ThreadId) == NULL) */
431 /* Somehow, somewhere we need to store this thread id, otherwise we won't be
432 able to close cleanly */
433 NewHandle = (HANDLE)_beginthreadex(NULL, 0, event_loop_thread,
434 new_chan, 0, &ThreadId);
435 if (NewHandle == (HANDLE)-1)
438 logf(LOG_FATAL|LOG_ERRNO, "Failed to create new thread.");
442 /* We successfully created the thread, so add it to the list */
443 statserv_add(NewHandle, new_chan);
445 logf(LOG_DEBUG, "Created new thread, iochan %p", new_chan);
446 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
450 logf(LOG_FATAL, "Bad event on listener.");
458 /* To save having an #ifdef in event_loop we need to define this empty function */
459 void statserv_remove(IOCHAN pIOChannel)
463 void statserv_closedown()
466 for (p = pListener; p; p = p->next)
470 static void listener(IOCHAN h, int event)
472 COMSTACK line = (COMSTACK) iochan_getdata(h);
475 static int child = 0;
478 if (event == EVENT_INPUT)
480 if (control_block.dynamic && !child)
486 logf(LOG_FATAL|LOG_ERRNO, "pipe");
490 if ((res = fork()) < 0)
492 logf(LOG_FATAL|LOG_ERRNO, "fork");
496 else if (res == 0) /* child */
503 for (pp = pListener; pp; pp = iochan_getnext(pp))
507 COMSTACK l = iochan_getdata(pp);
512 sprintf(nbuf, "%s(%d)", me, getpid());
513 log_init(control_block.loglevel, nbuf, 0);
518 /* wait for child to take the call */
524 if ((res = read(hand[0], dummy, 1)) < 0 && errno != EINTR)
526 logf(LOG_FATAL|LOG_ERRNO, "handshake read");
532 logf(LOG_DEBUG, "P: Child has taken the call");
537 if ((res = cs_listen(line, 0, 0)) < 0)
539 logf(LOG_FATAL, "cs_listen failed.");
544 logf(LOG_DEBUG, "listen ok");
545 iochan_setevent(h, EVENT_OUTPUT);
546 iochan_setflags(h, EVENT_OUTPUT | EVENT_EXCEPT); /* set up for acpt */
548 /* in dynamic mode, only the child ever comes down here */
549 else if (event == EVENT_OUTPUT)
555 if (!(new_line = cs_accept(line)))
557 logf(LOG_FATAL, "Accept failed.");
558 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
561 logf(LOG_DEBUG, "accept ok");
562 if (control_block.dynamic)
565 /* close our half of the listener socket */
566 for (pp = pListener; pp; pp = iochan_getnext(pp))
568 COMSTACK l = iochan_getdata(pp);
573 logf(LOG_DEBUG, "Releasing parent");
577 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
579 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session,
582 logf(LOG_FATAL, "Failed to create iochan");
586 new_chan->next = pListener;
587 pListener = new_chan;
588 if (!(newas = create_association(new_chan, new_line)))
590 logf(LOG_FATAL, "Failed to create new assoc.");
594 iochan_setdata(new_chan, newas);
595 iochan_settimeout(new_chan, control_block.idle_timeout * 60);
596 a = cs_addrstr(new_line);
597 logf(LOG_LOG, "Accepted connection from %s", a ? a : "[Unknown]");
601 logf(LOG_FATAL, "Bad event on listener.");
609 static void inetd_connection(int what)
616 if ((line = cs_createbysocket(0, tcpip_type, 0, what)))
618 if ((chan = iochan_create(cs_fileno(line), ir_session, EVENT_INPUT)))
620 if ((assoc = create_association(chan, line)))
622 iochan_setdata(chan, assoc);
623 iochan_settimeout(chan, control_block.idle_timeout * 60);
624 addr = cs_addrstr(line);
625 logf(LOG_LOG, "Inetd association from %s", addr ? addr : "[UNKNOWN]");
629 logf(LOG_FATAL, "Failed to create association structure");
634 logf(LOG_FATAL, "Failed to create iochan");
639 logf(LOG_ERRNO|LOG_FATAL, "Failed to create comstack on socket 0");
644 * Set up a listening endpoint, and give it to the event-handler.
646 static void add_listener(char *where, int what)
650 char mode[100], addr[100];
654 if (!where || sscanf(where, "%[^:]:%s", mode, addr) != 2)
656 logf (LOG_WARN, "%s: Address format: ('tcp'|'osi')':'<address>", me);
659 if (!strcmp(mode, "tcp"))
661 else if (!strcmp(mode, "osi"))
666 logf (LOG_WARN, "OSI Transport not allowed by configuration.");
672 logf (LOG_WARN, "You must specify either 'osi:' or 'tcp:'");
675 logf(LOG_LOG, "Adding %s %s listener on %s",
676 control_block.dynamic ? "dynamic" : "static",
677 what == PROTO_SR ? "SR" : "Z3950", where);
678 if (!(l = cs_create(type, 0, what)))
680 logf(LOG_FATAL|LOG_ERRNO, "Failed to create listener");
682 ap = cs_straddr (l, addr);
685 fprintf(stderr, "Address resolution failed.\n");
689 if (cs_bind(l, ap, CS_SERVER) < 0)
691 logf(LOG_FATAL|LOG_ERRNO, "Failed to bind to %s", where);
693 if (!(lst = iochan_create(cs_fileno(l), listener, EVENT_INPUT |
696 logf(LOG_FATAL|LOG_ERRNO, "Failed to create IOCHAN-type");
698 iochan_setdata(lst, l);
700 /* Ensure our listener chain is setup properly */
701 lst->next = pListener;
706 /* For windows we don't need to catch the signals */
707 static void catchchld(int num)
709 while (waitpid(-1, 0, WNOHANG) > 0)
711 signal(SIGCHLD, catchchld);
715 statserv_options_block *statserv_getcontrol(void)
717 static statserv_options_block cb;
719 memcpy(&cb, &control_block, sizeof(cb));
723 void statserv_setcontrol(statserv_options_block *block)
725 memcpy(&control_block, block, sizeof(*block));
728 int statserv_start(int argc, char **argv)
730 int ret, listeners = 0, inetd = 0, r;
732 int protocol = control_block.default_proto;
736 /* We need to initialize the thread list */
737 ThreadList_Initialize();
741 if ((me = strrchr (argv[0], '\\')))
748 while ((ret = options("a:iszSl:v:u:c:w:t:k:", argv, argc, &arg)) != -2)
753 add_listener(arg, protocol);
756 case 'z': protocol = PROTO_Z3950; break;
757 case 's': protocol = PROTO_SR; break;
758 case 'S': control_block.dynamic = 0; break;
760 strcpy(control_block.logfile, arg ? arg : "");
761 log_init(control_block.loglevel, me, control_block.logfile);
764 control_block.loglevel = log_mask_str(arg);
765 log_init(control_block.loglevel, me, control_block.logfile);
768 strcpy(control_block.apdufile, arg ? arg : ""); break;
770 strcpy(control_block.setuid, arg ? arg : ""); break;
772 strcpy(control_block.configname, arg ? arg : ""); break;
774 if (!arg || !(r = atoi(arg)))
776 fprintf(stderr, "%s: Specify positive timeout for -t.\n",
780 control_block.idle_timeout = r;
783 if (!arg || !(r = atoi(arg)))
785 fprintf(stderr, "%s: Specify positive timeout for -t.\n",
789 control_block.maxrecordsize = r * 1024;
802 fprintf(stderr, "Usage: %s [ -i -a <pdufile> -v <loglevel>"
803 " -l <logfile> -u <user> -c <config> -t <minutes>"
805 " -zsS <listener-addr> -w <directory> ... ]\n", me);
810 if ((pListener == NULL) && *control_block.default_listen)
811 add_listener(control_block.default_listen, protocol);
815 inetd_connection(protocol);
818 if (control_block.pre_init)
819 (*control_block.pre_init)(&control_block);
820 if (control_block.dynamic)
821 signal(SIGCHLD, catchchld);
823 if (*control_block.setuid)
827 if (!(pw = getpwnam(control_block.setuid)))
829 logf(LOG_FATAL, "%s: Unknown user", control_block.setuid);
832 if (setuid(pw->pw_uid) < 0)
834 logf(LOG_FATAL|LOG_ERRNO, "setuid");
840 logf(LOG_LOG, "Entering event loop.");
842 if (pListener == NULL)
845 ret = event_loop(&pListener);
857 static Args ArgDetails;
859 /* name of the executable */
860 #define SZAPPNAME "server"
862 /* list of service dependencies - "dep1\0dep2\0\0" */
863 #define SZDEPENDENCIES ""
865 int statserv_main(int argc, char **argv)
867 statserv_options_block *cb = statserv_getcontrol();
869 /* Lets setup the Arg structure */
870 ArgDetails.argc = argc;
871 ArgDetails.argv = argv;
873 /* Now setup the service with the service controller */
874 SetupService(argc, argv, &ArgDetails, SZAPPNAME,
875 cb->service_name, /* internal service name */
876 cb->service_name, /* displayed name of the service */
881 int StartAppService(void *pHandle, int argc, char **argv)
883 /* Initializes the App */
887 void RunAppService(void *pHandle)
889 Args *pArgs = (Args *)pHandle;
891 /* Starts the app running */
892 statserv_start(pArgs->argc, pArgs->argv);
895 void StopAppService(void *pHandle)
898 statserv_closedown();
901 int statserv_main(int argc, char **argv)
903 int ret = statserv_start (argc, argv);
904 statserv_closedown ();