* Debugged all possible ways for a session to terminate; do them cleanly.
[citadel.git] / citadel / sysdep.c
1 /*
2  * Citadel/UX "system dependent" stuff.
3  * See copyright.txt for copyright information.
4  *
5  * $Id$
6  *
7  * Here's where we (hopefully) have all the parts of the Citadel server that
8  * would need to be altered to run the server in a non-POSIX environment.
9  * Wherever possible, we use function wrappers and type definitions to create
10  * abstractions that are platform-independent from the calling side.
11  * 
12  * Eventually we'll try porting to a different platform and either have
13  * multiple variants of this file or simply load it up with #ifdefs.
14  */
15
16
17 #include "sysdep.h"
18 #include <stdlib.h>
19 #include <unistd.h>
20 #include <stdio.h>
21 #include <fcntl.h>
22 #include <ctype.h>
23 #include <signal.h>
24 #include <sys/types.h>
25 #include <sys/wait.h>
26 #include <sys/socket.h>
27 #include <sys/time.h>
28 #include <limits.h>
29 #include <netinet/in.h>
30 #include <netdb.h>
31 #include <string.h>
32 #include <pwd.h>
33 #include <errno.h>
34 #include <stdarg.h>
35 #include <syslog.h>
36 #include <grp.h>
37 #ifdef __GNUC__
38 #include <malloc.h>
39 #endif
40 #ifdef HAVE_PTHREAD_H
41 #include <pthread.h>
42 #endif
43 #include "citadel.h"
44 #include "server.h"
45 #include "sysdep_decls.h"
46 #include "citserver.h"
47 #include "support.h"
48 #include "config.h"
49 #include "database.h"
50 #include "housekeeping.h"
51 #include "dynloader.h"
52 #include "tools.h"
53
54 #ifdef HAVE_SYS_SELECT_H
55 #include <sys/select.h>
56 #endif
57
58 #ifndef HAVE_SNPRINTF
59 #include "snprintf.h"
60 #endif
61
62 #ifdef DEBUG_MEMORY_LEAKS
63 struct TheHeap *heap = NULL;
64 #endif
65
66 pthread_mutex_t Critters[MAX_SEMAPHORES];       /* Things needing locking */
67 pthread_key_t MyConKey;                         /* TSD key for MyContext() */
68
69 int msock;                                      /* master listening socket */
70 int verbosity = DEFAULT_VERBOSITY;              /* Logging level */
71
72 struct CitContext masterCC;
73 int rescan[2];                                  /* The Rescan Pipe */
74
75 /*
76  * lprintf()  ...   Write logging information
77  */
78 void lprintf(int loglevel, const char *format, ...) {   
79         va_list arg_ptr;
80         char buf[512];
81   
82         va_start(arg_ptr, format);   
83         vsprintf(buf, format, arg_ptr);   
84         va_end(arg_ptr);   
85
86         if (loglevel <= verbosity) { 
87                 fprintf(stderr, "%s", buf);
88                 fflush(stderr);
89                 }
90
91         PerformLogHooks(loglevel, buf);
92         }   
93
94
95
96 #ifdef DEBUG_MEMORY_LEAKS
97 void *tracked_malloc(size_t tsize, char *tfile, int tline) {
98         void *ptr;
99         struct TheHeap *hptr;
100
101         ptr = malloc(tsize);
102         if (ptr == NULL) {
103                 lprintf(3, "DANGER!  mallok(%d) at %s:%d failed!\n",
104                         tsize, tfile, tline);
105                 return(NULL);
106         }
107
108         hptr = (struct TheHeap *) malloc(sizeof(struct TheHeap));
109         strcpy(hptr->h_file, tfile);
110         hptr->h_line = tline;
111         hptr->next = heap;
112         hptr->h_ptr = ptr;
113         heap = hptr;
114         return ptr;
115         }
116
117 char *tracked_strdup(const char *orig, char *tfile, int tline) {
118         char *s;
119
120         s = tracked_malloc( (strlen(orig)+1), tfile, tline);
121         if (s == NULL) return NULL;
122
123         strcpy(s, orig);
124         return s;
125 }
126
127 void tracked_free(void *ptr) {
128         struct TheHeap *hptr, *freeme;
129
130         if (heap->h_ptr == ptr) {
131                 hptr = heap->next;
132                 free(heap);
133                 heap = hptr;
134                 }
135         else {
136                 for (hptr=heap; hptr->next!=NULL; hptr=hptr->next) {
137                         if (hptr->next->h_ptr == ptr) {
138                                 freeme = hptr->next;
139                                 hptr->next = hptr->next->next;
140                                 free(freeme);
141                                 }
142                         }
143                 }
144
145         free(ptr);
146         }
147
148 void *tracked_realloc(void *ptr, size_t size) {
149         void *newptr;
150         struct TheHeap *hptr;
151         
152         newptr = realloc(ptr, size);
153
154         for (hptr=heap; hptr!=NULL; hptr=hptr->next) {
155                 if (hptr->h_ptr == ptr) hptr->h_ptr = newptr;
156                 }
157
158         return newptr;
159         }
160
161
162 void dump_tracked() {
163         struct TheHeap *hptr;
164
165         cprintf("%d Here's what's allocated...\n", LISTING_FOLLOWS);    
166         for (hptr=heap; hptr!=NULL; hptr=hptr->next) {
167                 cprintf("%20s %5d\n",
168                         hptr->h_file, hptr->h_line);
169                 }
170 #ifdef __GNUC__
171         malloc_stats();
172 #endif
173
174         cprintf("000\n");
175         }
176 #endif
177
178
179 /*
180  * we used to use master_cleanup() as a signal handler to shut down the server.
181  * however, master_cleanup() and the functions it calls do some things that
182  * aren't such a good idea to do from a signal handler: acquiring mutexes,
183  * playing with signal masks on BSDI systems, etc. so instead we install the
184  * following signal handler to set a global variable to inform the main loop
185  * that it's time to call master_cleanup() and exit.
186  */
187
188 static volatile int time_to_die = 0;
189
190 static RETSIGTYPE signal_cleanup(int signum) {
191         time_to_die = 1;
192         }
193
194
195 /*
196  * Some initialization stuff...
197  */
198 void init_sysdep(void) {
199         int a;
200
201         /* Set up a bunch of semaphores to be used for critical sections */
202         for (a=0; a<MAX_SEMAPHORES; ++a) {
203                 pthread_mutex_init(&Critters[a], NULL);
204                 }
205
206         /*
207          * Set up a place to put thread-specific data.
208          * We only need a single pointer per thread - it points to the
209          * thread's CitContext structure in the ContextList linked list.
210          */
211         if (pthread_key_create(&MyConKey, NULL) != 0) {
212                 lprintf(1, "Can't create TSD key!!  %s\n", strerror(errno));
213                 }
214
215         /*
216          * The action for unexpected signals and exceptions should be to
217          * call signal_cleanup() to gracefully shut down the server.
218          */
219         signal(SIGINT, signal_cleanup);
220         signal(SIGQUIT, signal_cleanup);
221         signal(SIGHUP, signal_cleanup);
222         signal(SIGTERM, signal_cleanup);
223
224         /*
225          * Do not shut down the server on broken pipe signals, otherwise the
226          * whole Citadel service would come down whenever a single client
227          * socket breaks.
228          */
229         signal(SIGPIPE, SIG_IGN);
230         }
231
232
233 /*
234  * Obtain a semaphore lock to begin a critical section.
235  */
236 void begin_critical_section(int which_one)
237 {
238         pthread_mutex_lock(&Critters[which_one]);
239 }
240
241 /*
242  * Release a semaphore lock to end a critical section.
243  */
244 void end_critical_section(int which_one)
245 {
246         pthread_mutex_unlock(&Critters[which_one]);
247 }
248
249
250
251 /*
252  * This is a generic function to set up a master socket for listening on
253  * a TCP port.  The server shuts down if the bind fails.
254  */
255 int ig_tcp_server(int port_number, int queue_len)
256 {
257         struct sockaddr_in sin;
258         int s, i;
259
260         memset(&sin, 0, sizeof(sin));
261         sin.sin_family = AF_INET;
262         sin.sin_addr.s_addr = INADDR_ANY;
263
264         if (port_number == 0) {
265                 lprintf(1,
266                         "citserver: No port number specified.  Run setup.\n");
267                 exit(1);
268                 }
269         
270         sin.sin_port = htons((u_short)port_number);
271
272         s = socket(PF_INET, SOCK_STREAM, (getprotobyname("tcp")->p_proto));
273         if (s < 0) {
274                 lprintf(1, "citserver: Can't create a socket: %s\n",
275                         strerror(errno));
276                 exit(errno);
277                 }
278
279         /* Set the SO_REUSEADDR socket option, because it makes sense. */
280         i = 1;
281         setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
282
283         if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
284                 lprintf(1, "citserver: Can't bind: %s\n", strerror(errno));
285                 exit(errno);
286                 }
287
288         if (listen(s, queue_len) < 0) {
289                 lprintf(1, "citserver: Can't listen: %s\n", strerror(errno));
290                 exit(errno);
291                 }
292
293         return(s);
294         }
295
296
297
298 /*
299  * Return a pointer to the CitContext structure bound to the thread which
300  * called this function.  If there's no such binding (for example, if it's
301  * called by the housekeeper thread) then a generic 'master' CC is returned.
302  */
303 struct CitContext *MyContext(void) {
304         struct CitContext *retCC;
305         retCC = (struct CitContext *) pthread_getspecific(MyConKey);
306         if (retCC == NULL) retCC = &masterCC;
307         return(retCC);
308         }
309
310
311 /*
312  * Initialize a new context and place it in the list.
313  */
314 struct CitContext *CreateNewContext(void) {
315         struct CitContext *me, *ptr;
316         int num = 1;
317
318         me = (struct CitContext *) mallok(sizeof(struct CitContext));
319         if (me == NULL) {
320                 lprintf(1, "citserver: can't allocate memory!!\n");
321                 return NULL;
322                 }
323         memset(me, 0, sizeof(struct CitContext));
324
325         /* The new context will be created already in the CON_EXECUTING state
326          * in order to prevent another thread from grabbing it while it's
327          * being set up.
328          */
329         me->state = CON_EXECUTING;
330
331         begin_critical_section(S_SESSION_TABLE);
332
333         /* obtain a unique session number */
334         for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
335                 if (ptr->cs_pid == num) {
336                         ++num;
337                         ptr = ContextList;
338                 }
339         }
340
341         me->cs_pid = num;
342         me->next = ContextList;
343         ContextList = me;
344
345         end_critical_section(S_SESSION_TABLE);
346         return(me);
347         }
348
349
350
351 /*
352  * Return the number of sessions currently running.
353  * (This should probably be moved out of sysdep.c)
354  */
355 int session_count(void) {
356         struct CitContext *ptr;
357         int TheCount = 0;
358
359         begin_critical_section(S_SESSION_TABLE);
360         for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
361                 ++TheCount;
362                 }
363         end_critical_section(S_SESSION_TABLE);
364
365         return(TheCount);
366         }
367
368
369 /*
370  * client_write()   ...    Send binary data to the client.
371  */
372 void client_write(char *buf, int nbytes)
373 {
374         int bytes_written = 0;
375         int retval;
376         while (bytes_written < nbytes) {
377                 retval = write(CC->client_socket, &buf[bytes_written],
378                         nbytes - bytes_written);
379                 if (retval < 1) {
380                         lprintf(2, "client_write() failed: %s\n",
381                                 strerror(errno));
382                         CC->kill_me = 1;
383                         return;
384                         }
385                 bytes_written = bytes_written + retval;
386                 }
387         }
388
389
390 /*
391  * cprintf()  ...   Send formatted printable data to the client.   It is
392  *                  implemented in terms of client_write() but remains in
393  *                  sysdep.c in case we port to somewhere without va_args...
394  */
395 void cprintf(const char *format, ...) {   
396         va_list arg_ptr;   
397         char buf[256];   
398    
399         va_start(arg_ptr, format);   
400         if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
401                 buf[sizeof buf - 2] = '\n';
402         client_write(buf, strlen(buf)); 
403         va_end(arg_ptr);
404         }   
405
406
407 /*
408  * Read data from the client socket.
409  * Return values are:
410  *      1       Requested number of bytes has been read.
411  *      0       Request timed out.
412  * If the socket breaks, the session is immediately terminated.
413  */
414 int client_read_to(char *buf, int bytes, int timeout)
415 {
416         int len,rlen;
417         fd_set rfds;
418         struct timeval tv;
419         int retval;
420
421         len = 0;
422         while(len<bytes) {
423                 FD_ZERO(&rfds);
424                 FD_SET(CC->client_socket, &rfds);
425                 tv.tv_sec = 1;
426                 tv.tv_usec = 0;
427
428                 retval = select( (CC->client_socket)+1, 
429                                         &rfds, NULL, NULL, &tv);
430
431                 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
432                         return(0);
433                         }
434
435                 rlen = read(CC->client_socket, &buf[len], bytes-len);
436                 if (rlen<1) {
437                         lprintf(2, "client_read() failed: %s\n",
438                                 strerror(errno));
439                         CC->kill_me = 1;
440                         return(-1);
441                         }
442                 len = len + rlen;
443                 }
444         return(1);
445         }
446
447 /*
448  * Read data from the client socket with default timeout.
449  * (This is implemented in terms of client_read_to() and could be
450  * justifiably moved out of sysdep.c)
451  */
452 int client_read(char *buf, int bytes)
453 {
454         return(client_read_to(buf, bytes, config.c_sleeping));
455         }
456
457
458 /*
459  * client_gets()   ...   Get a LF-terminated line of text from the client.
460  * (This is implemented in terms of client_read() and could be
461  * justifiably moved out of sysdep.c)
462  */
463 int client_gets(char *buf)
464 {
465         int i, retval;
466
467         /* Read one character at a time.
468          */
469         for (i = 0;;i++) {
470                 retval = client_read(&buf[i], 1);
471                 if (retval != 1 || buf[i] == '\n' || i == 255)
472                         break;
473                 }
474
475         /* If we got a long line, discard characters until the newline.
476          */
477         if (i == 255)
478                 while (buf[i] != '\n' && retval == 1)
479                         retval = client_read(&buf[i], 1);
480
481         /* Strip the trailing newline and any trailing nonprintables (cr's)
482          */
483         buf[i] = 0;
484         while ((strlen(buf)>0)&&(!isprint(buf[strlen(buf)-1])))
485                 buf[strlen(buf)-1] = 0;
486         return(retval);
487         }
488
489
490
491 /*
492  * The system-dependent part of master_cleanup() - close the master socket.
493  */
494 void sysdep_master_cleanup(void) {
495         lprintf(7, "Closing master socket %d\n", msock);
496         close(msock);
497         }
498
499
500 /*
501  * Terminate another session.
502  * FIX ... now we need some way to wake that session up so it knows it
503  * needs to terminate.
504  */
505 void kill_session(int session_to_kill) {
506         struct CitContext *ptr;
507
508         begin_critical_section(S_SESSION_TABLE);
509         for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
510                 if (ptr->cs_pid == session_to_kill) {
511                         ptr->kill_me = 1;
512                         }
513                 }
514         end_critical_section(S_SESSION_TABLE);
515         }
516
517
518
519
520 /*
521  * Start running as a daemon.  Only close stdio if do_close_stdio is set.
522  */
523 void start_daemon(int do_close_stdio) {
524         if (do_close_stdio) {
525                 /* close(0); */
526                 close(1);
527                 close(2);
528                 }
529         signal(SIGHUP,SIG_IGN);
530         signal(SIGINT,SIG_IGN);
531         signal(SIGQUIT,SIG_IGN);
532         if (fork()!=0) exit(0);
533         }
534
535
536
537 /*
538  * Tie in to the 'netsetup' program.
539  *
540  * (We're going to hope that netsetup never feeds more than 4096 bytes back.)
541  */
542 void cmd_nset(char *cmdbuf)
543 {
544         int retcode;
545         char fbuf[4096];
546         FILE *netsetup;
547         int ch;
548         int a, b;
549         char netsetup_args[3][256];
550
551         if (CC->usersupp.axlevel < 6) {
552                 cprintf("%d Higher access required.\n", 
553                         ERROR + HIGHER_ACCESS_REQUIRED);
554                 return;
555                 }
556
557         for (a=1; a<=3; ++a) {
558                 if (num_parms(cmdbuf) >= a) {
559                         extract(netsetup_args[a-1], cmdbuf, a-1);
560                         for (b=0; b<strlen(netsetup_args[a-1]); ++b) {
561                                 if (netsetup_args[a-1][b] == 34) {
562                                         netsetup_args[a-1][b] = '_';
563                                         }
564                                 }
565                         }
566                 else {
567                         netsetup_args[a-1][0] = 0;
568                         }
569                 }
570
571         sprintf(fbuf, "./netsetup \"%s\" \"%s\" \"%s\" </dev/null 2>&1",
572                 netsetup_args[0], netsetup_args[1], netsetup_args[2]);
573         netsetup = popen(fbuf, "r");
574         if (netsetup == NULL) {
575                 cprintf("%d %s\n", ERROR, strerror(errno));
576                 return;
577                 }
578
579         fbuf[0] = 0;
580         while (ch = getc(netsetup), (ch > 0)) {
581                 fbuf[strlen(fbuf)+1] = 0;
582                 fbuf[strlen(fbuf)] = ch;
583                 }
584
585         retcode = pclose(netsetup);
586
587         if (retcode != 0) {
588                 for (a=0; a<strlen(fbuf); ++a) {
589                         if (fbuf[a] < 32) fbuf[a] = 32;
590                         }
591                 fbuf[245] = 0;
592                 cprintf("%d %s\n", ERROR, fbuf);
593                 return;
594                 }
595
596         cprintf("%d Command succeeded.  Output follows:\n", LISTING_FOLLOWS);
597         cprintf("%s", fbuf);
598         if (fbuf[strlen(fbuf)-1] != 10) cprintf("\n");
599         cprintf("000\n");
600         }
601
602
603
604 /*
605  * Generic routine to convert a login name to a full name (gecos)
606  * Returns nonzero if a conversion took place
607  */
608 int convert_login(char NameToConvert[]) {
609         struct passwd *pw;
610         int a;
611
612         pw = getpwnam(NameToConvert);
613         if (pw == NULL) {
614                 return(0);
615                 }
616         else {
617                 strcpy(NameToConvert, pw->pw_gecos);
618                 for (a=0; a<strlen(NameToConvert); ++a) {
619                         if (NameToConvert[a] == ',') NameToConvert[a] = 0;
620                         }
621                 return(1);
622                 }
623         }
624
625
626
627 /*
628  * Purge all sessions which have the 'kill_me' flag set.
629  * This function has code to prevent it from running more than once every
630  * few seconds, because running it after every single unbind would waste a lot
631  * of CPU time and keep the context list locked too much.
632  */
633 void dead_session_purge(void) {
634         static time_t last_purge = 0;
635         struct CitContext *ptr, *rem;
636         
637         if ( (time(NULL) - last_purge) < 5 ) return;    /* Too soon, go away */
638
639         do {
640                 rem = NULL;
641                 begin_critical_section(S_SESSION_TABLE);
642                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
643                         if ( (ptr->state == CON_IDLE) && (ptr->kill_me) ) {
644                                 rem = ptr;      
645                         }
646                 }
647                 end_critical_section(S_SESSION_TABLE);
648
649                 /* RemoveContext() enters its own S_SESSION_TABLE critical
650                  * section, so we have to do it like this.
651                  */     
652                 if (rem != NULL) RemoveContext(rem);
653
654         } while (rem != NULL);
655 }
656
657
658         
659
660 /*
661  * Here's where it all begins.
662  */
663 int main(int argc, char **argv)
664 {
665         pthread_t HousekeepingThread;   /* Thread descriptor */
666         pthread_attr_t attr;            /* Thread attributes */
667         char tracefile[128];            /* Name of file to log traces to */
668         int a, i;                       /* General-purpose variables */
669         struct passwd *pw;
670         int drop_root_perms = 1;
671         char *moddir;
672         
673         /* specify default port name and trace file */
674         strcpy(tracefile, "");
675
676         /* parse command-line arguments */
677         for (a=1; a<argc; ++a) {
678
679                 /* -t specifies where to log trace messages to */
680                 if (!strncmp(argv[a], "-t", 2)) {
681                         strcpy(tracefile, argv[a]);
682                         strcpy(tracefile, &tracefile[2]);
683                         freopen(tracefile, "r", stdin);
684                         freopen(tracefile, "w", stdout);
685                         freopen(tracefile, "w", stderr);
686                         }
687
688                 /* run in the background if -d was specified */
689                 else if (!strcmp(argv[a], "-d")) {
690                         start_daemon( (strlen(tracefile) > 0) ? 0 : 1 ) ;
691                         }
692
693                 /* -x specifies the desired logging level */
694                 else if (!strncmp(argv[a], "-x", 2)) {
695                         verbosity = atoi(&argv[a][2]);
696                         }
697
698                 else if (!strncmp(argv[a], "-h", 2)) {
699                         safestrncpy(bbs_home_directory, &argv[a][2],
700                                     sizeof bbs_home_directory);
701                         home_specified = 1;
702                         }
703
704                 else if (!strncmp(argv[a], "-f", 2)) {
705                         do_defrag = 1;
706                         }
707
708                 /* -r tells the server not to drop root permissions. don't use
709                  * this unless you know what you're doing. this should be
710                  * removed in the next release if it proves unnecessary. */
711                 else if (!strcmp(argv[a], "-r"))
712                         drop_root_perms = 0;
713
714                 /* any other parameter makes it crash and burn */
715                 else {
716                         lprintf(1,      "citserver: usage: "
717                                         "citserver [-tTraceFile] [-d] [-f]"
718                                         " [-xLogLevel] [-hHomeDir]\n");
719                         exit(1);
720                         }
721
722                 }
723
724         /* Tell 'em who's in da house */
725         lprintf(1,
726 "\nMultithreaded message server for Citadel/UX\n"
727 "Copyright (C) 1987-1999 by the Citadel/UX development team.\n"
728 "Citadel/UX is free software, covered by the GNU General Public License, and\n"
729 "you are welcome to change it and/or distribute copies of it under certain\n"
730 "conditions.  There is absolutely no warranty for this software.  Please\n"
731 "read the 'COPYING.txt' file for details.\n\n");
732
733         /* Initialize... */
734         init_sysdep();
735         openlog("citserver",LOG_PID,LOG_USER);
736
737         /* Load site-specific parameters */
738         lprintf(7, "Loading citadel.config\n");
739         get_config();
740
741         /*
742          * Bind the server to our favourite port.
743          * There is no need to check for errors, because ig_tcp_server()
744          * exits if it doesn't succeed.
745          */
746         lprintf(7, "Attempting to bind to port %d...\n", config.c_port_number);
747         msock = ig_tcp_server(config.c_port_number, 5);
748         lprintf(7, "Listening on socket %d\n", msock);
749
750         /*
751          * Now that we've bound the socket, change to the BBS user id and its
752          * corresponding group ids
753          */
754         if (drop_root_perms) {
755                 if ((pw = getpwuid(BBSUID)) == NULL)
756                         lprintf(1, "WARNING: getpwuid(%d): %s\n"
757                                    "Group IDs will be incorrect.\n", BBSUID,
758                                 strerror(errno));
759                 else {
760                         initgroups(pw->pw_name, pw->pw_gid);
761                         if (setgid(pw->pw_gid))
762                                 lprintf(3, "setgid(%d): %s\n", pw->pw_gid,
763                                         strerror(errno));
764                         }
765                 lprintf(7, "Changing uid to %d\n", BBSUID);
766                 if (setuid(BBSUID) != 0) {
767                         lprintf(3, "setuid() failed: %s\n", strerror(errno));
768                         }
769                 }
770
771         /*
772          * Do non system dependent startup functions.
773          */
774         master_startup();
775
776         /*
777          * Load any server-side modules (plugins) available here.
778          */
779         lprintf(7, "Initializing loadable modules\n");
780         if ((moddir = malloc(strlen(bbs_home_directory) + 9)) != NULL) {
781                 sprintf(moddir, "%s/modules", bbs_home_directory);
782                 DLoader_Init(moddir);
783                 free(moddir);
784                 }
785
786         lprintf(7, "Starting housekeeper thread\n");
787         pthread_attr_init(&attr);
788         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
789         if (pthread_create(&HousekeepingThread, &attr,
790            (void* (*)(void*)) housekeeping_loop, NULL) != 0) {
791                 lprintf(1, "Can't create housekeeping thead: %s\n",
792                         strerror(errno));
793         }
794
795
796         /*
797          * The rescan pipe exists so that worker threads can be woken up and
798          * told to re-scan the context list for fd's to listen on.  This is
799          * necessary, for example, when a context is about to go idle and needs
800          * to get back on that list.
801          */
802         if (pipe(rescan)) {
803                 lprintf(1, "Can't create rescan pipe!\n");
804                 exit(errno);
805         }
806
807         /*
808          * Now create a bunch of worker threads.
809          */
810         for (i=0; i<(NUM_WORKER_THREADS-1); ++i) {
811                 pthread_attr_init(&attr);
812                 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
813                 if (pthread_create(&HousekeepingThread, &attr,
814                    (void* (*)(void*)) worker_thread, NULL) != 0) {
815                         lprintf(1, "Can't create worker thead: %s\n",
816                         strerror(errno));
817                 }
818         }
819
820         /* Now this thread can become a worker as well. */
821         worker_thread();
822
823         return(0);
824 }
825
826
827
828
829
830
831
832 /* 
833  * This loop just keeps going and going and going...
834  */     
835 void worker_thread(void) {
836         int i;
837         char junk;
838         int numselect = 0;
839         int highest;
840         struct CitContext *ptr;
841         struct CitContext *bind_me = NULL;
842         fd_set readfds;
843         int retval;
844         struct CitContext *con= NULL;   /* Temporary context pointer */
845         struct sockaddr_in fsin;        /* Data for master socket */
846         int alen;                       /* Data for master socket */
847         int ssock;                      /* Descriptor for client socket */
848
849         while (!time_to_die) {
850
851                 /* 
852                  * In a stupid environment, we would have all idle threads
853                  * calling select() and then they'd all wake up at once.  We
854                  * solve this problem by putting the select() in a critical
855                  * section, so only one thread has the opportunity to wake
856                  * up.  If we wake up on the master socket, create a new
857                  * session context; otherwise, just bind the thread to the
858                  * context we want and go on our merry way.
859                  */
860
861                 begin_critical_section(S_I_WANNA_SELECT);
862 SETUP_FD:       FD_ZERO(&readfds);
863                 FD_SET(msock, &readfds);
864                 highest = msock;
865                 FD_SET(rescan[0], &readfds);
866                 if (rescan[0] > highest) highest = rescan[0];
867                 numselect = 2;
868
869                 begin_critical_section(S_SESSION_TABLE);
870                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
871                         if (ptr->state == CON_IDLE) {
872                                 FD_SET(ptr->client_socket, &readfds);
873                                 if (ptr->client_socket > highest)
874                                         highest = ptr->client_socket;
875                                 ++numselect;
876                         }
877                 }
878                 end_critical_section(S_SESSION_TABLE);
879
880                 retval = select(highest + 1, &readfds, NULL, NULL, NULL);
881
882                 /* Now figure out who made this select() unblock.
883                  * First, check for an error or exit condition.
884                  */
885                 if (retval < 0) {
886                         end_critical_section(S_I_WANNA_SELECT);
887                         lprintf(9, "Exiting (%s)\n", errno);
888                         time_to_die = 1;
889                 }
890
891                 /* Next, check to see if it's a new client connecting
892                  * on the master socket.
893                  */
894                 else if (FD_ISSET(msock, &readfds)) {
895                         alen = sizeof fsin;
896                         ssock = accept(msock, (struct sockaddr *)&fsin, &alen);
897                         if (ssock < 0) {
898                                 lprintf(2, "citserver: accept() failed: %s\n",
899                                         strerror(errno));
900                         }
901                         else {
902                                 lprintf(7, "citserver: New client socket %d\n",
903                                         ssock);
904
905                                 /* New context will be created already set up
906                                  * in the CON_EXECUTING state.
907                                  */
908                                 con = CreateNewContext();
909
910                                 /* Assign our new socket number to it. */
911                                 con->client_socket = ssock;
912         
913                                 /* Set the SO_REUSEADDR socket option */
914                                 i = 1;
915                                 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
916                                         &i, sizeof(i));
917
918                                 pthread_setspecific(MyConKey, (void *)con);
919                                 begin_session(con);
920                                 /* do_command_loop(); */
921                                 pthread_setspecific(MyConKey, (void *)NULL);
922                                 con->state = CON_IDLE;
923                                 goto SETUP_FD;
924                         }
925                 }
926
927                 /* If the rescan pipe went active, someone is telling this
928                  * thread that the &readfds needs to be refreshed with more
929                  * current data.
930                  */
931                 else if (FD_ISSET(rescan[0], &readfds)) {
932                         read(rescan[0], &junk, 1);
933                         goto SETUP_FD;
934                 }
935
936                 /* It must be a client socket.  Find a context that has data
937                  * waiting on its socket *and* is in the CON_IDLE state.
938                  */
939                 else {
940                         bind_me = NULL;
941                         begin_critical_section(S_SESSION_TABLE);
942                         for (ptr = ContextList;
943                             ( (ptr != NULL) && (bind_me == NULL) );
944                             ptr = ptr->next) {
945                                 if ( (FD_ISSET(ptr->client_socket, &readfds))
946                                    && (ptr->state == CON_IDLE) ) {
947                                         bind_me = ptr;
948                                 }
949                         }
950                         if (bind_me != NULL) {
951                                 /* Found one.  Stake a claim to it before
952                                  * letting anyone else touch the context list.
953                                  */
954                                 bind_me->state = CON_EXECUTING;
955                         }
956
957                         end_critical_section(S_SESSION_TABLE);
958                         end_critical_section(S_I_WANNA_SELECT);
959
960                         /* We're bound to a session, now do *one* command */
961                         if (bind_me != NULL) {
962                                 pthread_setspecific(MyConKey, (void *)bind_me);
963                                 do_command_loop();
964                                 pthread_setspecific(MyConKey, (void *)NULL);
965                                 bind_me->state = CON_IDLE;
966                                 if (bind_me->kill_me == 1) {
967                                         RemoveContext(bind_me);
968                                 } 
969                                 write(rescan[1], &junk, 1);
970                         }
971                         else {
972                                 lprintf(9, "Thread %02d found nothing to do!\n",
973                                         getpid());
974                         }
975
976                 }
977                 dead_session_purge();
978         }
979
980         pthread_exit(NULL);
981 }
982