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