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