]> code.citadel.org Git - citadel.git/blob - citadel/sysdep.c
* Minor fixenbugs after running with Valgrind
[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, nbytes, 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_gets()   ...   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_gets(char *buf)
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 == (SIZ-1))
628                         break;
629         }
630
631         /* If we got a long line, discard characters until the newline.
632          */
633         if (i == (SIZ-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         /* we seem to need something bigger than FreeBSD's default 64k stack */
762
763         if ((ret = pthread_attr_setstacksize(&attr, 128 * 1024))) {
764                 lprintf(CTDL_EMERG, "pthread_attr_setstacksize: %s\n", strerror(ret));
765                 time_to_die = -1;
766                 pthread_attr_destroy(&attr);
767                 return;
768         }
769
770         if ((ret = pthread_create(&n->tid, &attr, worker_thread, NULL) != 0))
771         {
772
773                 lprintf(CTDL_ALERT, "Can't create worker thread: %s\n",
774                         strerror(ret));
775         }
776
777         n->next = worker_list;
778         worker_list = n;
779         pthread_attr_destroy(&attr);
780 }
781
782
783
784 /*
785  * Purge all sessions which have the 'kill_me' flag set.
786  * This function has code to prevent it from running more than once every
787  * few seconds, because running it after every single unbind would waste a lot
788  * of CPU time and keep the context list locked too much.  To force it to run
789  * anyway, set "force" to nonzero.
790  *
791  *
792  * After that's done, we raise the size of the worker thread pool
793  * if such an action is appropriate.
794  */
795 void dead_session_purge(int force) {
796         struct CitContext *ptr, *rem;
797
798         if (force == 0) {
799                 if ( (time(NULL) - last_purge) < 5 ) {
800                         return; /* Too soon, go away */
801                 }
802         }
803         time(&last_purge);
804
805         do {
806                 rem = NULL;
807                 begin_critical_section(S_SESSION_TABLE);
808                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
809                         if ( (ptr->state == CON_IDLE) && (ptr->kill_me) ) {
810                                 rem = ptr;
811                         }
812                 }
813                 end_critical_section(S_SESSION_TABLE);
814
815                 /* RemoveContext() enters its own S_SESSION_TABLE critical
816                  * section, so we have to do it like this.
817                  */     
818                 if (rem != NULL) {
819                         lprintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
820                         RemoveContext(rem);
821                 }
822
823         } while (rem != NULL);
824
825         /* Raise the size of the worker thread pool if necessary. */
826
827         if ( (num_sessions > num_threads)
828            && (num_threads < config.c_max_workers) ) {
829                 begin_critical_section(S_WORKER_LIST);
830                 create_worker();
831                 end_critical_section(S_WORKER_LIST);
832         }
833 }
834
835
836
837
838
839 /*
840  * Redirect a session's output to a file or socket.
841  * This function may be called with a file handle *or* a socket (but not
842  * both).  Call with neither to return output to its normal client socket.
843  */
844 void CtdlRedirectOutput(FILE *fp, int sock) {
845
846         if (fp != NULL) CC->redirect_fp = fp;
847         else CC->redirect_fp = NULL;
848
849         if (sock > 0) CC->redirect_sock = sock;
850         else CC->redirect_sock = (-1);
851
852 }
853
854
855 /*
856  * masterCC is the context we use when not attached to a session.  This
857  * function initializes it.
858  */
859 void InitializeMasterCC(void) {
860         memset(&masterCC, 0, sizeof(struct CitContext));
861         masterCC.internal_pgm = 1;
862         masterCC.cs_pid = 0;
863 }
864
865
866
867
868
869
870 /*
871  * Bind a thread to a context.  (It's inline merely to speed things up.)
872  */
873 INLINE void become_session(struct CitContext *which_con) {
874         pthread_setspecific(MyConKey, (void *)which_con );
875 }
876
877
878
879 /* 
880  * This loop just keeps going and going and going...
881  */     
882 void *worker_thread(void *arg) {
883         int i;
884         int highest;
885         struct CitContext *ptr;
886         struct CitContext *bind_me = NULL;
887         fd_set readfds;
888         int retval = 0;
889         struct CitContext *con= NULL;   /* Temporary context pointer */
890         struct ServiceFunctionHook *serviceptr;
891         int ssock;                      /* Descriptor for client socket */
892         struct timeval tv;
893         int force_purge = 0;
894         int m;
895
896         num_threads++;
897
898         cdb_allocate_tsd();
899
900         while (!time_to_die) {
901
902                 /* make doubly sure we're not holding any stale db handles
903                  * which might cause a deadlock.
904                  */
905                 cdb_check_handles();
906 do_select:      force_purge = 0;
907                 bind_me = NULL;         /* Which session shall we handle? */
908
909                 /* Initialize the fdset. */
910                 FD_ZERO(&readfds);
911                 highest = 0;
912
913                 begin_critical_section(S_SESSION_TABLE);
914                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
915                         if (ptr->state == CON_IDLE) {
916                                 FD_SET(ptr->client_socket, &readfds);
917                                 if (ptr->client_socket > highest)
918                                         highest = ptr->client_socket;
919                         }
920                         if ((bind_me == NULL) && (ptr->state == CON_READY)) {
921                                 bind_me = ptr;
922                                 ptr->state = CON_EXECUTING;
923                         }
924                 }
925                 end_critical_section(S_SESSION_TABLE);
926
927                 if (bind_me) goto SKIP_SELECT;
928
929                 /* If we got this far, it means that there are no sessions
930                  * which a previous thread marked for attention, so we go
931                  * ahead and get ready to select().
932                  */
933
934                 /* First, add the various master sockets to the fdset. */
935                 for (serviceptr = ServiceHookTable; serviceptr != NULL;
936                 serviceptr = serviceptr->next ) {
937                         m = serviceptr->msock;
938                         FD_SET(m, &readfds);
939                         if (m > highest) {
940                                 highest = m;
941                         }
942                 }
943
944                 if (!time_to_die) {
945                         tv.tv_sec = 1;          /* wake up every second if no input */
946                         tv.tv_usec = 0;
947                         retval = select(highest + 1, &readfds, NULL, NULL, &tv);
948                 }
949
950                 if (time_to_die) return(NULL);
951
952                 /* Now figure out who made this select() unblock.
953                  * First, check for an error or exit condition.
954                  */
955                 if (retval < 0) {
956                         if (errno == EBADF) {
957                                 lprintf(CTDL_NOTICE, "select() failed: (%s)\n",
958                                         strerror(errno));
959                                 goto do_select;
960                         }
961                         if (errno != EINTR) {
962                                 lprintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
963                                 time_to_die = 1;
964                         } else if (!time_to_die)
965                                 goto do_select;
966                 }
967
968                 /* Next, check to see if it's a new client connecting
969                  * on a master socket.
970                  */
971                 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
972                      serviceptr = serviceptr->next ) {
973
974                         if (FD_ISSET(serviceptr->msock, &readfds)) {
975                                 ssock = accept(serviceptr->msock, NULL, 0);
976                                 if (ssock < 0) {
977                                         lprintf(CTDL_CRIT,
978                                                 "citserver: accept(): %s\n",
979                                                 strerror(errno));
980                                 }
981                                 else {
982                                         lprintf(CTDL_DEBUG,
983                                                 "New client socket %d\n",
984                                                 ssock);
985
986                                         /* New context will be created already
987                                         * set up in the CON_EXECUTING state.
988                                         */
989                                         con = CreateNewContext();
990
991                                         /* Assign new socket number to it. */
992                                         con->client_socket = ssock;
993                                         con->h_command_function =
994                                                 serviceptr->h_command_function;
995                                         con->h_async_function =
996                                                 serviceptr->h_async_function;
997
998                                         /* Determine whether local socket */
999                                         if (serviceptr->sockpath != NULL)
1000                                                 con->is_local_socket = 1;
1001         
1002                                         /* Set the SO_REUSEADDR socket option */
1003                                         i = 1;
1004                                         setsockopt(ssock, SOL_SOCKET,
1005                                                 SO_REUSEADDR,
1006                                                 &i, sizeof(i));
1007
1008                                         become_session(con);
1009                                         begin_session(con);
1010                                         serviceptr->h_greeting_function();
1011                                         become_session(NULL);
1012                                         con->state = CON_IDLE;
1013                                         goto do_select;
1014                                 }
1015                         }
1016                 }
1017
1018                 /* It must be a client socket.  Find a context that has data
1019                  * waiting on its socket *and* is in the CON_IDLE state.  Any
1020                  * active sockets other than our chosen one are marked as
1021                  * CON_READY so the next thread that comes around can just bind
1022                  * to one without having to select() again.
1023                  */
1024                 begin_critical_section(S_SESSION_TABLE);
1025                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1026                         if ( (FD_ISSET(ptr->client_socket, &readfds))
1027                            && (ptr->state != CON_EXECUTING) ) {
1028                                 ptr->input_waiting = 1;
1029                                 if (!bind_me) {
1030                                         bind_me = ptr;  /* I choose you! */
1031                                         bind_me->state = CON_EXECUTING;
1032                                 }
1033                                 else {
1034                                         ptr->state = CON_READY;
1035                                 }
1036                         }
1037                 }
1038                 end_critical_section(S_SESSION_TABLE);
1039
1040 SKIP_SELECT:
1041                 /* We're bound to a session */
1042                 if (bind_me != NULL) {
1043                         become_session(bind_me);
1044
1045                         /* If the client has sent a command, execute it. */
1046                         if (CC->input_waiting) {
1047                                 CC->h_command_function();
1048                                 CC->input_waiting = 0;
1049                         }
1050
1051                         /* If there are asynchronous messages waiting and the
1052                          * client supports it, do those now */
1053                         if ((CC->is_async) && (CC->async_waiting)
1054                            && (CC->h_async_function != NULL)) {
1055                                 CC->h_async_function();
1056                                 CC->async_waiting = 0;
1057                         }
1058                         
1059                         force_purge = CC->kill_me;
1060                         become_session(NULL);
1061                         bind_me->state = CON_IDLE;
1062                 }
1063
1064                 dead_session_purge(force_purge);
1065                 do_housekeeping();
1066                 check_sched_shutdown();
1067         }
1068
1069         /* If control reaches this point, the server is shutting down */        
1070         return(NULL);
1071 }
1072
1073
1074
1075
1076 /*
1077  * SyslogFacility()
1078  * Translate text facility name to syslog.h defined value.
1079  */
1080 int SyslogFacility(char *name)
1081 {
1082         int i;
1083         struct
1084         {
1085                 int facility;
1086                 char *name;
1087         }   facTbl[] =
1088         {
1089                 {   LOG_KERN,   "kern"          },
1090                 {   LOG_USER,   "user"          },
1091                 {   LOG_MAIL,   "mail"          },
1092                 {   LOG_DAEMON, "daemon"        },
1093                 {   LOG_AUTH,   "auth"          },
1094                 {   LOG_SYSLOG, "syslog"        },
1095                 {   LOG_LPR,    "lpr"           },
1096                 {   LOG_NEWS,   "news"          },
1097                 {   LOG_UUCP,   "uucp"          },
1098                 {   LOG_LOCAL0, "local0"        },
1099                 {   LOG_LOCAL1, "local1"        },
1100                 {   LOG_LOCAL2, "local2"        },
1101                 {   LOG_LOCAL3, "local3"        },
1102                 {   LOG_LOCAL4, "local4"        },
1103                 {   LOG_LOCAL5, "local5"        },
1104                 {   LOG_LOCAL6, "local6"        },
1105                 {   LOG_LOCAL7, "local7"        },
1106                 {   0,            NULL          }
1107         };
1108         for(i = 0; facTbl[i].name != NULL; i++) {
1109                 if(!strcasecmp(name, facTbl[i].name))
1110                         return facTbl[i].facility;
1111         }
1112         return -1;
1113 }
1114
1115
1116 /********** MEM CHEQQER ***********/
1117
1118 #ifdef DEBUG_MEMORY_LEAKS
1119
1120 #undef malloc
1121 #undef realloc
1122 #undef strdup
1123 #undef free
1124
1125 void *tracked_malloc(size_t size, char *file, int line) {
1126         struct igheap *thisheap;
1127         void *block;
1128
1129         block = malloc(size);
1130         if (block == NULL) return(block);
1131
1132         thisheap = malloc(sizeof(struct igheap));
1133         if (thisheap == NULL) {
1134                 free(block);
1135                 return(NULL);
1136         }
1137
1138         thisheap->block = block;
1139         strcpy(thisheap->file, file);
1140         thisheap->line = line;
1141         
1142         begin_critical_section(S_DEBUGMEMLEAKS);
1143         thisheap->next = igheap;
1144         igheap = thisheap;
1145         end_critical_section(S_DEBUGMEMLEAKS);
1146
1147         return(block);
1148 }
1149
1150
1151 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
1152         struct igheap *thisheap;
1153         void *block;
1154
1155         block = realloc(ptr, size);
1156         if (block == NULL) return(block);
1157
1158         thisheap = malloc(sizeof(struct igheap));
1159         if (thisheap == NULL) {
1160                 free(block);
1161                 return(NULL);
1162         }
1163
1164         thisheap->block = block;
1165         strcpy(thisheap->file, file);
1166         thisheap->line = line;
1167         
1168         begin_critical_section(S_DEBUGMEMLEAKS);
1169         thisheap->next = igheap;
1170         igheap = thisheap;
1171         end_critical_section(S_DEBUGMEMLEAKS);
1172
1173         return(block);
1174 }
1175
1176
1177
1178 void tracked_free(void *ptr) {
1179         struct igheap *thisheap;
1180         struct igheap *trash;
1181
1182         free(ptr);
1183
1184         if (igheap == NULL) return;
1185         begin_critical_section(S_DEBUGMEMLEAKS);
1186         for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1187                 if (thisheap->next != NULL) {
1188                         if (thisheap->next->block == ptr) {
1189                                 trash = thisheap->next;
1190                                 thisheap->next = thisheap->next->next;
1191                                 free(trash);
1192                         }
1193                 }
1194         }
1195         if (igheap->block == ptr) {
1196                 trash = igheap;
1197                 igheap = igheap->next;
1198                 free(trash);
1199         }
1200         end_critical_section(S_DEBUGMEMLEAKS);
1201 }
1202
1203 char *tracked_strdup(const char *s, char *file, int line) {
1204         char *ptr;
1205
1206         if (s == NULL) return(NULL);
1207         ptr = tracked_malloc(strlen(s) + 1, file, line);
1208         if (ptr == NULL) return(NULL);
1209         strncpy(ptr, s, strlen(s));
1210         return(ptr);
1211 }
1212
1213 void dump_heap(void) {
1214         struct igheap *thisheap;
1215
1216         for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1217                 lprintf(CTDL_CRIT, "UNFREED: %30s : %d\n",
1218                         thisheap->file, thisheap->line);
1219         }
1220 }
1221
1222 #endif /*  DEBUG_MEMORY_LEAKS */