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