2 * Copyright (c) 1995-1997, 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.44 1997-11-07 13:31:52 adam
11 * Added NT Service name part of statserv_options_block. Moved NT
12 * service utility to server library.
14 * Revision 1.43 1997/10/31 12:20:09 adam
15 * Improved memory debugging for xmalloc/nmem.c. References to NMEM
16 * instead of ODR in n ESPEC-1 handling in source d1_espec.c.
17 * Bug fix: missing fclose in data1_read_espec1.
19 * Revision 1.42 1997/10/27 14:03:02 adam
20 * Added new member to statserver_options_block, pre_init, which
21 * specifies a callback to be invoked after command line parsing and
22 * before the server listens for the first time.
24 * Revision 1.41 1997/09/29 07:19:32 adam
25 * Server library uses nmem_init/nmem_exit. The log prefix no longer
26 * includes leading path on NT.
28 * Revision 1.40 1997/09/17 12:10:41 adam
31 * Revision 1.39 1997/09/09 10:10:19 adam
32 * Another MSV5.0 port. Changed projects to include proper
33 * library/include paths.
34 * Server starts server in test-mode when no options are given.
36 * Revision 1.38 1997/09/04 14:19:14 adam
39 * Revision 1.37 1997/09/01 08:53:01 adam
40 * New windows NT/95 port using MSV5.0. The test server 'ztest' was
41 * moved a separate directory. MSV5.0 project server.dsp created.
42 * As an option, the server can now operate as an NT service.
44 * Revision 1.36 1996/07/06 19:58:36 quinn
45 * System headerfiles gathered in yconfig
47 * Revision 1.35 1996/05/29 10:03:28 quinn
50 * Revision 1.34 1996/02/21 13:12:07 quinn
51 * *** empty log message ***
53 * Revision 1.33 1996/02/10 12:23:49 quinn
54 * Enable inetd operations fro TCP/IP stack
56 * Revision 1.32 1996/01/19 15:41:52 quinn
57 * *** empty log message ***
59 * Revision 1.31 1995/11/17 11:09:39 adam
60 * Added new option '-c' to specify configuration name in control block.
62 * Revision 1.30 1995/11/01 13:54:59 quinn
65 * Revision 1.29 1995/10/30 12:41:29 quinn
66 * Added hostname lookup for server.
68 * Revision 1.28 1995/09/29 17:12:30 quinn
71 * Revision 1.27 1995/09/27 15:03:02 quinn
72 * Modified function heads & prototypes.
74 * Revision 1.26 1995/08/29 14:44:51 quinn
77 * Revision 1.25 1995/08/29 11:18:02 quinn
78 * Added code to receive close
80 * Revision 1.24 1995/06/16 10:31:39 quinn
81 * Added session timeout.
83 * Revision 1.23 1995/06/15 12:30:48 quinn
86 * Revision 1.22 1995/06/15 07:45:17 quinn
89 * Revision 1.21 1995/06/06 08:15:40 quinn
92 * Revision 1.20 1995/05/29 08:12:09 quinn
95 * Revision 1.19 1995/05/16 09:37:27 quinn
98 * Revision 1.18 1995/05/16 08:51:09 quinn
99 * License, documentation, and memory fixes
101 * Revision 1.17 1995/05/15 11:56:42 quinn
102 * Asynchronous facilities. Restructuring of seshigh code.
104 * Revision 1.16 1995/04/10 10:23:40 quinn
105 * Some work to add scan and other things.
107 * Revision 1.15 1995/03/31 10:16:51 quinn
110 * Revision 1.14 1995/03/31 09:18:58 quinn
113 * Revision 1.13 1995/03/30 16:08:39 quinn
116 * Revision 1.12 1995/03/30 13:29:02 quinn
119 * Revision 1.11 1995/03/30 12:18:17 quinn
122 * Revision 1.10 1995/03/29 15:40:16 quinn
123 * Ongoing work. Statserv is now dynamic by default
125 * Revision 1.9 1995/03/27 08:34:30 quinn
126 * Added dynamic server functionality.
127 * Released bindings to session.c (is now redundant)
129 * Revision 1.8 1995/03/20 09:46:26 quinn
132 * Revision 1.7 1995/03/16 13:29:04 quinn
133 * Partitioned server.
135 * Revision 1.6 1995/03/15 15:18:52 quinn
136 * Little changes to better support nonblocking I/O
139 * Revision 1.5 1995/03/15 08:37:45 quinn
140 * Now we're pretty much set for nonblocking I/O.
142 * Revision 1.4 1995/03/14 16:59:48 quinn
145 * Revision 1.3 1995/03/14 11:30:15 quinn
148 * Revision 1.2 1995/03/14 10:28:03 quinn
149 * More work on demo server.
151 * Revision 1.1 1995/03/10 18:22:45 quinn
152 * The rudiments of an asynchronous server.
175 #include <comstack.h>
181 #include <statserv.h>
183 static IOCHAN pListener;
185 static char *me = "statserver";
189 static statserv_options_block control_block = {
190 1, /* dynamic mode */
191 LOG_DEFAULT_LEVEL, /* log level */
193 "", /* diagnostic output to stderr */
194 "tcp:@:9999", /* default listener port */
195 PROTO_Z3950, /* default application protocol */
196 60, /* idle timeout (minutes) */
197 1024*1024, /* maximum PDU size (approx.) to allow */
198 "default-config", /* configuration name to pass to backend */
199 "", /* set user id */
200 NULL, /* pre init handler */
201 "Z39.50 Server" /* NT Service Name */
205 * handle incoming connect requests.
206 * The dynamic mode is a bit tricky mostly because we want to avoid
207 * doing all of the listening and accepting in the parent - it's
212 typedef struct _ThreadList ThreadList;
214 typedef struct _ThreadList
221 static ThreadList *pFirstThread;
222 static CRITICAL_SECTION Thread_CritSect;
223 static BOOL bInitialized = FALSE;
225 static void ThreadList_Initialize()
227 /* Initialize the critical Sections */
228 InitializeCriticalSection(&Thread_CritSect);
230 /* Set the first thraed */
233 /* we have been initialized */
237 static void statserv_add(HANDLE hThread, IOCHAN pIOChannel)
239 /* Only one thread can go through this section at a time */
240 EnterCriticalSection(&Thread_CritSect);
243 /* Lets create our new object */
244 ThreadList *pNewThread = (ThreadList *)malloc(sizeof(ThreadList));
245 pNewThread->hThread = hThread;
246 pNewThread->pIOChannel = pIOChannel;
247 pNewThread->pNext = pFirstThread;
248 pFirstThread = pNewThread;
250 /* Lets let somebody else create a new object now */
251 LeaveCriticalSection(&Thread_CritSect);
255 void statserv_remove(IOCHAN pIOChannel)
257 /* Only one thread can go through this section at a time */
258 EnterCriticalSection(&Thread_CritSect);
261 ThreadList *pCurrentThread = pFirstThread;
262 ThreadList *pNextThread;
263 ThreadList *pPrevThread =NULL;
265 /* Step through alll the threads */
266 for (; pCurrentThread != NULL; pCurrentThread = pNextThread)
268 /* We only need to compare on the IO Channel */
269 if (pCurrentThread->pIOChannel == pIOChannel)
271 /* We have found the thread we want to delete */
272 /* First of all reset the next pointers */
273 if (pPrevThread == NULL)
274 pFirstThread = pCurrentThread->pNext;
276 pPrevThread->pNext = pCurrentThread->pNext;
278 /* All we need todo now is delete the memory */
279 free(pCurrentThread);
281 /* No need to look at any more threads */
286 /* We need to look at another thread */
287 pNextThread = pCurrentThread->pNext;
291 /* Lets let somebody else remove an object now */
292 LeaveCriticalSection(&Thread_CritSect);
296 void statserv_closedown()
298 /* Shouldn't do anything if we are not initialized */
302 HANDLE *pThreadHandles = NULL;
304 /* We need to stop threads adding and removing while we */
305 /* start the closedown process */
306 EnterCriticalSection(&Thread_CritSect);
309 /* We have exclusive access to the thread stuff now */
310 /* Y didn't i use a semaphore - Oh well never mind */
311 ThreadList *pCurrentThread = pFirstThread;
313 /* Before we do anything else, we need to shutdown the listener */
314 if (pListener != NULL)
315 iochan_destroy(pListener);
317 for (; pCurrentThread != NULL; pCurrentThread = pCurrentThread->pNext)
319 /* Just destroy the IOCHAN, that should do the trick */
320 iochan_destroy(pCurrentThread->pIOChannel);
322 /* Keep a running count of our handles */
328 HANDLE *pCurrentHandle ;
330 /* Allocate the thread handle array */
331 pThreadHandles = (HANDLE *)malloc(sizeof(HANDLE) * iHandles);
332 pCurrentHandle = pThreadHandles;
334 for (pCurrentThread = pFirstThread;
335 pCurrentThread != NULL;
336 pCurrentThread = pCurrentThread->pNext, pCurrentHandle++)
338 /* Just the handle */
339 *pCurrentHandle = pCurrentThread->hThread;
343 /* We can now leave the critical section */
344 LeaveCriticalSection(&Thread_CritSect);
347 /* Now we can really do something */
350 /* This will now wait, until all the threads close */
351 WaitForMultipleObjects(iHandles, pThreadHandles, TRUE, INFINITE);
353 /* Free the memory we allocated for the handle array */
354 free(pThreadHandles);
357 /* No longer require the critical section, since all threads are dead */
358 DeleteCriticalSection(&Thread_CritSect);
362 static void listener(IOCHAN h, int event)
364 COMSTACK line = (COMSTACK) iochan_getdata(h);
369 if (event == EVENT_INPUT)
371 if ((res = cs_listen(line, 0, 0)) < 0)
373 logf(LOG_FATAL, "cs_listen failed.");
378 logf(LOG_DEBUG, "listen ok");
379 iochan_setevent(h, EVENT_OUTPUT);
380 iochan_setflags(h, EVENT_OUTPUT | EVENT_EXCEPT); /* set up for acpt */
382 else if (event == EVENT_OUTPUT)
389 if (!(new_line = cs_accept(line)))
391 logf(LOG_FATAL, "Accept failed.");
392 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
395 logf(LOG_DEBUG, "Accept ok");
397 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session, EVENT_INPUT)))
399 logf(LOG_FATAL, "Failed to create iochan");
404 logf(LOG_DEBUG, "Creating association");
405 if (!(newas = create_association(new_chan, new_line)))
407 logf(LOG_FATAL, "Failed to create new assoc.");
411 logf(LOG_DEBUG, "Setting timeout %d", control_block.idle_timeout);
412 iochan_setdata(new_chan, newas);
413 iochan_settimeout(new_chan, control_block.idle_timeout * 60);
415 logf(LOG_DEBUG, "Determining client address");
416 a = cs_addrstr(new_line);
417 logf(LOG_LOG, "Accepted connection from %s", a ? a : "[Unknown]");
419 /* Now what we need todo is create a new thread with this iochan as
421 /* if (CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)event_loop, new_chan,
422 0, &ThreadId) == NULL) */
423 /* Somehow, somewhere we need to store this thread id, otherwise we won't be
424 able to close cleanly */
425 NewHandle = (HANDLE)_beginthreadex(NULL, 0, event_loop, new_chan, 0, &ThreadId);
426 if (NewHandle == (HANDLE)-1)
429 logf(LOG_FATAL|LOG_ERRNO, "Failed to create new thread.");
433 /* We successfully created the thread, so add it to the list */
434 statserv_add(NewHandle, new_chan);
436 logf(LOG_DEBUG, "Created new thread, iochan %p", new_chan);
437 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
441 logf(LOG_FATAL, "Bad event on listener.");
449 /* To save having an #ifdef in event_loop we need to define this empty function */
450 void statserv_remove(IOCHAN pIOChannel)
454 void statserv_closedown()
456 /* We don't need todoanything here - or do we */
457 if (pListener != NULL)
458 iochan_destroy(pListener);
461 static void listener(IOCHAN h, int event)
463 COMSTACK line = (COMSTACK) iochan_getdata(h);
466 static int child = 0;
469 if (event == EVENT_INPUT)
471 if (control_block.dynamic && !child)
477 logf(LOG_FATAL|LOG_ERRNO, "pipe");
481 if ((res = fork()) < 0)
483 logf(LOG_FATAL|LOG_ERRNO, "fork");
487 else if (res == 0) /* child */
494 for (pp = iochan_getchan(); pp; pp = iochan_getnext(pp))
498 COMSTACK l = iochan_getdata(pp);
503 sprintf(nbuf, "%s(%d)", me, getpid());
504 log_init(control_block.loglevel, nbuf, 0);
509 /* wait for child to take the call */
515 if ((res = read(hand[0], dummy, 1)) < 0 && errno != EINTR)
517 logf(LOG_FATAL|LOG_ERRNO, "handshake read");
523 logf(LOG_DEBUG, "P: Child has taken the call");
528 if ((res = cs_listen(line, 0, 0)) < 0)
530 logf(LOG_FATAL, "cs_listen failed.");
535 logf(LOG_DEBUG, "listen ok");
536 iochan_setevent(h, EVENT_OUTPUT);
537 iochan_setflags(h, EVENT_OUTPUT | EVENT_EXCEPT); /* set up for acpt */
539 /* in dynamic mode, only the child ever comes down here */
540 else if (event == EVENT_OUTPUT)
546 if (!(new_line = cs_accept(line)))
548 logf(LOG_FATAL, "Accept failed.");
549 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
552 logf(LOG_DEBUG, "accept ok");
553 if (control_block.dynamic)
556 /* close our half of the listener socket */
557 for (pp = iochan_getchan(); pp; pp = iochan_getnext(pp))
559 COMSTACK l = iochan_getdata(pp);
564 logf(LOG_DEBUG, "Releasing parent");
568 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
570 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session,
573 logf(LOG_FATAL, "Failed to create iochan");
577 if (!(newas = create_association(new_chan, new_line)))
579 logf(LOG_FATAL, "Failed to create new assoc.");
583 iochan_setdata(new_chan, newas);
584 iochan_settimeout(new_chan, control_block.idle_timeout * 60);
585 a = cs_addrstr(new_line);
586 logf(LOG_LOG, "Accepted connection from %s", a ? a : "[Unknown]");
590 logf(LOG_FATAL, "Bad event on listener.");
598 static void inetd_connection(int what)
605 if ((line = cs_createbysocket(0, tcpip_type, 0, what)))
607 if ((chan = iochan_create(cs_fileno(line), ir_session, EVENT_INPUT)))
609 if ((assoc = create_association(chan, line)))
611 iochan_setdata(chan, assoc);
612 iochan_settimeout(chan, control_block.idle_timeout * 60);
613 addr = cs_addrstr(line);
614 logf(LOG_LOG, "Inetd association from %s", addr ? addr : "[UNKNOWN]");
618 logf(LOG_FATAL, "Failed to create association structure");
623 logf(LOG_FATAL, "Failed to create iochan");
628 logf(LOG_ERRNO|LOG_FATAL, "Failed to create comstack on socket 0");
633 * Set up a listening endpoint, and give it to the event-handler.
635 static void add_listener(char *where, int what)
639 char mode[100], addr[100];
643 if (!where || sscanf(where, "%[^:]:%s", mode, addr) != 2)
645 logf (LOG_WARN, "%s: Address format: ('tcp'|'osi')':'<address>", me);
648 if (!strcmp(mode, "tcp"))
650 else if (!strcmp(mode, "osi"))
655 logf (LOG_WARN, "OSI Transport not allowed by configuration.");
661 logf (LOG_WARN, "You must specify either 'osi:' or 'tcp:'");
664 logf(LOG_LOG, "Adding %s %s listener on %s",
665 control_block.dynamic ? "dynamic" : "static",
666 what == PROTO_SR ? "SR" : "Z3950", where);
667 if (!(l = cs_create(type, 0, what)))
669 logf(LOG_FATAL|LOG_ERRNO, "Failed to create listener");
671 ap = cs_straddr (l, addr);
674 fprintf(stderr, "Address resolution failed.\n");
678 if (cs_bind(l, ap, CS_SERVER) < 0)
680 logf(LOG_FATAL|LOG_ERRNO, "Failed to bind to %s", where);
682 if (!(lst = iochan_create(cs_fileno(l), listener, EVENT_INPUT |
685 logf(LOG_FATAL|LOG_ERRNO, "Failed to create IOCHAN-type");
687 iochan_setdata(lst, l);
689 /* Ensure our listener chain is setup properly */
690 lst->next = pListener;
695 /* For windows we don't need to catch the signals */
696 static void catchchld(int num)
698 while (waitpid(-1, 0, WNOHANG) > 0)
700 signal(SIGCHLD, catchchld);
704 statserv_options_block *statserv_getcontrol(void)
706 static statserv_options_block cb;
708 memcpy(&cb, &control_block, sizeof(cb));
712 void statserv_setcontrol(statserv_options_block *block)
714 memcpy(&control_block, block, sizeof(*block));
718 int statserv_start(int argc, char **argv)
720 int ret, listeners = 0, inetd = 0, r;
722 int protocol = control_block.default_proto;
726 /* We need to initialize the thread list */
727 ThreadList_Initialize();
731 if ((me = strrchr (argv[0], '\\')))
738 while ((ret = options("a:iszSl:v:u:c:w:t:k:", argv, argc, &arg)) != -2)
743 add_listener(arg, protocol);
746 case 'z': protocol = PROTO_Z3950; break;
747 case 's': protocol = PROTO_SR; break;
748 case 'S': control_block.dynamic = 0; break;
750 strcpy(control_block.logfile, arg ? arg : "");
751 log_init(control_block.loglevel, me, control_block.logfile);
754 control_block.loglevel = log_mask_str(arg);
755 log_init(control_block.loglevel, me, control_block.logfile);
758 strcpy(control_block.apdufile, arg ? arg : ""); break;
760 strcpy(control_block.setuid, arg ? arg : ""); break;
762 strcpy(control_block.configname, arg ? arg : ""); break;
764 if (!arg || !(r = atoi(arg)))
766 fprintf(stderr, "%s: Specify positive timeout for -t.\n",
770 control_block.idle_timeout = r;
773 if (!arg || !(r = atoi(arg)))
775 fprintf(stderr, "%s: Specify positive timeout for -t.\n",
779 control_block.maxrecordsize = r * 1024;
792 fprintf(stderr, "Usage: %s [ -i -a <pdufile> -v <loglevel>"
793 " -l <logfile> -u <user> -c <config> -t <minutes>"
795 " -zsS <listener-addr> -w <directory> ... ]\n", me);
800 if ((pListener == NULL) && *control_block.default_listen)
801 add_listener(control_block.default_listen, protocol);
805 inetd_connection(protocol);
808 if (control_block.pre_init)
809 (*control_block.pre_init)(&control_block);
810 if (control_block.dynamic)
811 signal(SIGCHLD, catchchld);
813 if (*control_block.setuid)
817 if (!(pw = getpwnam(control_block.setuid)))
819 logf(LOG_FATAL, "%s: Unknown user", control_block.setuid);
822 if (setuid(pw->pw_uid) < 0)
824 logf(LOG_FATAL|LOG_ERRNO, "setuid");
830 logf(LOG_LOG, "Entering event loop.");
832 if (pListener == NULL)
835 ret = event_loop(pListener);
847 static Args ArgDetails;
849 /* name of the executable */
850 #define SZAPPNAME "server"
852 /* list of service dependencies - "dep1\0dep2\0\0" */
853 #define SZDEPENDENCIES ""
855 int statserv_main(int argc, char **argv)
857 statserv_options_block *cb = statserv_getcontrol();
859 /* Lets setup the Arg structure */
860 ArgDetails.argc = argc;
861 ArgDetails.argv = argv;
863 /* Now setup the service with the service controller */
864 SetupService(argc, argv, &ArgDetails, SZAPPNAME,
865 cb->service_name, /* internal service name */
866 cb->service_name, /* displayed name of the service */
871 int StartAppService(void *pHandle, int argc, char **argv)
873 /* Initializes the App */
877 void RunAppService(void *pHandle)
879 Args *pArgs = (Args *)pHandle;
881 /* Starts the app running */
882 statserv_start(pArgs->argc, pArgs->argv);
885 void StopAppService(void *pHandle)
888 statserv_closedown();
891 int statserv_main(int argc, char **argv)
893 int ret = statserv_start (argc, argv);
894 statserv_closedown ();