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