]> code.citadel.org Git - citadel.git/blob - citadel/sysdep.c
* Completed 'fsck'-like reference count verifier (server and client)
[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         /* lprintf(9, "begin_critical_section(%d)\n", which_one); */
245         pthread_mutex_lock(&Critters[which_one]);
246 }
247
248 /*
249  * Release a semaphore lock to end a critical section.
250  */
251 void end_critical_section(int which_one)
252 {
253         /* lprintf(9, "end_critical_section(%d)\n", which_one); */
254         pthread_mutex_unlock(&Critters[which_one]);
255 }
256
257
258
259 /*
260  * This is a generic function to set up a master socket for listening on
261  * a TCP port.  The server shuts down if the bind fails.
262  */
263 int ig_tcp_server(int port_number, int queue_len)
264 {
265         struct sockaddr_in sin;
266         int s, i;
267
268         memset(&sin, 0, sizeof(sin));
269         sin.sin_family = AF_INET;
270         sin.sin_addr.s_addr = INADDR_ANY;
271
272         if (port_number == 0) {
273                 lprintf(1, "citserver: illegal port number specified\n");
274                 return(-1);
275         }
276         
277         sin.sin_port = htons((u_short)port_number);
278
279         s = socket(PF_INET, SOCK_STREAM, (getprotobyname("tcp")->p_proto));
280         if (s < 0) {
281                 lprintf(1, "citserver: Can't create a socket: %s\n",
282                         strerror(errno));
283                 return(-1);
284         }
285
286         /* Set the SO_REUSEADDR socket option, because it makes sense. */
287         i = 1;
288         setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
289
290         if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
291                 lprintf(1, "citserver: Can't bind: %s\n", strerror(errno));
292                 return(-1);
293         }
294
295         if (listen(s, queue_len) < 0) {
296                 lprintf(1, "citserver: Can't listen: %s\n", strerror(errno));
297                 return(-1);
298         }
299
300         return(s);
301 }
302
303
304
305 /*
306  * Return a pointer to the CitContext structure bound to the thread which
307  * called this function.  If there's no such binding (for example, if it's
308  * called by the housekeeper thread) then a generic 'master' CC is returned.
309  */
310 struct CitContext *MyContext(void) {
311         struct CitContext *retCC;
312         retCC = (struct CitContext *) pthread_getspecific(MyConKey);
313         if (retCC == NULL) retCC = &masterCC;
314         return(retCC);
315 }
316
317
318 /*
319  * Initialize a new context and place it in the list.
320  */
321 struct CitContext *CreateNewContext(void) {
322         struct CitContext *me, *ptr;
323         int num = 1;
324         int startover = 0;
325
326         me = (struct CitContext *) mallok(sizeof(struct CitContext));
327         if (me == NULL) {
328                 lprintf(1, "citserver: can't allocate memory!!\n");
329                 return NULL;
330         }
331         memset(me, 0, sizeof(struct CitContext));
332
333         /* The new context will be created already in the CON_EXECUTING state
334          * in order to prevent another thread from grabbing it while it's
335          * being set up.
336          */
337         me->state = CON_EXECUTING;
338
339         begin_critical_section(S_SESSION_TABLE);
340
341         /* obtain a unique session number */
342         do {
343                 startover = 0;
344                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
345                         if (ptr->cs_pid == num) {
346                                 ++num;
347                                 startover = 1;
348                         }
349                 }
350         } while (startover == 1);
351
352         me->cs_pid = num;
353         me->next = ContextList;
354         ContextList = me;
355         ++num_sessions;
356
357         end_critical_section(S_SESSION_TABLE);
358         return(me);
359 }
360
361
362
363 /*
364  * client_write()   ...    Send binary data to the client.
365  */
366 void client_write(char *buf, int nbytes)
367 {
368         int bytes_written = 0;
369         int retval;
370         int sock;
371
372         if (CC->redirect_fp != NULL) {
373                 fwrite(buf, nbytes, 1, CC->redirect_fp);
374                 return;
375         }
376
377         if (CC->redirect_sock > 0) {
378                 sock = CC->redirect_sock;       /* and continue below... */
379         }
380         else {
381                 sock = CC->client_socket;
382         }
383
384         while (bytes_written < nbytes) {
385                 retval = write(sock, &buf[bytes_written],
386                         nbytes - bytes_written);
387                 if (retval < 1) {
388                         lprintf(2, "client_write() failed: %s\n",
389                                 strerror(errno));
390                         if (sock == CC->client_socket) CC->kill_me = 1;
391                         return;
392                 }
393                 bytes_written = bytes_written + retval;
394         }
395 }
396
397
398 /*
399  * cprintf()  ...   Send formatted printable data to the client.   It is
400  *                  implemented in terms of client_write() but remains in
401  *                  sysdep.c in case we port to somewhere without va_args...
402  */
403 void cprintf(const char *format, ...) {   
404         va_list arg_ptr;   
405         char buf[256];   
406    
407         va_start(arg_ptr, format);   
408         if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
409                 buf[sizeof buf - 2] = '\n';
410         client_write(buf, strlen(buf)); 
411         va_end(arg_ptr);
412 }   
413
414
415 /*
416  * Read data from the client socket.
417  * Return values are:
418  *      1       Requested number of bytes has been read.
419  *      0       Request timed out.
420  *      -1      The socket is broken.
421  * If the socket breaks, the session will be terminated.
422  */
423 int client_read_to(char *buf, int bytes, int timeout)
424 {
425         int len,rlen;
426         fd_set rfds;
427         struct timeval tv;
428         int retval;
429
430         len = 0;
431         while(len<bytes) {
432                 FD_ZERO(&rfds);
433                 FD_SET(CC->client_socket, &rfds);
434                 tv.tv_sec = timeout;
435                 tv.tv_usec = 0;
436
437                 retval = select( (CC->client_socket)+1, 
438                                         &rfds, NULL, NULL, &tv);
439
440                 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
441                         return(0);
442                 }
443
444                 rlen = read(CC->client_socket, &buf[len], bytes-len);
445                 if (rlen<1) {
446                         lprintf(2, "client_read() failed: %s\n",
447                                 strerror(errno));
448                         CC->kill_me = 1;
449                         return(-1);
450                 }
451                 len = len + rlen;
452         }
453         return(1);
454 }
455
456 /*
457  * Read data from the client socket with default timeout.
458  * (This is implemented in terms of client_read_to() and could be
459  * justifiably moved out of sysdep.c)
460  */
461 int client_read(char *buf, int bytes)
462 {
463         return(client_read_to(buf, bytes, config.c_sleeping));
464 }
465
466
467 /*
468  * client_gets()   ...   Get a LF-terminated line of text from the client.
469  * (This is implemented in terms of client_read() and could be
470  * justifiably moved out of sysdep.c)
471  */
472 int client_gets(char *buf)
473 {
474         int i, retval;
475
476         /* Read one character at a time.
477          */
478         for (i = 0;;i++) {
479                 retval = client_read(&buf[i], 1);
480                 if (retval != 1 || buf[i] == '\n' || i == 255)
481                         break;
482         }
483
484         /* If we got a long line, discard characters until the newline.
485          */
486         if (i == 255)
487                 while (buf[i] != '\n' && retval == 1)
488                         retval = client_read(&buf[i], 1);
489
490         /* Strip the trailing newline and any trailing nonprintables (cr's)
491          */
492         buf[i] = 0;
493         while ((strlen(buf)>0)&&(!isprint(buf[strlen(buf)-1])))
494                 buf[strlen(buf)-1] = 0;
495         return(retval);
496 }
497
498
499
500 /*
501  * The system-dependent part of master_cleanup() - close the master socket.
502  */
503 void sysdep_master_cleanup(void) {
504         struct ServiceFunctionHook *serviceptr;
505
506         /*
507          * close all protocol master sockets
508          */
509         for (serviceptr = ServiceHookTable; serviceptr != NULL;
510             serviceptr = serviceptr->next ) {
511                 lprintf(3, "Closing listener on port %d\n",
512                         serviceptr->tcp_port);
513                 close(serviceptr->msock);
514         }
515 }
516
517
518 /*
519  * Terminate another session.
520  * (This could justifiably be moved out of sysdep.c because it
521  * no longer does anything that is system-dependent.)
522  */
523 void kill_session(int session_to_kill) {
524         struct CitContext *ptr;
525
526         begin_critical_section(S_SESSION_TABLE);
527         for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
528                 if (ptr->cs_pid == session_to_kill) {
529                         ptr->kill_me = 1;
530                 }
531         }
532         end_critical_section(S_SESSION_TABLE);
533 }
534
535
536
537
538 /*
539  * Start running as a daemon.  Only close stdio if do_close_stdio is set.
540  */
541 void start_daemon(int do_close_stdio) {
542         if (do_close_stdio) {
543                 /* close(0); */
544                 close(1);
545                 close(2);
546         }
547         signal(SIGHUP,SIG_IGN);
548         signal(SIGINT,SIG_IGN);
549         signal(SIGQUIT,SIG_IGN);
550         if (fork()!=0) exit(0);
551 }
552
553
554
555 /*
556  * Tie in to the 'netsetup' program.
557  *
558  * (We're going to hope that netsetup never feeds more than 4096 bytes back.)
559  */
560 void cmd_nset(char *cmdbuf)
561 {
562         int retcode;
563         char fbuf[4096];
564         FILE *netsetup;
565         int ch;
566         int a, b;
567         char netsetup_args[3][256];
568
569         if (CC->usersupp.axlevel < 6) {
570                 cprintf("%d Higher access required.\n", 
571                         ERROR + HIGHER_ACCESS_REQUIRED);
572                 return;
573         }
574
575         for (a=1; a<=3; ++a) {
576                 if (num_parms(cmdbuf) >= a) {
577                         extract(netsetup_args[a-1], cmdbuf, a-1);
578                         for (b=0; b<strlen(netsetup_args[a-1]); ++b) {
579                                 if (netsetup_args[a-1][b] == 34) {
580                                         netsetup_args[a-1][b] = '_';
581                                 }
582                         }
583                 }
584                 else {
585                         netsetup_args[a-1][0] = 0;
586                 }
587         }
588
589         sprintf(fbuf, "./netsetup \"%s\" \"%s\" \"%s\" </dev/null 2>&1",
590                 netsetup_args[0], netsetup_args[1], netsetup_args[2]);
591         netsetup = popen(fbuf, "r");
592         if (netsetup == NULL) {
593                 cprintf("%d %s\n", ERROR, strerror(errno));
594                 return;
595         }
596
597         fbuf[0] = 0;
598         while (ch = getc(netsetup), (ch > 0)) {
599                 fbuf[strlen(fbuf)+1] = 0;
600                 fbuf[strlen(fbuf)] = ch;
601         }
602
603         retcode = pclose(netsetup);
604
605         if (retcode != 0) {
606                 for (a=0; a<strlen(fbuf); ++a) {
607                         if (fbuf[a] < 32) fbuf[a] = 32;
608                 }
609                 fbuf[245] = 0;
610                 cprintf("%d %s\n", ERROR, fbuf);
611                 return;
612         }
613
614         cprintf("%d Command succeeded.  Output follows:\n", LISTING_FOLLOWS);
615         cprintf("%s", fbuf);
616         if (fbuf[strlen(fbuf)-1] != 10) cprintf("\n");
617         cprintf("000\n");
618 }
619
620
621
622 /*
623  * Generic routine to convert a login name to a full name (gecos)
624  * Returns nonzero if a conversion took place
625  */
626 int convert_login(char NameToConvert[]) {
627         struct passwd *pw;
628         int a;
629
630         pw = getpwnam(NameToConvert);
631         if (pw == NULL) {
632                 return(0);
633         }
634         else {
635                 strcpy(NameToConvert, pw->pw_gecos);
636                 for (a=0; a<strlen(NameToConvert); ++a) {
637                         if (NameToConvert[a] == ',') NameToConvert[a] = 0;
638                 }
639                 return(1);
640         }
641 }
642
643
644
645 /*
646  * Purge all sessions which have the 'kill_me' flag set.
647  * This function has code to prevent it from running more than once every
648  * few seconds, because running it after every single unbind would waste a lot
649  * of CPU time and keep the context list locked too much.
650  *
651  * After that's done, we raise or lower the size of the worker thread pool
652  * if such an action is appropriate.
653  */
654 void dead_session_purge(void) {
655         struct CitContext *ptr, *rem;
656         pthread_attr_t attr;
657         pthread_t newthread;
658
659         if ( (time(NULL) - last_purge) < 5 ) return;    /* Too soon, go away */
660         time(&last_purge);
661
662         do {
663                 rem = NULL;
664                 begin_critical_section(S_SESSION_TABLE);
665                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
666                         if ( (ptr->state == CON_IDLE) && (ptr->kill_me) ) {
667                                 rem = ptr;
668                         }
669                 }
670                 end_critical_section(S_SESSION_TABLE);
671
672                 /* RemoveContext() enters its own S_SESSION_TABLE critical
673                  * section, so we have to do it like this.
674                  */     
675                 if (rem != NULL) {
676                         lprintf(9, "Purging session %d\n", rem->cs_pid);
677                         RemoveContext(rem);
678                 }
679
680         } while (rem != NULL);
681
682
683         /* Raise or lower the size of the worker thread pool if such
684          * an action is appropriate.
685          */
686
687         if ( (num_sessions > num_threads)
688            && (num_threads < config.c_max_workers) ) {
689
690                 pthread_attr_init(&attr);
691                 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
692                 if (pthread_create(&newthread, &attr,
693                    (void* (*)(void*)) worker_thread, NULL) != 0) {
694                         lprintf(1, "Can't create worker thead: %s\n",
695                         strerror(errno));
696                 }
697
698         }
699         
700         else if ( (num_sessions < num_threads)
701            && (num_threads > config.c_min_workers) ) {
702                 --num_threads;
703                 pthread_exit(NULL);
704         }
705
706 }
707
708
709
710
711
712 /*
713  * Redirect a session's output to a file or socket.
714  * This function may be called with a file handle *or* a socket (but not
715  * both).  Call with neither to return output to its normal client socket.
716  */
717 void CtdlRedirectOutput(FILE *fp, int sock) {
718
719         if (fp != NULL) CC->redirect_fp = fp;
720         else CC->redirect_fp = NULL;
721
722         if (sock > 0) CC->redirect_sock = sock;
723         else CC->redirect_sock = (-1);
724
725 }
726
727
728 /*
729  * masterCC is the context we use when not attached to a session.  This
730  * function initializes it.
731  */
732 void InitializeMasterCC(void) {
733         memset(&masterCC, 0, sizeof(struct CitContext));
734         masterCC.internal_pgm = 1;
735 }
736
737
738
739 /*
740  * Here's where it all begins.
741  */
742 int main(int argc, char **argv)
743 {
744         pthread_t HousekeepingThread;   /* Thread descriptor */
745         pthread_attr_t attr;            /* Thread attributes */
746         char tracefile[128];            /* Name of file to log traces to */
747         int a, i;                       /* General-purpose variables */
748         struct passwd *pw;
749         int drop_root_perms = 1;
750         char *moddir;
751         struct ServiceFunctionHook *serviceptr;
752         
753         /* specify default port name and trace file */
754         strcpy(tracefile, "");
755
756         /* initialize the master context */
757         InitializeMasterCC();
758
759         /* parse command-line arguments */
760         for (a=1; a<argc; ++a) {
761
762                 /* -t specifies where to log trace messages to */
763                 if (!strncmp(argv[a], "-t", 2)) {
764                         strcpy(tracefile, argv[a]);
765                         strcpy(tracefile, &tracefile[2]);
766                         freopen(tracefile, "r", stdin);
767                         freopen(tracefile, "w", stdout);
768                         freopen(tracefile, "w", stderr);
769                 }
770
771                 /* run in the background if -d was specified */
772                 else if (!strcmp(argv[a], "-d")) {
773                         start_daemon( (strlen(tracefile) > 0) ? 0 : 1 ) ;
774                 }
775
776                 /* -x specifies the desired logging level */
777                 else if (!strncmp(argv[a], "-x", 2)) {
778                         verbosity = atoi(&argv[a][2]);
779                 }
780
781                 else if (!strncmp(argv[a], "-h", 2)) {
782                         safestrncpy(bbs_home_directory, &argv[a][2],
783                                     sizeof bbs_home_directory);
784                         home_specified = 1;
785                 }
786
787                 else if (!strncmp(argv[a], "-f", 2)) {
788                         do_defrag = 1;
789                 }
790
791                 /* -r tells the server not to drop root permissions. don't use
792                  * this unless you know what you're doing. this should be
793                  * removed in the next release if it proves unnecessary. */
794                 else if (!strcmp(argv[a], "-r"))
795                         drop_root_perms = 0;
796
797                 /* any other parameter makes it crash and burn */
798                 else {
799                         lprintf(1,      "citserver: usage: "
800                                         "citserver [-tTraceFile] [-d] [-f]"
801                                         " [-xLogLevel] [-hHomeDir]\n");
802                         exit(1);
803                 }
804
805         }
806
807         /* Tell 'em who's in da house */
808         lprintf(1,
809 "\nMultithreaded message server for Citadel/UX\n"
810 "Copyright (C) 1987-1999 by the Citadel/UX development team.\n"
811 "Citadel/UX is free software, covered by the GNU General Public License, and\n"
812 "you are welcome to change it and/or distribute copies of it under certain\n"
813 "conditions.  There is absolutely no warranty for this software.  Please\n"
814 "read the 'COPYING.txt' file for details.\n\n");
815
816         /* Initialize... */
817         init_sysdep();
818         openlog("citserver",LOG_PID,LOG_USER);
819
820         /* Load site-specific parameters */
821         lprintf(7, "Loading citadel.config\n");
822         get_config();
823
824         /*
825          * Do non system dependent startup functions.
826          */
827         master_startup();
828
829         /*
830          * Bind the server to our favorite ports.
831          */
832         CtdlRegisterServiceHook(config.c_port_number,
833                                 citproto_begin_session,
834                                 do_command_loop);
835
836         /*
837          * Load any server-side modules (plugins) available here.
838          */
839         lprintf(7, "Initializing loadable modules\n");
840         if ((moddir = malloc(strlen(bbs_home_directory) + 9)) != NULL) {
841                 sprintf(moddir, "%s/modules", bbs_home_directory);
842                 DLoader_Init(moddir);
843                 free(moddir);
844         }
845
846         /*
847          * The rescan pipe exists so that worker threads can be woken up and
848          * told to re-scan the context list for fd's to listen on.  This is
849          * necessary, for example, when a context is about to go idle and needs
850          * to get back on that list.
851          */
852         if (pipe(rescan)) {
853                 lprintf(1, "Can't create rescan pipe!\n");
854                 exit(errno);
855         }
856
857         /*
858          * Set up a fd_set containing all the master sockets to which we
859          * always listen.  It's computationally less expensive to just copy
860          * this to a local fd_set when starting a new select() and then add
861          * the client sockets than it is to initialize a new one and then
862          * figure out what to put there.
863          */
864         FD_ZERO(&masterfds);
865         masterhighest = 0;
866         FD_SET(rescan[0], &masterfds);
867         if (rescan[0] > masterhighest) masterhighest = rescan[0];
868
869         for (serviceptr = ServiceHookTable; serviceptr != NULL;
870             serviceptr = serviceptr->next ) {
871                 FD_SET(serviceptr->msock, &masterfds);
872                 if (serviceptr->msock > masterhighest) {
873                         masterhighest = serviceptr->msock;
874                 }
875         }
876
877
878         /*
879          * Now that we've bound the sockets, change to the BBS user id and its
880          * corresponding group ids
881          */
882         if (drop_root_perms) {
883                 if ((pw = getpwuid(BBSUID)) == NULL)
884                         lprintf(1, "WARNING: getpwuid(%d): %s\n"
885                                    "Group IDs will be incorrect.\n", BBSUID,
886                                 strerror(errno));
887                 else {
888                         initgroups(pw->pw_name, pw->pw_gid);
889                         if (setgid(pw->pw_gid))
890                                 lprintf(3, "setgid(%d): %s\n", pw->pw_gid,
891                                         strerror(errno));
892                 }
893                 lprintf(7, "Changing uid to %d\n", BBSUID);
894                 if (setuid(BBSUID) != 0) {
895                         lprintf(3, "setuid() failed: %s\n", strerror(errno));
896                 }
897         }
898
899         /*
900          * Create the housekeeper thread
901          */
902         lprintf(7, "Starting housekeeper thread\n");
903         pthread_attr_init(&attr);
904         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
905         if (pthread_create(&HousekeepingThread, &attr,
906            (void* (*)(void*)) housekeeping_loop, NULL) != 0) {
907                 lprintf(1, "Can't create housekeeping thead: %s\n",
908                         strerror(errno));
909         }
910
911
912         /*
913          * Now create a bunch of worker threads.
914          */
915         for (i=0; i<(config.c_min_workers-1); ++i) {
916                 pthread_attr_init(&attr);
917                 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
918                 if (pthread_create(&HousekeepingThread, &attr,
919                    (void* (*)(void*)) worker_thread, NULL) != 0) {
920                         lprintf(1, "Can't create worker thead: %s\n",
921                         strerror(errno));
922                 }
923         }
924
925         /* Now this thread can become a worker as well. */
926         worker_thread();
927
928         return(0);
929 }
930
931
932 /*
933  * Bind a thread to a context.
934  */
935 inline void become_session(struct CitContext *which_con) {
936         pthread_setspecific(MyConKey, (void *)which_con );
937 }
938
939
940
941 /* 
942  * This loop just keeps going and going and going...
943  */     
944 void worker_thread(void) {
945         int i;
946         char junk;
947         int highest;
948         struct CitContext *ptr;
949         struct CitContext *bind_me = NULL;
950         fd_set readfds;
951         int retval;
952         struct CitContext *con= NULL;   /* Temporary context pointer */
953         struct ServiceFunctionHook *serviceptr;
954         struct sockaddr_in fsin;        /* Data for master socket */
955         int alen;                       /* Data for master socket */
956         int ssock;                      /* Descriptor for client socket */
957         struct timeval tv;
958
959         ++num_threads;
960
961         while (!time_to_die) {
962
963                 /* 
964                  * A naive implementation would have all idle threads
965                  * calling select() and then they'd all wake up at once.  We
966                  * solve this problem by putting the select() in a critical
967                  * section, so only one thread has the opportunity to wake
968                  * up.  If we wake up on the master socket, create a new
969                  * session context; otherwise, just bind the thread to the
970                  * context we want and go on our merry way.
971                  */
972
973                 begin_critical_section(S_I_WANNA_SELECT);
974 SETUP_FD:       memcpy(&readfds, &masterfds, sizeof(fd_set) );
975                 highest = masterhighest;
976                 begin_critical_section(S_SESSION_TABLE);
977                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
978                         if (ptr->state == CON_IDLE) {
979                                 FD_SET(ptr->client_socket, &readfds);
980                                 if (ptr->client_socket > highest)
981                                         highest = ptr->client_socket;
982                         }
983                 }
984                 end_critical_section(S_SESSION_TABLE);
985
986                 tv.tv_sec = 60;         /* wake up every minute if no input */
987                 tv.tv_usec = 0;
988                 retval = select(highest + 1, &readfds, NULL, NULL, &tv);
989
990                 /* Now figure out who made this select() unblock.
991                  * First, check for an error or exit condition.
992                  */
993                 if (retval < 0) {
994                         end_critical_section(S_I_WANNA_SELECT);
995                         lprintf(9, "Exiting (%s)\n", strerror(errno));
996                         time_to_die = 1;
997                 }
998
999                 /* Next, check to see if it's a new client connecting
1000                  * on the master socket.
1001                  */
1002                 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1003                      serviceptr = serviceptr->next ) {
1004
1005                         if (FD_ISSET(serviceptr->msock, &readfds)) {
1006                                 alen = sizeof fsin;
1007                                 ssock = accept(serviceptr->msock,
1008                                         (struct sockaddr *)&fsin, &alen);
1009                                 if (ssock < 0) {
1010                                         lprintf(2, "citserver: accept(): %s\n",
1011                                                 strerror(errno));
1012                                 }
1013                                 else {
1014                                         lprintf(7, "citserver: "
1015                                                 "New client socket %d\n",
1016                                                 ssock);
1017
1018                                         /* New context will be created already
1019                                         * set up in the CON_EXECUTING state.
1020                                         */
1021                                         con = CreateNewContext();
1022
1023                                         /* Assign new socket number to it. */
1024                                         con->client_socket = ssock;
1025                                         con->h_command_function =
1026                                                 serviceptr->h_command_function;
1027         
1028                                         /* Set the SO_REUSEADDR socket option */
1029                                         i = 1;
1030                                         setsockopt(ssock, SOL_SOCKET,
1031                                                 SO_REUSEADDR,
1032                                                 &i, sizeof(i));
1033
1034                                         become_session(con);
1035                                         begin_session(con);
1036                                         serviceptr->h_greeting_function();
1037                                         become_session(NULL);
1038                                         con->state = CON_IDLE;
1039                                         goto SETUP_FD;
1040                                 }
1041                         }
1042                 }
1043
1044                 /* If the rescan pipe went active, someone is telling this
1045                  * thread that the &readfds needs to be refreshed with more
1046                  * current data.
1047                  */
1048                 if (!time_to_die) if (FD_ISSET(rescan[0], &readfds)) {
1049                         read(rescan[0], &junk, 1);
1050                         goto SETUP_FD;
1051                 }
1052
1053                 /* It must be a client socket.  Find a context that has data
1054                  * waiting on its socket *and* is in the CON_IDLE state.
1055                  */
1056                 else {
1057                         bind_me = NULL;
1058                         begin_critical_section(S_SESSION_TABLE);
1059                         for (ptr = ContextList;
1060                             ( (ptr != NULL) && (bind_me == NULL) );
1061                             ptr = ptr->next) {
1062                                 if ( (FD_ISSET(ptr->client_socket, &readfds))
1063                                    && (ptr->state == CON_IDLE) ) {
1064                                         bind_me = ptr;
1065                                 }
1066                         }
1067                         if (bind_me != NULL) {
1068                                 /* Found one.  Stake a claim to it before
1069                                  * letting anyone else touch the context list.
1070                                  */
1071                                 bind_me->state = CON_EXECUTING;
1072                         }
1073
1074                         end_critical_section(S_SESSION_TABLE);
1075                         end_critical_section(S_I_WANNA_SELECT);
1076
1077                         /* We're bound to a session, now do *one* command */
1078                         if (bind_me != NULL) {
1079                                 become_session(bind_me);
1080                                 CC->h_command_function();
1081                                 become_session(NULL);
1082                                 bind_me->state = CON_IDLE;
1083                                 if (bind_me->kill_me == 1) {
1084                                         RemoveContext(bind_me);
1085                                 } 
1086                                 write(rescan[1], &junk, 1);
1087                         }
1088                         else {
1089                                 lprintf(9, "Thread found nothing to do!\n");
1090                         }
1091
1092                 }
1093                 dead_session_purge();
1094                 if ((time(NULL) - last_timer) > 60L) {
1095                         last_timer = time(NULL);
1096                         PerformSessionHooks(EVT_TIMER);
1097                 }
1098         }
1099
1100         /* If control reaches this point, the server is shutting down */        
1101         master_cleanup();
1102         --num_threads;
1103         pthread_exit(NULL);
1104 }
1105