Added the functions to allow scheduling of a thread to start at some
[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         
793         /* We need to update the ContextList because some modules may want to itterate it
794          * Question is should we NULL it before iterating here or should we just keep updating it
795          * as we remove items?
796          */
797         while (ptr != NULL){
798                 /* Remove the session from the active list */
799                 rem = ptr->next;
800                 --num_sessions;
801                 
802                 lprintf(CTDL_DEBUG, "Purging session %d\n", ptr->cs_pid);
803                 RemoveContext(ptr);
804                 free (ptr);
805                 ptr = rem;
806                 ContextList = rem; // Update ContextList since a module may try to iterate the list.
807         }
808 }
809
810
811 /*
812  * The system-dependent part of master_cleanup() - close the master socket.
813  */
814 void sysdep_master_cleanup(void) {
815         struct ServiceFunctionHook *serviceptr;
816         
817         /*
818          * close all protocol master sockets
819          */
820         for (serviceptr = ServiceHookTable; serviceptr != NULL;
821             serviceptr = serviceptr->next ) {
822
823                 if (serviceptr->tcp_port > 0)
824                         CtdlLogPrintf(CTDL_INFO, "Closing listener on port %d\n",
825                                 serviceptr->tcp_port);
826
827                 if (serviceptr->sockpath != NULL)
828                         CtdlLogPrintf(CTDL_INFO, "Closing listener on '%s'\n",
829                                 serviceptr->sockpath);
830
831                 close(serviceptr->msock);
832
833                 /* If it's a Unix domain socket, remove the file. */
834                 if (serviceptr->sockpath != NULL) {
835                         unlink(serviceptr->sockpath);
836                 }
837         }
838         
839         context_cleanup();
840         
841 #ifdef HAVE_OPENSSL
842         destruct_ssl();
843 #endif
844         CtdlDestroyProtoHooks();
845         CtdlDestroyDeleteHooks();
846         CtdlDestroyXmsgHooks();
847         CtdlDestroyNetprocHooks();
848         CtdlDestroyUserHooks();
849         CtdlDestroyMessageHook();
850         CtdlDestroyCleanupHooks();
851         CtdlDestroyFixedOutputHooks();  
852         CtdlDestroySessionHooks();
853         CtdlDestroyServiceHook();
854         #ifdef HAVE_BACKTRACE
855         eCrash_Uninit();
856         #endif
857 }
858
859
860
861 /*
862  * Terminate another session.
863  * (This could justifiably be moved out of sysdep.c because it
864  * no longer does anything that is system-dependent.)
865  */
866 void kill_session(int session_to_kill) {
867         struct CitContext *ptr;
868
869         begin_critical_section(S_SESSION_TABLE);
870         for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
871                 if (ptr->cs_pid == session_to_kill) {
872                         ptr->kill_me = 1;
873                 }
874         }
875         end_critical_section(S_SESSION_TABLE);
876 }
877
878 pid_t current_child;
879 void graceful_shutdown(int signum) {
880         kill(current_child, signum);
881         unlink(file_pid_file);
882         exit(0);
883 }
884
885
886 /*
887  * Start running as a daemon.
888  */
889 void start_daemon(int unused) {
890         int status = 0;
891         pid_t child = 0;
892         FILE *fp;
893         int do_restart = 0;
894
895         current_child = 0;
896
897         /* Close stdin/stdout/stderr and replace them with /dev/null.
898          * We don't just call close() because we don't want these fd's
899          * to be reused for other files.
900          */
901         chdir(ctdl_run_dir);
902
903         child = fork();
904         if (child != 0) {
905                 exit(0);
906         }
907         
908         signal(SIGHUP, SIG_IGN);
909         signal(SIGINT, SIG_IGN);
910         signal(SIGQUIT, SIG_IGN);
911
912         setsid();
913         umask(0);
914         freopen("/dev/null", "r", stdin);
915         freopen("/dev/null", "w", stdout);
916         freopen("/dev/null", "w", stderr);
917
918         do {
919                 current_child = fork();
920
921                 signal(SIGTERM, graceful_shutdown);
922         
923                 if (current_child < 0) {
924                         perror("fork");
925                         exit(errno);
926                 }
927         
928                 else if (current_child == 0) {
929                         return; /* continue starting citadel. */
930                 }
931         
932                 else {
933                         fp = fopen(file_pid_file, "w");
934                         if (fp != NULL) {
935                 /*
936                  * NB.. The pid file contains the pid of the actual server.
937                  * This is not the pid of the watcher process
938                  */
939                                 fprintf(fp, ""F_PID_T"\n", current_child);
940                                 fclose(fp);
941                         }
942                         waitpid(current_child, &status, 0);
943                 }
944
945                 do_restart = 0;
946
947                 /* Did the main process exit with an actual exit code? */
948                 if (WIFEXITED(status)) {
949
950                         /* Exit code 0 means the watcher should exit */
951                         if (WEXITSTATUS(status) == 0) {
952                                 do_restart = 0;
953                         }
954
955                         /* Exit code 101-109 means the watcher should exit */
956                         else if ( (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109) ) {
957                                 do_restart = 0;
958                         }
959
960                         /* Any other exit code means we should restart. */
961                         else {
962                                 do_restart = 1;
963                         }
964                 }
965
966                 /* Any other type of termination (signals, etc.) should also restart. */
967                 else {
968                         do_restart = 1;
969                 }
970
971         } while (do_restart);
972
973         unlink(file_pid_file);
974         exit(WEXITSTATUS(status));
975 }
976
977
978
979 /*
980  * Generic routine to convert a login name to a full name (gecos)
981  * Returns nonzero if a conversion took place
982  */
983 int convert_login(char NameToConvert[]) {
984         struct passwd *pw;
985         int a;
986
987         pw = getpwnam(NameToConvert);
988         if (pw == NULL) {
989                 return(0);
990         }
991         else {
992                 strcpy(NameToConvert, pw->pw_gecos);
993                 for (a=0; a<strlen(NameToConvert); ++a) {
994                         if (NameToConvert[a] == ',') NameToConvert[a] = 0;
995                 }
996                 return(1);
997         }
998 }
999
1000
1001
1002 /*
1003  * New thread interface.
1004  * To create a thread you must call one of the create thread functions.
1005  * You must pass it the address of (a pointer to a CtdlThreadNode initialised to NULL) like this
1006  * struct CtdlThreadNode *node = NULL;
1007  * pass in &node
1008  * If the thread is created *node will point to the thread control structure for the created thread.
1009  * If the thread creation fails *node remains NULL
1010  * Do not free the memory pointed to by *node, it doesn't belong to you.
1011  * This new interface duplicates much of the eCrash stuff. We should go for closer integration since that would
1012  * remove the need for the calls to eCrashRegisterThread and friends
1013  */
1014
1015
1016 struct CtdlThreadNode *CtdlThreadList = NULL;
1017 struct CtdlThreadNode *CtdlThreadSchedList = NULL;
1018
1019 /*
1020  * Condition variable and Mutex for thread garbage collection
1021  */
1022 /*static pthread_mutex_t thread_gc_mutex = PTHREAD_MUTEX_INITIALIZER;
1023 static pthread_cond_t thread_gc_cond = PTHREAD_COND_INITIALIZER;
1024 */
1025 static pthread_t GC_thread;
1026 static char *CtdlThreadStates[CTDL_THREAD_LAST_STATE];
1027 double CtdlThreadLoadAvg = 0;
1028 double CtdlThreadWorkerAvg = 0;
1029 pthread_key_t ThreadKey;
1030
1031 /*
1032  * A function to destroy the TSD
1033  */
1034 static void ctdl_thread_internal_dest_tsd(void *arg)
1035 {
1036         if (arg != NULL) {
1037                 check_handles(arg);
1038                 free(arg);
1039         }
1040 }
1041
1042
1043 /*
1044  * A function to initialise the thread TSD
1045  */
1046 void ctdl_thread_internal_init_tsd(void)
1047 {
1048         int ret;
1049         
1050         if ((ret = pthread_key_create(&ThreadKey, ctdl_thread_internal_dest_tsd))) {
1051                 lprintf(CTDL_EMERG, "pthread_key_create: %s\n",
1052                         strerror(ret));
1053                 exit(CTDLEXIT_DB);
1054         }
1055 }
1056
1057 /*
1058  * Ensure that we have a key for thread-specific data. 
1059  *
1060  * This should be called immediately after startup by any thread 
1061  * 
1062  */
1063 void CtdlThreadAllocTSD(void)
1064 {
1065         ThreadTSD *tsd;
1066
1067         if (pthread_getspecific(ThreadKey) != NULL)
1068                 return;
1069
1070         tsd = malloc(sizeof(ThreadTSD));
1071
1072         tsd->tid = NULL;
1073
1074         memset(tsd->cursors, 0, sizeof tsd->cursors);
1075         tsd->self = NULL;
1076         
1077         pthread_setspecific(ThreadKey, tsd);
1078 }
1079
1080
1081 void ctdl_thread_internal_free_tsd(void)
1082 {
1083         ctdl_thread_internal_dest_tsd(pthread_getspecific(ThreadKey));
1084         pthread_setspecific(ThreadKey, NULL);
1085 }
1086
1087
1088 void ctdl_thread_internal_cleanup(void)
1089 {
1090         int i;
1091         struct CtdlThreadNode *this_thread, *that_thread;
1092         
1093         for (i=0; i<CTDL_THREAD_LAST_STATE; i++)
1094         {
1095                 free (CtdlThreadStates[i]);
1096         }
1097         
1098         /* Clean up the scheduled thread list */
1099         this_thread = CtdlThreadSchedList;
1100         while (this_thread)
1101         {
1102                 that_thread = this_thread;
1103                 this_thread = this_thread->next;
1104                 pthread_mutex_destroy(&that_thread->ThreadMutex);
1105                 pthread_cond_destroy(&that_thread->ThreadCond);
1106                 pthread_mutex_destroy(&that_thread->SleepMutex);
1107                 pthread_cond_destroy(&that_thread->SleepCond);
1108                 pthread_attr_destroy(&that_thread->attr);
1109                 free(that_thread);
1110         }
1111         ctdl_thread_internal_free_tsd();
1112 }
1113
1114 void ctdl_thread_internal_init(void)
1115 {
1116         struct CtdlThreadNode *this_thread;
1117         int ret = 0;
1118         
1119         GC_thread = pthread_self();
1120         CtdlThreadStates[CTDL_THREAD_INVALID] = strdup ("Invalid Thread");
1121         CtdlThreadStates[CTDL_THREAD_VALID] = strdup("Valid Thread");
1122         CtdlThreadStates[CTDL_THREAD_CREATE] = strdup("Thread being Created");
1123         CtdlThreadStates[CTDL_THREAD_CANCELLED] = strdup("Thread Cancelled");
1124         CtdlThreadStates[CTDL_THREAD_EXITED] = strdup("Thread Exited");
1125         CtdlThreadStates[CTDL_THREAD_STOPPING] = strdup("Thread Stopping");
1126         CtdlThreadStates[CTDL_THREAD_STOP_REQ] = strdup("Thread Stop Requested");
1127         CtdlThreadStates[CTDL_THREAD_SLEEPING] = strdup("Thread Sleeping");
1128         CtdlThreadStates[CTDL_THREAD_RUNNING] = strdup("Thread Running");
1129         CtdlThreadStates[CTDL_THREAD_BLOCKED] = strdup("Thread Blocked");
1130         
1131         /* Get ourself a thread entry */
1132         this_thread = malloc(sizeof(struct CtdlThreadNode));
1133         if (this_thread == NULL) {
1134                 CtdlLogPrintf(CTDL_EMERG, "Thread system, can't allocate CtdlThreadNode, exiting\n");
1135                 return;
1136         }
1137         // Ensuring this is zero'd means we make sure the thread doesn't start doing its thing until we are ready.
1138         memset (this_thread, 0, sizeof(struct CtdlThreadNode));
1139         
1140         pthread_mutex_init (&(this_thread->ThreadMutex), NULL);
1141         pthread_cond_init (&(this_thread->ThreadCond), NULL);
1142         pthread_mutex_init (&(this_thread->SleepMutex), NULL);
1143         pthread_cond_init (&(this_thread->SleepCond), NULL);
1144         
1145         /* We are garbage collector so create us as running */
1146         this_thread->state = CTDL_THREAD_RUNNING;
1147         
1148         if ((ret = pthread_attr_init(&this_thread->attr))) {
1149                 CtdlLogPrintf(CTDL_EMERG, "Thread system, pthread_attr_init: %s\n", strerror(ret));
1150                 free(this_thread);
1151                 return;
1152         }
1153
1154         this_thread->name = "Garbage Collection Thread";
1155         
1156         this_thread->tid = GC_thread;
1157         CT = this_thread;
1158         
1159         num_threads++;  // Increase the count of threads in the system.
1160
1161         this_thread->next = CtdlThreadList;
1162         CtdlThreadList = this_thread;
1163         if (this_thread->next)
1164                 this_thread->next->prev = this_thread;
1165         /* Set up start times */
1166         gettimeofday(&this_thread->start_time, NULL);           /* Time this thread started */
1167         memcpy(&this_thread->last_state_change, &this_thread->start_time, sizeof (struct timeval));     /* Changed state so mark it. */
1168 }
1169
1170
1171 /*
1172  * A function to update a threads load averages
1173  */
1174  void ctdl_thread_internal_update_avgs(struct CtdlThreadNode *this_thread)
1175  {
1176         struct timeval now, result;
1177         double last_duration;
1178
1179         gettimeofday(&now, NULL);
1180         timersub(&now, &(this_thread->last_state_change), &result);
1181         pthread_mutex_lock(&this_thread->ThreadMutex);
1182         // result now has a timeval for the time we spent in the last state since we last updated
1183         last_duration = (double)result.tv_sec + ((double)result.tv_usec / (double) 1000000);
1184         if (this_thread->state == CTDL_THREAD_SLEEPING)
1185                 this_thread->avg_sleeping += last_duration;
1186         if (this_thread->state == CTDL_THREAD_RUNNING)
1187                 this_thread->avg_running += last_duration;
1188         if (this_thread->state == CTDL_THREAD_BLOCKED)
1189                 this_thread->avg_blocked += last_duration;
1190         memcpy (&this_thread->last_state_change, &now, sizeof (struct timeval));
1191         pthread_mutex_unlock(&this_thread->ThreadMutex);
1192 }
1193
1194 /*
1195  * A function to chenge the state of a thread
1196  */
1197 void ctdl_thread_internal_change_state (struct CtdlThreadNode *this_thread, enum CtdlThreadState new_state)
1198 {
1199         /*
1200          * Wether we change state or not we need update the load values
1201          */
1202         ctdl_thread_internal_update_avgs(this_thread);
1203         pthread_mutex_lock(&this_thread->ThreadMutex); /* To prevent race condition of a sleeping thread */
1204         if ((new_state == CTDL_THREAD_STOP_REQ) && (this_thread->state > CTDL_THREAD_STOP_REQ))
1205                 this_thread->state = new_state;
1206         if (((new_state == CTDL_THREAD_SLEEPING) || (new_state == CTDL_THREAD_BLOCKED)) && (this_thread->state == CTDL_THREAD_RUNNING))
1207                 this_thread->state = new_state;
1208         if ((new_state == CTDL_THREAD_RUNNING) && ((this_thread->state == CTDL_THREAD_SLEEPING) || (this_thread->state == CTDL_THREAD_BLOCKED)))
1209                 this_thread->state = new_state;
1210         pthread_mutex_unlock(&this_thread->ThreadMutex);
1211 }
1212
1213
1214 /*
1215  * A function to tell all threads to exit
1216  */
1217 void CtdlThreadStopAll(void)
1218 {
1219         //FIXME: The signalling of the condition should not be in the critical_section
1220         // We need to build a list of threads we are going to signal and then signal them afterwards
1221         
1222         struct CtdlThreadNode *this_thread;
1223         
1224         begin_critical_section(S_THREAD_LIST);
1225         this_thread = CtdlThreadList;
1226         while(this_thread)
1227         {
1228                 ctdl_thread_internal_change_state (this_thread, CTDL_THREAD_STOP_REQ);
1229                 pthread_cond_signal(&this_thread->ThreadCond);
1230                 pthread_cond_signal(&this_thread->SleepCond);
1231                 CtdlLogPrintf(CTDL_DEBUG, "Thread system stopping thread \"%s\" (%ld).\n", this_thread->name, this_thread->tid);
1232                 this_thread = this_thread->next;
1233         }
1234         end_critical_section(S_THREAD_LIST);
1235 }
1236
1237
1238 /*
1239  * A function to wake up all sleeping threads
1240  */
1241 void CtdlThreadWakeAll(void)
1242 {
1243         struct CtdlThreadNode *this_thread;
1244         
1245         CtdlLogPrintf(CTDL_DEBUG, "Thread system waking all threads.\n");
1246         
1247         begin_critical_section(S_THREAD_LIST);
1248         this_thread = CtdlThreadList;
1249         while(this_thread)
1250         {
1251                 if (!this_thread->thread_func)
1252                 {
1253                         pthread_cond_signal(&this_thread->ThreadCond);
1254                         pthread_cond_signal(&this_thread->SleepCond);
1255                 }
1256                 this_thread = this_thread->next;
1257         }
1258         end_critical_section(S_THREAD_LIST);
1259 }
1260
1261
1262 /*
1263  * A function to return the number of threads running in the system
1264  */
1265 int CtdlThreadGetCount(void)
1266 {
1267         int ret;
1268         
1269         begin_critical_section(S_THREAD_LIST);
1270         ret = num_threads;
1271         end_critical_section(S_THREAD_LIST);
1272         return ret;
1273 }
1274
1275 int CtdlThreadGetWorkers(void)
1276 {
1277         int ret;
1278         
1279         begin_critical_section(S_THREAD_LIST);
1280         ret =  num_workers;
1281         end_critical_section(S_THREAD_LIST);
1282         return ret;
1283 }
1284
1285 double CtdlThreadGetWorkerAvg(void)
1286 {
1287         double ret;
1288         
1289         begin_critical_section(S_THREAD_LIST);
1290         ret =  CtdlThreadWorkerAvg;
1291         end_critical_section(S_THREAD_LIST);
1292         return ret;
1293 }
1294
1295 double CtdlThreadGetLoadAvg(void)
1296 {
1297         double ret;
1298         
1299         begin_critical_section(S_THREAD_LIST);
1300         ret =  CtdlThreadLoadAvg;
1301         end_critical_section(S_THREAD_LIST);
1302         return ret;
1303 }
1304
1305
1306
1307
1308 /*
1309  * A function to rename a thread
1310  * Returns a const char *
1311  */
1312 const char *CtdlThreadName(const char *name)
1313 {
1314         const char *old_name;
1315         
1316         if (!CT)
1317         {
1318                 CtdlLogPrintf(CTDL_WARNING, "Thread system WARNING. Attempt to CtdlThreadRename() a non thread. %s\n", name);
1319                 return NULL;
1320         }
1321         pthread_mutex_lock(&CT->ThreadMutex);
1322         old_name = CT->name;
1323         if (name)
1324                 CT->name = name;
1325         pthread_mutex_unlock(&CT->ThreadMutex);
1326         return (old_name);
1327 }       
1328
1329
1330 /*
1331  * A function to force a thread to exit
1332  */
1333 void CtdlThreadCancel(struct CtdlThreadNode *thread)
1334 {
1335         struct CtdlThreadNode *this_thread;
1336         
1337         if (!thread)
1338                 this_thread = CT;
1339         else
1340                 this_thread = thread;
1341         if (!this_thread)
1342         {
1343                 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC. Attempt to CtdlThreadCancel() a non thread.\n");
1344                 CtdlThreadStopAll();
1345                 return;
1346         }
1347         
1348         if (!this_thread->thread_func)
1349         {
1350                 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC. Attempt to CtdlThreadCancel() the garbage collector.\n");
1351                 CtdlThreadStopAll();
1352                 return;
1353         }
1354         
1355         ctdl_thread_internal_change_state (this_thread, CTDL_THREAD_CANCELLED);
1356         pthread_cancel(this_thread->tid);
1357 }
1358
1359
1360
1361 /*
1362  * A function for a thread to check if it has been asked to stop
1363  */
1364 int CtdlThreadCheckStop(void)
1365 {
1366         if (!CT)
1367         {
1368                 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC, CtdlThreadCheckStop() called by a non thread.\n");
1369                 CtdlThreadStopAll();
1370                 return -1;
1371         }
1372         pthread_mutex_lock(&CT->ThreadMutex);
1373         if(CT->state == CTDL_THREAD_STOP_REQ)
1374         {
1375                 CT->state = CTDL_THREAD_STOPPING;
1376                 pthread_mutex_unlock(&CT->ThreadMutex);
1377                 return -1;
1378         }
1379         else if((CT->state < CTDL_THREAD_STOP_REQ) && (CT->state > CTDL_THREAD_CREATE))
1380         {
1381                 pthread_mutex_unlock(&CT->ThreadMutex);
1382                 return -1;
1383         }
1384         pthread_mutex_unlock(&CT->ThreadMutex);
1385         return 0;
1386 }
1387
1388
1389 /*
1390  * A function to ask a thread to exit
1391  * The thread must call CtdlThreadCheckStop() periodically to determine if it should exit
1392  */
1393 void CtdlThreadStop(struct CtdlThreadNode *thread)
1394 {
1395         struct CtdlThreadNode *this_thread;
1396         
1397         if (!thread)
1398                 this_thread = CT;
1399         else
1400                 this_thread = thread;
1401         if (!this_thread)
1402                 return;
1403         if (!(this_thread->thread_func))
1404                 return;         // Don't stop garbage collector
1405                 
1406         ctdl_thread_internal_change_state (this_thread, CTDL_THREAD_STOP_REQ);
1407         pthread_cond_signal(&this_thread->ThreadCond);
1408         pthread_cond_signal(&this_thread->SleepCond);
1409 }
1410
1411 /*
1412  * So we now have a sleep command that works with threads but it is in seconds
1413  */
1414 void CtdlThreadSleep(int secs)
1415 {
1416         struct timespec wake_time;
1417         struct timeval time_now;
1418         
1419         
1420         if (!CT)
1421         {
1422                 CtdlLogPrintf(CTDL_WARNING, "CtdlThreadSleep() called by something that is not a thread. Should we die?\n");
1423                 return;
1424         }
1425         
1426         memset (&wake_time, 0, sizeof(struct timespec));
1427         gettimeofday(&time_now, NULL);
1428         wake_time.tv_sec = time_now.tv_sec + secs;
1429         wake_time.tv_nsec = time_now.tv_usec * 10;
1430
1431         ctdl_thread_internal_change_state (CT, CTDL_THREAD_SLEEPING);
1432         
1433         pthread_mutex_lock(&CT->ThreadMutex); /* Prevent something asking us to awaken before we've gone to sleep */
1434         pthread_cond_timedwait(&CT->SleepCond, &CT->ThreadMutex, &wake_time);
1435         pthread_mutex_unlock(&CT->ThreadMutex);
1436         
1437         ctdl_thread_internal_change_state (CT, CTDL_THREAD_RUNNING);
1438 }
1439
1440
1441 /*
1442  * Routine to clean up our thread function on exit
1443  */
1444 static void ctdl_internal_thread_cleanup(void *arg)
1445 {
1446         /*
1447          * In here we were called by the current thread because it is exiting
1448          * NB. WE ARE THE CURRENT THREAD
1449          */
1450         CtdlLogPrintf(CTDL_NOTICE, "Thread \"%s\" (%ld) exited.\n", CT->name, CT->tid);
1451         
1452         #ifdef HAVE_BACKTRACE
1453         eCrash_UnregisterThread();
1454         #endif
1455         
1456         pthread_mutex_lock(&CT->ThreadMutex);
1457         CT->state = CTDL_THREAD_EXITED; // needs to be last thing else house keeping will unlink us too early
1458         pthread_mutex_unlock(&CT->ThreadMutex);
1459 }
1460
1461 /*
1462  * A quick function to show the load averages
1463  */
1464 void ctdl_thread_internal_calc_loadavg(void)
1465 {
1466         struct CtdlThreadNode *that_thread;
1467         double load_avg, worker_avg;
1468         int workers = 0;
1469
1470         that_thread = CtdlThreadList;
1471         load_avg = 0;
1472         worker_avg = 0;
1473         while(that_thread)
1474         {
1475                 /* Update load averages */
1476                 ctdl_thread_internal_update_avgs(that_thread);
1477                 pthread_mutex_lock(&that_thread->ThreadMutex);
1478                 that_thread->load_avg = that_thread->avg_sleeping + that_thread->avg_running + that_thread->avg_blocked;
1479                 that_thread->load_avg = that_thread->avg_running / that_thread->load_avg * 100;
1480                 that_thread->avg_sleeping /= 2;
1481                 that_thread->avg_running /= 2;
1482                 that_thread->avg_blocked /= 2;
1483                 load_avg += that_thread->load_avg;
1484                 if (that_thread->flags & CTDLTHREAD_WORKER)
1485                 {
1486                         worker_avg += that_thread->load_avg;
1487                         workers++;
1488                 }
1489 #ifdef WITH_THREADLOG
1490                 CtdlLogPrintf(CTDL_DEBUG, "CtdlThread, \"%s\" (%ld) \"%s\" %f %f %f %f.\n",
1491                         that_thread->name,
1492                         that_thread->tid,
1493                         CtdlThreadStates[that_thread->state],
1494                         that_thread->avg_sleeping,
1495                         that_thread->avg_running,
1496                         that_thread->avg_blocked,
1497                         that_thread->load_avg);
1498 #endif
1499                 pthread_mutex_unlock(&that_thread->ThreadMutex);
1500                 that_thread = that_thread->next;
1501         }
1502         CtdlThreadLoadAvg = load_avg/num_threads;
1503         CtdlThreadWorkerAvg = worker_avg/workers;
1504 #ifdef WITH_THREADLOG
1505         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);
1506 #endif
1507 }
1508
1509
1510 /*
1511  * Garbage collection routine.
1512  * Gets called by main() in a loop to clean up the thread list periodically.
1513  */
1514 void CtdlThreadGC (void)
1515 {
1516         struct CtdlThreadNode *this_thread, *that_thread;
1517         int workers = 0;
1518         
1519         begin_critical_section(S_THREAD_LIST);
1520         
1521         /* Handle exiting of garbage collector thread */
1522         if(num_threads == 1)
1523                 CtdlThreadList->state = CTDL_THREAD_EXITED;
1524         
1525 #ifdef WITH_THREADLOG
1526         CtdlLogPrintf(CTDL_DEBUG, "Thread system running garbage collection.\n");
1527 #endif
1528         /*
1529          * Woke up to do garbage collection
1530          */
1531         this_thread = CtdlThreadList;
1532         while(this_thread)
1533         {
1534                 that_thread = this_thread;
1535                 this_thread = this_thread->next;
1536                 
1537                 /* Do we need to clean up this thread? */
1538                 pthread_mutex_lock(&that_thread->ThreadMutex);
1539                 if (that_thread->state != CTDL_THREAD_EXITED)
1540                 {
1541                         if(that_thread->flags & CTDLTHREAD_WORKER)
1542                                 workers++;      /* Sanity check on number of worker threads */
1543                         pthread_mutex_unlock(&that_thread->ThreadMutex);
1544                         continue;
1545                 }
1546                 
1547                 if (pthread_equal(that_thread->tid, pthread_self()) && that_thread->thread_func)
1548                 {       /* Sanity check */
1549                         pthread_mutex_unlock(&that_thread->ThreadMutex);
1550                         end_critical_section(S_THREAD_LIST);
1551                         CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC, a thread is trying to clean up after itself.\n");
1552                         abort();
1553                         return;
1554                 }
1555                 
1556                 if (num_threads <= 0)
1557                 {       /* Sanity check */
1558                         pthread_mutex_unlock(&that_thread->ThreadMutex);
1559                         end_critical_section(S_THREAD_LIST);
1560                         CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC, num_threads <= 0 and trying to do Garbage Collection.\n");
1561                         abort();
1562                         return;
1563                 }
1564
1565                 if(that_thread->flags & CTDLTHREAD_WORKER)
1566                         num_workers--;  /* This is a wroker thread so reduce the count. */
1567                 num_threads--;
1568                 /* If we are unlinking the list head then the next becomes the list head */
1569                 if(that_thread->prev)
1570                         that_thread->prev->next = that_thread->next;
1571                 else
1572                         CtdlThreadList = that_thread->next;
1573                 if(that_thread->next)
1574                         that_thread->next->prev = that_thread->prev;
1575                 
1576                 pthread_mutex_unlock(&that_thread->ThreadMutex);
1577                 pthread_cond_signal(&that_thread->ThreadCond);
1578                 pthread_cond_signal(&that_thread->SleepCond);   // Make sure this thread is awake
1579                 pthread_mutex_lock(&that_thread->ThreadMutex);  // Make sure it has done what its doing
1580                 pthread_mutex_unlock(&that_thread->ThreadMutex);
1581                 /*
1582                  * Join on the thread to do clean up and prevent memory leaks
1583                  * Also makes sure the thread has cleaned up after itself before we remove it from the list
1584                  * If that thread has no function it must be the garbage collector
1585                  */
1586                 if (that_thread->thread_func)
1587                         pthread_join (that_thread->tid, NULL);
1588                 
1589                 /*
1590                  * Now we own that thread entry
1591                  */
1592                 CtdlLogPrintf(CTDL_INFO, "Garbage Collection for thread \"%s\" (%ld).\n", that_thread->name, that_thread->tid);
1593                 pthread_mutex_destroy(&that_thread->ThreadMutex);
1594                 pthread_cond_destroy(&that_thread->ThreadCond);
1595                 pthread_mutex_destroy(&that_thread->SleepMutex);
1596                 pthread_cond_destroy(&that_thread->SleepCond);
1597                 pthread_attr_destroy(&that_thread->attr);
1598                 free(that_thread);
1599         }
1600         
1601         /* Sanity check number of worker threads */
1602         if (workers != num_workers)
1603         {
1604                 end_critical_section(S_THREAD_LIST);
1605                 CtdlLogPrintf(CTDL_EMERG,
1606                         "Thread system PANIC, discrepancy in number of worker threads. Counted %d, should be %d.\n",
1607                         workers, num_workers
1608                         );
1609                 abort();
1610         }
1611         end_critical_section(S_THREAD_LIST);
1612 }
1613
1614
1615
1616  
1617 /*
1618  * Runtime function for a Citadel Thread.
1619  * This initialises the threads environment and then calls the user supplied thread function
1620  * Note that this is the REAL thread function and wraps the users thread function.
1621  */ 
1622 static void *ctdl_internal_thread_func (void *arg)
1623 {
1624         struct CtdlThreadNode *this_thread;
1625         void *ret = NULL;
1626
1627         /* lock and unlock the thread list.
1628          * This causes this thread to wait until all its creation stuff has finished before it
1629          * can continue its execution.
1630          */
1631         begin_critical_section(S_THREAD_LIST);
1632         this_thread = (struct CtdlThreadNode *) arg;
1633         gettimeofday(&this_thread->start_time, NULL);           /* Time this thread started */
1634         pthread_mutex_lock(&this_thread->ThreadMutex);
1635         
1636         // Register the cleanup function to take care of when we exit.
1637         pthread_cleanup_push(ctdl_internal_thread_cleanup, NULL);
1638         // Get our thread data structure
1639         CtdlThreadAllocTSD();
1640         CT = this_thread;
1641         this_thread->pid = getpid();
1642         memcpy(&this_thread->last_state_change, &this_thread->start_time, sizeof (struct timeval));     /* Changed state so mark it. */
1643         /* Only change to running state if we weren't asked to stop during the create cycle
1644          * Other wise there is a window to allow this threads creation to continue to full grown and
1645          * therby prevent a shutdown of the server.
1646          */
1647         pthread_mutex_unlock(&this_thread->ThreadMutex);
1648                 
1649         if (!CtdlThreadCheckStop())
1650         {
1651                 pthread_mutex_lock(&this_thread->ThreadMutex);
1652                 this_thread->state = CTDL_THREAD_RUNNING;
1653                 pthread_mutex_unlock(&this_thread->ThreadMutex);
1654         }
1655         end_critical_section(S_THREAD_LIST);
1656         
1657         // Register for tracing
1658         #ifdef HAVE_BACKTRACE
1659         eCrash_RegisterThread(this_thread->name, 0);
1660         #endif
1661         
1662         // Tell the world we are here
1663         CtdlLogPrintf(CTDL_NOTICE, "Created a new thread \"%s\" (%ld). \n", this_thread->name, this_thread->tid);
1664
1665         
1666         
1667         /*
1668          * run the thread to do the work but only if we haven't been asked to stop
1669          */
1670         if (!CtdlThreadCheckStop())
1671                 ret = (this_thread->thread_func)(this_thread->user_args);
1672         
1673         /*
1674          * Our thread is exiting either because it wanted to end or because the server is stopping
1675          * We need to clean up
1676          */
1677         pthread_cleanup_pop(1); // Execute our cleanup routine and remove it
1678         
1679         return(ret);
1680 }
1681
1682
1683  
1684 /*
1685  * Internal function to create a thread.
1686  * Must be called from within a S_THREAD_LIST critical section
1687  */ 
1688 struct CtdlThreadNode *ctdl_internal_create_thread(char *name, long flags, void *(*thread_func) (void *arg), void *args)
1689 {
1690         int ret = 0;
1691         struct CtdlThreadNode *this_thread;
1692
1693         if (num_threads >= 32767)
1694         {
1695                 CtdlLogPrintf(CTDL_EMERG, "Thread system. Thread list full.\n");
1696                 return NULL;
1697         }
1698                 
1699         this_thread = malloc(sizeof(struct CtdlThreadNode));
1700         if (this_thread == NULL) {
1701                 CtdlLogPrintf(CTDL_EMERG, "Thread system, can't allocate CtdlThreadNode, exiting\n");
1702                 return NULL;
1703         }
1704         // Ensuring this is zero'd means we make sure the thread doesn't start doing its thing until we are ready.
1705         memset (this_thread, 0, sizeof(struct CtdlThreadNode));
1706         
1707         /* Create the mutex's early so we can use them */
1708         pthread_mutex_init (&(this_thread->ThreadMutex), NULL);
1709         pthread_cond_init (&(this_thread->ThreadCond), NULL);
1710         pthread_mutex_init (&(this_thread->SleepMutex), NULL);
1711         pthread_cond_init (&(this_thread->SleepCond), NULL);
1712         
1713         pthread_mutex_lock(&this_thread->ThreadMutex);
1714         
1715         this_thread->state = CTDL_THREAD_CREATE;
1716         
1717         if ((ret = pthread_attr_init(&this_thread->attr))) {
1718                 pthread_mutex_unlock(&this_thread->ThreadMutex);
1719                 pthread_mutex_destroy(&(this_thread->ThreadMutex));
1720                 pthread_cond_destroy(&(this_thread->ThreadCond));
1721                 pthread_mutex_destroy(&(this_thread->SleepMutex));
1722                 pthread_cond_destroy(&(this_thread->SleepCond));
1723                 CtdlLogPrintf(CTDL_EMERG, "Thread system, pthread_attr_init: %s\n", strerror(ret));
1724                 free(this_thread);
1725                 return NULL;
1726         }
1727
1728         /* Our per-thread stacks need to be bigger than the default size,
1729          * otherwise the MIME parser crashes on FreeBSD, and the IMAP service
1730          * crashes on 64-bit Linux.
1731          */
1732         if (flags & CTDLTHREAD_BIGSTACK)
1733         {
1734                 CtdlLogPrintf(CTDL_INFO, "Thread system. Creating BIG STACK thread.\n");
1735                 if ((ret = pthread_attr_setstacksize(&this_thread->attr, THREADSTACKSIZE))) {
1736                         pthread_mutex_unlock(&this_thread->ThreadMutex);
1737                         pthread_mutex_destroy(&(this_thread->ThreadMutex));
1738                         pthread_cond_destroy(&(this_thread->ThreadCond));
1739                         pthread_mutex_destroy(&(this_thread->SleepMutex));
1740                         pthread_cond_destroy(&(this_thread->SleepCond));
1741                         pthread_attr_destroy(&this_thread->attr);
1742                         CtdlLogPrintf(CTDL_EMERG, "Thread system, pthread_attr_setstacksize: %s\n",
1743                                 strerror(ret));
1744                         free(this_thread);
1745                         return NULL;
1746                 }
1747         }
1748
1749         /*
1750          * If we got here we are going to create the thread so we must initilise the structure
1751          * first because most implimentations of threading can't create it in a stopped state
1752          * and it might want to do things with its structure that aren't initialised otherwise.
1753          */
1754         if(name)
1755         {
1756                 this_thread->name = name;
1757         }
1758         else
1759         {
1760                 this_thread->name = "Un-named Thread";
1761         }
1762         
1763         this_thread->flags = flags;
1764         this_thread->thread_func = thread_func;
1765         this_thread->user_args = args;
1766         /* Set this new thread with an avg_blocked of 2. We do this so that its creation affects the
1767          * load average for the system. If we don't do this then we create a mass of threads at the same time 
1768          * because the creation didn't affect the load average.
1769          */
1770         this_thread->avg_blocked = 2;
1771         
1772         /*
1773          * We pass this_thread into the thread as its args so that it can find out information
1774          * about itself and it has a bit of storage space for itself, not to mention that the REAL
1775          * thread function needs to finish off the setup of the structure
1776          */
1777         if ((ret = pthread_create(&this_thread->tid, &this_thread->attr, ctdl_internal_thread_func, this_thread) != 0))
1778         {
1779
1780                 CtdlLogPrintf(CTDL_ALERT, "Thread system, Can't create thread: %s\n",
1781                         strerror(ret));
1782                 pthread_mutex_unlock(&this_thread->ThreadMutex);
1783                 pthread_mutex_destroy(&(this_thread->ThreadMutex));
1784                 pthread_cond_destroy(&(this_thread->ThreadCond));
1785                 pthread_mutex_destroy(&(this_thread->SleepMutex));
1786                 pthread_cond_destroy(&(this_thread->SleepCond));
1787                 pthread_attr_destroy(&this_thread->attr);
1788                 free(this_thread);
1789                 return NULL;
1790         }
1791         
1792         num_threads++;  // Increase the count of threads in the system.
1793         if(this_thread->flags & CTDLTHREAD_WORKER)
1794                 num_workers++;
1795
1796         this_thread->next = CtdlThreadList;
1797         CtdlThreadList = this_thread;
1798         if (this_thread->next)
1799                 this_thread->next->prev = this_thread;
1800         
1801         pthread_mutex_unlock(&this_thread->ThreadMutex);
1802         
1803         ctdl_thread_internal_calc_loadavg();
1804         return this_thread;
1805 }
1806
1807 /*
1808  * Wrapper function to create a thread
1809  * ensures the critical section and other protections are in place.
1810  * char *name = name to give to thread, if NULL, use generic name
1811  * int flags = flags to determine type of thread and standard facilities
1812  */
1813 struct CtdlThreadNode *CtdlThreadCreate(char *name, long flags, void *(*thread_func) (void *arg), void *args)
1814 {
1815         struct CtdlThreadNode *ret = NULL;
1816         
1817         begin_critical_section(S_THREAD_LIST);
1818         ret = ctdl_internal_create_thread(name, flags, thread_func, args);
1819         end_critical_section(S_THREAD_LIST);
1820         return ret;
1821 }
1822
1823
1824
1825 /*
1826  * Internal function to schedule a thread.
1827  * Must be called from within a S_THREAD_LIST critical section
1828  */ 
1829 struct CtdlThreadNode *CtdlThreadSchedule(char *name, long flags, void *(*thread_func) (void *arg), void *args, time_t when)
1830 {
1831         int ret = 0;
1832         struct CtdlThreadNode *this_thread;
1833
1834         if (num_threads >= 32767)
1835         {
1836                 CtdlLogPrintf(CTDL_EMERG, "Thread system. Thread list full.\n");
1837                 return NULL;
1838         }
1839                 
1840         this_thread = malloc(sizeof(struct CtdlThreadNode));
1841         if (this_thread == NULL) {
1842                 CtdlLogPrintf(CTDL_EMERG, "Thread system, can't allocate CtdlThreadNode, exiting\n");
1843                 return NULL;
1844         }
1845         // Ensuring this is zero'd means we make sure the thread doesn't start doing its thing until we are ready.
1846         memset (this_thread, 0, sizeof(struct CtdlThreadNode));
1847         
1848         /* Create the mutex's early so we can use them */
1849         pthread_mutex_init (&(this_thread->ThreadMutex), NULL);
1850         pthread_cond_init (&(this_thread->ThreadCond), NULL);
1851         pthread_mutex_init (&(this_thread->SleepMutex), NULL);
1852         pthread_cond_init (&(this_thread->SleepCond), NULL);
1853         
1854         this_thread->state = CTDL_THREAD_CREATE;
1855         
1856         if ((ret = pthread_attr_init(&this_thread->attr))) {
1857                 pthread_mutex_destroy(&(this_thread->ThreadMutex));
1858                 pthread_cond_destroy(&(this_thread->ThreadCond));
1859                 pthread_mutex_destroy(&(this_thread->SleepMutex));
1860                 pthread_cond_destroy(&(this_thread->SleepCond));
1861                 CtdlLogPrintf(CTDL_EMERG, "Thread system, pthread_attr_init: %s\n", strerror(ret));
1862                 free(this_thread);
1863                 return NULL;
1864         }
1865
1866         /* Our per-thread stacks need to be bigger than the default size,
1867          * otherwise the MIME parser crashes on FreeBSD, and the IMAP service
1868          * crashes on 64-bit Linux.
1869          */
1870         if (flags & CTDLTHREAD_BIGSTACK)
1871         {
1872                 CtdlLogPrintf(CTDL_INFO, "Thread system. Creating BIG STACK thread.\n");
1873                 if ((ret = pthread_attr_setstacksize(&this_thread->attr, THREADSTACKSIZE))) {
1874                         pthread_mutex_destroy(&(this_thread->ThreadMutex));
1875                         pthread_cond_destroy(&(this_thread->ThreadCond));
1876                         pthread_mutex_destroy(&(this_thread->SleepMutex));
1877                         pthread_cond_destroy(&(this_thread->SleepCond));
1878                         pthread_attr_destroy(&this_thread->attr);
1879                         CtdlLogPrintf(CTDL_EMERG, "Thread system, pthread_attr_setstacksize: %s\n",
1880                                 strerror(ret));
1881                         free(this_thread);
1882                         return NULL;
1883                 }
1884         }
1885
1886         /*
1887          * If we got here we are going to create the thread so we must initilise the structure
1888          * first because most implimentations of threading can't create it in a stopped state
1889          * and it might want to do things with its structure that aren't initialised otherwise.
1890          */
1891         if(name)
1892         {
1893                 this_thread->name = name;
1894         }
1895         else
1896         {
1897                 this_thread->name = "Un-named Thread";
1898         }
1899         
1900         this_thread->flags = flags;
1901         this_thread->thread_func = thread_func;
1902         this_thread->user_args = args;
1903         /* Set this new thread with an avg_blocked of 2. We do this so that its creation affects the
1904          * load average for the system. If we don't do this then we create a mass of threads at the same time 
1905          * because the creation didn't affect the load average.
1906          */
1907         this_thread->avg_blocked = 2;
1908         
1909         /*
1910          * When to start this thread
1911          */
1912         this_thread->when = when;
1913
1914         begin_critical_section(S_SCHEDULE_LIST);
1915         this_thread->next = CtdlThreadSchedList;
1916         CtdlThreadSchedList = this_thread;
1917         if (this_thread->next)
1918                 this_thread->next->prev = this_thread;
1919         end_critical_section(S_SCHEDULE_LIST);
1920         
1921         return this_thread;
1922 }
1923
1924
1925
1926 struct CtdlThreadNode *ctdl_thread_internal_start_scheduled (struct CtdlThreadNode *this_thread)
1927 {
1928         int ret = 0;
1929         
1930         /*
1931          * We pass this_thread into the thread as its args so that it can find out information
1932          * about itself and it has a bit of storage space for itself, not to mention that the REAL
1933          * thread function needs to finish off the setup of the structure
1934          */
1935         if ((ret = pthread_create(&this_thread->tid, &this_thread->attr, ctdl_internal_thread_func, this_thread) != 0))
1936         {
1937
1938                 CtdlLogPrintf(CTDL_ALERT, "Thread system, Can't create thread: %s\n",
1939                         strerror(ret));
1940                 return NULL;
1941         }
1942         
1943         
1944         num_threads++;  // Increase the count of threads in the system.
1945         if(this_thread->flags & CTDLTHREAD_WORKER)
1946                 num_workers++;
1947
1948         this_thread->next = CtdlThreadList;
1949         CtdlThreadList = this_thread;
1950         if (this_thread->next)
1951                 this_thread->next->prev = this_thread;
1952         
1953         return this_thread;
1954 }
1955
1956
1957
1958 void ctdl_thread_internal_check_scheduled(void)
1959 {
1960         struct CtdlThreadNode *this_thread, *that_thread;
1961         time_t now;
1962         
1963         if (try_critical_section(S_SCHEDULE_LIST))
1964                 return; /* If this list is locked we wait till the next chance */
1965         
1966         now = time(NULL);
1967         
1968         this_thread = CtdlThreadSchedList;
1969         while(this_thread)
1970         {
1971                 that_thread = this_thread;
1972                 this_thread = this_thread->next;
1973                 
1974                 if (now > that_thread->when)
1975                 {
1976                         /* Unlink from schedule list */
1977                         if (that_thread->next)
1978                                 that_thread->next->prev = that_thread->prev;
1979                         if (that_thread->prev)
1980                                 that_thread->prev->next = that_thread->next;
1981                         else
1982                                 CtdlThreadSchedList = that_thread->next;
1983                         
1984                         begin_critical_section(S_THREAD_LIST);
1985                         if (CT->state > CTDL_THREAD_STOP_REQ)
1986                         {       /* Only start it if the system is not stopping */
1987                                 pthread_mutex_lock(&that_thread->ThreadMutex);
1988                                 if (ctdl_thread_internal_start_scheduled (that_thread) == NULL)
1989                                 {
1990                                         pthread_mutex_unlock(&that_thread->ThreadMutex);
1991                                         pthread_mutex_destroy(&(that_thread->ThreadMutex));
1992                                         pthread_cond_destroy(&(that_thread->ThreadCond));
1993                                         pthread_mutex_destroy(&(that_thread->SleepMutex));
1994                                         pthread_cond_destroy(&(that_thread->SleepCond));
1995                                         pthread_attr_destroy(&that_thread->attr);
1996                                         free(that_thread);
1997                                 }
1998                                 else
1999                                 {
2000                                         CtdlLogPrintf(CTDL_INFO, "Thread system, Started a sceduled thread \"%s\".\n",
2001                                                 that_thread->name);
2002                                         pthread_mutex_unlock(&that_thread->ThreadMutex);
2003                                         ctdl_thread_internal_calc_loadavg();
2004                                 }
2005                         }
2006                         end_critical_section(S_THREAD_LIST);
2007                 }
2008         }
2009         end_critical_section(S_SCHEDULE_LIST);
2010 }
2011
2012
2013 /*
2014  * A warapper function for select so we can show a thread as blocked
2015  */
2016 int CtdlThreadSelect(int n, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout, struct CtdlThreadNode *self)
2017 {
2018         int ret;
2019         
2020         ctdl_thread_internal_change_state(self, CTDL_THREAD_BLOCKED);
2021         ret = select(n, readfds, writefds, exceptfds, timeout);
2022         ctdl_thread_internal_change_state(self, CTDL_THREAD_RUNNING);
2023         return ret;
2024 }
2025
2026 /*
2027  * Purge all sessions which have the 'kill_me' flag set.
2028  * This function has code to prevent it from running more than once every
2029  * few seconds, because running it after every single unbind would waste a lot
2030  * of CPU time and keep the context list locked too much.  To force it to run
2031  * anyway, set "force" to nonzero.
2032  */
2033 void dead_session_purge(int force) {
2034         struct CitContext *ptr, *ptr2;          /* general-purpose utility pointer */
2035         struct CitContext *rem = NULL;  /* list of sessions to be destroyed */
2036         
2037         if (force == 0) {
2038                 if ( (time(NULL) - last_purge) < 5 ) {
2039                         return; /* Too soon, go away */
2040                 }
2041         }
2042         time(&last_purge);
2043
2044         if (try_critical_section(S_SESSION_TABLE))
2045                 return;
2046                 
2047         ptr = ContextList;
2048         while (ptr) {
2049                 ptr2 = ptr;
2050                 ptr = ptr->next;
2051                 
2052                 if ( (ptr2->state == CON_IDLE) && (ptr2->kill_me) ) {
2053                         /* Remove the session from the active list */
2054                         if (ptr2->prev) {
2055                                 ptr2->prev->next = ptr2->next;
2056                         }
2057                         else {
2058                                 ContextList = ptr2->next;
2059                         }
2060                         if (ptr2->next) {
2061                                 ptr2->next->prev = ptr2->prev;
2062                         }
2063
2064                         --num_sessions;
2065                         /* And put it on our to-be-destroyed list */
2066                         ptr2->next = rem;
2067                         rem = ptr2;
2068                 }
2069         }
2070         end_critical_section(S_SESSION_TABLE);
2071
2072         /* Now that we no longer have the session list locked, we can take
2073          * our time and destroy any sessions on the to-be-killed list, which
2074          * is allocated privately on this thread's stack.
2075          */
2076         while (rem != NULL) {
2077                 CtdlLogPrintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
2078                 RemoveContext(rem);
2079                 ptr = rem;
2080                 rem = rem->next;
2081                 free(ptr);
2082         }
2083 }
2084
2085
2086
2087
2088
2089 /*
2090  * masterCC is the context we use when not attached to a session.  This
2091  * function initializes it.
2092  */
2093 void InitializeMasterCC(void) {
2094         memset(&masterCC, 0, sizeof(struct CitContext));
2095         masterCC.internal_pgm = 1;
2096         masterCC.cs_pid = 0;
2097 }
2098
2099
2100
2101
2102
2103
2104 /*
2105  * Bind a thread to a context.  (It's inline merely to speed things up.)
2106  */
2107 INLINE void become_session(struct CitContext *which_con) {
2108         pthread_setspecific(MyConKey, (void *)which_con );
2109 }
2110
2111
2112
2113 /* 
2114  * This loop just keeps going and going and going...
2115  */     
2116 void *worker_thread(void *arg) {
2117         int i;
2118         int highest;
2119         struct CitContext *ptr;
2120         struct CitContext *bind_me = NULL;
2121         fd_set readfds;
2122         int retval = 0;
2123         struct CitContext *con= NULL;   /* Temporary context pointer */
2124         struct ServiceFunctionHook *serviceptr;
2125         int ssock;                      /* Descriptor for client socket */
2126         struct timeval tv;
2127         int force_purge = 0;
2128         int m;
2129         
2130
2131         while (!CtdlThreadCheckStop()) {
2132
2133                 /* make doubly sure we're not holding any stale db handles
2134                  * which might cause a deadlock.
2135                  */
2136                 cdb_check_handles();
2137 do_select:      force_purge = 0;
2138                 bind_me = NULL;         /* Which session shall we handle? */
2139
2140                 /* Initialize the fdset. */
2141                 FD_ZERO(&readfds);
2142                 highest = 0;
2143
2144                 begin_critical_section(S_SESSION_TABLE);
2145                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
2146                         if (ptr->state == CON_IDLE) {
2147                                 FD_SET(ptr->client_socket, &readfds);
2148                                 if (ptr->client_socket > highest)
2149                                         highest = ptr->client_socket;
2150                         }
2151                         if ((bind_me == NULL) && (ptr->state == CON_READY)) {
2152                                 bind_me = ptr;
2153                                 ptr->state = CON_EXECUTING;
2154                         }
2155                 }
2156                 end_critical_section(S_SESSION_TABLE);
2157
2158                 if (bind_me) {
2159                         goto SKIP_SELECT;
2160                 }
2161
2162                 /* If we got this far, it means that there are no sessions
2163                  * which a previous thread marked for attention, so we go
2164                  * ahead and get ready to select().
2165                  */
2166
2167                 /* First, add the various master sockets to the fdset. */
2168                 for (serviceptr = ServiceHookTable; serviceptr != NULL;
2169                 serviceptr = serviceptr->next ) {
2170                         m = serviceptr->msock;
2171                         FD_SET(m, &readfds);
2172                         if (m > highest) {
2173                                 highest = m;
2174                         }
2175                 }
2176
2177                 if (!CtdlThreadCheckStop()) {
2178                         tv.tv_sec = 1;          /* wake up every second if no input */
2179                         tv.tv_usec = 0;
2180                         retval = CtdlThreadSelect(highest + 1, &readfds, NULL, NULL, &tv, CT);
2181                 }
2182
2183                 if (CtdlThreadCheckStop()) return(NULL);
2184
2185                 /* Now figure out who made this select() unblock.
2186                  * First, check for an error or exit condition.
2187                  */
2188                 if (retval < 0) {
2189                         if (errno == EBADF) {
2190                                 CtdlLogPrintf(CTDL_NOTICE, "select() failed: (%s)\n",
2191                                         strerror(errno));
2192                                 goto do_select;
2193                         }
2194                         if (errno != EINTR) {
2195                                 CtdlLogPrintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
2196                                 CtdlThreadStopAll();
2197                         } else if (!CtdlThreadCheckStop()) {
2198                                 CtdlLogPrintf(CTDL_DEBUG, "Un handled select failure.\n");
2199                                 goto do_select;
2200                         }
2201                 }
2202                 else if(retval == 0) {
2203                         goto SKIP_SELECT;
2204                 }
2205                 /* Next, check to see if it's a new client connecting
2206                  * on a master socket.
2207                  */
2208                 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
2209                      serviceptr = serviceptr->next ) {
2210
2211                         if (FD_ISSET(serviceptr->msock, &readfds)) {
2212                                 ssock = accept(serviceptr->msock, NULL, 0);
2213                                 if (ssock >= 0) {
2214                                         CtdlLogPrintf(CTDL_DEBUG,
2215                                                 "New client socket %d\n",
2216                                                 ssock);
2217
2218                                         /* The master socket is non-blocking but the client
2219                                          * sockets need to be blocking, otherwise certain
2220                                          * operations barf on FreeBSD.  Not a fatal error.
2221                                          */
2222                                         if (fcntl(ssock, F_SETFL, 0) < 0) {
2223                                                 CtdlLogPrintf(CTDL_EMERG,
2224                                                         "citserver: Can't set socket to blocking: %s\n",
2225                                                         strerror(errno));
2226                                         }
2227
2228                                         /* New context will be created already
2229                                          * set up in the CON_EXECUTING state.
2230                                          */
2231                                         con = CreateNewContext();
2232
2233                                         /* Assign our new socket number to it. */
2234                                         con->client_socket = ssock;
2235                                         con->h_command_function =
2236                                                 serviceptr->h_command_function;
2237                                         con->h_async_function =
2238                                                 serviceptr->h_async_function;
2239                                         con->ServiceName =
2240                                                 serviceptr->ServiceName;
2241                                         
2242                                         /* Determine whether it's a local socket */
2243                                         if (serviceptr->sockpath != NULL)
2244                                                 con->is_local_socket = 1;
2245         
2246                                         /* Set the SO_REUSEADDR socket option */
2247                                         i = 1;
2248                                         setsockopt(ssock, SOL_SOCKET,
2249                                                 SO_REUSEADDR,
2250                                                 &i, sizeof(i));
2251
2252                                         become_session(con);
2253                                         begin_session(con);
2254                                         serviceptr->h_greeting_function();
2255                                         become_session(NULL);
2256                                         con->state = CON_IDLE;
2257                                         goto do_select;
2258                                 }
2259                         }
2260                 }
2261
2262                 /* It must be a client socket.  Find a context that has data
2263                  * waiting on its socket *and* is in the CON_IDLE state.  Any
2264                  * active sockets other than our chosen one are marked as
2265                  * CON_READY so the next thread that comes around can just bind
2266                  * to one without having to select() again.
2267                  */
2268                 begin_critical_section(S_SESSION_TABLE);
2269                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
2270                         if ( (FD_ISSET(ptr->client_socket, &readfds))
2271                            && (ptr->state != CON_EXECUTING) ) {
2272                                 ptr->input_waiting = 1;
2273                                 if (!bind_me) {
2274                                         bind_me = ptr;  /* I choose you! */
2275                                         bind_me->state = CON_EXECUTING;
2276                                 }
2277                                 else {
2278                                         ptr->state = CON_READY;
2279                                 }
2280                         }
2281                 }
2282                 end_critical_section(S_SESSION_TABLE);
2283
2284 SKIP_SELECT:
2285                 /* We're bound to a session */
2286                 if (bind_me != NULL) {
2287                         become_session(bind_me);
2288
2289                         /* If the client has sent a command, execute it. */
2290                         if (CC->input_waiting) {
2291                                 CC->h_command_function();
2292                                 CC->input_waiting = 0;
2293                         }
2294
2295                         /* If there are asynchronous messages waiting and the
2296                          * client supports it, do those now */
2297                         if ((CC->is_async) && (CC->async_waiting)
2298                            && (CC->h_async_function != NULL)) {
2299                                 CC->h_async_function();
2300                                 CC->async_waiting = 0;
2301                         }
2302                         
2303                         force_purge = CC->kill_me;
2304                         become_session(NULL);
2305                         bind_me->state = CON_IDLE;
2306                 }
2307
2308                 dead_session_purge(force_purge);
2309                 do_housekeeping();
2310         }
2311         /* If control reaches this point, the server is shutting down */        
2312         return(NULL);
2313 }
2314
2315
2316
2317
2318 /*
2319  * SyslogFacility()
2320  * Translate text facility name to syslog.h defined value.
2321  */
2322 int SyslogFacility(char *name)
2323 {
2324         int i;
2325         struct
2326         {
2327                 int facility;
2328                 char *name;
2329         }   facTbl[] =
2330         {
2331                 {   LOG_KERN,   "kern"          },
2332                 {   LOG_USER,   "user"          },
2333                 {   LOG_MAIL,   "mail"          },
2334                 {   LOG_DAEMON, "daemon"        },
2335                 {   LOG_AUTH,   "auth"          },
2336                 {   LOG_SYSLOG, "syslog"        },
2337                 {   LOG_LPR,    "lpr"           },
2338                 {   LOG_NEWS,   "news"          },
2339                 {   LOG_UUCP,   "uucp"          },
2340                 {   LOG_LOCAL0, "local0"        },
2341                 {   LOG_LOCAL1, "local1"        },
2342                 {   LOG_LOCAL2, "local2"        },
2343                 {   LOG_LOCAL3, "local3"        },
2344                 {   LOG_LOCAL4, "local4"        },
2345                 {   LOG_LOCAL5, "local5"        },
2346                 {   LOG_LOCAL6, "local6"        },
2347                 {   LOG_LOCAL7, "local7"        },
2348                 {   0,            NULL          }
2349         };
2350         for(i = 0; facTbl[i].name != NULL; i++) {
2351                 if(!strcasecmp(name, facTbl[i].name))
2352                         return facTbl[i].facility;
2353         }
2354         enable_syslog = 0;
2355         return LOG_DAEMON;
2356 }
2357
2358
2359 /********** MEM CHEQQER ***********/
2360
2361 #ifdef DEBUG_MEMORY_LEAKS
2362
2363 #undef malloc
2364 #undef realloc
2365 #undef strdup
2366 #undef free
2367
2368 void *tracked_malloc(size_t size, char *file, int line) {
2369         struct igheap *thisheap;
2370         void *block;
2371
2372         block = malloc(size);
2373         if (block == NULL) return(block);
2374
2375         thisheap = malloc(sizeof(struct igheap));
2376         if (thisheap == NULL) {
2377                 free(block);
2378                 return(NULL);
2379         }
2380
2381         thisheap->block = block;
2382         strcpy(thisheap->file, file);
2383         thisheap->line = line;
2384         
2385         begin_critical_section(S_DEBUGMEMLEAKS);
2386         thisheap->next = igheap;
2387         igheap = thisheap;
2388         end_critical_section(S_DEBUGMEMLEAKS);
2389
2390         return(block);
2391 }
2392
2393
2394 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
2395         struct igheap *thisheap;
2396         void *block;
2397
2398         block = realloc(ptr, size);
2399         if (block == NULL) return(block);
2400
2401         thisheap = malloc(sizeof(struct igheap));
2402         if (thisheap == NULL) {
2403                 free(block);
2404                 return(NULL);
2405         }
2406
2407         thisheap->block = block;
2408         strcpy(thisheap->file, file);
2409         thisheap->line = line;
2410         
2411         begin_critical_section(S_DEBUGMEMLEAKS);
2412         thisheap->next = igheap;
2413         igheap = thisheap;
2414         end_critical_section(S_DEBUGMEMLEAKS);
2415
2416         return(block);
2417 }
2418
2419
2420
2421 void tracked_free(void *ptr) {
2422         struct igheap *thisheap;
2423         struct igheap *trash;
2424
2425         free(ptr);
2426
2427         if (igheap == NULL) return;
2428         begin_critical_section(S_DEBUGMEMLEAKS);
2429         for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
2430                 if (thisheap->next != NULL) {
2431                         if (thisheap->next->block == ptr) {
2432                                 trash = thisheap->next;
2433                                 thisheap->next = thisheap->next->next;
2434                                 free(trash);
2435                         }
2436                 }
2437         }
2438         if (igheap->block == ptr) {
2439                 trash = igheap;
2440                 igheap = igheap->next;
2441                 free(trash);
2442         }
2443         end_critical_section(S_DEBUGMEMLEAKS);
2444 }
2445
2446 char *tracked_strdup(const char *s, char *file, int line) {
2447         char *ptr;
2448
2449         if (s == NULL) return(NULL);
2450         ptr = tracked_malloc(strlen(s) + 1, file, line);
2451         if (ptr == NULL) return(NULL);
2452         strncpy(ptr, s, strlen(s));
2453         return(ptr);
2454 }
2455
2456 void dump_heap(void) {
2457         struct igheap *thisheap;
2458
2459         for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
2460                 CtdlLogPrintf(CTDL_CRIT, "UNFREED: %30s : %d\n",
2461                         thisheap->file, thisheap->line);
2462         }
2463 }
2464
2465 #endif /*  DEBUG_MEMORY_LEAKS */