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