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