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