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