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