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