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