]> code.citadel.org Git - citadel.git/blob - citadel/sysdep.c
* client_gets(char *buf) has been replaced by
[citadel.git] / citadel / sysdep.c
1 /*
2  * $Id$
3  *
4  * Citadel "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 #ifdef DLL_EXPORT
16 #define IN_LIBCIT
17 #endif
18
19 #include "sysdep.h"
20 #include <stdlib.h>
21 #include <unistd.h>
22 #include <stdio.h>
23 #include <fcntl.h>
24 #include <ctype.h>
25 #include <signal.h>
26 #include <sys/types.h>
27 #include <sys/stat.h>
28 #include <sys/wait.h>
29 #include <sys/socket.h>
30 #include <sys/syslog.h>
31
32 #if TIME_WITH_SYS_TIME
33 # include <sys/time.h>
34 # include <time.h>
35 #else
36 # if HAVE_SYS_TIME_H
37 #  include <sys/time.h>
38 # else
39 #  include <time.h>
40 # endif
41 #endif
42
43 #include <limits.h>
44 #include <sys/resource.h>
45 #include <netinet/in.h>
46 #include <arpa/inet.h>
47 #include <netdb.h>
48 #include <sys/un.h>
49 #include <string.h>
50 #include <pwd.h>
51 #include <errno.h>
52 #include <stdarg.h>
53 #include <grp.h>
54 #ifdef HAVE_PTHREAD_H
55 #include <pthread.h>
56 #endif
57 #include "citadel.h"
58 #include "server.h"
59 #include "serv_extensions.h"
60 #include "sysdep_decls.h"
61 #include "citserver.h"
62 #include "support.h"
63 #include "config.h"
64 #include "database.h"
65 #include "housekeeping.h"
66 #include "tools.h"
67 #include "serv_crypto.h"
68
69 #ifdef HAVE_SYS_SELECT_H
70 #include <sys/select.h>
71 #endif
72
73 #ifndef HAVE_SNPRINTF
74 #include "snprintf.h"
75 #endif
76
77
78 #ifdef DEBUG_MEMORY_LEAKS
79 struct igheap {
80         struct igheap *next;
81         char file[32];
82         int line;
83         void *block;
84 };
85
86 struct igheap *igheap = NULL;
87 #endif
88
89
90 pthread_mutex_t Critters[MAX_SEMAPHORES];       /* Things needing locking */
91 pthread_key_t MyConKey;                         /* TSD key for MyContext() */
92
93 int verbosity = DEFAULT_VERBOSITY;              /* Logging level */
94
95 struct CitContext masterCC;
96 time_t last_purge = 0;                          /* Last dead session purge */
97 static int num_threads = 0;                     /* Current number of threads */
98 int num_sessions = 0;                           /* Current number of sessions */
99
100 int syslog_facility = (-1);
101
102
103 /*
104  * lprintf()  ...   Write logging information
105  * 
106  * Note: the variable "buf" below needs to be large enough to handle any
107  * log data sent through this function.  BE CAREFUL!
108  */
109 void lprintf(enum LogLevel loglevel, const char *format, ...) {   
110         va_list arg_ptr;
111         char buf[SIZ];
112
113         va_start(arg_ptr, format);   
114         vsnprintf(buf, sizeof(buf), format, arg_ptr);   
115         va_end(arg_ptr);   
116
117         if (syslog_facility >= 0) {
118                 if (loglevel <= verbosity) {
119                         /* Hackery -IO */
120                         if (CC->cs_pid != 0) {
121                                 memmove(&buf[6], buf, sizeof(buf) - 6);
122                                 snprintf(buf, 6, "[%3d]", CC->cs_pid);
123                                 buf[5] = ' ';
124                         }
125                         syslog(loglevel, "%s", buf);
126                 }
127         }
128         else if (loglevel <= verbosity) { 
129                 struct timeval tv;
130                 struct tm tim;
131                 time_t unixtime;
132
133                 gettimeofday(&tv, NULL);
134                 /* Promote to time_t; types differ on some OSes (like darwin) */
135                 unixtime = tv.tv_sec;
136                 localtime_r(&unixtime, &tim);
137                 if (CC->cs_pid != 0) {
138                         fprintf(stderr,
139                                 "%04d/%02d/%02d %2d:%02d:%02d.%06ld [%3d] %s",
140                                 tim.tm_year + 1900, tim.tm_mon + 1,
141                                 tim.tm_mday, tim.tm_hour, tim.tm_min,
142                                 tim.tm_sec, (long)tv.tv_usec,
143                                 CC->cs_pid, buf);
144                 } else {
145                         fprintf(stderr,
146                                 "%04d/%02d/%02d %2d:%02d:%02d.%06ld %s",
147                                 tim.tm_year + 1900, tim.tm_mon + 1,
148                                 tim.tm_mday, tim.tm_hour, tim.tm_min,
149                                 tim.tm_sec, (long)tv.tv_usec, buf);
150                 }
151                 fflush(stderr);
152         }
153
154         PerformLogHooks(loglevel, buf);
155 }   
156
157
158
159 /*
160  * We used to use master_cleanup() as a signal handler to shut down the server.
161  * however, master_cleanup() and the functions it calls do some things that
162  * aren't such a good idea to do from a signal handler: acquiring mutexes,
163  * playing with signal masks on BSDI systems, etc. so instead we install the
164  * following signal handler to set a global variable to inform the main loop
165  * that it's time to call master_cleanup() and exit.
166  */
167
168 volatile int time_to_die = 0;
169
170 static RETSIGTYPE signal_cleanup(int signum) {
171         time_to_die = 1;
172 }
173
174
175 /*
176  * Some initialization stuff...
177  */
178 void init_sysdep(void) {
179         int i;
180
181         /* Avoid vulnerabilities related to FD_SETSIZE if we can. */
182 #ifdef FD_SETSIZE
183 #ifdef RLIMIT_NOFILE
184         struct rlimit rl;
185         getrlimit(RLIMIT_NOFILE, &rl);
186         rl.rlim_cur = FD_SETSIZE;
187         rl.rlim_max = FD_SETSIZE;
188         setrlimit(RLIMIT_NOFILE, &rl);
189 #endif
190 #endif
191
192         /* If we've got OpenSSL, we're going to use it. */
193 #ifdef HAVE_OPENSSL
194         init_ssl();
195 #endif
196
197         /* Set up a bunch of semaphores to be used for critical sections */
198         for (i=0; i<MAX_SEMAPHORES; ++i) {
199                 pthread_mutex_init(&Critters[i], NULL);
200         }
201
202         /*
203          * Set up a place to put thread-specific data.
204          * We only need a single pointer per thread - it points to the
205          * CitContext structure (in the ContextList linked list) of the
206          * session to which the calling thread is currently bound.
207          */
208         if (pthread_key_create(&MyConKey, NULL) != 0) {
209                 lprintf(CTDL_CRIT, "Can't create TSD key!!  %s\n", strerror(errno));
210         }
211
212         /*
213          * The action for unexpected signals and exceptions should be to
214          * call signal_cleanup() to gracefully shut down the server.
215          */
216         signal(SIGINT, signal_cleanup);
217         signal(SIGQUIT, signal_cleanup);
218         signal(SIGHUP, signal_cleanup);
219         signal(SIGTERM, signal_cleanup);
220
221         /*
222          * Do not shut down the server on broken pipe signals, otherwise the
223          * whole Citadel service would come down whenever a single client
224          * socket breaks.
225          */
226         signal(SIGPIPE, SIG_IGN);
227 }
228
229
230 /*
231  * Obtain a semaphore lock to begin a critical section.
232  */
233 void begin_critical_section(int which_one)
234 {
235         /* lprintf(CTDL_DEBUG, "begin_critical_section(%d)\n", which_one); */
236
237         /* For all types of critical sections except those listed here,
238          * ensure nobody ever tries to do a critical section within a
239          * transaction; this could lead to deadlock.
240          */
241         if (    (which_one != S_FLOORCACHE)
242 #ifdef DEBUG_MEMORY_LEAKS
243                 && (which_one != S_DEBUGMEMLEAKS)
244 #endif
245         ) {
246                 cdb_check_handles();
247         }
248         pthread_mutex_lock(&Critters[which_one]);
249 }
250
251 /*
252  * Release a semaphore lock to end a critical section.
253  */
254 void end_critical_section(int which_one)
255 {
256         pthread_mutex_unlock(&Critters[which_one]);
257 }
258
259
260
261 /*
262  * This is a generic function to set up a master socket for listening on
263  * a TCP port.  The server shuts down if the bind fails.
264  *
265  */
266 int ig_tcp_server(char *ip_addr, int port_number, int queue_len)
267 {
268         struct sockaddr_in sin;
269         int s, i;
270         int actual_queue_len;
271
272         actual_queue_len = queue_len;
273         if (actual_queue_len < 5) actual_queue_len = 5;
274
275         memset(&sin, 0, sizeof(sin));
276         sin.sin_family = AF_INET;
277         sin.sin_port = htons((u_short)port_number);
278         if (ip_addr == NULL) {
279                 sin.sin_addr.s_addr = INADDR_ANY;
280         }
281         else {
282                 sin.sin_addr.s_addr = inet_addr(ip_addr);
283         }
284                                                                                 
285         if (sin.sin_addr.s_addr == INADDR_NONE) {
286                 sin.sin_addr.s_addr = INADDR_ANY;
287         }
288
289         s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
290
291         if (s < 0) {
292                 lprintf(CTDL_EMERG, "citserver: Can't create a socket: %s\n",
293                         strerror(errno));
294                 return(-1);
295         }
296
297         i = 1;
298         setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
299
300         if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
301                 lprintf(CTDL_EMERG, "citserver: Can't bind: %s\n",
302                         strerror(errno));
303                 close(s);
304                 return(-1);
305         }
306
307         if (listen(s, actual_queue_len) < 0) {
308                 lprintf(CTDL_EMERG, "citserver: Can't listen: %s\n", strerror(errno));
309                 close(s);
310                 return(-1);
311         }
312
313         return(s);
314 }
315
316
317
318 /*
319  * Create a Unix domain socket and listen on it
320  */
321 int ig_uds_server(char *sockpath, int queue_len)
322 {
323         struct sockaddr_un addr;
324         int s;
325         int i;
326         int actual_queue_len;
327
328         actual_queue_len = queue_len;
329         if (actual_queue_len < 5) actual_queue_len = 5;
330
331         i = unlink(sockpath);
332         if (i != 0) if (errno != ENOENT) {
333                 lprintf(CTDL_EMERG, "citserver: can't unlink %s: %s\n",
334                         sockpath, strerror(errno));
335                 return(-1);
336         }
337
338         memset(&addr, 0, sizeof(addr));
339         addr.sun_family = AF_UNIX;
340         safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
341
342         s = socket(AF_UNIX, SOCK_STREAM, 0);
343         if (s < 0) {
344                 lprintf(CTDL_EMERG, "citserver: Can't create a socket: %s\n",
345                         strerror(errno));
346                 return(-1);
347         }
348
349         if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
350                 lprintf(CTDL_EMERG, "citserver: Can't bind: %s\n",
351                         strerror(errno));
352                 return(-1);
353         }
354
355         if (listen(s, actual_queue_len) < 0) {
356                 lprintf(CTDL_EMERG, "citserver: Can't listen: %s\n", strerror(errno));
357                 return(-1);
358         }
359
360         chmod(sockpath, 0777);
361         return(s);
362 }
363
364
365
366 /*
367  * Return a pointer to the CitContext structure bound to the thread which
368  * called this function.  If there's no such binding (for example, if it's
369  * called by the housekeeper thread) then a generic 'master' CC is returned.
370  *
371  * This function is used *VERY* frequently and must be kept small.
372  */
373 struct CitContext *MyContext(void) {
374
375         register struct CitContext *c;
376
377         return ((c = (struct CitContext *) pthread_getspecific(MyConKey),
378                 c == NULL) ? &masterCC : c
379         );
380 }
381
382
383 /*
384  * Initialize a new context and place it in the list.  The session number
385  * used to be the PID (which is why it's called cs_pid), but that was when we
386  * had one process per session.  Now we just assign them sequentially, starting
387  * at 1 (don't change it to 0 because masterCC uses 0) and re-using them when
388  * sessions terminate.
389  */
390 struct CitContext *CreateNewContext(void) {
391         struct CitContext *me, *ptr;
392
393         me = (struct CitContext *) malloc(sizeof(struct CitContext));
394         if (me == NULL) {
395                 lprintf(CTDL_ALERT, "citserver: can't allocate memory!!\n");
396                 return NULL;
397         }
398         memset(me, 0, sizeof(struct CitContext));
399
400         /* The new context will be created already in the CON_EXECUTING state
401          * in order to prevent another thread from grabbing it while it's
402          * being set up.
403          */
404         me->state = CON_EXECUTING;
405
406
407         /*
408          * Generate a unique session number and insert this context into
409          * the list.
410          */
411         begin_critical_section(S_SESSION_TABLE);
412
413         if (ContextList == NULL) {
414                 ContextList = me;
415                 me->cs_pid = 1;
416                 me->next = NULL;
417         }
418
419         else if (ContextList->cs_pid > 1) {
420                 me->next = ContextList;
421                 ContextList = me;
422                 me->cs_pid = 1;
423         }
424
425         else {
426                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
427                         if (ptr->next == NULL) {
428                                 ptr->next = me;
429                                 me->cs_pid = ptr->cs_pid + 1;
430                                 me->next = NULL;
431                                 goto DONE;
432                         }
433                         else if (ptr->next->cs_pid > (ptr->cs_pid+1)) {
434                                 me->next = ptr->next;
435                                 ptr->next = me;
436                                 me->cs_pid = ptr->cs_pid + 1;
437                                 goto DONE;
438                         }
439                 }
440         }
441
442 DONE:   ++num_sessions;
443         end_critical_section(S_SESSION_TABLE);
444         return(me);
445 }
446
447
448 /*
449  * buffer_output() ... tell client_write to buffer all output until
450  *                   instructed to dump it all out later
451  */
452 void buffer_output(void) {
453         if (CC->buffering == 0) {
454                 CC->buffering = 1;
455                 CC->buffer_len = 0;
456                 CC->output_buffer = malloc(SIZ);
457         }
458 }
459
460 /*
461  * flush_output()  ...   dump out all that output we've been buffering.
462  */
463 void flush_output(void) {
464         if (CC->buffering == 1) {
465                 client_write(CC->output_buffer, CC->buffer_len);
466                 CC->buffer_len = 0;
467         }
468 }
469
470 /*
471  * unbuffer_output()  ...  stop buffering output.
472  */
473 void unbuffer_output(void) {
474         if (CC->buffering == 1) {
475                 CC->buffering = 0;
476                 /* We don't call flush_output because we can't. */
477                 client_write(CC->output_buffer, CC->buffer_len);
478                 CC->buffer_len = 0;
479                 free(CC->output_buffer);
480                 CC->output_buffer = NULL;
481         }
482 }
483
484
485
486 /*
487  * client_write()   ...    Send binary data to the client.
488  */
489 void client_write(char *buf, int nbytes)
490 {
491         int bytes_written = 0;
492         int retval;
493         int sock;
494         int old_buffer_len = 0;
495
496         if (CC->redirect_fp != NULL) {
497                 fwrite(buf, (size_t)nbytes, (size_t)1, CC->redirect_fp);
498                 return;
499         }
500
501         if (CC->redirect_sock > 0) {
502                 sock = CC->redirect_sock;       /* and continue below... */
503         }
504         else {
505                 sock = CC->client_socket;
506         }
507
508         /* If we're buffering for later, do that now. */
509         if (CC->buffering) {
510                 old_buffer_len = CC->buffer_len;
511                 CC->buffer_len += nbytes;
512                 CC->output_buffer = realloc(CC->output_buffer, CC->buffer_len);
513                 memcpy(&CC->output_buffer[old_buffer_len], buf, nbytes);
514                 return;
515         }
516
517         /* Ok, at this point we're not buffering.  Go ahead and write. */
518
519 #ifdef HAVE_OPENSSL
520         if (CC->redirect_ssl) {
521                 client_write_ssl(buf, nbytes);
522                 return;
523         }
524 #endif
525
526         while (bytes_written < nbytes) {
527                 retval = write(sock, &buf[bytes_written],
528                         nbytes - bytes_written);
529                 if (retval < 1) {
530                         lprintf(CTDL_ERR, "client_write() failed: %s\n",
531                                 strerror(errno));
532                         if (sock == CC->client_socket) CC->kill_me = 1;
533                         return;
534                 }
535                 bytes_written = bytes_written + retval;
536         }
537 }
538
539
540 /*
541  * cprintf()  ...   Send formatted printable data to the client.   It is
542  *                implemented in terms of client_write() but remains in
543  *                sysdep.c in case we port to somewhere without va_args...
544  */
545 void cprintf(const char *format, ...) {   
546         va_list arg_ptr;   
547         char buf[SIZ];   
548    
549         va_start(arg_ptr, format);   
550         if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
551                 buf[sizeof buf - 2] = '\n';
552         client_write(buf, strlen(buf)); 
553         va_end(arg_ptr);
554 }   
555
556
557 /*
558  * Read data from the client socket.
559  * Return values are:
560  *      1       Requested number of bytes has been read.
561  *      0       Request timed out.
562  *      -1      The socket is broken.
563  * If the socket breaks, the session will be terminated.
564  */
565 int client_read_to(char *buf, int bytes, int timeout)
566 {
567         int len,rlen;
568         fd_set rfds;
569         struct timeval tv;
570         int retval;
571
572 #ifdef HAVE_OPENSSL
573         if (CC->redirect_ssl) {
574                 return (client_read_ssl(buf, bytes, timeout));
575         }
576 #endif
577         len = 0;
578         while(len<bytes) {
579                 FD_ZERO(&rfds);
580                 FD_SET(CC->client_socket, &rfds);
581                 tv.tv_sec = timeout;
582                 tv.tv_usec = 0;
583
584                 retval = select( (CC->client_socket)+1, 
585                                         &rfds, NULL, NULL, &tv);
586
587                 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
588                         return(0);
589                 }
590
591                 rlen = read(CC->client_socket, &buf[len], bytes-len);
592                 if (rlen<1) {
593                         lprintf(CTDL_ERR, "client_read() failed: %s\n",
594                                 strerror(errno));
595                         CC->kill_me = 1;
596                         return(-1);
597                 }
598                 len = len + rlen;
599         }
600         return(1);
601 }
602
603 /*
604  * Read data from the client socket with default timeout.
605  * (This is implemented in terms of client_read_to() and could be
606  * justifiably moved out of sysdep.c)
607  */
608 INLINE int client_read(char *buf, int bytes)
609 {
610         return(client_read_to(buf, bytes, config.c_sleeping));
611 }
612
613
614 /*
615  * client_getln()   ...   Get a LF-terminated line of text from the client.
616  * (This is implemented in terms of client_read() and could be
617  * justifiably moved out of sysdep.c)
618  */
619 int client_getln(char *buf, int bufsize)
620 {
621         int i, retval;
622
623         /* Read one character at a time.
624          */
625         for (i = 0;;i++) {
626                 retval = client_read(&buf[i], 1);
627                 if (retval != 1 || buf[i] == '\n' || i == (bufsize-1))
628                         break;
629         }
630
631         /* If we got a long line, discard characters until the newline.
632          */
633         if (i == (bufsize-1))
634                 while (buf[i] != '\n' && retval == 1)
635                         retval = client_read(&buf[i], 1);
636
637         /* Strip the trailing newline and any trailing nonprintables (cr's)
638          */
639         buf[i] = 0;
640         while ((strlen(buf)>0)&&(!isprint(buf[strlen(buf)-1])))
641                 buf[strlen(buf)-1] = 0;
642         if (retval < 0) strcpy(buf, "000");
643         return(retval);
644 }
645
646
647
648 /*
649  * The system-dependent part of master_cleanup() - close the master socket.
650  */
651 void sysdep_master_cleanup(void) {
652         struct ServiceFunctionHook *serviceptr;
653
654         /*
655          * close all protocol master sockets
656          */
657         for (serviceptr = ServiceHookTable; serviceptr != NULL;
658             serviceptr = serviceptr->next ) {
659
660                 if (serviceptr->tcp_port > 0)
661                         lprintf(CTDL_INFO, "Closing listener on port %d\n",
662                                 serviceptr->tcp_port);
663
664                 if (serviceptr->sockpath != NULL)
665                         lprintf(CTDL_INFO, "Closing listener on '%s'\n",
666                                 serviceptr->sockpath);
667
668                 close(serviceptr->msock);
669
670                 /* If it's a Unix domain socket, remove the file. */
671                 if (serviceptr->sockpath != NULL) {
672                         unlink(serviceptr->sockpath);
673                 }
674         }
675 }
676
677
678 /*
679  * Terminate another session.
680  * (This could justifiably be moved out of sysdep.c because it
681  * no longer does anything that is system-dependent.)
682  */
683 void kill_session(int session_to_kill) {
684         struct CitContext *ptr;
685
686         begin_critical_section(S_SESSION_TABLE);
687         for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
688                 if (ptr->cs_pid == session_to_kill) {
689                         ptr->kill_me = 1;
690                 }
691         }
692         end_critical_section(S_SESSION_TABLE);
693 }
694
695
696
697
698 /*
699  * Start running as a daemon.  Only close stdio if do_close_stdio is set.
700  */
701 void start_daemon(int do_close_stdio) {
702         if (do_close_stdio) {
703                 /* close(0); */
704                 close(1);
705                 close(2);
706         }
707         signal(SIGHUP,SIG_IGN);
708         signal(SIGINT,SIG_IGN);
709         signal(SIGQUIT,SIG_IGN);
710         if (fork()!=0) exit(0);
711 }
712
713
714
715 /*
716  * Generic routine to convert a login name to a full name (gecos)
717  * Returns nonzero if a conversion took place
718  */
719 int convert_login(char NameToConvert[]) {
720         struct passwd *pw;
721         int a;
722
723         pw = getpwnam(NameToConvert);
724         if (pw == NULL) {
725                 return(0);
726         }
727         else {
728                 strcpy(NameToConvert, pw->pw_gecos);
729                 for (a=0; a<strlen(NameToConvert); ++a) {
730                         if (NameToConvert[a] == ',') NameToConvert[a] = 0;
731                 }
732                 return(1);
733         }
734 }
735
736 struct worker_node *worker_list = NULL;
737
738
739 /*
740  * create a worker thread. this function must always be called from within
741  * an S_WORKER_LIST critical section!
742  */
743 void create_worker(void) {
744         int ret;
745         struct worker_node *n;
746         pthread_attr_t attr;
747
748         n = malloc(sizeof(struct worker_node));
749         if (n == NULL) {
750                 lprintf(CTDL_EMERG, "can't allocate worker_node, exiting\n");
751                 time_to_die = -1;
752                 return;
753         }
754
755         if ((ret = pthread_attr_init(&attr))) {
756                 lprintf(CTDL_EMERG, "pthread_attr_init: %s\n", strerror(ret));
757                 time_to_die = -1;
758                 return;
759         }
760
761         /* Our per-thread stacks need to be bigger than the default size, otherwise
762          * the MIME parser crashes on FreeBSD, and the IMAP service crashes on
763          * 64-bit Linux.
764          */
765         if ((ret = pthread_attr_setstacksize(&attr, 1024 * 1024))) {
766                 lprintf(CTDL_EMERG, "pthread_attr_setstacksize: %s\n", strerror(ret));
767                 time_to_die = -1;
768                 pthread_attr_destroy(&attr);
769                 return;
770         }
771
772         if ((ret = pthread_create(&n->tid, &attr, worker_thread, NULL) != 0))
773         {
774
775                 lprintf(CTDL_ALERT, "Can't create worker thread: %s\n",
776                         strerror(ret));
777         }
778
779         n->next = worker_list;
780         worker_list = n;
781         pthread_attr_destroy(&attr);
782 }
783
784
785
786 /*
787  * Purge all sessions which have the 'kill_me' flag set.
788  * This function has code to prevent it from running more than once every
789  * few seconds, because running it after every single unbind would waste a lot
790  * of CPU time and keep the context list locked too much.  To force it to run
791  * anyway, set "force" to nonzero.
792  *
793  *
794  * After that's done, we raise the size of the worker thread pool
795  * if such an action is appropriate.
796  */
797 void dead_session_purge(int force) {
798         struct CitContext *ptr, *rem;
799
800         if (force == 0) {
801                 if ( (time(NULL) - last_purge) < 5 ) {
802                         return; /* Too soon, go away */
803                 }
804         }
805         time(&last_purge);
806
807         do {
808                 rem = NULL;
809                 begin_critical_section(S_SESSION_TABLE);
810                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
811                         if ( (ptr->state == CON_IDLE) && (ptr->kill_me) ) {
812                                 rem = ptr;
813                         }
814                 }
815                 end_critical_section(S_SESSION_TABLE);
816
817                 /* RemoveContext() enters its own S_SESSION_TABLE critical
818                  * section, so we have to do it like this.
819                  */     
820                 if (rem != NULL) {
821                         lprintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
822                         RemoveContext(rem);
823                 }
824
825         } while (rem != NULL);
826
827         /* Raise the size of the worker thread pool if necessary. */
828
829         if ( (num_sessions > num_threads)
830            && (num_threads < config.c_max_workers) ) {
831                 begin_critical_section(S_WORKER_LIST);
832                 create_worker();
833                 end_critical_section(S_WORKER_LIST);
834         }
835 }
836
837
838
839
840
841 /*
842  * Redirect a session's output to a file or socket.
843  * This function may be called with a file handle *or* a socket (but not
844  * both).  Call with neither to return output to its normal client socket.
845  */
846 void CtdlRedirectOutput(FILE *fp, int sock) {
847
848         if (fp != NULL) CC->redirect_fp = fp;
849         else CC->redirect_fp = NULL;
850
851         if (sock > 0) CC->redirect_sock = sock;
852         else CC->redirect_sock = (-1);
853
854 }
855
856
857 /*
858  * masterCC is the context we use when not attached to a session.  This
859  * function initializes it.
860  */
861 void InitializeMasterCC(void) {
862         memset(&masterCC, 0, sizeof(struct CitContext));
863         masterCC.internal_pgm = 1;
864         masterCC.cs_pid = 0;
865 }
866
867
868
869
870
871
872 /*
873  * Bind a thread to a context.  (It's inline merely to speed things up.)
874  */
875 INLINE void become_session(struct CitContext *which_con) {
876         pthread_setspecific(MyConKey, (void *)which_con );
877 }
878
879
880
881 /* 
882  * This loop just keeps going and going and going...
883  */     
884 void *worker_thread(void *arg) {
885         int i;
886         int highest;
887         struct CitContext *ptr;
888         struct CitContext *bind_me = NULL;
889         fd_set readfds;
890         int retval = 0;
891         struct CitContext *con= NULL;   /* Temporary context pointer */
892         struct ServiceFunctionHook *serviceptr;
893         int ssock;                      /* Descriptor for client socket */
894         struct timeval tv;
895         int force_purge = 0;
896         int m;
897
898         num_threads++;
899
900         cdb_allocate_tsd();
901
902         while (!time_to_die) {
903
904                 /* make doubly sure we're not holding any stale db handles
905                  * which might cause a deadlock.
906                  */
907                 cdb_check_handles();
908 do_select:      force_purge = 0;
909                 bind_me = NULL;         /* Which session shall we handle? */
910
911                 /* Initialize the fdset. */
912                 FD_ZERO(&readfds);
913                 highest = 0;
914
915                 begin_critical_section(S_SESSION_TABLE);
916                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
917                         if (ptr->state == CON_IDLE) {
918                                 FD_SET(ptr->client_socket, &readfds);
919                                 if (ptr->client_socket > highest)
920                                         highest = ptr->client_socket;
921                         }
922                         if ((bind_me == NULL) && (ptr->state == CON_READY)) {
923                                 bind_me = ptr;
924                                 ptr->state = CON_EXECUTING;
925                         }
926                 }
927                 end_critical_section(S_SESSION_TABLE);
928
929                 if (bind_me) goto SKIP_SELECT;
930
931                 /* If we got this far, it means that there are no sessions
932                  * which a previous thread marked for attention, so we go
933                  * ahead and get ready to select().
934                  */
935
936                 /* First, add the various master sockets to the fdset. */
937                 for (serviceptr = ServiceHookTable; serviceptr != NULL;
938                 serviceptr = serviceptr->next ) {
939                         m = serviceptr->msock;
940                         FD_SET(m, &readfds);
941                         if (m > highest) {
942                                 highest = m;
943                         }
944                 }
945
946                 if (!time_to_die) {
947                         tv.tv_sec = 1;          /* wake up every second if no input */
948                         tv.tv_usec = 0;
949                         retval = select(highest + 1, &readfds, NULL, NULL, &tv);
950                 }
951
952                 if (time_to_die) return(NULL);
953
954                 /* Now figure out who made this select() unblock.
955                  * First, check for an error or exit condition.
956                  */
957                 if (retval < 0) {
958                         if (errno == EBADF) {
959                                 lprintf(CTDL_NOTICE, "select() failed: (%s)\n",
960                                         strerror(errno));
961                                 goto do_select;
962                         }
963                         if (errno != EINTR) {
964                                 lprintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
965                                 time_to_die = 1;
966                         } else if (!time_to_die)
967                                 goto do_select;
968                 }
969
970                 /* Next, check to see if it's a new client connecting
971                  * on a master socket.
972                  */
973                 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
974                      serviceptr = serviceptr->next ) {
975
976                         if (FD_ISSET(serviceptr->msock, &readfds)) {
977                                 ssock = accept(serviceptr->msock, NULL, 0);
978                                 if (ssock < 0) {
979                                         lprintf(CTDL_CRIT,
980                                                 "citserver: accept(): %s\n",
981                                                 strerror(errno));
982                                 }
983                                 else {
984                                         lprintf(CTDL_DEBUG,
985                                                 "New client socket %d\n",
986                                                 ssock);
987
988                                         /* New context will be created already
989                                         * set up in the CON_EXECUTING state.
990                                         */
991                                         con = CreateNewContext();
992
993                                         /* Assign new socket number to it. */
994                                         con->client_socket = ssock;
995                                         con->h_command_function =
996                                                 serviceptr->h_command_function;
997                                         con->h_async_function =
998                                                 serviceptr->h_async_function;
999
1000                                         /* Determine whether local socket */
1001                                         if (serviceptr->sockpath != NULL)
1002                                                 con->is_local_socket = 1;
1003         
1004                                         /* Set the SO_REUSEADDR socket option */
1005                                         i = 1;
1006                                         setsockopt(ssock, SOL_SOCKET,
1007                                                 SO_REUSEADDR,
1008                                                 &i, sizeof(i));
1009
1010                                         become_session(con);
1011                                         begin_session(con);
1012                                         serviceptr->h_greeting_function();
1013                                         become_session(NULL);
1014                                         con->state = CON_IDLE;
1015                                         goto do_select;
1016                                 }
1017                         }
1018                 }
1019
1020                 /* It must be a client socket.  Find a context that has data
1021                  * waiting on its socket *and* is in the CON_IDLE state.  Any
1022                  * active sockets other than our chosen one are marked as
1023                  * CON_READY so the next thread that comes around can just bind
1024                  * to one without having to select() again.
1025                  */
1026                 begin_critical_section(S_SESSION_TABLE);
1027                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1028                         if ( (FD_ISSET(ptr->client_socket, &readfds))
1029                            && (ptr->state != CON_EXECUTING) ) {
1030                                 ptr->input_waiting = 1;
1031                                 if (!bind_me) {
1032                                         bind_me = ptr;  /* I choose you! */
1033                                         bind_me->state = CON_EXECUTING;
1034                                 }
1035                                 else {
1036                                         ptr->state = CON_READY;
1037                                 }
1038                         }
1039                 }
1040                 end_critical_section(S_SESSION_TABLE);
1041
1042 SKIP_SELECT:
1043                 /* We're bound to a session */
1044                 if (bind_me != NULL) {
1045                         become_session(bind_me);
1046
1047                         /* If the client has sent a command, execute it. */
1048                         if (CC->input_waiting) {
1049                                 CC->h_command_function();
1050                                 CC->input_waiting = 0;
1051                         }
1052
1053                         /* If there are asynchronous messages waiting and the
1054                          * client supports it, do those now */
1055                         if ((CC->is_async) && (CC->async_waiting)
1056                            && (CC->h_async_function != NULL)) {
1057                                 CC->h_async_function();
1058                                 CC->async_waiting = 0;
1059                         }
1060                         
1061                         force_purge = CC->kill_me;
1062                         become_session(NULL);
1063                         bind_me->state = CON_IDLE;
1064                 }
1065
1066                 dead_session_purge(force_purge);
1067                 do_housekeeping();
1068                 check_sched_shutdown();
1069         }
1070
1071         /* If control reaches this point, the server is shutting down */        
1072         return(NULL);
1073 }
1074
1075
1076
1077
1078 /*
1079  * SyslogFacility()
1080  * Translate text facility name to syslog.h defined value.
1081  */
1082 int SyslogFacility(char *name)
1083 {
1084         int i;
1085         struct
1086         {
1087                 int facility;
1088                 char *name;
1089         }   facTbl[] =
1090         {
1091                 {   LOG_KERN,   "kern"          },
1092                 {   LOG_USER,   "user"          },
1093                 {   LOG_MAIL,   "mail"          },
1094                 {   LOG_DAEMON, "daemon"        },
1095                 {   LOG_AUTH,   "auth"          },
1096                 {   LOG_SYSLOG, "syslog"        },
1097                 {   LOG_LPR,    "lpr"           },
1098                 {   LOG_NEWS,   "news"          },
1099                 {   LOG_UUCP,   "uucp"          },
1100                 {   LOG_LOCAL0, "local0"        },
1101                 {   LOG_LOCAL1, "local1"        },
1102                 {   LOG_LOCAL2, "local2"        },
1103                 {   LOG_LOCAL3, "local3"        },
1104                 {   LOG_LOCAL4, "local4"        },
1105                 {   LOG_LOCAL5, "local5"        },
1106                 {   LOG_LOCAL6, "local6"        },
1107                 {   LOG_LOCAL7, "local7"        },
1108                 {   0,            NULL          }
1109         };
1110         for(i = 0; facTbl[i].name != NULL; i++) {
1111                 if(!strcasecmp(name, facTbl[i].name))
1112                         return facTbl[i].facility;
1113         }
1114         return -1;
1115 }
1116
1117
1118 /********** MEM CHEQQER ***********/
1119
1120 #ifdef DEBUG_MEMORY_LEAKS
1121
1122 #undef malloc
1123 #undef realloc
1124 #undef strdup
1125 #undef free
1126
1127 void *tracked_malloc(size_t size, char *file, int line) {
1128         struct igheap *thisheap;
1129         void *block;
1130
1131         block = malloc(size);
1132         if (block == NULL) return(block);
1133
1134         thisheap = malloc(sizeof(struct igheap));
1135         if (thisheap == NULL) {
1136                 free(block);
1137                 return(NULL);
1138         }
1139
1140         thisheap->block = block;
1141         strcpy(thisheap->file, file);
1142         thisheap->line = line;
1143         
1144         begin_critical_section(S_DEBUGMEMLEAKS);
1145         thisheap->next = igheap;
1146         igheap = thisheap;
1147         end_critical_section(S_DEBUGMEMLEAKS);
1148
1149         return(block);
1150 }
1151
1152
1153 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
1154         struct igheap *thisheap;
1155         void *block;
1156
1157         block = realloc(ptr, size);
1158         if (block == NULL) return(block);
1159
1160         thisheap = malloc(sizeof(struct igheap));
1161         if (thisheap == NULL) {
1162                 free(block);
1163                 return(NULL);
1164         }
1165
1166         thisheap->block = block;
1167         strcpy(thisheap->file, file);
1168         thisheap->line = line;
1169         
1170         begin_critical_section(S_DEBUGMEMLEAKS);
1171         thisheap->next = igheap;
1172         igheap = thisheap;
1173         end_critical_section(S_DEBUGMEMLEAKS);
1174
1175         return(block);
1176 }
1177
1178
1179
1180 void tracked_free(void *ptr) {
1181         struct igheap *thisheap;
1182         struct igheap *trash;
1183
1184         free(ptr);
1185
1186         if (igheap == NULL) return;
1187         begin_critical_section(S_DEBUGMEMLEAKS);
1188         for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1189                 if (thisheap->next != NULL) {
1190                         if (thisheap->next->block == ptr) {
1191                                 trash = thisheap->next;
1192                                 thisheap->next = thisheap->next->next;
1193                                 free(trash);
1194                         }
1195                 }
1196         }
1197         if (igheap->block == ptr) {
1198                 trash = igheap;
1199                 igheap = igheap->next;
1200                 free(trash);
1201         }
1202         end_critical_section(S_DEBUGMEMLEAKS);
1203 }
1204
1205 char *tracked_strdup(const char *s, char *file, int line) {
1206         char *ptr;
1207
1208         if (s == NULL) return(NULL);
1209         ptr = tracked_malloc(strlen(s) + 1, file, line);
1210         if (ptr == NULL) return(NULL);
1211         strncpy(ptr, s, strlen(s));
1212         return(ptr);
1213 }
1214
1215 void dump_heap(void) {
1216         struct igheap *thisheap;
1217
1218         for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1219                 lprintf(CTDL_CRIT, "UNFREED: %30s : %d\n",
1220                         thisheap->file, thisheap->line);
1221         }
1222 }
1223
1224 #endif /*  DEBUG_MEMORY_LEAKS */