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