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