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