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