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