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