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