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