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