]> code.citadel.org Git - citadel.git/blob - citadel/sysdep.c
Signals can't call thread functions so don't do CtdlThreadStopAll in 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 #include "sysdep.h"
16 #include <stdlib.h>
17 #include <unistd.h>
18 #include <stdio.h>
19 #include <fcntl.h>
20 #include <ctype.h>
21 #include <signal.h>
22 #include <sys/types.h>
23 #include <sys/stat.h>
24 #include <sys/wait.h>
25 #include <sys/socket.h>
26 #include <syslog.h>
27 #include <sys/syslog.h>
28
29 #if TIME_WITH_SYS_TIME
30 # include <sys/time.h>
31 # include <time.h>
32 #else
33 # if HAVE_SYS_TIME_H
34 #  include <sys/time.h>
35 # else
36 #  include <time.h>
37 # endif
38 #endif
39
40 #include <limits.h>
41 #include <sys/resource.h>
42 #include <netinet/in.h>
43 #include <netinet/tcp.h>
44 #include <arpa/inet.h>
45 #include <netdb.h>
46 #include <sys/un.h>
47 #include <string.h>
48 #include <pwd.h>
49 #include <errno.h>
50 #include <stdarg.h>
51 #include <grp.h>
52 #ifdef HAVE_PTHREAD_H
53 #include <pthread.h>
54 #endif
55 #include <libcitadel.h>
56 #include "citadel.h"
57 #include "server.h"
58 #include "sysdep_decls.h"
59 #include "citserver.h"
60 #include "support.h"
61 #include "config.h"
62 #include "database.h"
63 #include "housekeeping.h"
64 #include "modules/crypto/serv_crypto.h" /* Needed for init_ssl, client_write_ssl, client_read_ssl, destruct_ssl */
65 #include "ecrash.h"
66
67 #ifdef HAVE_SYS_SELECT_H
68 #include <sys/select.h>
69 #endif
70
71 #ifndef HAVE_SNPRINTF
72 #include "snprintf.h"
73 #endif
74
75 #include "ctdl_module.h"
76
77 #ifdef DEBUG_MEMORY_LEAKS
78 struct igheap {
79         struct igheap *next;
80         char file[32];
81         int line;
82         void *block;
83 };
84
85 struct igheap *igheap = NULL;
86 #endif
87
88
89 pthread_mutex_t Critters[MAX_SEMAPHORES];       /* Things needing locking */
90 pthread_key_t MyConKey;                         /* TSD key for MyContext() */
91
92 int verbosity = DEFAULT_VERBOSITY;              /* Logging level */
93
94 struct CitContext masterCC;
95 time_t last_purge = 0;                          /* Last dead session purge */
96 static int num_threads = 0;                     /* Current number of threads */
97 static int num_workers = 0;                     /* Current number of worker threads */
98 int num_sessions = 0;                           /* Current number of sessions */
99
100 int syslog_facility = LOG_DAEMON;
101 int enable_syslog = 0;
102
103
104 /*
105  * Create an interface to lprintf that follows the coding convention.
106  * This is here until such time as we have replaced all calls to lprintf with CtdlLogPrintf
107  */
108  
109 void CtdlLogPrintf(enum LogLevel loglevel, const char *format, ...)
110 {
111         va_list arg_ptr;
112         va_start(arg_ptr, format);
113         vlprintf(loglevel, format, arg_ptr);
114         va_end(arg_ptr);
115 }
116
117
118 /*
119  * lprintf()  ...   Write logging information
120  */
121 void lprintf(enum LogLevel loglevel, const char *format, ...) {   
122         va_list arg_ptr;
123         va_start(arg_ptr, format);
124         vlprintf(loglevel, format, arg_ptr);
125         va_end(arg_ptr);
126 }
127
128 void vlprintf(enum LogLevel loglevel, const char *format, va_list arg_ptr)
129 {
130         char buf[SIZ], buf2[SIZ];
131
132         if (enable_syslog) {
133                 vsyslog((syslog_facility | loglevel), format, arg_ptr);
134         }
135
136         /* stderr output code */
137         if (enable_syslog || running_as_daemon) return;
138
139         /* if we run in forground and syslog is disabled, log to terminal */
140         if (loglevel <= verbosity) { 
141                 struct timeval tv;
142                 struct tm tim;
143                 time_t unixtime;
144
145                 gettimeofday(&tv, NULL);
146                 /* Promote to time_t; types differ on some OSes (like darwin) */
147                 unixtime = tv.tv_sec;
148                 localtime_r(&unixtime, &tim);
149                 if (CC->cs_pid != 0) {
150                         sprintf(buf,
151                                 "%04d/%02d/%02d %2d:%02d:%02d.%06ld [%3d] ",
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,
155                                 CC->cs_pid);
156                 } else {
157                         sprintf(buf,
158                                 "%04d/%02d/%02d %2d:%02d:%02d.%06ld ",
159                                 tim.tm_year + 1900, tim.tm_mon + 1,
160                                 tim.tm_mday, tim.tm_hour, tim.tm_min,
161                                 tim.tm_sec, (long)tv.tv_usec);
162                 }
163                 vsprintf(buf2, format, arg_ptr);   
164
165                 fprintf(stderr, "%s%s", buf, buf2);
166                 fflush(stderr);
167         }
168 }   
169
170
171
172 /*
173  * Signal handler to shut down the server.
174  */
175
176 volatile int exit_signal = 0;
177 volatile int shutdown_and_halt = 0;
178 volatile int restart_server = 0;
179 volatile int running_as_daemon = 0;
180
181 static RETSIGTYPE signal_cleanup(int signum) {
182         CtdlLogPrintf(CTDL_DEBUG, "Caught signal %d; shutting down.\n", signum);
183         exit_signal = signum;
184 }
185
186
187
188
189 void InitialiseSemaphores(void)
190 {
191         int i;
192
193         /* Set up a bunch of semaphores to be used for critical sections */
194         for (i=0; i<MAX_SEMAPHORES; ++i) {
195                 pthread_mutex_init(&Critters[i], NULL);
196         }
197 }
198
199
200
201 /*
202  * Some initialization stuff...
203  */
204 void init_sysdep(void) {
205         sigset_t set;
206
207         /* Avoid vulnerabilities related to FD_SETSIZE if we can. */
208 #ifdef FD_SETSIZE
209 #ifdef RLIMIT_NOFILE
210         struct rlimit rl;
211         getrlimit(RLIMIT_NOFILE, &rl);
212         rl.rlim_cur = FD_SETSIZE;
213         rl.rlim_max = FD_SETSIZE;
214         setrlimit(RLIMIT_NOFILE, &rl);
215 #endif
216 #endif
217
218         /* If we've got OpenSSL, we're going to use it. */
219 #ifdef HAVE_OPENSSL
220         init_ssl();
221 #endif
222
223         /*
224          * Set up a place to put thread-specific data.
225          * We only need a single pointer per thread - it points to the
226          * CitContext structure (in the ContextList linked list) of the
227          * session to which the calling thread is currently bound.
228          */
229         if (pthread_key_create(&MyConKey, NULL) != 0) {
230                 CtdlLogPrintf(CTDL_CRIT, "Can't create TSD key: %s\n",
231                         strerror(errno));
232         }
233
234         /*
235          * The action for unexpected signals and exceptions should be to
236          * call signal_cleanup() to gracefully shut down the server.
237          */
238         sigemptyset(&set);
239         sigaddset(&set, SIGINT);
240         sigaddset(&set, SIGQUIT);
241         sigaddset(&set, SIGHUP);
242         sigaddset(&set, SIGTERM);
243         // sigaddset(&set, SIGSEGV);    commented out because
244         // sigaddset(&set, SIGILL);     we want core dumps
245         // sigaddset(&set, SIGBUS);
246         sigprocmask(SIG_UNBLOCK, &set, NULL);
247
248         signal(SIGINT, signal_cleanup);
249         signal(SIGQUIT, signal_cleanup);
250         signal(SIGHUP, signal_cleanup);
251         signal(SIGTERM, signal_cleanup);
252         // signal(SIGSEGV, signal_cleanup);     commented out because
253         // signal(SIGILL, signal_cleanup);      we want core dumps
254         // signal(SIGBUS, signal_cleanup);
255
256         /*
257          * Do not shut down the server on broken pipe signals, otherwise the
258          * whole Citadel service would come down whenever a single client
259          * socket breaks.
260          */
261         signal(SIGPIPE, SIG_IGN);
262 }
263
264
265 /*
266  * Obtain a semaphore lock to begin a critical section.
267  */
268 void begin_critical_section(int which_one)
269 {
270         /* CtdlLogPrintf(CTDL_DEBUG, "begin_critical_section(%d)\n", which_one); */
271
272         /* For all types of critical sections except those listed here,
273          * ensure nobody ever tries to do a critical section within a
274          * transaction; this could lead to deadlock.
275          */
276         if (    (which_one != S_FLOORCACHE)
277 #ifdef DEBUG_MEMORY_LEAKS
278                 && (which_one != S_DEBUGMEMLEAKS)
279 #endif
280                 && (which_one != S_RPLIST)
281         ) {
282                 cdb_check_handles();
283         }
284         pthread_mutex_lock(&Critters[which_one]);
285 }
286
287 /*
288  * Release a semaphore lock to end a critical section.
289  */
290 void end_critical_section(int which_one)
291 {
292         pthread_mutex_unlock(&Critters[which_one]);
293 }
294
295
296
297 /*
298  * This is a generic function to set up a master socket for listening on
299  * a TCP port.  The server shuts down if the bind fails.
300  *
301  */
302 int ig_tcp_server(char *ip_addr, int port_number, int queue_len, char **errormessage)
303 {
304         struct sockaddr_in sin;
305         int s, i;
306         int actual_queue_len;
307
308         actual_queue_len = queue_len;
309         if (actual_queue_len < 5) actual_queue_len = 5;
310
311         memset(&sin, 0, sizeof(sin));
312         sin.sin_family = AF_INET;
313         sin.sin_port = htons((u_short)port_number);
314         if (ip_addr == NULL) {
315                 sin.sin_addr.s_addr = INADDR_ANY;
316         }
317         else {
318                 sin.sin_addr.s_addr = inet_addr(ip_addr);
319         }
320                                                                                 
321         if (sin.sin_addr.s_addr == !INADDR_ANY) {
322                 sin.sin_addr.s_addr = INADDR_ANY;
323         }
324
325         s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
326
327         if (s < 0) {
328                 *errormessage = (char*) malloc(SIZ + 1);
329                 snprintf(*errormessage, SIZ, 
330                                  "citserver: Can't create a socket: %s",
331                                  strerror(errno));
332                 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
333                 return(-1);
334         }
335
336         i = 1;
337         setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
338
339         if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
340                 *errormessage = (char*) malloc(SIZ + 1);
341                 snprintf(*errormessage, SIZ, 
342                                  "citserver: Can't bind: %s",
343                                  strerror(errno));
344                 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
345                 close(s);
346                 return(-1);
347         }
348
349         /* set to nonblock - we need this for some obscure situations */
350         if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
351                 *errormessage = (char*) malloc(SIZ + 1);
352                 snprintf(*errormessage, SIZ, 
353                                  "citserver: Can't set socket to non-blocking: %s",
354                                  strerror(errno));
355                 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
356                 close(s);
357                 return(-1);
358         }
359
360         if (listen(s, actual_queue_len) < 0) {
361                 *errormessage = (char*) malloc(SIZ + 1);
362                 snprintf(*errormessage, SIZ, 
363                                  "citserver: Can't listen: %s",
364                                  strerror(errno));
365                 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
366                 close(s);
367                 return(-1);
368         }
369
370         return(s);
371 }
372
373
374
375 /*
376  * Create a Unix domain socket and listen on it
377  */
378 int ig_uds_server(char *sockpath, int queue_len, char **errormessage)
379 {
380         struct sockaddr_un addr;
381         int s;
382         int i;
383         int actual_queue_len;
384
385         actual_queue_len = queue_len;
386         if (actual_queue_len < 5) actual_queue_len = 5;
387
388         i = unlink(sockpath);
389         if (i != 0) if (errno != ENOENT) {
390                 *errormessage = (char*) malloc(SIZ + 1);
391                 snprintf(*errormessage, SIZ, "citserver: can't unlink %s: %s",
392                         sockpath, strerror(errno));
393                 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
394                 return(-1);
395         }
396
397         memset(&addr, 0, sizeof(addr));
398         addr.sun_family = AF_UNIX;
399         safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
400
401         s = socket(AF_UNIX, SOCK_STREAM, 0);
402         if (s < 0) {
403                 *errormessage = (char*) malloc(SIZ + 1);
404                 snprintf(*errormessage, SIZ, 
405                          "citserver: Can't create a socket: %s",
406                          strerror(errno));
407                 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
408                 return(-1);
409         }
410
411         if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
412                 *errormessage = (char*) malloc(SIZ + 1);
413                 snprintf(*errormessage, SIZ, 
414                          "citserver: Can't bind: %s",
415                          strerror(errno));
416                 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
417                 return(-1);
418         }
419
420         /* set to nonblock - we need this for some obscure situations */
421         if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
422                 *errormessage = (char*) malloc(SIZ + 1);
423                 snprintf(*errormessage, SIZ, 
424                          "citserver: Can't set socket to non-blocking: %s",
425                          strerror(errno));
426                 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
427                 close(s);
428                 return(-1);
429         }
430
431         if (listen(s, actual_queue_len) < 0) {
432                 *errormessage = (char*) malloc(SIZ + 1);
433                 snprintf(*errormessage, SIZ, 
434                          "citserver: Can't listen: %s",
435                          strerror(errno));
436                 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
437                 return(-1);
438         }
439
440         chmod(sockpath, S_ISGID|S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
441         return(s);
442 }
443
444
445
446 /*
447  * Return a pointer to the CitContext structure bound to the thread which
448  * called this function.  If there's no such binding (for example, if it's
449  * called by the housekeeper thread) then a generic 'master' CC is returned.
450  *
451  * This function is used *VERY* frequently and must be kept small.
452  */
453 struct CitContext *MyContext(void) {
454
455         register struct CitContext *c;
456
457         return ((c = (struct CitContext *) pthread_getspecific(MyConKey),
458                 c == NULL) ? &masterCC : c
459         );
460 }
461
462
463 /*
464  * Initialize a new context and place it in the list.  The session number
465  * used to be the PID (which is why it's called cs_pid), but that was when we
466  * had one process per session.  Now we just assign them sequentially, starting
467  * at 1 (don't change it to 0 because masterCC uses 0).
468  */
469 struct CitContext *CreateNewContext(void) {
470         struct CitContext *me;
471         static int next_pid = 0;
472
473         me = (struct CitContext *) malloc(sizeof(struct CitContext));
474         if (me == NULL) {
475                 CtdlLogPrintf(CTDL_ALERT, "citserver: can't allocate memory!!\n");
476                 return NULL;
477         }
478         memset(me, 0, sizeof(struct CitContext));
479
480         /* The new context will be created already in the CON_EXECUTING state
481          * in order to prevent another thread from grabbing it while it's
482          * being set up.
483          */
484         me->state = CON_EXECUTING;
485
486         /*
487          * Generate a unique session number and insert this context into
488          * the list.
489          */
490         begin_critical_section(S_SESSION_TABLE);
491         me->cs_pid = ++next_pid;
492         me->prev = NULL;
493         me->next = ContextList;
494         ContextList = me;
495         if (me->next != NULL) {
496                 me->next->prev = me;
497         }
498         ++num_sessions;
499         end_critical_section(S_SESSION_TABLE);
500         return(me);
501 }
502
503
504 /*
505  * The following functions implement output buffering. If the kernel supplies
506  * native TCP buffering (Linux & *BSD), use that; otherwise, emulate it with
507  * user-space buffering.
508  */
509 #ifndef HAVE_DARWIN
510 #ifdef TCP_CORK
511 #       define HAVE_TCP_BUFFERING
512 #else
513 #       ifdef TCP_NOPUSH
514 #               define HAVE_TCP_BUFFERING
515 #               define TCP_CORK TCP_NOPUSH
516 #       endif
517 #endif /* TCP_CORK */
518 #endif /* HAVE_DARWIN */
519
520 #ifdef HAVE_TCP_BUFFERING
521 static unsigned on = 1, off = 0;
522 void buffer_output(void) {
523         struct CitContext *ctx = MyContext();
524         setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
525         ctx->buffering = 1;
526 }
527
528 void unbuffer_output(void) {
529         struct CitContext *ctx = MyContext();
530         setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
531         ctx->buffering = 0;
532 }
533
534 void flush_output(void) {
535         struct CitContext *ctx = MyContext();
536         setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
537         setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
538 }
539 #else 
540 #ifdef HAVE_DARWIN
541 /* Stub functions for Darwin/OS X where TCP buffering isn't liked at all */
542 void buffer_output(void) {
543         CC->buffering = 0;
544 }
545 void unbuffer_output(void) {
546         CC->buffering = 0;
547 }
548 void flush_output(void) {
549 }
550 #else
551 void buffer_output(void) {
552         if (CC->buffering == 0) {
553                 CC->buffering = 1;
554                 CC->buffer_len = 0;
555                 CC->output_buffer = malloc(SIZ);
556         }
557 }
558
559 void flush_output(void) {
560         if (CC->buffering == 1) {
561                 client_write(CC->output_buffer, CC->buffer_len);
562                 CC->buffer_len = 0;
563         }
564 }
565
566 void unbuffer_output(void) {
567         if (CC->buffering == 1) {
568                 CC->buffering = 0;
569                 /* We don't call flush_output because we can't. */
570                 client_write(CC->output_buffer, CC->buffer_len);
571                 CC->buffer_len = 0;
572                 free(CC->output_buffer);
573                 CC->output_buffer = NULL;
574         }
575 }
576 #endif /* HAVE_DARWIN */
577 #endif /* HAVE_TCP_BUFFERING */
578
579
580
581 /*
582  * client_write()   ...    Send binary data to the client.
583  */
584 void client_write(char *buf, int nbytes)
585 {
586         int bytes_written = 0;
587         int retval;
588 #ifndef HAVE_TCP_BUFFERING
589         int old_buffer_len = 0;
590 #endif
591         t_context *Ctx;
592
593         Ctx = CC;
594         if (Ctx->redirect_buffer != NULL) {
595                 if ((Ctx->redirect_len + nbytes + 2) >= Ctx->redirect_alloc) {
596                         Ctx->redirect_alloc = (Ctx->redirect_alloc * 2) + nbytes;
597                         Ctx->redirect_buffer = realloc(Ctx->redirect_buffer,
598                                                 Ctx->redirect_alloc);
599                 }
600                 memcpy(&Ctx->redirect_buffer[Ctx->redirect_len], buf, nbytes);
601                 Ctx->redirect_len += nbytes;
602                 Ctx->redirect_buffer[Ctx->redirect_len] = 0;
603                 return;
604         }
605
606 #ifndef HAVE_TCP_BUFFERING
607         /* If we're buffering for later, do that now. */
608         if (Ctx->buffering) {
609                 old_buffer_len = Ctx->buffer_len;
610                 Ctx->buffer_len += nbytes;
611                 Ctx->output_buffer = realloc(Ctx->output_buffer, Ctx->buffer_len);
612                 memcpy(&Ctx->output_buffer[old_buffer_len], buf, nbytes);
613                 return;
614         }
615 #endif
616
617         /* Ok, at this point we're not buffering.  Go ahead and write. */
618
619 #ifdef HAVE_OPENSSL
620         if (Ctx->redirect_ssl) {
621                 client_write_ssl(buf, nbytes);
622                 return;
623         }
624 #endif
625
626         while (bytes_written < nbytes) {
627                 retval = write(Ctx->client_socket, &buf[bytes_written],
628                         nbytes - bytes_written);
629                 if (retval < 1) {
630                         CtdlLogPrintf(CTDL_ERR,
631                                 "client_write(%d bytes) failed: %s (%d)\n",
632                                 nbytes - bytes_written,
633                                 strerror(errno), errno);
634                         cit_backtrace();
635                         // CtdlLogPrintf(CTDL_DEBUG, "Tried to send: %s",  &buf[bytes_written]);
636                         Ctx->kill_me = 1;
637                         return;
638                 }
639                 bytes_written = bytes_written + retval;
640         }
641 }
642
643
644 /*
645  * cprintf()  ...   Send formatted printable data to the client.   It is
646  *                implemented in terms of client_write() but remains in
647  *                sysdep.c in case we port to somewhere without va_args...
648  */
649 void cprintf(const char *format, ...) {   
650         va_list arg_ptr;   
651         char buf[1024];   
652    
653         va_start(arg_ptr, format);   
654         if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
655                 buf[sizeof buf - 2] = '\n';
656         client_write(buf, strlen(buf)); 
657         va_end(arg_ptr);
658 }   
659
660
661 /*
662  * Read data from the client socket.
663  * Return values are:
664  *      1       Requested number of bytes has been read.
665  *      0       Request timed out.
666  *      -1      The socket is broken.
667  * If the socket breaks, the session will be terminated.
668  */
669 int client_read_to(char *buf, int bytes, int timeout)
670 {
671         int len,rlen;
672         fd_set rfds;
673         int fd;
674         struct timeval tv;
675         int retval;
676
677 #ifdef HAVE_OPENSSL
678         if (CC->redirect_ssl) {
679                 return (client_read_ssl(buf, bytes, timeout));
680         }
681 #endif
682         len = 0;
683         fd = CC->client_socket;
684         while(len<bytes) {
685                 FD_ZERO(&rfds);
686                 FD_SET(fd, &rfds);
687                 tv.tv_sec = timeout;
688                 tv.tv_usec = 0;
689
690                 retval = select( (fd)+1, 
691                                  &rfds, NULL, NULL, &tv);
692
693                 if (FD_ISSET(fd, &rfds) == 0) {
694                         return(0);
695                 }
696
697                 rlen = read(fd, &buf[len], bytes-len);
698                 if (rlen<1) {
699                         /* The socket has been disconnected! */
700                         CC->kill_me = 1;
701                         return(-1);
702                 }
703                 len = len + rlen;
704         }
705         return(1);
706 }
707
708 /*
709  * Read data from the client socket with default timeout.
710  * (This is implemented in terms of client_read_to() and could be
711  * justifiably moved out of sysdep.c)
712  */
713 INLINE int client_read(char *buf, int bytes)
714 {
715         return(client_read_to(buf, bytes, config.c_sleeping));
716 }
717
718
719 /*
720  * client_getln()   ...   Get a LF-terminated line of text from the client.
721  * (This is implemented in terms of client_read() and could be
722  * justifiably moved out of sysdep.c)
723  */
724 int client_getln(char *buf, int bufsize)
725 {
726         int i, retval;
727
728         /* Read one character at a time.
729          */
730         for (i = 0;;i++) {
731                 retval = client_read(&buf[i], 1);
732                 if (retval != 1 || buf[i] == '\n' || i == (bufsize-1))
733                         break;
734         }
735
736         /* If we got a long line, discard characters until the newline.
737          */
738         if (i == (bufsize-1))
739                 while (buf[i] != '\n' && retval == 1)
740                         retval = client_read(&buf[i], 1);
741
742         /* Strip the trailing LF, and the trailing CR if present.
743          */
744         buf[i] = 0;
745         while ( (i > 0)
746                 && ( (buf[i - 1]==13)
747                      || ( buf[i - 1]==10)) ) {
748                 i--;
749                 buf[i] = 0;
750         }
751         if (retval < 0) safestrncpy(&buf[i], "000", bufsize - i);
752         return(retval);
753 }
754
755
756 /*
757  * Cleanup any contexts that are left lying around
758  */
759 void context_cleanup(void)
760 {
761         struct CitContext *ptr = NULL;
762         struct CitContext *rem = NULL;
763
764         /*
765          * Clean up the contexts.
766          * There are no threads so no critical_section stuff is needed.
767          */
768         ptr = ContextList;
769         while (ptr != NULL){
770                 /* Remove the session from the active list */
771                 rem = ptr->next;
772                 --num_sessions;
773                 
774                 lprintf(CTDL_DEBUG, "Purging session %d\n", ptr->cs_pid);
775                 RemoveContext(ptr);
776                 free (ptr);
777                 ptr = rem;
778         }
779         
780 }
781
782
783 /*
784  * The system-dependent part of master_cleanup() - close the master socket.
785  */
786 void sysdep_master_cleanup(void) {
787         struct ServiceFunctionHook *serviceptr;
788         
789         /*
790          * close all protocol master sockets
791          */
792         for (serviceptr = ServiceHookTable; serviceptr != NULL;
793             serviceptr = serviceptr->next ) {
794
795                 if (serviceptr->tcp_port > 0)
796                         CtdlLogPrintf(CTDL_INFO, "Closing listener on port %d\n",
797                                 serviceptr->tcp_port);
798
799                 if (serviceptr->sockpath != NULL)
800                         CtdlLogPrintf(CTDL_INFO, "Closing listener on '%s'\n",
801                                 serviceptr->sockpath);
802
803                 close(serviceptr->msock);
804
805                 /* If it's a Unix domain socket, remove the file. */
806                 if (serviceptr->sockpath != NULL) {
807                         unlink(serviceptr->sockpath);
808                 }
809         }
810         
811         context_cleanup();
812         
813 #ifdef HAVE_OPENSSL
814         destruct_ssl();
815 #endif
816         CtdlDestroyProtoHooks();
817         CtdlDestroyDeleteHooks();
818         CtdlDestroyXmsgHooks();
819         CtdlDestroyNetprocHooks();
820         CtdlDestroyUserHooks();
821         CtdlDestroyMessageHook();
822         CtdlDestroyCleanupHooks();
823         CtdlDestroyFixedOutputHooks();  
824         CtdlDestroySessionHooks();
825         CtdlDestroyServiceHook();
826         #ifdef HAVE_BACKTRACE
827         eCrash_Uninit();
828         #endif
829 }
830
831
832
833 /*
834  * Terminate another session.
835  * (This could justifiably be moved out of sysdep.c because it
836  * no longer does anything that is system-dependent.)
837  */
838 void kill_session(int session_to_kill) {
839         struct CitContext *ptr;
840
841         begin_critical_section(S_SESSION_TABLE);
842         for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
843                 if (ptr->cs_pid == session_to_kill) {
844                         ptr->kill_me = 1;
845                 }
846         }
847         end_critical_section(S_SESSION_TABLE);
848 }
849
850 pid_t current_child;
851 void graceful_shutdown(int signum) {
852         kill(current_child, signum);
853         unlink(file_pid_file);
854         exit(0);
855 }
856
857
858 /*
859  * Start running as a daemon.
860  */
861 void start_daemon(int unused) {
862         int status = 0;
863         pid_t child = 0;
864         FILE *fp;
865         int do_restart = 0;
866
867         current_child = 0;
868
869         /* Close stdin/stdout/stderr and replace them with /dev/null.
870          * We don't just call close() because we don't want these fd's
871          * to be reused for other files.
872          */
873         chdir(ctdl_run_dir);
874
875         child = fork();
876         if (child != 0) {
877                 exit(0);
878         }
879         
880         signal(SIGHUP, SIG_IGN);
881         signal(SIGINT, SIG_IGN);
882         signal(SIGQUIT, SIG_IGN);
883
884         setsid();
885         umask(0);
886         freopen("/dev/null", "r", stdin);
887         freopen("/dev/null", "w", stdout);
888         freopen("/dev/null", "w", stderr);
889
890         do {
891                 current_child = fork();
892
893                 signal(SIGTERM, graceful_shutdown);
894         
895                 if (current_child < 0) {
896                         perror("fork");
897                         exit(errno);
898                 }
899         
900                 else if (current_child == 0) {
901                         return; /* continue starting citadel. */
902                 }
903         
904                 else {
905                         fp = fopen(file_pid_file, "w");
906                         if (fp != NULL) {
907                 /*
908                  * NB.. The pid file contains the pid of the actual server.
909                  * This is not the pid of the watcher process
910                  */
911                                 fprintf(fp, ""F_PID_T"\n", current_child);
912                                 fclose(fp);
913                         }
914                         waitpid(current_child, &status, 0);
915                 }
916
917                 do_restart = 0;
918
919                 /* Did the main process exit with an actual exit code? */
920                 if (WIFEXITED(status)) {
921
922                         /* Exit code 0 means the watcher should exit */
923                         if (WEXITSTATUS(status) == 0) {
924                                 do_restart = 0;
925                         }
926
927                         /* Exit code 101-109 means the watcher should exit */
928                         else if ( (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109) ) {
929                                 do_restart = 0;
930                         }
931
932                         /* Any other exit code means we should restart. */
933                         else {
934                                 do_restart = 1;
935                         }
936                 }
937
938                 /* Any other type of termination (signals, etc.) should also restart. */
939                 else {
940                         do_restart = 1;
941                 }
942
943         } while (do_restart);
944
945         unlink(file_pid_file);
946         exit(WEXITSTATUS(status));
947 }
948
949
950
951 /*
952  * Generic routine to convert a login name to a full name (gecos)
953  * Returns nonzero if a conversion took place
954  */
955 int convert_login(char NameToConvert[]) {
956         struct passwd *pw;
957         int a;
958
959         pw = getpwnam(NameToConvert);
960         if (pw == NULL) {
961                 return(0);
962         }
963         else {
964                 strcpy(NameToConvert, pw->pw_gecos);
965                 for (a=0; a<strlen(NameToConvert); ++a) {
966                         if (NameToConvert[a] == ',') NameToConvert[a] = 0;
967                 }
968                 return(1);
969         }
970 }
971
972
973
974 /*
975  * New thread interface.
976  * To create a thread you must call one of the create thread functions.
977  * You must pass it the address of (a pointer to a CtdlThreadNode initialised to NULL) like this
978  * struct CtdlThreadNode *node = NULL;
979  * pass in &node
980  * If the thread is created *node will point to the thread control structure for the created thread.
981  * If the thread creation fails *node remains NULL
982  * Do not free the memory pointed to by *node, it doesn't belong to you.
983  * If your thread function returns it will be started again without creating a new thread.
984  * If your thread function wants to exit it should call CtdlThreadExit(ret_code);
985  * This new interface duplicates much of the eCrash stuff. We should go for closer integration since that would
986  * remove the need for the calls to eCrashRegisterThread and friends
987  */
988
989
990 struct CtdlThreadNode *CtdlThreadList = NULL;
991
992 /*
993  * Condition variable and Mutex for thread garbage collection
994  */
995 /*static pthread_mutex_t thread_gc_mutex = PTHREAD_MUTEX_INITIALIZER;
996 static pthread_cond_t thread_gc_cond = PTHREAD_COND_INITIALIZER;
997 */
998 static pthread_t GC_thread;
999 static char *CtdlThreadStates[CTDL_THREAD_LAST_STATE];
1000 double CtdlThreadLoadAvg = 0;
1001 double CtdlThreadWorkerAvg = 0;
1002 /*
1003  * Pinched the following bits regarding signals from Kannel.org
1004  */
1005  
1006 /*
1007  * Change this thread's signal mask to block user-visible signals
1008  * (HUP, TERM, QUIT, INT), and store the old signal mask in
1009  * *old_set_storage.
1010  * Return 0 for success, or -1 if an error occurred.
1011  */
1012  
1013  /* 
1014   * This does not work in Darwin alias MacOS X alias Mach kernel,
1015   * however. So we define a dummy function doing nothing.
1016   */
1017 #if defined(DARWIN_OLD)
1018     static int pthread_sigmask();
1019 #endif
1020   
1021 static int ctdl_thread_internal_block_signals(sigset_t *old_set_storage)
1022 {
1023     int ret;
1024     sigset_t block_signals;
1025
1026     ret = sigemptyset(&block_signals);
1027     if (ret != 0) {
1028         CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC. Couldn't initialize signal set\n");
1029             return -1;
1030     }
1031     ret = sigaddset(&block_signals, SIGHUP);
1032     ret |= sigaddset(&block_signals, SIGTERM);
1033     ret |= sigaddset(&block_signals, SIGQUIT);
1034     ret |= sigaddset(&block_signals, SIGINT);
1035     if (ret != 0) {
1036         CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC. Couldn't add signal to signal set.\n");
1037             return -1;
1038     }
1039     ret = pthread_sigmask(SIG_BLOCK, &block_signals, old_set_storage);
1040     if (ret != 0) {
1041         CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC. Couldn't disable signals for thread creation\n");
1042         return -1;
1043     }
1044     return 0;
1045 }
1046
1047 static void ctdl_thread_internal_restore_signals(sigset_t *old_set)
1048 {
1049     int ret;
1050
1051     ret = pthread_sigmask(SIG_SETMASK, old_set, NULL);
1052     if (ret != 0) {
1053         CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC. Couldn't restore signal set.\n");
1054     }
1055 }
1056
1057
1058 void ctdl_thread_internal_cleanup(void)
1059 {
1060         int i;
1061         
1062         for (i=0; i<CTDL_THREAD_LAST_STATE; i++)
1063         {
1064                 free (CtdlThreadStates[i]);
1065         }
1066 }
1067
1068 void ctdl_thread_internal_init(void)
1069 {
1070         struct CtdlThreadNode *this_thread;
1071         int ret = 0;
1072         
1073         GC_thread = pthread_self();
1074         CtdlThreadStates[CTDL_THREAD_INVALID] = strdup ("Invalid Thread");
1075         CtdlThreadStates[CTDL_THREAD_VALID] = strdup("Valid Thread");
1076         CtdlThreadStates[CTDL_THREAD_CREATE] = strdup("Thread being Created");
1077         CtdlThreadStates[CTDL_THREAD_CANCELLED] = strdup("Thread Cancelled");
1078         CtdlThreadStates[CTDL_THREAD_EXITED] = strdup("Thread Exited");
1079         CtdlThreadStates[CTDL_THREAD_STOPPING] = strdup("Thread Stopping");
1080         CtdlThreadStates[CTDL_THREAD_STOP_REQ] = strdup("Thread Stop Requested");
1081         CtdlThreadStates[CTDL_THREAD_SLEEPING] = strdup("Thread Sleeping");
1082         CtdlThreadStates[CTDL_THREAD_RUNNING] = strdup("Thread Running");
1083         CtdlThreadStates[CTDL_THREAD_BLOCKED] = strdup("Thread Blocked");
1084         
1085         /* Get ourself a thread entry */
1086         this_thread = malloc(sizeof(struct CtdlThreadNode));
1087         if (this_thread == NULL) {
1088                 CtdlLogPrintf(CTDL_EMERG, "Thread system, can't allocate CtdlThreadNode, exiting\n");
1089                 return;
1090         }
1091         // Ensuring this is zero'd means we make sure the thread doesn't start doing its thing until we are ready.
1092         memset (this_thread, 0, sizeof(struct CtdlThreadNode));
1093         
1094         /* We are garbage collector so create us as running */
1095         this_thread->state = CTDL_THREAD_RUNNING;
1096         
1097         if ((ret = pthread_attr_init(&this_thread->attr))) {
1098                 CtdlLogPrintf(CTDL_EMERG, "Thread system, pthread_attr_init: %s\n", strerror(ret));
1099                 free(this_thread);
1100                 return;
1101         }
1102
1103         this_thread->name = strdup("Garbage Collection Thread");
1104         
1105         pthread_mutex_init (&(this_thread->ThreadMutex), NULL);
1106         pthread_cond_init (&(this_thread->ThreadCond), NULL);
1107         
1108         this_thread->tid = GC_thread;
1109         
1110         num_threads++;  // Increase the count of threads in the system.
1111
1112         this_thread->next = CtdlThreadList;
1113         CtdlThreadList = this_thread;
1114         if (this_thread->next)
1115                 this_thread->next->prev = this_thread;
1116         /* Set up start times */
1117         gettimeofday(&this_thread->start_time, NULL);           /* Time this thread started */
1118         memcpy(&this_thread->last_state_change, &this_thread->start_time, sizeof (struct timeval));     /* Changed state so mark it. */
1119 }
1120
1121
1122 /*
1123  * A function to update a threads load averages
1124  */
1125  void ctdl_thread_internal_update_avgs(struct CtdlThreadNode *this_thread)
1126  {
1127         struct timeval now, result;
1128         double last_duration;
1129
1130         pthread_mutex_lock(&this_thread->ThreadMutex); /* To prevent race condition of a sleeping thread */
1131         gettimeofday(&now, NULL);
1132         timersub(&now, &(this_thread->last_state_change), &result);
1133         // result now has a timeval for the time we spent in the last state since we last updated
1134         last_duration = (double)result.tv_sec + ((double)result.tv_usec / (double) 1000000);
1135         if (this_thread->state == CTDL_THREAD_SLEEPING)
1136                 this_thread->avg_sleeping += last_duration;
1137         if (this_thread->state == CTDL_THREAD_RUNNING)
1138                 this_thread->avg_running += last_duration;
1139         if (this_thread->state == CTDL_THREAD_BLOCKED)
1140                 this_thread->avg_blocked += last_duration;
1141         memcpy (&this_thread->last_state_change, &now, sizeof (struct timeval));
1142         pthread_mutex_unlock(&this_thread->ThreadMutex);
1143 }
1144
1145 /*
1146  * A function to chenge the state of a thread
1147  */
1148 void ctdl_thread_internal_change_state (struct CtdlThreadNode *this_thread, enum CtdlThreadState new_state)
1149 {
1150         /*
1151          * Wether we change state or not we need update the load values
1152          */
1153         ctdl_thread_internal_update_avgs(this_thread);
1154         pthread_mutex_lock(&this_thread->ThreadMutex); /* To prevent race condition of a sleeping thread */
1155         if ((new_state == CTDL_THREAD_STOP_REQ) && (this_thread->state > CTDL_THREAD_STOP_REQ))
1156                 this_thread->state = new_state;
1157         if (((new_state == CTDL_THREAD_SLEEPING) || (new_state == CTDL_THREAD_BLOCKED)) && (this_thread->state == CTDL_THREAD_RUNNING))
1158                 this_thread->state = new_state;
1159         if ((new_state == CTDL_THREAD_RUNNING) && ((this_thread->state == CTDL_THREAD_SLEEPING) || (this_thread->state == CTDL_THREAD_BLOCKED)))
1160                 this_thread->state = new_state;
1161         pthread_mutex_unlock(&this_thread->ThreadMutex);
1162 }
1163
1164
1165 /*
1166  * A function to tell all threads to exit
1167  */
1168 void CtdlThreadStopAll(void)
1169 {
1170         struct CtdlThreadNode *this_thread;
1171         
1172         begin_critical_section(S_THREAD_LIST);
1173         this_thread = CtdlThreadList;
1174         while(this_thread)
1175         {
1176                 if (this_thread->thread_func) // Don't tell garbage collector to stop
1177                 {
1178                         ctdl_thread_internal_change_state (this_thread, CTDL_THREAD_STOP_REQ);
1179                         pthread_cond_signal(&this_thread->ThreadCond);
1180                         CtdlLogPrintf(CTDL_DEBUG, "Thread system stopping thread \"%s\" (%ld).\n", this_thread->name, this_thread->tid);
1181                 }
1182                 this_thread = this_thread->next;
1183         }
1184         end_critical_section(S_THREAD_LIST);
1185 }
1186
1187
1188 /*
1189  * A function to signal that we need to do garbage collection on the thread list
1190  */
1191 void CtdlThreadGC(void)
1192 {
1193         struct CtdlThreadNode *this_thread;
1194         
1195         CtdlLogPrintf(CTDL_DEBUG, "Thread system signalling garbage collection.\n");
1196         
1197         begin_critical_section(S_THREAD_LIST);
1198         this_thread = CtdlThreadList;
1199         while(this_thread)
1200         {
1201                 if (!this_thread->thread_func)
1202                         pthread_cond_signal(&this_thread->ThreadCond);
1203                         
1204                 this_thread = this_thread->next;
1205         }
1206         end_critical_section(S_THREAD_LIST);
1207 }
1208
1209
1210 /*
1211  * A function to return the number of threads running in the system
1212  */
1213 int CtdlThreadGetCount(void)
1214 {
1215         return num_threads;
1216 }
1217
1218 /*
1219  * A function to find the thread structure for this thread
1220  */
1221 struct CtdlThreadNode *CtdlThreadSelf(void)
1222 {
1223         pthread_t self_tid;
1224         struct CtdlThreadNode *this_thread;
1225         
1226         self_tid = pthread_self();
1227         
1228         begin_critical_section(S_THREAD_LIST);
1229         this_thread = CtdlThreadList;
1230         while(this_thread)
1231         {
1232                 if (pthread_equal(self_tid, this_thread->tid))
1233                 {
1234                         end_critical_section(S_THREAD_LIST);
1235                         return this_thread;
1236                 }
1237                 this_thread = this_thread->next;
1238         }
1239         end_critical_section(S_THREAD_LIST);
1240         return NULL;
1241 }
1242
1243
1244
1245
1246 /*
1247  * A function to rename a thread
1248  * Returns a char * and the caller owns the memory and should free it
1249  */
1250 char *CtdlThreadName(struct CtdlThreadNode *thread, char *name)
1251 {
1252         struct CtdlThreadNode *this_thread;
1253         char *old_name;
1254         
1255         if (!thread)
1256                 this_thread = CtdlThreadSelf();
1257         else
1258                 this_thread = thread;
1259         if (!this_thread)
1260         {
1261                 CtdlLogPrintf(CTDL_WARNING, "Thread system WARNING. Attempt to CtdlThreadRename() a non thread.\n");
1262                 return NULL;
1263         }
1264         begin_critical_section(S_THREAD_LIST);
1265         old_name = this_thread->name;
1266         if (name)
1267                 this_thread->name = strdup (name);
1268         else
1269                 old_name = strdup(old_name);
1270         end_critical_section (S_THREAD_LIST);
1271         return (old_name);
1272 }       
1273
1274
1275 /*
1276  * A function to force a thread to exit
1277  */
1278 void CtdlThreadCancel(struct CtdlThreadNode *thread)
1279 {
1280         struct CtdlThreadNode *this_thread;
1281         
1282         if (!thread)
1283                 this_thread = CtdlThreadSelf();
1284         else
1285                 this_thread = thread;
1286         if (!this_thread)
1287         {
1288                 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC. Attempt to CtdlThreadCancel() a non thread.\n");
1289                 CtdlThreadStopAll();
1290                 return;
1291         }
1292         
1293         if (!this_thread->thread_func)
1294         {
1295                 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC. Attempt to CtdlThreadCancel() the garbage collector.\n");
1296                 CtdlThreadStopAll();
1297                 return;
1298         }
1299         
1300         begin_critical_section(S_THREAD_LIST);
1301         ctdl_thread_internal_change_state (this_thread, CTDL_THREAD_CANCELLED);
1302         pthread_cancel(this_thread->tid);
1303         end_critical_section (S_THREAD_LIST);
1304 }
1305
1306
1307
1308 /*
1309  * A function for a thread to check if it has been asked to stop
1310  */
1311 int CtdlThreadCheckStop(void)
1312 {
1313         struct CtdlThreadNode *this_thread;
1314         
1315         this_thread = CtdlThreadSelf();
1316         if (!this_thread)
1317         {
1318                 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC, CtdlThreadCheckStop() called by a non thread.\n");
1319                 CtdlThreadStopAll();
1320                 return -1;
1321         }
1322         if(this_thread->state == CTDL_THREAD_STOP_REQ)
1323         {
1324                 this_thread->state = CTDL_THREAD_STOPPING;
1325                 return -1;
1326         }
1327         else if(this_thread->state < CTDL_THREAD_STOP_REQ)
1328                 return -1;
1329                 
1330         return 0;
1331 }
1332
1333
1334 /*
1335  * A function to ask a thread to exit
1336  * The thread must call CtdlThreadCheckStop() periodically to determine if it should exit
1337  */
1338 void CtdlThreadStop(struct CtdlThreadNode *thread)
1339 {
1340         struct CtdlThreadNode *this_thread;
1341         
1342         if (!thread)
1343                 this_thread = CtdlThreadSelf();
1344         else
1345                 this_thread = thread;
1346         if (!this_thread)
1347                 return;
1348         if (!(this_thread->thread_func))
1349                 return;         // Don't stop garbage collector
1350                 
1351         begin_critical_section (S_THREAD_LIST);
1352         ctdl_thread_internal_change_state (this_thread, CTDL_THREAD_STOP_REQ);
1353         pthread_cond_signal(&this_thread->ThreadCond);
1354         end_critical_section(S_THREAD_LIST);
1355 }
1356
1357 /*
1358  * So we now have a sleep command that works with threads but it is in seconds
1359  */
1360 void CtdlThreadSleep(int secs)
1361 {
1362         struct timespec wake_time;
1363         struct timeval time_now;
1364         struct CtdlThreadNode *self;
1365         
1366         
1367         self = CtdlThreadSelf();
1368         if (!self)
1369         {
1370                 CtdlLogPrintf(CTDL_WARNING, "CtdlThreadSleep() called by something that is not a thread. Should we die?\n");
1371                 return;
1372         }
1373         
1374         begin_critical_section(S_THREAD_LIST);
1375         ctdl_thread_internal_change_state (self, CTDL_THREAD_SLEEPING);
1376         pthread_mutex_lock(&self->ThreadMutex); /* Prevent something asking us to awaken before we've gone to sleep */
1377         end_critical_section(S_THREAD_LIST);
1378         
1379         memset (&wake_time, 0, sizeof(struct timespec));
1380         gettimeofday(&time_now, NULL);
1381         wake_time.tv_sec = time_now.tv_sec + secs;
1382         wake_time.tv_nsec = time_now.tv_usec * 10;
1383         pthread_cond_timedwait(&self->ThreadCond, &self->ThreadMutex, &wake_time);
1384         begin_critical_section(S_THREAD_LIST);
1385         pthread_mutex_unlock(&self->ThreadMutex);
1386         ctdl_thread_internal_change_state (self, CTDL_THREAD_RUNNING);
1387         end_critical_section(S_THREAD_LIST);
1388 }
1389
1390
1391 /*
1392  * Routine to clean up our thread function on exit
1393  */
1394 static void ctdl_internal_thread_cleanup(void *arg)
1395 {
1396         struct CtdlThreadNode *this_thread;
1397         this_thread = CtdlThreadSelf();
1398         /*
1399          * In here we were called by the current thread because it is exiting
1400          * NB. WE ARE THE CURRENT THREAD
1401          */
1402         CtdlLogPrintf(CTDL_NOTICE, "Thread \"%s\" (%ld) exited.\n", this_thread->name, this_thread->tid);
1403         begin_critical_section(S_THREAD_LIST);
1404         #ifdef HAVE_BACKTRACE
1405         eCrash_UnregisterThread();
1406         #endif
1407         this_thread->state = CTDL_THREAD_EXITED;        // needs to be last thing else house keeping will unlink us too early
1408         end_critical_section(S_THREAD_LIST);
1409 //      CtdlThreadGC();
1410 }
1411
1412 /*
1413  * A quick function to show the load averages
1414  */
1415 void ctdl_thread_internal_calc_loadavg(void)
1416 {
1417         struct CtdlThreadNode *that_thread;
1418         double load_avg, worker_avg;
1419         int workers = 0;
1420
1421         begin_critical_section(S_THREAD_LIST);
1422         that_thread = CtdlThreadList;
1423         load_avg = 0;
1424         worker_avg = 0;
1425         while(that_thread)
1426         {
1427                 /* Update load averages */
1428                 ctdl_thread_internal_update_avgs(that_thread);
1429                 pthread_mutex_lock(&that_thread->ThreadMutex);
1430                 that_thread->load_avg = that_thread->avg_sleeping + that_thread->avg_running + that_thread->avg_blocked;
1431                 that_thread->load_avg = that_thread->avg_running / that_thread->load_avg * 100;
1432                 that_thread->avg_sleeping /= 2;
1433                 that_thread->avg_running /= 2;
1434                 that_thread->avg_blocked /= 2;
1435                 load_avg += that_thread->load_avg;
1436                 if (that_thread->flags & CTDLTHREAD_WORKER)
1437                 {
1438                         worker_avg += that_thread->load_avg;
1439                         workers++;
1440                 }
1441 #ifdef WITH_THREADLOG
1442                 CtdlLogPrintf(CTDL_DEBUG, "CtdlThread, \"%s\" (%ld) \"%s\" %f %f %f %f.\n",
1443                         that_thread->name,
1444                         that_thread->tid,
1445                         CtdlThreadStates[that_thread->state],
1446                         that_thread->avg_sleeping,
1447                         that_thread->avg_running,
1448                         that_thread->avg_blocked,
1449                         that_thread->load_avg);
1450 #endif
1451                 pthread_mutex_unlock(&that_thread->ThreadMutex);
1452                 that_thread = that_thread->next;
1453         }
1454         CtdlThreadLoadAvg = load_avg/num_threads;
1455         CtdlThreadWorkerAvg = worker_avg/workers;
1456 #ifdef WITH_THREADLOG
1457         CtdlLogPrintf(CTDL_INFO, "System load average %f, workers averag %f\n", CtdlThreadLoadAvg, CtdlThreadWorkerAvg);
1458 #endif
1459         end_critical_section(S_THREAD_LIST);
1460 }
1461
1462
1463 /*
1464  * Garbage collection routine.
1465  * Gets called by main() in a loop to clean up the thread list periodically.
1466  */
1467 void ctdl_internal_thread_gc (void)
1468 {
1469         struct CtdlThreadNode *this_thread, *that_thread;
1470         int workers = 0;
1471         
1472         /* Handle exiting of garbage collector thread */
1473         if(num_threads == 1)
1474                 CtdlThreadList->state = CTDL_THREAD_EXITED;
1475         
1476 #ifdef WITH_THREADLOG
1477         CtdlLogPrintf(CTDL_DEBUG, "Thread system running garbage collection.\n");
1478 #endif
1479         /*
1480          * Woke up to do garbage collection
1481          */
1482         begin_critical_section(S_THREAD_LIST);
1483         this_thread = CtdlThreadList;
1484         while(this_thread)
1485         {
1486                 that_thread = this_thread;
1487                 this_thread = this_thread->next;
1488                 
1489                 /* Do we need to clean up this thread? */
1490                 if (that_thread->state != CTDL_THREAD_EXITED)
1491                 {
1492                         if(that_thread->flags & CTDLTHREAD_WORKER)
1493                                 workers++;      /* Sanity check on number of worker threads */
1494                         continue;
1495                 }
1496                 
1497                 if (pthread_equal(that_thread->tid, pthread_self()) && that_thread->thread_func)
1498                 {       /* Sanity check */
1499                         end_critical_section(S_THREAD_LIST);
1500                         CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC, a thread is trying to clean up after itself.\n");
1501                         CtdlThreadStopAll();
1502                         return;
1503                 }
1504                 
1505                 if (num_threads <= 0)
1506                 {       /* Sanity check */
1507                         end_critical_section (S_THREAD_LIST);
1508                         CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC, num_threads <= 0 and trying to do Garbage Collection.\n");
1509                         CtdlThreadStopAll();
1510                         return;
1511                 }
1512
1513                 /* If we are unlinking the list head then the next becomes the list head */
1514                 if (that_thread == CtdlThreadList)
1515                         CtdlThreadList = that_thread->next;
1516                 if(that_thread->prev)
1517                         that_thread->prev->next = that_thread->next;
1518                 if(that_thread->next)
1519                         that_thread->next->prev = that_thread->next;
1520                 num_threads--;
1521                 if(that_thread->flags & CTDLTHREAD_WORKER)
1522                         num_workers--;  /* This is a wroker thread so reduce the count. */
1523                 
1524                 /*
1525                  * Join on the thread to do clean up and prevent memory leaks
1526                  * Also makes sure the thread has cleaned up after itself before we remove it from the list
1527                  * If that thread has no function it must be the garbage collector
1528                  */
1529                 if (that_thread->thread_func)
1530                         pthread_join (that_thread->tid, NULL);
1531                 
1532                 /*
1533                  * Now we own that thread entry
1534                  */
1535                 CtdlLogPrintf(CTDL_INFO, "Garbage Collection for thread \"%s\" (%ld).\n", that_thread->name, that_thread->tid);
1536                 if(that_thread->name)
1537                         free(that_thread->name);
1538                 pthread_mutex_destroy(&that_thread->ThreadMutex);
1539                 pthread_cond_destroy(&that_thread->ThreadCond);
1540                 pthread_attr_destroy(&that_thread->attr);
1541                 free(that_thread);
1542         }
1543         
1544         /* Sanity check number of worker threads */
1545         if (workers != num_workers)
1546         {
1547                 end_critical_section(S_THREAD_LIST);
1548                 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC, discrepancy in number of worker threads. Counted %d, should be %d.\n", workers, num_workers);
1549                 return;
1550         }
1551         end_critical_section(S_THREAD_LIST);
1552 }
1553
1554
1555
1556  
1557 /*
1558  * Runtime function for a Citadel Thread.
1559  * This initialises the threads environment and then calls the user supplied thread function
1560  * Note that this is the REAL thread function and wraps the users thread function.
1561  */ 
1562 static void *ctdl_internal_thread_func (void *arg)
1563 {
1564         struct CtdlThreadNode *this_thread;
1565         void *ret = NULL;
1566
1567         /* lock and unlock the thread list.
1568          * This causes this thread to wait until all its creation stuff has finished before it
1569          * can continue its execution.
1570          */
1571         begin_critical_section(S_THREAD_LIST);
1572         // Get our thread data structure
1573         this_thread = (struct CtdlThreadNode *) arg;
1574         this_thread->state = CTDL_THREAD_RUNNING;
1575         this_thread->pid = getpid();
1576         gettimeofday(&this_thread->start_time, NULL);           /* Time this thread started */
1577         memcpy(&this_thread->last_state_change, &this_thread->start_time, sizeof (struct timeval));     /* Changed state so mark it. */
1578         end_critical_section(S_THREAD_LIST);
1579                 
1580         // Tell the world we are here
1581         CtdlLogPrintf(CTDL_NOTICE, "Created a new thread \"%s\" (%ld). \n", this_thread->name, this_thread->tid);
1582
1583         // Register the cleanup function to take care of when we exit.
1584         pthread_cleanup_push(ctdl_internal_thread_cleanup, NULL);
1585         
1586         
1587         /*
1588          * run the thread to do the work
1589          */
1590         ret = (this_thread->thread_func)(this_thread->user_args);
1591         
1592         /*
1593          * Our thread is exiting either because it wanted to end or because the server is stopping
1594          * We need to clean up
1595          */
1596         pthread_cleanup_pop(1); // Execute our cleanup routine and remove it
1597         
1598         return(ret);
1599 }
1600
1601
1602  
1603 /*
1604  * Internal function to create a thread.
1605  * Must be called from within a S_THREAD_LIST critical section
1606  */ 
1607 struct CtdlThreadNode *ctdl_internal_create_thread(char *name, long flags, void *(*thread_func) (void *arg), void *args)
1608 {
1609         int ret = 0;
1610         struct CtdlThreadNode *this_thread;
1611         int sigtrick = 0;
1612         sigset_t old_signal_set;
1613
1614         if (num_threads >= 32767)
1615         {
1616                 CtdlLogPrintf(CTDL_EMERG, "Thread system. Thread list full.\n");
1617                 return NULL;
1618         }
1619                 
1620         this_thread = malloc(sizeof(struct CtdlThreadNode));
1621         if (this_thread == NULL) {
1622                 CtdlLogPrintf(CTDL_EMERG, "Thread system, can't allocate CtdlThreadNode, exiting\n");
1623                 return NULL;
1624         }
1625         // Ensuring this is zero'd means we make sure the thread doesn't start doing its thing until we are ready.
1626         memset (this_thread, 0, sizeof(struct CtdlThreadNode));
1627         
1628         this_thread->state = CTDL_THREAD_CREATE;
1629         
1630         if ((ret = pthread_attr_init(&this_thread->attr))) {
1631                 CtdlLogPrintf(CTDL_EMERG, "Thread system, pthread_attr_init: %s\n", strerror(ret));
1632                 free(this_thread);
1633                 return NULL;
1634         }
1635
1636         /* Our per-thread stacks need to be bigger than the default size,
1637          * otherwise the MIME parser crashes on FreeBSD, and the IMAP service
1638          * crashes on 64-bit Linux.
1639          */
1640         if (flags & CTDLTHREAD_BIGSTACK)
1641         {
1642                 CtdlLogPrintf(CTDL_INFO, "Thread system. Creating BIG STACK thread.\n");
1643                 if ((ret = pthread_attr_setstacksize(&this_thread->attr, THREADSTACKSIZE))) {
1644                         CtdlLogPrintf(CTDL_EMERG, "Thread system, pthread_attr_setstacksize: %s\n",
1645                                 strerror(ret));
1646                         pthread_attr_destroy(&this_thread->attr);
1647                         free(this_thread);
1648                         return NULL;
1649                 }
1650         }
1651
1652         /*
1653          * If we got here we are going to create the thread so we must initilise the structure
1654          * first because most implimentations of threading can't create it in a stopped state
1655          * and it might want to do things with its structure that aren't initialised otherwise.
1656          */
1657         if(name)
1658         {
1659                 this_thread->name = strdup(name);
1660         }
1661         else
1662         {
1663                 this_thread->name = strdup("Un-named Thread");
1664         }
1665         
1666         this_thread->flags = flags;
1667         this_thread->thread_func = thread_func;
1668         this_thread->user_args = args;
1669         pthread_mutex_init (&(this_thread->ThreadMutex), NULL);
1670         pthread_cond_init (&(this_thread->ThreadCond), NULL);
1671         
1672         /*
1673          * We want to make sure that only the main thread handles signals,
1674          * so that each signal is handled exactly once.  To do this, we
1675          * make sure that each new thread has all the signals that we
1676          * handle blocked.  To avoid race conditions, we block them in 
1677          * the spawning thread first, then create the new thread (which
1678          * inherits the settings), and then restore the old settings in
1679          * the spawning thread.  This means that there is a brief period
1680          * when no signals will be processed, but during that time they
1681          * should be queued by the operating system.
1682          */
1683         if (pthread_equal(GC_thread, pthread_self())) 
1684             sigtrick = ctdl_thread_internal_block_signals(&old_signal_set) == 0;
1685
1686         /*
1687          * We pass this_thread into the thread as its args so that it can find out information
1688          * about itself and it has a bit of storage space for itself, not to mention that the REAL
1689          * thread function needs to finish off the setup of the structure
1690          */
1691         if ((ret = pthread_create(&this_thread->tid, &this_thread->attr, ctdl_internal_thread_func, this_thread) != 0))
1692         {
1693
1694                 CtdlLogPrintf(CTDL_ALERT, "Thread system, Can't create thread: %s\n",
1695                         strerror(ret));
1696                 if (this_thread->name)
1697                         free (this_thread->name);
1698                 pthread_mutex_destroy(&(this_thread->ThreadMutex));
1699                 pthread_cond_destroy(&(this_thread->ThreadCond));
1700                 pthread_attr_destroy(&this_thread->attr);
1701                 free(this_thread);
1702                 if (sigtrick)
1703                         ctdl_thread_internal_restore_signals(&old_signal_set);
1704                 return NULL;
1705         }
1706         
1707         if (sigtrick)
1708                 ctdl_thread_internal_restore_signals(&old_signal_set);
1709         
1710         num_threads++;  // Increase the count of threads in the system.
1711         if(this_thread->flags & CTDLTHREAD_WORKER)
1712                 num_workers++;
1713
1714         this_thread->next = CtdlThreadList;
1715         CtdlThreadList = this_thread;
1716         if (this_thread->next)
1717                 this_thread->next->prev = this_thread;
1718         // Register for tracing
1719         #ifdef HAVE_BACKTRACE
1720         eCrash_RegisterThread(this_thread->name, 0);
1721         #endif
1722         return this_thread;
1723 }
1724
1725 /*
1726  * Wrapper function to create a thread
1727  * ensures the critical section and other protections are in place.
1728  * char *name = name to give to thread, if NULL, use generic name
1729  * int flags = flags to determine type of thread and standard facilities
1730  */
1731 struct CtdlThreadNode *CtdlThreadCreate(char *name, long flags, void *(*thread_func) (void *arg), void *args)
1732 {
1733         struct CtdlThreadNode *ret = NULL;
1734         
1735         begin_critical_section(S_THREAD_LIST);
1736         ret = ctdl_internal_create_thread(name, flags, thread_func, args);
1737         end_critical_section(S_THREAD_LIST);
1738         return ret;
1739 }
1740
1741
1742
1743 /*
1744  * A warapper function for select so we can show a thread as blocked
1745  */
1746 int CtdlThreadSelect(int n, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, const struct timeval *timeout)
1747 {
1748         struct CtdlThreadNode *self;
1749         int ret;
1750         
1751         self = CtdlThreadSelf();
1752         ctdl_thread_internal_change_state(self, CTDL_THREAD_BLOCKED);
1753         ret = select(n, readfds, writefds, exceptfds, timeout);
1754         ctdl_thread_internal_change_state(self, CTDL_THREAD_RUNNING);
1755         return ret;
1756 }
1757
1758 /*
1759  * Purge all sessions which have the 'kill_me' flag set.
1760  * This function has code to prevent it from running more than once every
1761  * few seconds, because running it after every single unbind would waste a lot
1762  * of CPU time and keep the context list locked too much.  To force it to run
1763  * anyway, set "force" to nonzero.
1764  *
1765  *
1766  * After that's done, we raise the size of the worker thread pool
1767  * if such an action is appropriate.
1768  */
1769 void dead_session_purge(int force) {
1770         struct CitContext *ptr, *ptr2;          /* general-purpose utility pointer */
1771         struct CitContext *rem = NULL;  /* list of sessions to be destroyed */
1772         
1773         CtdlThreadPushName("dead_session_purge");
1774         
1775         if (force == 0) {
1776                 if ( (time(NULL) - last_purge) < 5 ) {
1777                         CtdlThreadPopName();
1778                         return; /* Too soon, go away */
1779                 }
1780         }
1781         time(&last_purge);
1782
1783         begin_critical_section(S_SESSION_TABLE);
1784         ptr = ContextList;
1785         while (ptr) {
1786                 ptr2 = ptr;
1787                 ptr = ptr->next;
1788                 
1789                 if ( (ptr2->state == CON_IDLE) && (ptr2->kill_me) ) {
1790                         /* Remove the session from the active list */
1791                         if (ptr2->prev) {
1792                                 ptr2->prev->next = ptr2->next;
1793                         }
1794                         else {
1795                                 ContextList = ptr2->next;
1796                         }
1797                         if (ptr2->next) {
1798                                 ptr2->next->prev = ptr2->prev;
1799                         }
1800
1801                         --num_sessions;
1802
1803                         /* And put it on our to-be-destroyed list */
1804                         ptr2->next = rem;
1805                         rem = ptr2;
1806
1807                 }
1808         }
1809         end_critical_section(S_SESSION_TABLE);
1810
1811         /* Now that we no longer have the session list locked, we can take
1812          * our time and destroy any sessions on the to-be-killed list, which
1813          * is allocated privately on this thread's stack.
1814          */
1815         while (rem != NULL) {
1816                 CtdlLogPrintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
1817                 RemoveContext(rem);
1818                 ptr = rem;
1819                 rem = rem->next;
1820                 free(ptr);
1821         }
1822
1823         /* Raise the size of the worker thread pool if necessary. */
1824         begin_critical_section(S_THREAD_LIST);
1825         if ( (num_sessions > num_workers)
1826            && (num_workers < config.c_max_workers) ) {
1827                 ctdl_internal_create_thread("Worker Thread", CTDLTHREAD_BIGSTACK + CTDLTHREAD_WORKER, worker_thread, NULL);
1828         }
1829         end_critical_section(S_THREAD_LIST);
1830         // FIXME: reduce the number of worker threads too
1831         
1832         CtdlThreadPopName();
1833         
1834 }
1835
1836
1837
1838
1839
1840 /*
1841  * masterCC is the context we use when not attached to a session.  This
1842  * function initializes it.
1843  */
1844 void InitializeMasterCC(void) {
1845         memset(&masterCC, 0, sizeof(struct CitContext));
1846         masterCC.internal_pgm = 1;
1847         masterCC.cs_pid = 0;
1848 }
1849
1850
1851
1852
1853
1854
1855 /*
1856  * Bind a thread to a context.  (It's inline merely to speed things up.)
1857  */
1858 INLINE void become_session(struct CitContext *which_con) {
1859         pthread_setspecific(MyConKey, (void *)which_con );
1860 }
1861
1862
1863
1864 /* 
1865  * This loop just keeps going and going and going...
1866  */     
1867 void *worker_thread(void *arg) {
1868         int i;
1869         int highest;
1870         struct CitContext *ptr;
1871         struct CitContext *bind_me = NULL;
1872         fd_set readfds;
1873         int retval = 0;
1874         struct CitContext *con= NULL;   /* Temporary context pointer */
1875         struct ServiceFunctionHook *serviceptr;
1876         int ssock;                      /* Descriptor for client socket */
1877         struct timeval tv;
1878         int force_purge = 0;
1879         int m;
1880
1881         cdb_allocate_tsd();
1882
1883         while (!CtdlThreadCheckStop()) {
1884
1885                 /* make doubly sure we're not holding any stale db handles
1886                  * which might cause a deadlock.
1887                  */
1888                 cdb_check_handles();
1889 do_select:      force_purge = 0;
1890                 bind_me = NULL;         /* Which session shall we handle? */
1891
1892                 /* Initialize the fdset. */
1893                 FD_ZERO(&readfds);
1894                 highest = 0;
1895
1896                 begin_critical_section(S_SESSION_TABLE);
1897                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1898                         if (ptr->state == CON_IDLE) {
1899                                 FD_SET(ptr->client_socket, &readfds);
1900                                 if (ptr->client_socket > highest)
1901                                         highest = ptr->client_socket;
1902                         }
1903                         if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1904                                 bind_me = ptr;
1905                                 ptr->state = CON_EXECUTING;
1906                         }
1907                 }
1908                 end_critical_section(S_SESSION_TABLE);
1909
1910                 if (bind_me) {
1911                         goto SKIP_SELECT;
1912                 }
1913
1914                 /* If we got this far, it means that there are no sessions
1915                  * which a previous thread marked for attention, so we go
1916                  * ahead and get ready to select().
1917                  */
1918
1919                 /* First, add the various master sockets to the fdset. */
1920                 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1921                 serviceptr = serviceptr->next ) {
1922                         m = serviceptr->msock;
1923                         FD_SET(m, &readfds);
1924                         if (m > highest) {
1925                                 highest = m;
1926                         }
1927                 }
1928
1929                 if (!CtdlThreadCheckStop()) {
1930                         tv.tv_sec = 1;          /* wake up every second if no input */
1931                         tv.tv_usec = 0;
1932                         retval = CtdlThreadSelect(highest + 1, &readfds, NULL, NULL, &tv);
1933 //                      retval = select(highest + 1, &readfds, NULL, NULL, &tv);
1934                 }
1935
1936                 if (CtdlThreadCheckStop()) return(NULL);
1937
1938                 /* Now figure out who made this select() unblock.
1939                  * First, check for an error or exit condition.
1940                  */
1941                 if (retval < 0) {
1942                         if (errno == EBADF) {
1943                                 CtdlLogPrintf(CTDL_NOTICE, "select() failed: (%s)\n",
1944                                         strerror(errno));
1945                                 goto do_select;
1946                         }
1947                         if (errno != EINTR) {
1948                                 CtdlLogPrintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1949                                 CtdlThreadStopAll();
1950                         } else if (!CtdlThreadCheckStop()) {
1951                                 CtdlLogPrintf(CTDL_DEBUG, "Un handled select failure.\n");
1952                                 goto do_select;
1953                         }
1954                 }
1955                 else if(retval == 0) {
1956                         goto SKIP_SELECT;
1957                 }
1958                 /* Next, check to see if it's a new client connecting
1959                  * on a master socket.
1960                  */
1961                 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1962                      serviceptr = serviceptr->next ) {
1963
1964                         if (FD_ISSET(serviceptr->msock, &readfds)) {
1965                                 ssock = accept(serviceptr->msock, NULL, 0);
1966                                 if (ssock >= 0) {
1967                                         CtdlLogPrintf(CTDL_DEBUG,
1968                                                 "New client socket %d\n",
1969                                                 ssock);
1970
1971                                         /* The master socket is non-blocking but the client
1972                                          * sockets need to be blocking, otherwise certain
1973                                          * operations barf on FreeBSD.  Not a fatal error.
1974                                          */
1975                                         if (fcntl(ssock, F_SETFL, 0) < 0) {
1976                                                 CtdlLogPrintf(CTDL_EMERG,
1977                                                         "citserver: Can't set socket to blocking: %s\n",
1978                                                         strerror(errno));
1979                                         }
1980
1981                                         /* New context will be created already
1982                                          * set up in the CON_EXECUTING state.
1983                                          */
1984                                         con = CreateNewContext();
1985
1986                                         /* Assign our new socket number to it. */
1987                                         con->client_socket = ssock;
1988                                         con->h_command_function =
1989                                                 serviceptr->h_command_function;
1990                                         con->h_async_function =
1991                                                 serviceptr->h_async_function;
1992                                         con->ServiceName =
1993                                                 serviceptr->ServiceName;
1994                                         
1995                                         /* Determine whether it's a local socket */
1996                                         if (serviceptr->sockpath != NULL)
1997                                                 con->is_local_socket = 1;
1998         
1999                                         /* Set the SO_REUSEADDR socket option */
2000                                         i = 1;
2001                                         setsockopt(ssock, SOL_SOCKET,
2002                                                 SO_REUSEADDR,
2003                                                 &i, sizeof(i));
2004
2005                                         become_session(con);
2006                                         begin_session(con);
2007                                         serviceptr->h_greeting_function();
2008                                         become_session(NULL);
2009                                         con->state = CON_IDLE;
2010                                         goto do_select;
2011                                 }
2012                         }
2013                 }
2014
2015                 /* It must be a client socket.  Find a context that has data
2016                  * waiting on its socket *and* is in the CON_IDLE state.  Any
2017                  * active sockets other than our chosen one are marked as
2018                  * CON_READY so the next thread that comes around can just bind
2019                  * to one without having to select() again.
2020                  */
2021                 begin_critical_section(S_SESSION_TABLE);
2022                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
2023                         if ( (FD_ISSET(ptr->client_socket, &readfds))
2024                            && (ptr->state != CON_EXECUTING) ) {
2025                                 ptr->input_waiting = 1;
2026                                 if (!bind_me) {
2027                                         bind_me = ptr;  /* I choose you! */
2028                                         bind_me->state = CON_EXECUTING;
2029                                 }
2030                                 else {
2031                                         ptr->state = CON_READY;
2032                                 }
2033                         }
2034                 }
2035                 end_critical_section(S_SESSION_TABLE);
2036
2037 SKIP_SELECT:
2038                 /* We're bound to a session */
2039                 if (bind_me != NULL) {
2040                         become_session(bind_me);
2041
2042                         /* If the client has sent a command, execute it. */
2043                         if (CC->input_waiting) {
2044                                 CC->h_command_function();
2045                                 CC->input_waiting = 0;
2046                         }
2047
2048                         /* If there are asynchronous messages waiting and the
2049                          * client supports it, do those now */
2050                         if ((CC->is_async) && (CC->async_waiting)
2051                            && (CC->h_async_function != NULL)) {
2052                                 CC->h_async_function();
2053                                 CC->async_waiting = 0;
2054                         }
2055                         
2056                         force_purge = CC->kill_me;
2057                         become_session(NULL);
2058                         bind_me->state = CON_IDLE;
2059                 }
2060
2061                 dead_session_purge(force_purge);
2062                 do_housekeeping();
2063                 check_sched_shutdown();
2064         }
2065         /* If control reaches this point, the server is shutting down */        
2066         return(NULL);
2067 }
2068
2069
2070
2071
2072 /*
2073  * SyslogFacility()
2074  * Translate text facility name to syslog.h defined value.
2075  */
2076 int SyslogFacility(char *name)
2077 {
2078         int i;
2079         struct
2080         {
2081                 int facility;
2082                 char *name;
2083         }   facTbl[] =
2084         {
2085                 {   LOG_KERN,   "kern"          },
2086                 {   LOG_USER,   "user"          },
2087                 {   LOG_MAIL,   "mail"          },
2088                 {   LOG_DAEMON, "daemon"        },
2089                 {   LOG_AUTH,   "auth"          },
2090                 {   LOG_SYSLOG, "syslog"        },
2091                 {   LOG_LPR,    "lpr"           },
2092                 {   LOG_NEWS,   "news"          },
2093                 {   LOG_UUCP,   "uucp"          },
2094                 {   LOG_LOCAL0, "local0"        },
2095                 {   LOG_LOCAL1, "local1"        },
2096                 {   LOG_LOCAL2, "local2"        },
2097                 {   LOG_LOCAL3, "local3"        },
2098                 {   LOG_LOCAL4, "local4"        },
2099                 {   LOG_LOCAL5, "local5"        },
2100                 {   LOG_LOCAL6, "local6"        },
2101                 {   LOG_LOCAL7, "local7"        },
2102                 {   0,            NULL          }
2103         };
2104         for(i = 0; facTbl[i].name != NULL; i++) {
2105                 if(!strcasecmp(name, facTbl[i].name))
2106                         return facTbl[i].facility;
2107         }
2108         enable_syslog = 0;
2109         return LOG_DAEMON;
2110 }
2111
2112
2113 /********** MEM CHEQQER ***********/
2114
2115 #ifdef DEBUG_MEMORY_LEAKS
2116
2117 #undef malloc
2118 #undef realloc
2119 #undef strdup
2120 #undef free
2121
2122 void *tracked_malloc(size_t size, char *file, int line) {
2123         struct igheap *thisheap;
2124         void *block;
2125
2126         block = malloc(size);
2127         if (block == NULL) return(block);
2128
2129         thisheap = malloc(sizeof(struct igheap));
2130         if (thisheap == NULL) {
2131                 free(block);
2132                 return(NULL);
2133         }
2134
2135         thisheap->block = block;
2136         strcpy(thisheap->file, file);
2137         thisheap->line = line;
2138         
2139         begin_critical_section(S_DEBUGMEMLEAKS);
2140         thisheap->next = igheap;
2141         igheap = thisheap;
2142         end_critical_section(S_DEBUGMEMLEAKS);
2143
2144         return(block);
2145 }
2146
2147
2148 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
2149         struct igheap *thisheap;
2150         void *block;
2151
2152         block = realloc(ptr, size);
2153         if (block == NULL) return(block);
2154
2155         thisheap = malloc(sizeof(struct igheap));
2156         if (thisheap == NULL) {
2157                 free(block);
2158                 return(NULL);
2159         }
2160
2161         thisheap->block = block;
2162         strcpy(thisheap->file, file);
2163         thisheap->line = line;
2164         
2165         begin_critical_section(S_DEBUGMEMLEAKS);
2166         thisheap->next = igheap;
2167         igheap = thisheap;
2168         end_critical_section(S_DEBUGMEMLEAKS);
2169
2170         return(block);
2171 }
2172
2173
2174
2175 void tracked_free(void *ptr) {
2176         struct igheap *thisheap;
2177         struct igheap *trash;
2178
2179         free(ptr);
2180
2181         if (igheap == NULL) return;
2182         begin_critical_section(S_DEBUGMEMLEAKS);
2183         for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
2184                 if (thisheap->next != NULL) {
2185                         if (thisheap->next->block == ptr) {
2186                                 trash = thisheap->next;
2187                                 thisheap->next = thisheap->next->next;
2188                                 free(trash);
2189                         }
2190                 }
2191         }
2192         if (igheap->block == ptr) {
2193                 trash = igheap;
2194                 igheap = igheap->next;
2195                 free(trash);
2196         }
2197         end_critical_section(S_DEBUGMEMLEAKS);
2198 }
2199
2200 char *tracked_strdup(const char *s, char *file, int line) {
2201         char *ptr;
2202
2203         if (s == NULL) return(NULL);
2204         ptr = tracked_malloc(strlen(s) + 1, file, line);
2205         if (ptr == NULL) return(NULL);
2206         strncpy(ptr, s, strlen(s));
2207         return(ptr);
2208 }
2209
2210 void dump_heap(void) {
2211         struct igheap *thisheap;
2212
2213         for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
2214                 CtdlLogPrintf(CTDL_CRIT, "UNFREED: %30s : %d\n",
2215                         thisheap->file, thisheap->line);
2216         }
2217 }
2218
2219 #endif /*  DEBUG_MEMORY_LEAKS */