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