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