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