2 * Copyright (c) 1995, Index Data
3 * See the file LICENSE for details.
4 * Sebastian Hammer, Adam Dickmeiss
7 * Revision 1.37 1997-09-01 08:53:01 adam
8 * New windows NT/95 port using MSV5.0. The test server 'ztest' was
9 * moved a separate directory. MSV5.0 project server.dsp created.
10 * As an option, the server can now operate as an NT service.
12 * Revision 1.36 1996/07/06 19:58:36 quinn
13 * System headerfiles gathered in yconfig
15 * Revision 1.35 1996/05/29 10:03:28 quinn
18 * Revision 1.34 1996/02/21 13:12:07 quinn
19 * *** empty log message ***
21 * Revision 1.33 1996/02/10 12:23:49 quinn
22 * Enable inetd operations fro TCP/IP stack
24 * Revision 1.32 1996/01/19 15:41:52 quinn
25 * *** empty log message ***
27 * Revision 1.31 1995/11/17 11:09:39 adam
28 * Added new option '-c' to specify configuration name in control block.
30 * Revision 1.30 1995/11/01 13:54:59 quinn
33 * Revision 1.29 1995/10/30 12:41:29 quinn
34 * Added hostname lookup for server.
36 * Revision 1.28 1995/09/29 17:12:30 quinn
39 * Revision 1.27 1995/09/27 15:03:02 quinn
40 * Modified function heads & prototypes.
42 * Revision 1.26 1995/08/29 14:44:51 quinn
45 * Revision 1.25 1995/08/29 11:18:02 quinn
46 * Added code to receive close
48 * Revision 1.24 1995/06/16 10:31:39 quinn
49 * Added session timeout.
51 * Revision 1.23 1995/06/15 12:30:48 quinn
54 * Revision 1.22 1995/06/15 07:45:17 quinn
57 * Revision 1.21 1995/06/06 08:15:40 quinn
60 * Revision 1.20 1995/05/29 08:12:09 quinn
63 * Revision 1.19 1995/05/16 09:37:27 quinn
66 * Revision 1.18 1995/05/16 08:51:09 quinn
67 * License, documentation, and memory fixes
69 * Revision 1.17 1995/05/15 11:56:42 quinn
70 * Asynchronous facilities. Restructuring of seshigh code.
72 * Revision 1.16 1995/04/10 10:23:40 quinn
73 * Some work to add scan and other things.
75 * Revision 1.15 1995/03/31 10:16:51 quinn
78 * Revision 1.14 1995/03/31 09:18:58 quinn
81 * Revision 1.13 1995/03/30 16:08:39 quinn
84 * Revision 1.12 1995/03/30 13:29:02 quinn
87 * Revision 1.11 1995/03/30 12:18:17 quinn
90 * Revision 1.10 1995/03/29 15:40:16 quinn
91 * Ongoing work. Statserv is now dynamic by default
93 * Revision 1.9 1995/03/27 08:34:30 quinn
94 * Added dynamic server functionality.
95 * Released bindings to session.c (is now redundant)
97 * Revision 1.8 1995/03/20 09:46:26 quinn
100 * Revision 1.7 1995/03/16 13:29:04 quinn
101 * Partitioned server.
103 * Revision 1.6 1995/03/15 15:18:52 quinn
104 * Little changes to better support nonblocking I/O
107 * Revision 1.5 1995/03/15 08:37:45 quinn
108 * Now we're pretty much set for nonblocking I/O.
110 * Revision 1.4 1995/03/14 16:59:48 quinn
113 * Revision 1.3 1995/03/14 11:30:15 quinn
116 * Revision 1.2 1995/03/14 10:28:03 quinn
117 * More work on demo server.
119 * Revision 1.1 1995/03/10 18:22:45 quinn
120 * The rudiments of an asynchronous server.
125 * Simple, static server. I wouldn't advise a static server unless you
126 * really have to, but it's great for debugging memory management. :)
146 #include <comstack.h>
152 #include <statserv.h>
154 static IOCHAN pListener;
156 static char *me = "statserver";
160 static statserv_options_block control_block = {
161 1, /* dynamic mode */
162 LOG_DEFAULT_LEVEL, /* log level */
164 "", /* diagnostic output to stderr */
165 "tcp:@:9999", /* default listener port */
166 PROTO_Z3950, /* default application protocol */
167 60, /* idle timeout (minutes) */
168 1024*1024, /* maximum PDU size (approx.) to allow */
169 "default-config", /* configuration name to pass to backend */
174 * handle incoming connect requests.
175 * The dynamic mode is a bit tricky mostly because we want to avoid
176 * doing all of the listening and accepting in the parent - it's
181 typedef struct _ThreadList ThreadList;
183 typedef struct _ThreadList
190 static ThreadList *pFirstThread;
191 static CRITICAL_SECTION Thread_CritSect;
192 static BOOL bInitialized = FALSE;
194 static void ThreadList_Initialize()
196 /* Initialize the critical Sections */
197 InitializeCriticalSection(&Thread_CritSect);
199 /* Set the first thraed */
202 /* we have been initialized */
206 static void statserv_add(HANDLE hThread, IOCHAN pIOChannel)
208 /* Only one thread can go through this section at a time */
209 EnterCriticalSection(&Thread_CritSect);
212 /* Lets create our new object */
213 ThreadList *pNewThread = (ThreadList *)malloc(sizeof(ThreadList));
214 pNewThread->hThread = hThread;
215 pNewThread->pIOChannel = pIOChannel;
216 pNewThread->pNext = pFirstThread;
217 pFirstThread = pNewThread;
219 /* Lets let somebody else create a new object now */
220 LeaveCriticalSection(&Thread_CritSect);
224 void statserv_remove(IOCHAN pIOChannel)
226 /* Only one thread can go through this section at a time */
227 EnterCriticalSection(&Thread_CritSect);
230 ThreadList *pCurrentThread = pFirstThread;
231 ThreadList *pNextThread;
232 ThreadList *pPrevThread =NULL;
234 /* Step through alll the threads */
235 for (; pCurrentThread != NULL; pCurrentThread = pNextThread)
237 /* We only need to compare on the IO Channel */
238 if (pCurrentThread->pIOChannel == pIOChannel)
240 /* We have found the thread we want to delete */
241 /* First of all reset the next pointers */
242 if (pPrevThread == NULL)
243 pFirstThread = pCurrentThread->pNext;
245 pPrevThread->pNext = pCurrentThread->pNext;
247 /* All we need todo now is delete the memory */
248 free(pCurrentThread);
250 /* No need to look at any more threads */
255 /* We need to look at another thread */
256 pNextThread = pCurrentThread->pNext;
260 /* Lets let somebody else remove an object now */
261 LeaveCriticalSection(&Thread_CritSect);
265 void statserv_closedown()
267 /* Shouldn't do anything if we are not initialized */
271 HANDLE *pThreadHandles = NULL;
273 /* We need to stop threads adding and removing while we start the closedown process */
274 EnterCriticalSection(&Thread_CritSect);
277 /* We have exclusive access to the thread stuff now */
278 /* Y didn't i use a semaphore - Oh well never mind */
279 ThreadList *pCurrentThread = pFirstThread;
281 /* Before we do anything else, we need to shutdown the listener */
282 if (pListener != NULL)
283 iochan_destroy(pListener);
285 for (; pCurrentThread != NULL; pCurrentThread = pCurrentThread->pNext)
287 /* Just destroy the IOCHAN, that should do the trick */
288 iochan_destroy(pCurrentThread->pIOChannel);
290 /* Keep a running count of our handles */
296 HANDLE *pCurrentHandle ;
298 /* Allocate the thread handle array */
299 pThreadHandles = (HANDLE *)malloc(sizeof(HANDLE) * iHandles);
300 pCurrentHandle = pThreadHandles;
302 for (pCurrentThread = pFirstThread;
303 pCurrentThread != NULL;
304 pCurrentThread = pCurrentThread->pNext, pCurrentHandle++)
306 /* Just the handle */
307 *pCurrentHandle = pCurrentThread->hThread;
311 /* We can now leave the critical section */
312 LeaveCriticalSection(&Thread_CritSect);
315 /* Now we can really do something */
318 /* This will now wait, until all the threads close */
319 WaitForMultipleObjects(iHandles, pThreadHandles, TRUE, INFINITE);
321 /* Free the memory we allocated for the handle array */
322 free(pThreadHandles);
325 /* No longer require the critical section, since all threads are dead */
326 DeleteCriticalSection(&Thread_CritSect);
330 static void listener(IOCHAN h, int event)
332 COMSTACK line = (COMSTACK) iochan_getdata(h);
337 if (event == EVENT_INPUT)
339 if ((res = cs_listen(line, 0, 0)) < 0)
341 logf(LOG_FATAL, "cs_listen failed.");
346 logf(LOG_DEBUG, "listen ok");
347 iochan_setevent(h, EVENT_OUTPUT);
348 iochan_setflags(h, EVENT_OUTPUT | EVENT_EXCEPT); /* set up for acpt */
350 else if (event == EVENT_OUTPUT)
357 if (!(new_line = cs_accept(line)))
359 logf(LOG_FATAL, "Accept failed.");
360 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
363 logf(LOG_DEBUG, "accept ok");
365 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session, EVENT_INPUT)))
367 logf(LOG_FATAL, "Failed to create iochan");
371 if (!(newas = create_association(new_chan, new_line)))
373 logf(LOG_FATAL, "Failed to create new assoc.");
377 iochan_setdata(new_chan, newas);
378 iochan_settimeout(new_chan, control_block.idle_timeout * 60);
379 a = cs_addrstr(new_line);
380 logf(LOG_LOG, "Accepted connection from %s", a ? a : "[Unknown]");
382 /* Now what we need todo is create a new thread with this iochan as the parameter */
383 /* if (CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)event_loop, new_chan, 0, &ThreadId) == NULL)
385 /* Somehow, somewhere we need to store this thread id, otherwise we won't be able to close cleanly */
386 NewHandle = (HANDLE)_beginthreadex(NULL, 0, event_loop, new_chan, 0, &ThreadId);
387 if (NewHandle == (HANDLE)-1)
389 logf(LOG_FATAL, "Failed to create new thread.");
394 /* We successfully created the thread, so add it to the list */
395 statserv_add(NewHandle, new_chan);
397 logf(LOG_DEBUG, "Created new thread, iochan %p", new_chan);
398 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
402 logf(LOG_FATAL, "Bad event on listener.");
410 /* To save having an #ifdef in event_loop we need to define this empty function */
411 void statserv_remove(IOCHAN pIOChannel)
415 void statserv_closedown()
417 /* We don't need todoanything here - or do we */
418 if (pListener != NULL)
419 iochan_destroy(pListener);
422 static void listener(IOCHAN h, int event)
424 COMSTACK line = (COMSTACK) iochan_getdata(h);
427 static int child = 0;
430 if (event == EVENT_INPUT)
432 if (control_block.dynamic && !child)
438 logf(LOG_FATAL|LOG_ERRNO, "pipe");
442 if ((res = fork()) < 0)
444 logf(LOG_FATAL|LOG_ERRNO, "fork");
448 else if (res == 0) /* child */
455 for (pp = iochan_getchan(); pp; pp = iochan_getnext(pp))
459 COMSTACK l = iochan_getdata(pp);
464 sprintf(nbuf, "%s(%d)", me, getpid());
465 log_init(control_block.loglevel, nbuf, 0);
470 /* wait for child to take the call */
476 if ((res = read(hand[0], dummy, 1)) < 0 && errno != EINTR)
478 logf(LOG_FATAL|LOG_ERRNO, "handshake read");
484 logf(LOG_DEBUG, "P: Child has taken the call");
489 if ((res = cs_listen(line, 0, 0)) < 0)
491 logf(LOG_FATAL, "cs_listen failed.");
496 logf(LOG_DEBUG, "listen ok");
497 iochan_setevent(h, EVENT_OUTPUT);
498 iochan_setflags(h, EVENT_OUTPUT | EVENT_EXCEPT); /* set up for acpt */
500 /* in dynamic mode, only the child ever comes down here */
501 else if (event == EVENT_OUTPUT)
507 if (!(new_line = cs_accept(line)))
509 logf(LOG_FATAL, "Accept failed.");
510 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
513 logf(LOG_DEBUG, "accept ok");
514 if (control_block.dynamic)
517 /* close our half of the listener socket */
518 for (pp = iochan_getchan(); pp; pp = iochan_getnext(pp))
520 COMSTACK l = iochan_getdata(pp);
525 logf(LOG_DEBUG, "Releasing parent");
529 iochan_setflags(h, EVENT_INPUT | EVENT_EXCEPT); /* reset listener */
531 if (!(new_chan = iochan_create(cs_fileno(new_line), ir_session,
534 logf(LOG_FATAL, "Failed to create iochan");
538 if (!(newas = create_association(new_chan, new_line)))
540 logf(LOG_FATAL, "Failed to create new assoc.");
544 iochan_setdata(new_chan, newas);
545 iochan_settimeout(new_chan, control_block.idle_timeout * 60);
546 a = cs_addrstr(new_line);
547 logf(LOG_LOG, "Accepted connection from %s", a ? a : "[Unknown]");
551 logf(LOG_FATAL, "Bad event on listener.");
559 static void inetd_connection(int what)
566 if ((line = cs_createbysocket(0, tcpip_type, 0, what)))
568 if ((chan = iochan_create(cs_fileno(line), ir_session, EVENT_INPUT)))
570 if ((assoc = create_association(chan, line)))
572 iochan_setdata(chan, assoc);
573 iochan_settimeout(chan, control_block.idle_timeout * 60);
574 addr = cs_addrstr(line);
575 logf(LOG_LOG, "Inetd association from %s", addr ? addr : "[UNKNOWN]");
579 logf(LOG_FATAL, "Failed to create association structure");
584 logf(LOG_FATAL, "Failed to create iochan");
589 logf(LOG_ERRNO|LOG_FATAL, "Failed to create comstack on socket 0");
594 * Set up a listening endpoint, and give it to the event-handler.
596 static void add_listener(char *where, int what)
600 char mode[100], addr[100];
604 if (!where || sscanf(where, "%[^:]:%s", mode, addr) != 2)
606 fprintf(stderr, "%s: Address format: ('tcp'|'osi')':'<address>.\n",
609 if (!strcmp(mode, "tcp"))
611 if (!(ap = tcpip_strtoaddr(addr)))
613 fprintf(stderr, "Address resolution failed for TCP.\n");
617 else if (!strcmp(mode, "osi"))
620 if (!(ap = mosi_strtoaddr(addr)))
622 fprintf(stderr, "Address resolution failed for TCP.\n");
626 fprintf(stderr, "OSI Transport not allowed by configuration.\n");
631 fprintf(stderr, "You must specify either 'osi:' or 'tcp:'.\n");
633 logf(LOG_LOG, "Adding %s %s listener on %s",
634 control_block.dynamic ? "dynamic" : "static",
635 what == PROTO_SR ? "SR" : "Z3950", where);
636 if (!(l = cs_create(type, 0, what)))
638 logf(LOG_FATAL|LOG_ERRNO, "Failed to create listener");
640 if (cs_bind(l, ap, CS_SERVER) < 0)
642 logf(LOG_FATAL|LOG_ERRNO, "Failed to bind to %s", where);
644 if (!(lst = iochan_create(cs_fileno(l), listener, EVENT_INPUT |
647 logf(LOG_FATAL|LOG_ERRNO, "Failed to create IOCHAN-type");
649 iochan_setdata(lst, l);
651 /* Ensure our listener chain is setup properly */
652 lst->next = pListener;
657 /* For windows we don't need to catch the signals */
658 static void catchchld(int num)
660 while (waitpid(-1, 0, WNOHANG) > 0)
662 signal(SIGCHLD, catchchld);
666 statserv_options_block *statserv_getcontrol(void)
668 static statserv_options_block cb;
670 memcpy(&cb, &control_block, sizeof(cb));
674 void statserv_setcontrol(statserv_options_block *block)
676 memcpy(&control_block, block, sizeof(*block));
679 int statserv_main(int argc, char **argv)
681 int ret, listeners = 0, inetd = 0, r;
683 int protocol = control_block.default_proto;
686 /* We need to initialize the thread list */
687 ThreadList_Initialize();
691 while ((ret = options("a:iszSl:v:u:c:w:t:k:", argv, argc, &arg)) != -2)
696 add_listener(arg, protocol);
699 case 'z': protocol = PROTO_Z3950; break;
700 case 's': protocol = PROTO_SR; break;
701 case 'S': control_block.dynamic = 0; break;
703 strcpy(control_block.logfile, arg ? arg : "");
704 log_init(control_block.loglevel, me, control_block.logfile);
707 control_block.loglevel = log_mask_str(arg);
708 log_init(control_block.loglevel, me, control_block.logfile);
711 strcpy(control_block.apdufile, arg ? arg : ""); break;
713 strcpy(control_block.setuid, arg ? arg : ""); break;
715 strcpy(control_block.configname, arg ? arg : ""); break;
717 if (!arg || !(r = atoi(arg)))
719 fprintf(stderr, "%s: Specify positive timeout for -t.\n",
723 control_block.idle_timeout = r;
726 if (!arg || !(r = atoi(arg)))
728 fprintf(stderr, "%s: Specify positive timeout for -t.\n",
732 control_block.maxrecordsize = r * 1024;
745 fprintf(stderr, "Usage: %s [ -i -a <pdufile> -v <loglevel>"
746 " -l <logfile> -u <user> -c <config> -t <minutes>"
748 " -zsS <listener-addr> -w <directory> ... ]\n", me);
754 log_init(control_block.loglevel, NULL, control_block.logfile);
757 if ((pListener == NULL) && *control_block.default_listen)
758 add_listener(control_block.default_listen, protocol);
762 inetd_connection(protocol);
765 if (control_block.dynamic)
766 signal(SIGCHLD, catchchld);
768 if (*control_block.setuid)
772 if (!(pw = getpwnam(control_block.setuid)))
774 logf(LOG_FATAL, "%s: Unknown user", control_block.setuid);
777 if (setuid(pw->pw_uid) < 0)
779 logf(LOG_FATAL|LOG_ERRNO, "setuid");
785 logf(LOG_LOG, "Entering event loop.");
787 if (pListener == NULL)
790 return event_loop(pListener);