3e3e2cff6419d554f64dfbdda8c0caae4fd7c1ac
[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 <sys/syslog.h>
27
28 #if TIME_WITH_SYS_TIME
29 # include <sys/time.h>
30 # include <time.h>
31 #else
32 # if HAVE_SYS_TIME_H
33 #  include <sys/time.h>
34 # else
35 #  include <time.h>
36 # endif
37 #endif
38
39 #include <limits.h>
40 #include <sys/resource.h>
41 #include <netinet/in.h>
42 #include <netinet/tcp.h>
43 #include <arpa/inet.h>
44 #include <netdb.h>
45 #include <sys/un.h>
46 #include <string.h>
47 #include <pwd.h>
48 #include <errno.h>
49 #include <stdarg.h>
50 #include <grp.h>
51 #ifdef HAVE_PTHREAD_H
52 #include <pthread.h>
53 #endif
54 #include "citadel.h"
55 #include "server.h"
56 #include "serv_extensions.h"
57 #include "sysdep_decls.h"
58 #include "citserver.h"
59 #include "support.h"
60 #include "config.h"
61 #include "database.h"
62 #include "housekeeping.h"
63 #include "tools.h"
64 #include "serv_crypto.h"
65 #include "serv_fulltext.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
76 #ifdef DEBUG_MEMORY_LEAKS
77 struct igheap {
78         struct igheap *next;
79         char file[32];
80         int line;
81         void *block;
82 };
83
84 struct igheap *igheap = NULL;
85 #endif
86
87
88 pthread_mutex_t Critters[MAX_SEMAPHORES];       /* Things needing locking */
89 pthread_key_t MyConKey;                         /* TSD key for MyContext() */
90
91 int verbosity = DEFAULT_VERBOSITY;              /* Logging level */
92
93 struct CitContext masterCC;
94 time_t last_purge = 0;                          /* Last dead session purge */
95 static int num_threads = 0;                     /* Current number of threads */
96 int num_sessions = 0;                           /* Current number of sessions */
97 pthread_t indexer_thread_tid;
98 pthread_t checkpoint_thread_tid;
99
100 int syslog_facility = LOG_DAEMON;
101 int enable_syslog = 0;
102 extern int running_as_daemon;
103
104 /*
105  * lprintf()  ...   Write logging information
106  */
107 void lprintf(enum LogLevel loglevel, const char *format, ...) {   
108         va_list arg_ptr;
109
110         if (enable_syslog) {
111                 va_start(arg_ptr, format);
112                         vsyslog((syslog_facility | loglevel), format, arg_ptr);
113                 va_end(arg_ptr);
114         }
115
116         /* stderr output code */
117         if (enable_syslog || running_as_daemon) return;
118
119         /* if we run in forground and syslog is disabled, log to terminal */
120         if (loglevel <= verbosity) { 
121                 struct timeval tv;
122                 struct tm tim;
123                 time_t unixtime;
124
125                 gettimeofday(&tv, NULL);
126                 /* Promote to time_t; types differ on some OSes (like darwin) */
127                 unixtime = tv.tv_sec;
128                 localtime_r(&unixtime, &tim);
129                 if (CC->cs_pid != 0) {
130                         fprintf(stderr,
131                                 "%04d/%02d/%02d %2d:%02d:%02d.%06ld [%3d] ",
132                                 tim.tm_year + 1900, tim.tm_mon + 1,
133                                 tim.tm_mday, tim.tm_hour, tim.tm_min,
134                                 tim.tm_sec, (long)tv.tv_usec,
135                                 CC->cs_pid);
136                 } else {
137                         fprintf(stderr,
138                                 "%04d/%02d/%02d %2d:%02d:%02d.%06ld ",
139                                 tim.tm_year + 1900, tim.tm_mon + 1,
140                                 tim.tm_mday, tim.tm_hour, tim.tm_min,
141                                 tim.tm_sec, (long)tv.tv_usec);
142                 }
143                 va_start(arg_ptr, format);   
144                         vfprintf(stderr, format, arg_ptr);   
145                 va_end(arg_ptr);   
146                 fflush(stderr);
147         }
148 }   
149
150
151
152 /*
153  * Signal handler to shut down the server.
154  */
155
156 volatile int time_to_die = 0;
157 volatile int shutdown_and_halt = 0;
158
159 static RETSIGTYPE signal_cleanup(int signum) {
160         lprintf(CTDL_DEBUG, "Caught signal %d; shutting down.\n", signum);
161         time_to_die = 1;
162         master_cleanup(signum);
163 }
164
165
166 /*
167  * Some initialization stuff...
168  */
169 void init_sysdep(void) {
170         int i;
171         sigset_t set;
172
173         /* Avoid vulnerabilities related to FD_SETSIZE if we can. */
174 #ifdef FD_SETSIZE
175 #ifdef RLIMIT_NOFILE
176         struct rlimit rl;
177         getrlimit(RLIMIT_NOFILE, &rl);
178         rl.rlim_cur = FD_SETSIZE;
179         rl.rlim_max = FD_SETSIZE;
180         setrlimit(RLIMIT_NOFILE, &rl);
181 #endif
182 #endif
183
184         /* If we've got OpenSSL, we're going to use it. */
185 #ifdef HAVE_OPENSSL
186         init_ssl();
187 #endif
188
189         /* Set up a bunch of semaphores to be used for critical sections */
190         for (i=0; i<MAX_SEMAPHORES; ++i) {
191                 pthread_mutex_init(&Critters[i], NULL);
192         }
193
194         /*
195          * Set up a place to put thread-specific data.
196          * We only need a single pointer per thread - it points to the
197          * CitContext structure (in the ContextList linked list) of the
198          * session to which the calling thread is currently bound.
199          */
200         if (pthread_key_create(&MyConKey, NULL) != 0) {
201                 lprintf(CTDL_CRIT, "Can't create TSD key: %s\n",
202                         strerror(errno));
203         }
204
205         /*
206          * The action for unexpected signals and exceptions should be to
207          * call signal_cleanup() to gracefully shut down the server.
208          */
209         sigemptyset(&set);
210         sigaddset(&set, SIGINT);
211         sigaddset(&set, SIGQUIT);
212         sigaddset(&set, SIGHUP);
213         sigaddset(&set, SIGTERM);
214         // sigaddset(&set, SIGSEGV);    commented out because
215         // sigaddset(&set, SIGILL);     we want core dumps
216         // sigaddset(&set, SIGBUS);
217         sigprocmask(SIG_UNBLOCK, &set, NULL);
218
219         signal(SIGINT, signal_cleanup);
220         signal(SIGQUIT, signal_cleanup);
221         signal(SIGHUP, signal_cleanup);
222         signal(SIGTERM, signal_cleanup);
223         // signal(SIGSEGV, signal_cleanup);     commented out because
224         // signal(SIGILL, signal_cleanup);      we want core dumps
225         // signal(SIGBUS, signal_cleanup);
226
227         /*
228          * Do not shut down the server on broken pipe signals, otherwise the
229          * whole Citadel service would come down whenever a single client
230          * socket breaks.
231          */
232         signal(SIGPIPE, SIG_IGN);
233 }
234
235
236 /*
237  * Obtain a semaphore lock to begin a critical section.
238  */
239 void begin_critical_section(int which_one)
240 {
241         /* lprintf(CTDL_DEBUG, "begin_critical_section(%d)\n", which_one); */
242
243         /* For all types of critical sections except those listed here,
244          * ensure nobody ever tries to do a critical section within a
245          * transaction; this could lead to deadlock.
246          */
247         if (    (which_one != S_FLOORCACHE)
248 #ifdef DEBUG_MEMORY_LEAKS
249                 && (which_one != S_DEBUGMEMLEAKS)
250 #endif
251                 && (which_one != S_RPLIST)
252         ) {
253                 cdb_check_handles();
254         }
255         pthread_mutex_lock(&Critters[which_one]);
256 }
257
258 /*
259  * Release a semaphore lock to end a critical section.
260  */
261 void end_critical_section(int which_one)
262 {
263         pthread_mutex_unlock(&Critters[which_one]);
264 }
265
266
267
268 /*
269  * This is a generic function to set up a master socket for listening on
270  * a TCP port.  The server shuts down if the bind fails.
271  *
272  */
273 int ig_tcp_server(char *ip_addr, int port_number, int queue_len)
274 {
275         struct sockaddr_in sin;
276         int s, i;
277         int actual_queue_len;
278
279         actual_queue_len = queue_len;
280         if (actual_queue_len < 5) actual_queue_len = 5;
281
282         memset(&sin, 0, sizeof(sin));
283         sin.sin_family = AF_INET;
284         sin.sin_port = htons((u_short)port_number);
285         if (ip_addr == NULL) {
286                 sin.sin_addr.s_addr = INADDR_ANY;
287         }
288         else {
289                 sin.sin_addr.s_addr = inet_addr(ip_addr);
290         }
291                                                                                 
292         if (sin.sin_addr.s_addr == INADDR_NONE) {
293                 sin.sin_addr.s_addr = INADDR_ANY;
294         }
295
296         s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
297
298         if (s < 0) {
299                 lprintf(CTDL_EMERG, "citserver: Can't create a socket: %s\n",
300                         strerror(errno));
301                 return(-1);
302         }
303
304         i = 1;
305         setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
306
307         if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
308                 lprintf(CTDL_EMERG, "citserver: Can't bind: %s\n",
309                         strerror(errno));
310                 close(s);
311                 return(-1);
312         }
313
314         /* set to nonblock - we need this for some obscure situations */
315         if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
316                 lprintf(CTDL_EMERG,
317                         "citserver: Can't set socket to non-blocking: %s\n",
318                         strerror(errno));
319                 close(s);
320                 return(-1);
321         }
322
323         if (listen(s, actual_queue_len) < 0) {
324                 lprintf(CTDL_EMERG, "citserver: Can't listen: %s\n",
325                         strerror(errno));
326                 close(s);
327                 return(-1);
328         }
329
330         return(s);
331 }
332
333
334
335 /*
336  * Create a Unix domain socket and listen on it
337  */
338 int ig_uds_server(char *sockpath, int queue_len)
339 {
340         struct sockaddr_un addr;
341         int s;
342         int i;
343         int actual_queue_len;
344
345         actual_queue_len = queue_len;
346         if (actual_queue_len < 5) actual_queue_len = 5;
347
348         i = unlink(sockpath);
349         if (i != 0) if (errno != ENOENT) {
350                 lprintf(CTDL_EMERG, "citserver: can't unlink %s: %s\n",
351                         sockpath, strerror(errno));
352                 return(-1);
353         }
354
355         memset(&addr, 0, sizeof(addr));
356         addr.sun_family = AF_UNIX;
357         safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
358
359         s = socket(AF_UNIX, SOCK_STREAM, 0);
360         if (s < 0) {
361                 lprintf(CTDL_EMERG, "citserver: Can't create a socket: %s\n",
362                         strerror(errno));
363                 return(-1);
364         }
365
366         if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
367                 lprintf(CTDL_EMERG, "citserver: Can't bind: %s\n",
368                         strerror(errno));
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                 lprintf(CTDL_EMERG,
375                         "citserver: Can't set socket to non-blocking: %s\n",
376                         strerror(errno));
377                 close(s);
378                 return(-1);
379         }
380
381         if (listen(s, actual_queue_len) < 0) {
382                 lprintf(CTDL_EMERG, "citserver: Can't listen: %s\n",
383                         strerror(errno));
384                 return(-1);
385         }
386
387         chmod(sockpath, 0777);
388         return(s);
389 }
390
391
392
393 /*
394  * Return a pointer to the CitContext structure bound to the thread which
395  * called this function.  If there's no such binding (for example, if it's
396  * called by the housekeeper thread) then a generic 'master' CC is returned.
397  *
398  * This function is used *VERY* frequently and must be kept small.
399  */
400 struct CitContext *MyContext(void) {
401
402         register struct CitContext *c;
403
404         return ((c = (struct CitContext *) pthread_getspecific(MyConKey),
405                 c == NULL) ? &masterCC : c
406         );
407 }
408
409
410 /*
411  * Initialize a new context and place it in the list.  The session number
412  * used to be the PID (which is why it's called cs_pid), but that was when we
413  * had one process per session.  Now we just assign them sequentially, starting
414  * at 1 (don't change it to 0 because masterCC uses 0).
415  */
416 struct CitContext *CreateNewContext(void) {
417         struct CitContext *me;
418         static int next_pid = 0;
419
420         me = (struct CitContext *) malloc(sizeof(struct CitContext));
421         if (me == NULL) {
422                 lprintf(CTDL_ALERT, "citserver: can't allocate memory!!\n");
423                 return NULL;
424         }
425         memset(me, 0, sizeof(struct CitContext));
426
427         /* The new context will be created already in the CON_EXECUTING state
428          * in order to prevent another thread from grabbing it while it's
429          * being set up.
430          */
431         me->state = CON_EXECUTING;
432
433         /*
434          * Generate a unique session number and insert this context into
435          * the list.
436          */
437         begin_critical_section(S_SESSION_TABLE);
438         me->cs_pid = ++next_pid;
439         me->prev = NULL;
440         me->next = ContextList;
441         ContextList = me;
442         if (me->next != NULL) {
443                 me->next->prev = me;
444         }
445         ++num_sessions;
446         end_critical_section(S_SESSION_TABLE);
447         return(me);
448 }
449
450
451 /*
452  * The following functions implement output buffering. If the kernel supplies
453  * native TCP buffering (Linux & *BSD), use that; otherwise, emulate it with
454  * user-space buffering.
455  */
456 #ifdef TCP_CORK
457 #       define HAVE_TCP_BUFFERING
458 #else
459 #       ifdef TCP_NOPUSH
460 #               define HAVE_TCP_BUFFERING
461 #               define TCP_CORK TCP_NOPUSH
462 #       endif
463 #endif
464
465
466 #ifdef HAVE_TCP_BUFFERING
467 static unsigned on = 1, off = 0;
468 void buffer_output(void) {
469         struct CitContext *ctx = MyContext();
470         setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
471         ctx->buffering = 1;
472 }
473
474 void unbuffer_output(void) {
475         struct CitContext *ctx = MyContext();
476         setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
477         ctx->buffering = 0;
478 }
479
480 void flush_output(void) {
481         struct CitContext *ctx = MyContext();
482         setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
483         setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
484 }
485 #else
486 void buffer_output(void) {
487         if (CC->buffering == 0) {
488                 CC->buffering = 1;
489                 CC->buffer_len = 0;
490                 CC->output_buffer = malloc(SIZ);
491         }
492 }
493
494 void flush_output(void) {
495         if (CC->buffering == 1) {
496                 client_write(CC->output_buffer, CC->buffer_len);
497                 CC->buffer_len = 0;
498         }
499 }
500
501 void unbuffer_output(void) {
502         if (CC->buffering == 1) {
503                 CC->buffering = 0;
504                 /* We don't call flush_output because we can't. */
505                 client_write(CC->output_buffer, CC->buffer_len);
506                 CC->buffer_len = 0;
507                 free(CC->output_buffer);
508                 CC->output_buffer = NULL;
509         }
510 }
511 #endif
512
513
514
515 /*
516  * client_write()   ...    Send binary data to the client.
517  */
518 void client_write(char *buf, int nbytes)
519 {
520         int bytes_written = 0;
521         int retval;
522 #ifndef HAVE_TCP_BUFFERING
523         int old_buffer_len = 0;
524 #endif
525
526         if (CC->redirect_buffer != NULL) {
527                 if ((CC->redirect_len + nbytes + 2) >= CC->redirect_alloc) {
528                         CC->redirect_alloc = (CC->redirect_alloc * 2) + nbytes;
529                         CC->redirect_buffer = realloc(CC->redirect_buffer,
530                                                 CC->redirect_alloc);
531                 }
532                 memcpy(&CC->redirect_buffer[CC->redirect_len], buf, nbytes);
533                 CC->redirect_len += nbytes;
534                 CC->redirect_buffer[CC->redirect_len] = 0;
535                 return;
536         }
537
538 #ifndef HAVE_TCP_BUFFERING
539         /* If we're buffering for later, do that now. */
540         if (CC->buffering) {
541                 old_buffer_len = CC->buffer_len;
542                 CC->buffer_len += nbytes;
543                 CC->output_buffer = realloc(CC->output_buffer, CC->buffer_len);
544                 memcpy(&CC->output_buffer[old_buffer_len], buf, nbytes);
545                 return;
546         }
547 #endif
548
549         /* Ok, at this point we're not buffering.  Go ahead and write. */
550
551 #ifdef HAVE_OPENSSL
552         if (CC->redirect_ssl) {
553                 client_write_ssl(buf, nbytes);
554                 return;
555         }
556 #endif
557
558         while (bytes_written < nbytes) {
559                 retval = write(CC->client_socket, &buf[bytes_written],
560                         nbytes - bytes_written);
561                 if (retval < 1) {
562                         lprintf(CTDL_ERR,
563                                 "client_write(%d bytes) failed: %s (%d)\n",
564                                 nbytes - bytes_written,
565                                 strerror(errno), errno);
566                         CC->kill_me = 1;
567                         return;
568                 }
569                 bytes_written = bytes_written + retval;
570         }
571 }
572
573
574 /*
575  * cprintf()  ...   Send formatted printable data to the client.   It is
576  *                implemented in terms of client_write() but remains in
577  *                sysdep.c in case we port to somewhere without va_args...
578  */
579 void cprintf(const char *format, ...) {   
580         va_list arg_ptr;   
581         char buf[1024];   
582    
583         va_start(arg_ptr, format);   
584         if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
585                 buf[sizeof buf - 2] = '\n';
586         client_write(buf, strlen(buf)); 
587         va_end(arg_ptr);
588 }   
589
590
591 /*
592  * Read data from the client socket.
593  * Return values are:
594  *      1       Requested number of bytes has been read.
595  *      0       Request timed out.
596  *      -1      The socket is broken.
597  * If the socket breaks, the session will be terminated.
598  */
599 int client_read_to(char *buf, int bytes, int timeout)
600 {
601         int len,rlen;
602         fd_set rfds;
603         struct timeval tv;
604         int retval;
605
606 #ifdef HAVE_OPENSSL
607         if (CC->redirect_ssl) {
608                 return (client_read_ssl(buf, bytes, timeout));
609         }
610 #endif
611         len = 0;
612         while(len<bytes) {
613                 FD_ZERO(&rfds);
614                 FD_SET(CC->client_socket, &rfds);
615                 tv.tv_sec = timeout;
616                 tv.tv_usec = 0;
617
618                 retval = select( (CC->client_socket)+1, 
619                                         &rfds, NULL, NULL, &tv);
620
621                 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
622                         return(0);
623                 }
624
625                 rlen = read(CC->client_socket, &buf[len], bytes-len);
626                 if (rlen<1) {
627                         /* The socket has been disconnected! */
628                         CC->kill_me = 1;
629                         return(-1);
630                 }
631                 len = len + rlen;
632         }
633         return(1);
634 }
635
636 /*
637  * Read data from the client socket with default timeout.
638  * (This is implemented in terms of client_read_to() and could be
639  * justifiably moved out of sysdep.c)
640  */
641 INLINE int client_read(char *buf, int bytes)
642 {
643         return(client_read_to(buf, bytes, config.c_sleeping));
644 }
645
646
647 /*
648  * client_getln()   ...   Get a LF-terminated line of text from the client.
649  * (This is implemented in terms of client_read() and could be
650  * justifiably moved out of sysdep.c)
651  */
652 int client_getln(char *buf, int bufsize)
653 {
654         int i, retval;
655
656         /* Read one character at a time.
657          */
658         for (i = 0;;i++) {
659                 retval = client_read(&buf[i], 1);
660                 if (retval != 1 || buf[i] == '\n' || i == (bufsize-1))
661                         break;
662         }
663
664         /* If we got a long line, discard characters until the newline.
665          */
666         if (i == (bufsize-1))
667                 while (buf[i] != '\n' && retval == 1)
668                         retval = client_read(&buf[i], 1);
669
670         /* Strip the trailing LF, and the trailing CR if present.
671          */
672         buf[i] = 0;
673         while ( (strlen(buf) > 0) && ((buf[strlen(buf)-1]==10) || (buf[strlen(buf)-1] == 13)) ) {
674                 buf[strlen(buf)-1] = 0;
675         }
676         if (retval < 0) safestrncpy(buf, "000", bufsize);
677         return(retval);
678 }
679
680
681
682 /*
683  * The system-dependent part of master_cleanup() - close the master socket.
684  */
685 void sysdep_master_cleanup(void) {
686         struct ServiceFunctionHook *serviceptr;
687
688         /*
689          * close all protocol master sockets
690          */
691         for (serviceptr = ServiceHookTable; serviceptr != NULL;
692             serviceptr = serviceptr->next ) {
693
694                 if (serviceptr->tcp_port > 0)
695                         lprintf(CTDL_INFO, "Closing listener on port %d\n",
696                                 serviceptr->tcp_port);
697
698                 if (serviceptr->sockpath != NULL)
699                         lprintf(CTDL_INFO, "Closing listener on '%s'\n",
700                                 serviceptr->sockpath);
701
702                 close(serviceptr->msock);
703
704                 /* If it's a Unix domain socket, remove the file. */
705                 if (serviceptr->sockpath != NULL) {
706                         unlink(serviceptr->sockpath);
707                 }
708         }
709 }
710
711
712 /*
713  * Terminate another session.
714  * (This could justifiably be moved out of sysdep.c because it
715  * no longer does anything that is system-dependent.)
716  */
717 void kill_session(int session_to_kill) {
718         struct CitContext *ptr;
719
720         begin_critical_section(S_SESSION_TABLE);
721         for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
722                 if (ptr->cs_pid == session_to_kill) {
723                         ptr->kill_me = 1;
724                 }
725         }
726         end_critical_section(S_SESSION_TABLE);
727 }
728
729
730
731
732 /*
733  * Start running as a daemon.
734  */
735 void start_daemon(int unused) {
736         close(0); close(1); close(2);
737         if (fork()) exit(0);
738         setsid();
739         signal(SIGHUP,SIG_IGN);
740         signal(SIGINT,SIG_IGN);
741         signal(SIGQUIT,SIG_IGN);
742 }
743
744
745
746 /*
747  * Generic routine to convert a login name to a full name (gecos)
748  * Returns nonzero if a conversion took place
749  */
750 int convert_login(char NameToConvert[]) {
751         struct passwd *pw;
752         int a;
753
754         pw = getpwnam(NameToConvert);
755         if (pw == NULL) {
756                 return(0);
757         }
758         else {
759                 strcpy(NameToConvert, pw->pw_gecos);
760                 for (a=0; a<strlen(NameToConvert); ++a) {
761                         if (NameToConvert[a] == ',') NameToConvert[a] = 0;
762                 }
763                 return(1);
764         }
765 }
766
767 struct worker_node *worker_list = NULL;
768
769
770 /*
771  * create a worker thread. this function must always be called from within
772  * an S_WORKER_LIST critical section!
773  */
774 void create_worker(void) {
775         int ret;
776         struct worker_node *n;
777         pthread_attr_t attr;
778
779         n = malloc(sizeof(struct worker_node));
780         if (n == NULL) {
781                 lprintf(CTDL_EMERG, "can't allocate worker_node, exiting\n");
782                 time_to_die = -1;
783                 return;
784         }
785
786         if ((ret = pthread_attr_init(&attr))) {
787                 lprintf(CTDL_EMERG, "pthread_attr_init: %s\n", strerror(ret));
788                 time_to_die = -1;
789                 return;
790         }
791
792         /* Our per-thread stacks need to be bigger than the default size,
793          * otherwise the MIME parser crashes on FreeBSD, and the IMAP service
794          * crashes on 64-bit Linux.
795          */
796         if ((ret = pthread_attr_setstacksize(&attr, THREADSTACKSIZE))) {
797                 lprintf(CTDL_EMERG, "pthread_attr_setstacksize: %s\n",
798                         strerror(ret));
799                 time_to_die = -1;
800                 pthread_attr_destroy(&attr);
801                 return;
802         }
803
804         if ((ret = pthread_create(&n->tid, &attr, worker_thread, NULL) != 0))
805         {
806
807                 lprintf(CTDL_ALERT, "Can't create worker thread: %s\n",
808                         strerror(ret));
809         }
810
811         n->next = worker_list;
812         worker_list = n;
813         pthread_attr_destroy(&attr);
814 }
815
816
817 /*
818  * Create the indexer thread and begin its operation.
819  * Then create the checkpoint thread and begin its operation.
820  */
821 void create_maintenance_threads(void) {
822         int ret;
823         pthread_attr_t attr;
824
825         if ((ret = pthread_attr_init(&attr))) {
826                 lprintf(CTDL_EMERG, "pthread_attr_init: %s\n", strerror(ret));
827                 time_to_die = -1;
828                 return;
829         }
830
831         /* Our per-thread stacks need to be bigger than the default size,
832          * otherwise the MIME parser crashes on FreeBSD, and the IMAP service
833          * crashes on 64-bit Linux.
834          */
835         if ((ret = pthread_attr_setstacksize(&attr, THREADSTACKSIZE))) {
836                 lprintf(CTDL_EMERG, "pthread_attr_setstacksize: %s\n",
837                         strerror(ret));
838                 time_to_die = -1;
839                 pthread_attr_destroy(&attr);
840                 return;
841         }
842
843         if ((ret = pthread_create(&indexer_thread_tid, &attr, indexer_thread, NULL) != 0)) {
844                 lprintf(CTDL_ALERT, "Can't create thread: %s\n", strerror(ret));
845         }
846
847         if ((ret = pthread_create(&checkpoint_thread_tid, &attr, checkpoint_thread, NULL) != 0)) {
848                 lprintf(CTDL_ALERT, "Can't create thread: %s\n", strerror(ret));
849         }
850
851         pthread_attr_destroy(&attr);
852 }
853
854
855
856 /*
857  * Purge all sessions which have the 'kill_me' flag set.
858  * This function has code to prevent it from running more than once every
859  * few seconds, because running it after every single unbind would waste a lot
860  * of CPU time and keep the context list locked too much.  To force it to run
861  * anyway, set "force" to nonzero.
862  *
863  *
864  * After that's done, we raise the size of the worker thread pool
865  * if such an action is appropriate.
866  */
867 void dead_session_purge(int force) {
868         struct CitContext *ptr;         /* general-purpose utility pointer */
869         struct CitContext *rem = NULL;  /* list of sessions to be destroyed */
870
871         if (force == 0) {
872                 if ( (time(NULL) - last_purge) < 5 ) {
873                         return; /* Too soon, go away */
874                 }
875         }
876         time(&last_purge);
877
878         begin_critical_section(S_SESSION_TABLE);
879         for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
880                 if ( (ptr->state == CON_IDLE) && (ptr->kill_me) ) {
881
882                         /* Remove the session from the active list */
883                         if (ptr->prev) {
884                                 ptr->prev->next = ptr->next;
885                         }
886                         else {
887                                 ContextList = ptr->next;
888                         }
889                         if (ptr->next) {
890                                 ptr->next->prev = ptr->prev;
891                         }
892
893                         --num_sessions;
894
895                         /* And put it on our to-be-destroyed list */
896                         ptr->next = rem;
897                         rem = ptr;
898
899                 }
900         }
901         end_critical_section(S_SESSION_TABLE);
902
903         /* Now that we no longer have the session list locked, we can take
904          * our time and destroy any sessions on the to-be-killed list, which
905          * is allocated privately on this thread's stack.
906          */
907         while (rem != NULL) {
908                 lprintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
909                 RemoveContext(rem);
910                 ptr = rem;
911                 rem = rem->next;
912                 free(ptr);
913         }
914
915         /* Raise the size of the worker thread pool if necessary. */
916         if ( (num_sessions > num_threads)
917            && (num_threads < config.c_max_workers) ) {
918                 begin_critical_section(S_WORKER_LIST);
919                 create_worker();
920                 end_critical_section(S_WORKER_LIST);
921         }
922 }
923
924
925
926
927
928 /*
929  * masterCC is the context we use when not attached to a session.  This
930  * function initializes it.
931  */
932 void InitializeMasterCC(void) {
933         memset(&masterCC, 0, sizeof(struct CitContext));
934         masterCC.internal_pgm = 1;
935         masterCC.cs_pid = 0;
936 }
937
938
939
940
941
942
943 /*
944  * Bind a thread to a context.  (It's inline merely to speed things up.)
945  */
946 INLINE void become_session(struct CitContext *which_con) {
947         pthread_setspecific(MyConKey, (void *)which_con );
948 }
949
950
951
952 /* 
953  * This loop just keeps going and going and going...
954  */     
955 void *worker_thread(void *arg) {
956         int i;
957         int highest;
958         struct CitContext *ptr;
959         struct CitContext *bind_me = NULL;
960         fd_set readfds;
961         int retval = 0;
962         struct CitContext *con= NULL;   /* Temporary context pointer */
963         struct ServiceFunctionHook *serviceptr;
964         int ssock;                      /* Descriptor for client socket */
965         struct timeval tv;
966         int force_purge = 0;
967         int m;
968
969         num_threads++;
970
971         cdb_allocate_tsd();
972
973         while (!time_to_die) {
974
975                 /* make doubly sure we're not holding any stale db handles
976                  * which might cause a deadlock.
977                  */
978                 cdb_check_handles();
979 do_select:      force_purge = 0;
980                 bind_me = NULL;         /* Which session shall we handle? */
981
982                 /* Initialize the fdset. */
983                 FD_ZERO(&readfds);
984                 highest = 0;
985
986                 begin_critical_section(S_SESSION_TABLE);
987                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
988                         if (ptr->state == CON_IDLE) {
989                                 FD_SET(ptr->client_socket, &readfds);
990                                 if (ptr->client_socket > highest)
991                                         highest = ptr->client_socket;
992                         }
993                         if ((bind_me == NULL) && (ptr->state == CON_READY)) {
994                                 bind_me = ptr;
995                                 ptr->state = CON_EXECUTING;
996                         }
997                 }
998                 end_critical_section(S_SESSION_TABLE);
999
1000                 if (bind_me) {
1001                         goto SKIP_SELECT;
1002                 }
1003
1004                 /* If we got this far, it means that there are no sessions
1005                  * which a previous thread marked for attention, so we go
1006                  * ahead and get ready to select().
1007                  */
1008
1009                 /* First, add the various master sockets to the fdset. */
1010                 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1011                 serviceptr = serviceptr->next ) {
1012                         m = serviceptr->msock;
1013                         FD_SET(m, &readfds);
1014                         if (m > highest) {
1015                                 highest = m;
1016                         }
1017                 }
1018
1019                 if (!time_to_die) {
1020                         tv.tv_sec = 1;          /* wake up every second if no input */
1021                         tv.tv_usec = 0;
1022                         retval = select(highest + 1, &readfds, NULL, NULL, &tv);
1023                 }
1024
1025                 if (time_to_die) return(NULL);
1026
1027                 /* Now figure out who made this select() unblock.
1028                  * First, check for an error or exit condition.
1029                  */
1030                 if (retval < 0) {
1031                         if (errno == EBADF) {
1032                                 lprintf(CTDL_NOTICE, "select() failed: (%s)\n",
1033                                         strerror(errno));
1034                                 goto do_select;
1035                         }
1036                         if (errno != EINTR) {
1037                                 lprintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1038                                 time_to_die = 1;
1039                         } else if (!time_to_die)
1040                                 goto do_select;
1041                 }
1042
1043                 /* Next, check to see if it's a new client connecting
1044                  * on a master socket.
1045                  */
1046                 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1047                      serviceptr = serviceptr->next ) {
1048
1049                         if (FD_ISSET(serviceptr->msock, &readfds)) {
1050                                 ssock = accept(serviceptr->msock, NULL, 0);
1051                                 if (ssock >= 0) {
1052                                         lprintf(CTDL_DEBUG,
1053                                                 "New client socket %d\n",
1054                                                 ssock);
1055
1056                                         /* The master socket is non-blocking but the client
1057                                          * sockets need to be blocking, otherwise certain
1058                                          * operations barf on FreeBSD.  Not a fatal error.
1059                                          */
1060                                         if (fcntl(ssock, F_SETFL, 0) < 0) {
1061                                                 lprintf(CTDL_EMERG,
1062                                                         "citserver: Can't set socket to blocking: %s\n",
1063                                                         strerror(errno));
1064                                         }
1065
1066                                         /* New context will be created already
1067                                          * set up in the CON_EXECUTING state.
1068                                          */
1069                                         con = CreateNewContext();
1070
1071                                         /* Assign our new socket number to it. */
1072                                         con->client_socket = ssock;
1073                                         con->h_command_function =
1074                                                 serviceptr->h_command_function;
1075                                         con->h_async_function =
1076                                                 serviceptr->h_async_function;
1077
1078                                         /* Determine whether it's a local socket */
1079                                         if (serviceptr->sockpath != NULL)
1080                                                 con->is_local_socket = 1;
1081         
1082                                         /* Set the SO_REUSEADDR socket option */
1083                                         i = 1;
1084                                         setsockopt(ssock, SOL_SOCKET,
1085                                                 SO_REUSEADDR,
1086                                                 &i, sizeof(i));
1087
1088                                         become_session(con);
1089                                         begin_session(con);
1090                                         serviceptr->h_greeting_function();
1091                                         become_session(NULL);
1092                                         con->state = CON_IDLE;
1093                                         goto do_select;
1094                                 }
1095                         }
1096                 }
1097
1098                 /* It must be a client socket.  Find a context that has data
1099                  * waiting on its socket *and* is in the CON_IDLE state.  Any
1100                  * active sockets other than our chosen one are marked as
1101                  * CON_READY so the next thread that comes around can just bind
1102                  * to one without having to select() again.
1103                  */
1104                 begin_critical_section(S_SESSION_TABLE);
1105                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1106                         if ( (FD_ISSET(ptr->client_socket, &readfds))
1107                            && (ptr->state != CON_EXECUTING) ) {
1108                                 ptr->input_waiting = 1;
1109                                 if (!bind_me) {
1110                                         bind_me = ptr;  /* I choose you! */
1111                                         bind_me->state = CON_EXECUTING;
1112                                 }
1113                                 else {
1114                                         ptr->state = CON_READY;
1115                                 }
1116                         }
1117                 }
1118                 end_critical_section(S_SESSION_TABLE);
1119
1120 SKIP_SELECT:
1121                 /* We're bound to a session */
1122                 if (bind_me != NULL) {
1123                         become_session(bind_me);
1124
1125                         /* If the client has sent a command, execute it. */
1126                         if (CC->input_waiting) {
1127                                 CC->h_command_function();
1128                                 CC->input_waiting = 0;
1129                         }
1130
1131                         /* If there are asynchronous messages waiting and the
1132                          * client supports it, do those now */
1133                         if ((CC->is_async) && (CC->async_waiting)
1134                            && (CC->h_async_function != NULL)) {
1135                                 CC->h_async_function();
1136                                 CC->async_waiting = 0;
1137                         }
1138                         
1139                         force_purge = CC->kill_me;
1140                         become_session(NULL);
1141                         bind_me->state = CON_IDLE;
1142                 }
1143
1144                 dead_session_purge(force_purge);
1145                 do_housekeeping();
1146                 check_sched_shutdown();
1147         }
1148
1149         /* If control reaches this point, the server is shutting down */        
1150         return(NULL);
1151 }
1152
1153
1154
1155
1156 /*
1157  * SyslogFacility()
1158  * Translate text facility name to syslog.h defined value.
1159  */
1160 int SyslogFacility(char *name)
1161 {
1162         int i;
1163         struct
1164         {
1165                 int facility;
1166                 char *name;
1167         }   facTbl[] =
1168         {
1169                 {   LOG_KERN,   "kern"          },
1170                 {   LOG_USER,   "user"          },
1171                 {   LOG_MAIL,   "mail"          },
1172                 {   LOG_DAEMON, "daemon"        },
1173                 {   LOG_AUTH,   "auth"          },
1174                 {   LOG_SYSLOG, "syslog"        },
1175                 {   LOG_LPR,    "lpr"           },
1176                 {   LOG_NEWS,   "news"          },
1177                 {   LOG_UUCP,   "uucp"          },
1178                 {   LOG_LOCAL0, "local0"        },
1179                 {   LOG_LOCAL1, "local1"        },
1180                 {   LOG_LOCAL2, "local2"        },
1181                 {   LOG_LOCAL3, "local3"        },
1182                 {   LOG_LOCAL4, "local4"        },
1183                 {   LOG_LOCAL5, "local5"        },
1184                 {   LOG_LOCAL6, "local6"        },
1185                 {   LOG_LOCAL7, "local7"        },
1186                 {   0,            NULL          }
1187         };
1188         for(i = 0; facTbl[i].name != NULL; i++) {
1189                 if(!strcasecmp(name, facTbl[i].name))
1190                         return facTbl[i].facility;
1191         }
1192         enable_syslog = 0;
1193         return LOG_DAEMON;
1194 }
1195
1196
1197 /********** MEM CHEQQER ***********/
1198
1199 #ifdef DEBUG_MEMORY_LEAKS
1200
1201 #undef malloc
1202 #undef realloc
1203 #undef strdup
1204 #undef free
1205
1206 void *tracked_malloc(size_t size, char *file, int line) {
1207         struct igheap *thisheap;
1208         void *block;
1209
1210         block = malloc(size);
1211         if (block == NULL) return(block);
1212
1213         thisheap = malloc(sizeof(struct igheap));
1214         if (thisheap == NULL) {
1215                 free(block);
1216                 return(NULL);
1217         }
1218
1219         thisheap->block = block;
1220         strcpy(thisheap->file, file);
1221         thisheap->line = line;
1222         
1223         begin_critical_section(S_DEBUGMEMLEAKS);
1224         thisheap->next = igheap;
1225         igheap = thisheap;
1226         end_critical_section(S_DEBUGMEMLEAKS);
1227
1228         return(block);
1229 }
1230
1231
1232 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
1233         struct igheap *thisheap;
1234         void *block;
1235
1236         block = realloc(ptr, size);
1237         if (block == NULL) return(block);
1238
1239         thisheap = malloc(sizeof(struct igheap));
1240         if (thisheap == NULL) {
1241                 free(block);
1242                 return(NULL);
1243         }
1244
1245         thisheap->block = block;
1246         strcpy(thisheap->file, file);
1247         thisheap->line = line;
1248         
1249         begin_critical_section(S_DEBUGMEMLEAKS);
1250         thisheap->next = igheap;
1251         igheap = thisheap;
1252         end_critical_section(S_DEBUGMEMLEAKS);
1253
1254         return(block);
1255 }
1256
1257
1258
1259 void tracked_free(void *ptr) {
1260         struct igheap *thisheap;
1261         struct igheap *trash;
1262
1263         free(ptr);
1264
1265         if (igheap == NULL) return;
1266         begin_critical_section(S_DEBUGMEMLEAKS);
1267         for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1268                 if (thisheap->next != NULL) {
1269                         if (thisheap->next->block == ptr) {
1270                                 trash = thisheap->next;
1271                                 thisheap->next = thisheap->next->next;
1272                                 free(trash);
1273                         }
1274                 }
1275         }
1276         if (igheap->block == ptr) {
1277                 trash = igheap;
1278                 igheap = igheap->next;
1279                 free(trash);
1280         }
1281         end_critical_section(S_DEBUGMEMLEAKS);
1282 }
1283
1284 char *tracked_strdup(const char *s, char *file, int line) {
1285         char *ptr;
1286
1287         if (s == NULL) return(NULL);
1288         ptr = tracked_malloc(strlen(s) + 1, file, line);
1289         if (ptr == NULL) return(NULL);
1290         strncpy(ptr, s, strlen(s));
1291         return(ptr);
1292 }
1293
1294 void dump_heap(void) {
1295         struct igheap *thisheap;
1296
1297         for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1298                 lprintf(CTDL_CRIT, "UNFREED: %30s : %d\n",
1299                         thisheap->file, thisheap->line);
1300         }
1301 }
1302
1303 #endif /*  DEBUG_MEMORY_LEAKS */