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