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