]> code.citadel.org Git - citadel.git/blob - citadel/sysdep.c
* Began implementation of a third RedirectOutput mode -- one which writes
[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         int sock;
546 #ifndef HAVE_TCP_BUFFERING
547         int old_buffer_len = 0;
548 #endif
549
550         if (CC->redirect_buffer != NULL) {
551                 if (CC->redirect_len + nbytes >= CC->redirect_alloc) {
552                         CC->redirect_alloc = CC->redirect_alloc * 2;
553                         CC->redirect_buffer = realloc(CC->redirect_buffer,
554                                                 CC->redirect_alloc);
555                 }
556                 memcpy(&CC->redirect_buffer[CC->redirect_len], buf, nbytes);
557                 CC->redirect_len += nbytes;
558                 return;
559         }
560
561         if (CC->redirect_fp != NULL) {
562                 fwrite(buf, (size_t)nbytes, (size_t)1, CC->redirect_fp);
563                 return;
564         }
565
566         if (CC->redirect_sock > 0) {
567                 sock = CC->redirect_sock;       /* and continue below... */
568         }
569         else {
570                 sock = CC->client_socket;
571         }
572
573 #ifndef HAVE_TCP_BUFFERING
574         /* If we're buffering for later, do that now. */
575         if (CC->buffering) {
576                 old_buffer_len = CC->buffer_len;
577                 CC->buffer_len += nbytes;
578                 CC->output_buffer = realloc(CC->output_buffer, CC->buffer_len);
579                 memcpy(&CC->output_buffer[old_buffer_len], buf, nbytes);
580                 return;
581         }
582 #endif
583
584         /* Ok, at this point we're not buffering.  Go ahead and write. */
585
586 #ifdef HAVE_OPENSSL
587         if (CC->redirect_ssl) {
588                 client_write_ssl(buf, nbytes);
589                 return;
590         }
591 #endif
592
593         while (bytes_written < nbytes) {
594                 retval = write(sock, &buf[bytes_written],
595                         nbytes - bytes_written);
596                 if (retval < 1) {
597                         lprintf(CTDL_ERR, "client_write() failed: %s\n",
598                                 strerror(errno));
599                         if (sock == CC->client_socket) CC->kill_me = 1;
600                         return;
601                 }
602                 bytes_written = bytes_written + retval;
603         }
604 }
605
606
607 /*
608  * cprintf()  ...   Send formatted printable data to the client.   It is
609  *                implemented in terms of client_write() but remains in
610  *                sysdep.c in case we port to somewhere without va_args...
611  */
612 void cprintf(const char *format, ...) {   
613         va_list arg_ptr;   
614         char buf[SIZ];   
615    
616         va_start(arg_ptr, format);   
617         if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
618                 buf[sizeof buf - 2] = '\n';
619         client_write(buf, strlen(buf)); 
620         va_end(arg_ptr);
621 }   
622
623
624 /*
625  * Read data from the client socket.
626  * Return values are:
627  *      1       Requested number of bytes has been read.
628  *      0       Request timed out.
629  *      -1      The socket is broken.
630  * If the socket breaks, the session will be terminated.
631  */
632 int client_read_to(char *buf, int bytes, int timeout)
633 {
634         int len,rlen;
635         fd_set rfds;
636         struct timeval tv;
637         int retval;
638
639 #ifdef HAVE_OPENSSL
640         if (CC->redirect_ssl) {
641                 return (client_read_ssl(buf, bytes, timeout));
642         }
643 #endif
644         len = 0;
645         while(len<bytes) {
646                 FD_ZERO(&rfds);
647                 FD_SET(CC->client_socket, &rfds);
648                 tv.tv_sec = timeout;
649                 tv.tv_usec = 0;
650
651                 retval = select( (CC->client_socket)+1, 
652                                         &rfds, NULL, NULL, &tv);
653
654                 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
655                         return(0);
656                 }
657
658                 rlen = read(CC->client_socket, &buf[len], bytes-len);
659                 if (rlen<1) {
660                         lprintf(CTDL_ERR, "client_read() failed: %s\n",
661                                 strerror(errno));
662                         CC->kill_me = 1;
663                         return(-1);
664                 }
665                 len = len + rlen;
666         }
667         return(1);
668 }
669
670 /*
671  * Read data from the client socket with default timeout.
672  * (This is implemented in terms of client_read_to() and could be
673  * justifiably moved out of sysdep.c)
674  */
675 INLINE int client_read(char *buf, int bytes)
676 {
677         return(client_read_to(buf, bytes, config.c_sleeping));
678 }
679
680
681 /*
682  * client_getln()   ...   Get a LF-terminated line of text from the client.
683  * (This is implemented in terms of client_read() and could be
684  * justifiably moved out of sysdep.c)
685  */
686 int client_getln(char *buf, int bufsize)
687 {
688         int i, retval;
689
690         /* Read one character at a time.
691          */
692         for (i = 0;;i++) {
693                 retval = client_read(&buf[i], 1);
694                 if (retval != 1 || buf[i] == '\n' || i == (bufsize-1))
695                         break;
696         }
697
698         /* If we got a long line, discard characters until the newline.
699          */
700         if (i == (bufsize-1))
701                 while (buf[i] != '\n' && retval == 1)
702                         retval = client_read(&buf[i], 1);
703
704         /* Strip the trailing newline and any trailing nonprintables (cr's)
705          */
706         buf[i] = 0;
707         while ((strlen(buf)>0)&&(!isprint(buf[strlen(buf)-1])))
708                 buf[strlen(buf)-1] = 0;
709         if (retval < 0) strcpy(buf, "000");
710         return(retval);
711 }
712
713
714
715 /*
716  * The system-dependent part of master_cleanup() - close the master socket.
717  */
718 void sysdep_master_cleanup(void) {
719         struct ServiceFunctionHook *serviceptr;
720
721         /*
722          * close all protocol master sockets
723          */
724         for (serviceptr = ServiceHookTable; serviceptr != NULL;
725             serviceptr = serviceptr->next ) {
726
727                 if (serviceptr->tcp_port > 0)
728                         lprintf(CTDL_INFO, "Closing listener on port %d\n",
729                                 serviceptr->tcp_port);
730
731                 if (serviceptr->sockpath != NULL)
732                         lprintf(CTDL_INFO, "Closing listener on '%s'\n",
733                                 serviceptr->sockpath);
734
735                 close(serviceptr->msock);
736
737                 /* If it's a Unix domain socket, remove the file. */
738                 if (serviceptr->sockpath != NULL) {
739                         unlink(serviceptr->sockpath);
740                 }
741         }
742 }
743
744
745 /*
746  * Terminate another session.
747  * (This could justifiably be moved out of sysdep.c because it
748  * no longer does anything that is system-dependent.)
749  */
750 void kill_session(int session_to_kill) {
751         struct CitContext *ptr;
752
753         begin_critical_section(S_SESSION_TABLE);
754         for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
755                 if (ptr->cs_pid == session_to_kill) {
756                         ptr->kill_me = 1;
757                 }
758         }
759         end_critical_section(S_SESSION_TABLE);
760 }
761
762
763
764
765 /*
766  * Start running as a daemon.
767  */
768 void start_daemon(int unused) {
769         close(0); close(1); close(2);
770         if (fork()) exit(0);
771         setsid();
772         signal(SIGHUP,SIG_IGN);
773         signal(SIGINT,SIG_IGN);
774         signal(SIGQUIT,SIG_IGN);
775 }
776
777
778
779 /*
780  * Generic routine to convert a login name to a full name (gecos)
781  * Returns nonzero if a conversion took place
782  */
783 int convert_login(char NameToConvert[]) {
784         struct passwd *pw;
785         int a;
786
787         pw = getpwnam(NameToConvert);
788         if (pw == NULL) {
789                 return(0);
790         }
791         else {
792                 strcpy(NameToConvert, pw->pw_gecos);
793                 for (a=0; a<strlen(NameToConvert); ++a) {
794                         if (NameToConvert[a] == ',') NameToConvert[a] = 0;
795                 }
796                 return(1);
797         }
798 }
799
800 struct worker_node *worker_list = NULL;
801
802
803 /*
804  * create a worker thread. this function must always be called from within
805  * an S_WORKER_LIST critical section!
806  */
807 void create_worker(void) {
808         int ret;
809         struct worker_node *n;
810         pthread_attr_t attr;
811
812         n = malloc(sizeof(struct worker_node));
813         if (n == NULL) {
814                 lprintf(CTDL_EMERG, "can't allocate worker_node, exiting\n");
815                 time_to_die = -1;
816                 return;
817         }
818
819         if ((ret = pthread_attr_init(&attr))) {
820                 lprintf(CTDL_EMERG, "pthread_attr_init: %s\n", strerror(ret));
821                 time_to_die = -1;
822                 return;
823         }
824
825         /* Our per-thread stacks need to be bigger than the default size, otherwise
826          * the MIME parser crashes on FreeBSD, and the IMAP service crashes on
827          * 64-bit Linux.
828          */
829         if ((ret = pthread_attr_setstacksize(&attr, 1024 * 1024))) {
830                 lprintf(CTDL_EMERG, "pthread_attr_setstacksize: %s\n", strerror(ret));
831                 time_to_die = -1;
832                 pthread_attr_destroy(&attr);
833                 return;
834         }
835
836         if ((ret = pthread_create(&n->tid, &attr, worker_thread, NULL) != 0))
837         {
838
839                 lprintf(CTDL_ALERT, "Can't create worker thread: %s\n",
840                         strerror(ret));
841         }
842
843         n->next = worker_list;
844         worker_list = n;
845         pthread_attr_destroy(&attr);
846 }
847
848
849
850 /*
851  * Purge all sessions which have the 'kill_me' flag set.
852  * This function has code to prevent it from running more than once every
853  * few seconds, because running it after every single unbind would waste a lot
854  * of CPU time and keep the context list locked too much.  To force it to run
855  * anyway, set "force" to nonzero.
856  *
857  *
858  * After that's done, we raise the size of the worker thread pool
859  * if such an action is appropriate.
860  */
861 void dead_session_purge(int force) {
862         struct CitContext *ptr, *rem;
863
864         if (force == 0) {
865                 if ( (time(NULL) - last_purge) < 5 ) {
866                         return; /* Too soon, go away */
867                 }
868         }
869         time(&last_purge);
870
871         do {
872                 rem = NULL;
873                 begin_critical_section(S_SESSION_TABLE);
874                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
875                         if ( (ptr->state == CON_IDLE) && (ptr->kill_me) ) {
876                                 rem = ptr;
877                         }
878                 }
879                 end_critical_section(S_SESSION_TABLE);
880
881                 /* RemoveContext() enters its own S_SESSION_TABLE critical
882                  * section, so we have to do it like this.
883                  */     
884                 if (rem != NULL) {
885                         lprintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
886                         RemoveContext(rem);
887                 }
888
889         } while (rem != NULL);
890
891         /* Raise the size of the worker thread pool if necessary. */
892
893         if ( (num_sessions > num_threads)
894            && (num_threads < config.c_max_workers) ) {
895                 begin_critical_section(S_WORKER_LIST);
896                 create_worker();
897                 end_critical_section(S_WORKER_LIST);
898         }
899 }
900
901
902
903
904
905 /*
906  * Redirect a session's output to a file or socket.
907  * This function may be called with a file handle *or* a socket (but not
908  * both).  Call with neither to return output to its normal client socket.
909  */
910 void CtdlRedirectOutput(FILE *fp, int sock) {
911
912         if (fp != NULL) CC->redirect_fp = fp;
913         else CC->redirect_fp = NULL;
914
915         if (sock > 0) CC->redirect_sock = sock;
916         else CC->redirect_sock = (-1);
917
918 }
919
920
921 /*
922  * masterCC is the context we use when not attached to a session.  This
923  * function initializes it.
924  */
925 void InitializeMasterCC(void) {
926         memset(&masterCC, 0, sizeof(struct CitContext));
927         masterCC.internal_pgm = 1;
928         masterCC.cs_pid = 0;
929 }
930
931
932
933
934
935
936 /*
937  * Bind a thread to a context.  (It's inline merely to speed things up.)
938  */
939 INLINE void become_session(struct CitContext *which_con) {
940         pthread_setspecific(MyConKey, (void *)which_con );
941 }
942
943
944
945 /* 
946  * This loop just keeps going and going and going...
947  */     
948 void *worker_thread(void *arg) {
949         int i;
950         int highest;
951         struct CitContext *ptr;
952         struct CitContext *bind_me = NULL;
953         fd_set readfds;
954         int retval = 0;
955         struct CitContext *con= NULL;   /* Temporary context pointer */
956         struct ServiceFunctionHook *serviceptr;
957         int ssock;                      /* Descriptor for client socket */
958         struct timeval tv;
959         int force_purge = 0;
960         int m;
961
962         num_threads++;
963
964         cdb_allocate_tsd();
965
966         while (!time_to_die) {
967
968                 /* make doubly sure we're not holding any stale db handles
969                  * which might cause a deadlock.
970                  */
971                 cdb_check_handles();
972 do_select:      force_purge = 0;
973                 bind_me = NULL;         /* Which session shall we handle? */
974
975                 /* Initialize the fdset. */
976                 FD_ZERO(&readfds);
977                 highest = 0;
978
979                 begin_critical_section(S_SESSION_TABLE);
980                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
981                         if (ptr->state == CON_IDLE) {
982                                 FD_SET(ptr->client_socket, &readfds);
983                                 if (ptr->client_socket > highest)
984                                         highest = ptr->client_socket;
985                         }
986                         if ((bind_me == NULL) && (ptr->state == CON_READY)) {
987                                 bind_me = ptr;
988                                 ptr->state = CON_EXECUTING;
989                         }
990                 }
991                 end_critical_section(S_SESSION_TABLE);
992
993                 if (bind_me) {
994                         goto SKIP_SELECT;
995                 }
996
997                 /* If we got this far, it means that there are no sessions
998                  * which a previous thread marked for attention, so we go
999                  * ahead and get ready to select().
1000                  */
1001
1002                 /* First, add the various master sockets to the fdset. */
1003                 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1004                 serviceptr = serviceptr->next ) {
1005                         m = serviceptr->msock;
1006                         FD_SET(m, &readfds);
1007                         if (m > highest) {
1008                                 highest = m;
1009                         }
1010                 }
1011
1012                 if (!time_to_die) {
1013                         tv.tv_sec = 1;          /* wake up every second if no input */
1014                         tv.tv_usec = 0;
1015                         retval = select(highest + 1, &readfds, NULL, NULL, &tv);
1016                 }
1017
1018                 if (time_to_die) return(NULL);
1019
1020                 /* Now figure out who made this select() unblock.
1021                  * First, check for an error or exit condition.
1022                  */
1023                 if (retval < 0) {
1024                         if (errno == EBADF) {
1025                                 lprintf(CTDL_NOTICE, "select() failed: (%s)\n",
1026                                         strerror(errno));
1027                                 goto do_select;
1028                         }
1029                         if (errno != EINTR) {
1030                                 lprintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1031                                 time_to_die = 1;
1032                         } else if (!time_to_die)
1033                                 goto do_select;
1034                 }
1035
1036                 /* Next, check to see if it's a new client connecting
1037                  * on a master socket.
1038                  */
1039                 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1040                      serviceptr = serviceptr->next ) {
1041
1042                         if (FD_ISSET(serviceptr->msock, &readfds)) {
1043                                 ssock = accept(serviceptr->msock, NULL, 0);
1044                                 if (ssock < 0) {
1045                                         lprintf(CTDL_CRIT,
1046                                                 "citserver: accept(): %s\n",
1047                                                 strerror(errno));
1048                                 }
1049                                 else {
1050                                         lprintf(CTDL_DEBUG,
1051                                                 "New client socket %d\n",
1052                                                 ssock);
1053
1054                                         /* New context will be created already
1055                                         * set up in the CON_EXECUTING state.
1056                                         */
1057                                         con = CreateNewContext();
1058
1059                                         /* Assign new socket number to it. */
1060                                         con->client_socket = ssock;
1061                                         con->h_command_function =
1062                                                 serviceptr->h_command_function;
1063                                         con->h_async_function =
1064                                                 serviceptr->h_async_function;
1065
1066                                         /* Determine whether local socket */
1067                                         if (serviceptr->sockpath != NULL)
1068                                                 con->is_local_socket = 1;
1069         
1070                                         /* Set the SO_REUSEADDR socket option */
1071                                         i = 1;
1072                                         setsockopt(ssock, SOL_SOCKET,
1073                                                 SO_REUSEADDR,
1074                                                 &i, sizeof(i));
1075
1076                                         become_session(con);
1077                                         begin_session(con);
1078                                         serviceptr->h_greeting_function();
1079                                         become_session(NULL);
1080                                         con->state = CON_IDLE;
1081                                         goto do_select;
1082                                 }
1083                         }
1084                 }
1085
1086                 /* It must be a client socket.  Find a context that has data
1087                  * waiting on its socket *and* is in the CON_IDLE state.  Any
1088                  * active sockets other than our chosen one are marked as
1089                  * CON_READY so the next thread that comes around can just bind
1090                  * to one without having to select() again.
1091                  */
1092                 begin_critical_section(S_SESSION_TABLE);
1093                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1094                         if ( (FD_ISSET(ptr->client_socket, &readfds))
1095                            && (ptr->state != CON_EXECUTING) ) {
1096                                 ptr->input_waiting = 1;
1097                                 if (!bind_me) {
1098                                         bind_me = ptr;  /* I choose you! */
1099                                         bind_me->state = CON_EXECUTING;
1100                                 }
1101                                 else {
1102                                         ptr->state = CON_READY;
1103                                 }
1104                         }
1105                 }
1106                 end_critical_section(S_SESSION_TABLE);
1107
1108 SKIP_SELECT:
1109                 /* We're bound to a session */
1110                 if (bind_me != NULL) {
1111                         become_session(bind_me);
1112
1113                         /* If the client has sent a command, execute it. */
1114                         if (CC->input_waiting) {
1115                                 CC->h_command_function();
1116                                 CC->input_waiting = 0;
1117                         }
1118
1119                         /* If there are asynchronous messages waiting and the
1120                          * client supports it, do those now */
1121                         if ((CC->is_async) && (CC->async_waiting)
1122                            && (CC->h_async_function != NULL)) {
1123                                 CC->h_async_function();
1124                                 CC->async_waiting = 0;
1125                         }
1126                         
1127                         force_purge = CC->kill_me;
1128                         become_session(NULL);
1129                         bind_me->state = CON_IDLE;
1130                 }
1131
1132                 dead_session_purge(force_purge);
1133                 do_housekeeping();
1134                 check_sched_shutdown();
1135         }
1136
1137         /* If control reaches this point, the server is shutting down */        
1138         return(NULL);
1139 }
1140
1141
1142
1143
1144 /*
1145  * SyslogFacility()
1146  * Translate text facility name to syslog.h defined value.
1147  */
1148 int SyslogFacility(char *name)
1149 {
1150         int i;
1151         struct
1152         {
1153                 int facility;
1154                 char *name;
1155         }   facTbl[] =
1156         {
1157                 {   LOG_KERN,   "kern"          },
1158                 {   LOG_USER,   "user"          },
1159                 {   LOG_MAIL,   "mail"          },
1160                 {   LOG_DAEMON, "daemon"        },
1161                 {   LOG_AUTH,   "auth"          },
1162                 {   LOG_SYSLOG, "syslog"        },
1163                 {   LOG_LPR,    "lpr"           },
1164                 {   LOG_NEWS,   "news"          },
1165                 {   LOG_UUCP,   "uucp"          },
1166                 {   LOG_LOCAL0, "local0"        },
1167                 {   LOG_LOCAL1, "local1"        },
1168                 {   LOG_LOCAL2, "local2"        },
1169                 {   LOG_LOCAL3, "local3"        },
1170                 {   LOG_LOCAL4, "local4"        },
1171                 {   LOG_LOCAL5, "local5"        },
1172                 {   LOG_LOCAL6, "local6"        },
1173                 {   LOG_LOCAL7, "local7"        },
1174                 {   0,            NULL          }
1175         };
1176         for(i = 0; facTbl[i].name != NULL; i++) {
1177                 if(!strcasecmp(name, facTbl[i].name))
1178                         return facTbl[i].facility;
1179         }
1180         enable_syslog = 0;
1181         return LOG_DAEMON;
1182 }
1183
1184
1185 /********** MEM CHEQQER ***********/
1186
1187 #ifdef DEBUG_MEMORY_LEAKS
1188
1189 #undef malloc
1190 #undef realloc
1191 #undef strdup
1192 #undef free
1193
1194 void *tracked_malloc(size_t size, char *file, int line) {
1195         struct igheap *thisheap;
1196         void *block;
1197
1198         block = malloc(size);
1199         if (block == NULL) return(block);
1200
1201         thisheap = malloc(sizeof(struct igheap));
1202         if (thisheap == NULL) {
1203                 free(block);
1204                 return(NULL);
1205         }
1206
1207         thisheap->block = block;
1208         strcpy(thisheap->file, file);
1209         thisheap->line = line;
1210         
1211         begin_critical_section(S_DEBUGMEMLEAKS);
1212         thisheap->next = igheap;
1213         igheap = thisheap;
1214         end_critical_section(S_DEBUGMEMLEAKS);
1215
1216         return(block);
1217 }
1218
1219
1220 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
1221         struct igheap *thisheap;
1222         void *block;
1223
1224         block = realloc(ptr, size);
1225         if (block == NULL) return(block);
1226
1227         thisheap = malloc(sizeof(struct igheap));
1228         if (thisheap == NULL) {
1229                 free(block);
1230                 return(NULL);
1231         }
1232
1233         thisheap->block = block;
1234         strcpy(thisheap->file, file);
1235         thisheap->line = line;
1236         
1237         begin_critical_section(S_DEBUGMEMLEAKS);
1238         thisheap->next = igheap;
1239         igheap = thisheap;
1240         end_critical_section(S_DEBUGMEMLEAKS);
1241
1242         return(block);
1243 }
1244
1245
1246
1247 void tracked_free(void *ptr) {
1248         struct igheap *thisheap;
1249         struct igheap *trash;
1250
1251         free(ptr);
1252
1253         if (igheap == NULL) return;
1254         begin_critical_section(S_DEBUGMEMLEAKS);
1255         for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1256                 if (thisheap->next != NULL) {
1257                         if (thisheap->next->block == ptr) {
1258                                 trash = thisheap->next;
1259                                 thisheap->next = thisheap->next->next;
1260                                 free(trash);
1261                         }
1262                 }
1263         }
1264         if (igheap->block == ptr) {
1265                 trash = igheap;
1266                 igheap = igheap->next;
1267                 free(trash);
1268         }
1269         end_critical_section(S_DEBUGMEMLEAKS);
1270 }
1271
1272 char *tracked_strdup(const char *s, char *file, int line) {
1273         char *ptr;
1274
1275         if (s == NULL) return(NULL);
1276         ptr = tracked_malloc(strlen(s) + 1, file, line);
1277         if (ptr == NULL) return(NULL);
1278         strncpy(ptr, s, strlen(s));
1279         return(ptr);
1280 }
1281
1282 void dump_heap(void) {
1283         struct igheap *thisheap;
1284
1285         for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1286                 lprintf(CTDL_CRIT, "UNFREED: %30s : %d\n",
1287                         thisheap->file, thisheap->line);
1288         }
1289 }
1290
1291 #endif /*  DEBUG_MEMORY_LEAKS */