b71c068a2819e4f359d47c1b64109f46bf346c90
[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
103 int syslog_facility = (-1);
104 int enable_syslog = 0;
105 extern int running_as_daemon;
106
107 /*
108  * lprintf()  ...   Write logging information
109  */
110 void lprintf(enum LogLevel loglevel, const char *format, ...) {   
111         va_list arg_ptr;
112
113         if (enable_syslog) {
114                 va_start(arg_ptr, format);
115                         vsyslog(loglevel, format, arg_ptr);
116                 va_end(arg_ptr);
117         }
118
119         /* stderr output code */
120         if (enable_syslog || running_as_daemon) return;
121
122         /* if we run in forground and syslog is disabled, log to terminal */
123         if (loglevel <= verbosity) { 
124                 struct timeval tv;
125                 struct tm tim;
126                 time_t unixtime;
127
128                 gettimeofday(&tv, NULL);
129                 /* Promote to time_t; types differ on some OSes (like darwin) */
130                 unixtime = tv.tv_sec;
131                 localtime_r(&unixtime, &tim);
132                 if (CC->cs_pid != 0) {
133                         fprintf(stderr,
134                                 "%04d/%02d/%02d %2d:%02d:%02d.%06ld [%3d] ",
135                                 tim.tm_year + 1900, tim.tm_mon + 1,
136                                 tim.tm_mday, tim.tm_hour, tim.tm_min,
137                                 tim.tm_sec, (long)tv.tv_usec,
138                                 CC->cs_pid);
139                 } else {
140                         fprintf(stderr,
141                                 "%04d/%02d/%02d %2d:%02d:%02d.%06ld ",
142                                 tim.tm_year + 1900, tim.tm_mon + 1,
143                                 tim.tm_mday, tim.tm_hour, tim.tm_min,
144                                 tim.tm_sec, (long)tv.tv_usec);
145                 }
146                 va_start(arg_ptr, format);   
147                         vfprintf(stderr, format, arg_ptr);   
148                 va_end(arg_ptr);   
149                 fflush(stderr);
150         }
151 }   
152
153
154
155 /*
156  * Signal handler to shut down the server.
157  */
158
159 volatile int time_to_die = 0;
160
161 static RETSIGTYPE signal_cleanup(int signum) {
162         lprintf(CTDL_DEBUG, "Caught signal %d; shutting down.\n", signum);
163         time_to_die = 1;
164         master_cleanup(signum);
165 }
166
167
168 /*
169  * Some initialization stuff...
170  */
171 void init_sysdep(void) {
172         int i;
173         sigset_t set;
174
175         /* Avoid vulnerabilities related to FD_SETSIZE if we can. */
176 #ifdef FD_SETSIZE
177 #ifdef RLIMIT_NOFILE
178         struct rlimit rl;
179         getrlimit(RLIMIT_NOFILE, &rl);
180         rl.rlim_cur = FD_SETSIZE;
181         rl.rlim_max = FD_SETSIZE;
182         setrlimit(RLIMIT_NOFILE, &rl);
183 #endif
184 #endif
185
186         /* If we've got OpenSSL, we're going to use it. */
187 #ifdef HAVE_OPENSSL
188         init_ssl();
189 #endif
190
191         /* Set up a bunch of semaphores to be used for critical sections */
192         for (i=0; i<MAX_SEMAPHORES; ++i) {
193                 pthread_mutex_init(&Critters[i], NULL);
194         }
195
196         /*
197          * Set up a place to put thread-specific data.
198          * We only need a single pointer per thread - it points to the
199          * CitContext structure (in the ContextList linked list) of the
200          * session to which the calling thread is currently bound.
201          */
202         if (pthread_key_create(&MyConKey, NULL) != 0) {
203                 lprintf(CTDL_CRIT, "Can't create TSD key: %s\n",
204                         strerror(errno));
205         }
206
207         /*
208          * The action for unexpected signals and exceptions should be to
209          * call signal_cleanup() to gracefully shut down the server.
210          */
211         sigemptyset(&set);
212         sigaddset(&set, SIGINT);
213         sigaddset(&set, SIGQUIT);
214         sigaddset(&set, SIGHUP);
215         sigaddset(&set, SIGTERM);
216         // sigaddset(&set, SIGSEGV);    commented out because
217         // sigaddset(&set, SIGILL);     we want core dumps
218         // sigaddset(&set, SIGBUS);
219         sigprocmask(SIG_UNBLOCK, &set, NULL);
220
221         signal(SIGINT, signal_cleanup);
222         signal(SIGQUIT, signal_cleanup);
223         signal(SIGHUP, signal_cleanup);
224         signal(SIGTERM, signal_cleanup);
225         // signal(SIGSEGV, signal_cleanup);     commented out because
226         // signal(SIGILL, signal_cleanup);      we want core dumps
227         // signal(SIGBUS, signal_cleanup);
228
229         /*
230          * Do not shut down the server on broken pipe signals, otherwise the
231          * whole Citadel service would come down whenever a single client
232          * socket breaks.
233          */
234         signal(SIGPIPE, SIG_IGN);
235 }
236
237
238 /*
239  * Obtain a semaphore lock to begin a critical section.
240  */
241 void begin_critical_section(int which_one)
242 {
243         /* lprintf(CTDL_DEBUG, "begin_critical_section(%d)\n", which_one); */
244
245         /* For all types of critical sections except those listed here,
246          * ensure nobody ever tries to do a critical section within a
247          * transaction; this could lead to deadlock.
248          */
249         if (    (which_one != S_FLOORCACHE)
250 #ifdef DEBUG_MEMORY_LEAKS
251                 && (which_one != S_DEBUGMEMLEAKS)
252 #endif
253         ) {
254                 cdb_check_handles();
255         }
256         pthread_mutex_lock(&Critters[which_one]);
257 }
258
259 /*
260  * Release a semaphore lock to end a critical section.
261  */
262 void end_critical_section(int which_one)
263 {
264         pthread_mutex_unlock(&Critters[which_one]);
265 }
266
267
268
269 /*
270  * This is a generic function to set up a master socket for listening on
271  * a TCP port.  The server shuts down if the bind fails.
272  *
273  */
274 int ig_tcp_server(char *ip_addr, int port_number, int queue_len)
275 {
276         struct sockaddr_in sin;
277         int s, i;
278         int actual_queue_len;
279
280         actual_queue_len = queue_len;
281         if (actual_queue_len < 5) actual_queue_len = 5;
282
283         memset(&sin, 0, sizeof(sin));
284         sin.sin_family = AF_INET;
285         sin.sin_port = htons((u_short)port_number);
286         if (ip_addr == NULL) {
287                 sin.sin_addr.s_addr = INADDR_ANY;
288         }
289         else {
290                 sin.sin_addr.s_addr = inet_addr(ip_addr);
291         }
292                                                                                 
293         if (sin.sin_addr.s_addr == INADDR_NONE) {
294                 sin.sin_addr.s_addr = INADDR_ANY;
295         }
296
297         s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
298
299         if (s < 0) {
300                 lprintf(CTDL_EMERG, "citserver: Can't create a socket: %s\n",
301                         strerror(errno));
302                 return(-1);
303         }
304
305         i = 1;
306         setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
307
308         if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
309                 lprintf(CTDL_EMERG, "citserver: Can't bind: %s\n",
310                         strerror(errno));
311                 close(s);
312                 return(-1);
313         }
314
315         /* set to nonblock - we need this for some obscure situations */
316         if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
317                 lprintf(CTDL_EMERG,
318                         "citserver: Can't set socket to non-blocking: %s\n",
319                         strerror(errno));
320                 close(s);
321                 return(-1);
322         }
323
324         if (listen(s, actual_queue_len) < 0) {
325                 lprintf(CTDL_EMERG, "citserver: Can't listen: %s\n",
326                         strerror(errno));
327                 close(s);
328                 return(-1);
329         }
330
331         return(s);
332 }
333
334
335
336 /*
337  * Create a Unix domain socket and listen on it
338  */
339 int ig_uds_server(char *sockpath, int queue_len)
340 {
341         struct sockaddr_un addr;
342         int s;
343         int i;
344         int actual_queue_len;
345
346         actual_queue_len = queue_len;
347         if (actual_queue_len < 5) actual_queue_len = 5;
348
349         i = unlink(sockpath);
350         if (i != 0) if (errno != ENOENT) {
351                 lprintf(CTDL_EMERG, "citserver: can't unlink %s: %s\n",
352                         sockpath, strerror(errno));
353                 return(-1);
354         }
355
356         memset(&addr, 0, sizeof(addr));
357         addr.sun_family = AF_UNIX;
358         safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
359
360         s = socket(AF_UNIX, SOCK_STREAM, 0);
361         if (s < 0) {
362                 lprintf(CTDL_EMERG, "citserver: Can't create a socket: %s\n",
363                         strerror(errno));
364                 return(-1);
365         }
366
367         if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
368                 lprintf(CTDL_EMERG, "citserver: Can't bind: %s\n",
369                         strerror(errno));
370                 return(-1);
371         }
372
373         /* set to nonblock - we need this for some obscure situations */
374         if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
375                 lprintf(CTDL_EMERG,
376                         "citserver: Can't set socket to non-blocking: %s\n",
377                         strerror(errno));
378                 close(s);
379                 return(-1);
380         }
381
382         if (listen(s, actual_queue_len) < 0) {
383                 lprintf(CTDL_EMERG, "citserver: Can't listen: %s\n",
384                         strerror(errno));
385                 return(-1);
386         }
387
388         chmod(sockpath, 0777);
389         return(s);
390 }
391
392
393
394 /*
395  * Return a pointer to the CitContext structure bound to the thread which
396  * called this function.  If there's no such binding (for example, if it's
397  * called by the housekeeper thread) then a generic 'master' CC is returned.
398  *
399  * This function is used *VERY* frequently and must be kept small.
400  */
401 struct CitContext *MyContext(void) {
402
403         register struct CitContext *c;
404
405         return ((c = (struct CitContext *) pthread_getspecific(MyConKey),
406                 c == NULL) ? &masterCC : c
407         );
408 }
409
410
411 /*
412  * Initialize a new context and place it in the list.  The session number
413  * used to be the PID (which is why it's called cs_pid), but that was when we
414  * had one process per session.  Now we just assign them sequentially, starting
415  * at 1 (don't change it to 0 because masterCC uses 0).
416  */
417 struct CitContext *CreateNewContext(void) {
418         struct CitContext *me;
419         static int next_pid = 0;
420
421         me = (struct CitContext *) malloc(sizeof(struct CitContext));
422         if (me == NULL) {
423                 lprintf(CTDL_ALERT, "citserver: can't allocate memory!!\n");
424                 return NULL;
425         }
426         memset(me, 0, sizeof(struct CitContext));
427
428         /* The new context will be created already in the CON_EXECUTING state
429          * in order to prevent another thread from grabbing it while it's
430          * being set up.
431          */
432         me->state = CON_EXECUTING;
433
434         /*
435          * Generate a unique session number and insert this context into
436          * the list.
437          */
438         begin_critical_section(S_SESSION_TABLE);
439         me->cs_pid = ++next_pid;
440         me->prev = NULL;
441         me->next = ContextList;
442         ContextList = me;
443         if (me->next != NULL) {
444                 me->next->prev = me;
445         }
446         ++num_sessions;
447         end_critical_section(S_SESSION_TABLE);
448         return(me);
449 }
450
451
452 /*
453  * The following functions implement output buffering. If the kernel supplies
454  * native TCP buffering (Linux & *BSD), use that; otherwise, emulate it with
455  * user-space buffering.
456  */
457 #ifdef TCP_CORK
458 #       define HAVE_TCP_BUFFERING
459 #else
460 #       ifdef TCP_NOPUSH
461 #               define HAVE_TCP_BUFFERING
462 #               define TCP_CORK TCP_NOPUSH
463 #       endif
464 #endif
465
466
467 #ifdef HAVE_TCP_BUFFERING
468 static unsigned on = 1, off = 0;
469 void buffer_output(void) {
470         struct CitContext *ctx = MyContext();
471         setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
472         ctx->buffering = 1;
473 }
474
475 void unbuffer_output(void) {
476         struct CitContext *ctx = MyContext();
477         setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
478         ctx->buffering = 0;
479 }
480
481 void flush_output(void) {
482         struct CitContext *ctx = MyContext();
483         setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
484         setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
485 }
486 #else
487 void buffer_output(void) {
488         if (CC->buffering == 0) {
489                 CC->buffering = 1;
490                 CC->buffer_len = 0;
491                 CC->output_buffer = malloc(SIZ);
492         }
493 }
494
495 void flush_output(void) {
496         if (CC->buffering == 1) {
497                 client_write(CC->output_buffer, CC->buffer_len);
498                 CC->buffer_len = 0;
499         }
500 }
501
502 void unbuffer_output(void) {
503         if (CC->buffering == 1) {
504                 CC->buffering = 0;
505                 /* We don't call flush_output because we can't. */
506                 client_write(CC->output_buffer, CC->buffer_len);
507                 CC->buffer_len = 0;
508                 free(CC->output_buffer);
509                 CC->output_buffer = NULL;
510         }
511 }
512 #endif
513
514
515
516 /*
517  * client_write()   ...    Send binary data to the client.
518  */
519 void client_write(char *buf, int nbytes)
520 {
521         int bytes_written = 0;
522         int retval;
523 #ifndef HAVE_TCP_BUFFERING
524         int old_buffer_len = 0;
525 #endif
526
527         if (CC->redirect_buffer != NULL) {
528                 if ((CC->redirect_len + nbytes + 2) >= CC->redirect_alloc) {
529                         CC->redirect_alloc = (CC->redirect_alloc * 2) + nbytes;
530                         CC->redirect_buffer = realloc(CC->redirect_buffer,
531                                                 CC->redirect_alloc);
532                 }
533                 memcpy(&CC->redirect_buffer[CC->redirect_len], buf, nbytes);
534                 CC->redirect_len += nbytes;
535                 CC->redirect_buffer[CC->redirect_len] = 0;
536                 return;
537         }
538
539 #ifndef HAVE_TCP_BUFFERING
540         /* If we're buffering for later, do that now. */
541         if (CC->buffering) {
542                 old_buffer_len = CC->buffer_len;
543                 CC->buffer_len += nbytes;
544                 CC->output_buffer = realloc(CC->output_buffer, CC->buffer_len);
545                 memcpy(&CC->output_buffer[old_buffer_len], buf, nbytes);
546                 return;
547         }
548 #endif
549
550         /* Ok, at this point we're not buffering.  Go ahead and write. */
551
552 #ifdef HAVE_OPENSSL
553         if (CC->redirect_ssl) {
554                 client_write_ssl(buf, nbytes);
555                 return;
556         }
557 #endif
558
559         while (bytes_written < nbytes) {
560                 retval = write(CC->client_socket, &buf[bytes_written],
561                         nbytes - bytes_written);
562                 if (retval < 1) {
563                         lprintf(CTDL_ERR, "client_write() failed: %s\n",
564                                 strerror(errno));
565                         CC->kill_me = 1;
566                         return;
567                 }
568                 bytes_written = bytes_written + retval;
569         }
570 }
571
572
573 /*
574  * cprintf()  ...   Send formatted printable data to the client.   It is
575  *                implemented in terms of client_write() but remains in
576  *                sysdep.c in case we port to somewhere without va_args...
577  */
578 void cprintf(const char *format, ...) {   
579         va_list arg_ptr;   
580         char buf[1024];   
581    
582         va_start(arg_ptr, format);   
583         if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
584                 buf[sizeof buf - 2] = '\n';
585         client_write(buf, strlen(buf)); 
586         va_end(arg_ptr);
587 }   
588
589
590 /*
591  * Read data from the client socket.
592  * Return values are:
593  *      1       Requested number of bytes has been read.
594  *      0       Request timed out.
595  *      -1      The socket is broken.
596  * If the socket breaks, the session will be terminated.
597  */
598 int client_read_to(char *buf, int bytes, int timeout)
599 {
600         int len,rlen;
601         fd_set rfds;
602         struct timeval tv;
603         int retval;
604
605 #ifdef HAVE_OPENSSL
606         if (CC->redirect_ssl) {
607                 return (client_read_ssl(buf, bytes, timeout));
608         }
609 #endif
610         len = 0;
611         while(len<bytes) {
612                 FD_ZERO(&rfds);
613                 FD_SET(CC->client_socket, &rfds);
614                 tv.tv_sec = timeout;
615                 tv.tv_usec = 0;
616
617                 retval = select( (CC->client_socket)+1, 
618                                         &rfds, NULL, NULL, &tv);
619
620                 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
621                         return(0);
622                 }
623
624                 rlen = read(CC->client_socket, &buf[len], bytes-len);
625                 if (rlen<1) {
626                         lprintf(CTDL_ERR, "client_read() failed: %s\n",
627                                 strerror(errno));
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  */
819 void create_indexer_thread(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         {
843                 lprintf(CTDL_ALERT, "Can't create indexer thread: %s\n",
844                         strerror(ret));
845         }
846
847         pthread_attr_destroy(&attr);
848 }
849
850
851
852 /*
853  * Purge all sessions which have the 'kill_me' flag set.
854  * This function has code to prevent it from running more than once every
855  * few seconds, because running it after every single unbind would waste a lot
856  * of CPU time and keep the context list locked too much.  To force it to run
857  * anyway, set "force" to nonzero.
858  *
859  *
860  * After that's done, we raise the size of the worker thread pool
861  * if such an action is appropriate.
862  */
863 void dead_session_purge(int force) {
864         struct CitContext *ptr;         /* general-purpose utility pointer */
865         struct CitContext *rem = NULL;  /* list of sessions to be destroyed */
866
867         if (force == 0) {
868                 if ( (time(NULL) - last_purge) < 5 ) {
869                         return; /* Too soon, go away */
870                 }
871         }
872         time(&last_purge);
873
874         begin_critical_section(S_SESSION_TABLE);
875         for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
876                 if ( (ptr->state == CON_IDLE) && (ptr->kill_me) ) {
877
878                         /* Remove the session from the active list */
879                         if (ptr->prev) {
880                                 ptr->prev->next = ptr->next;
881                         }
882                         else {
883                                 ContextList = ptr->next;
884                         }
885                         if (ptr->next) {
886                                 ptr->next->prev = ptr->prev;
887                         }
888
889                         --num_sessions;
890
891                         /* And put it on our to-be-destroyed list */
892                         ptr->next = rem;
893                         rem = ptr;
894
895                 }
896         }
897         end_critical_section(S_SESSION_TABLE);
898
899         /* Now that we no longer have the session list locked, we can take
900          * our time and destroy any sessions on the to-be-killed list, which
901          * is allocated privately on this thread's stack.
902          */
903         while (rem != NULL) {
904                 lprintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
905                 RemoveContext(rem);
906                 ptr = rem;
907                 rem = rem->next;
908                 free(ptr);
909         }
910
911         /* Raise the size of the worker thread pool if necessary. */
912         if ( (num_sessions > num_threads)
913            && (num_threads < config.c_max_workers) ) {
914                 begin_critical_section(S_WORKER_LIST);
915                 create_worker();
916                 end_critical_section(S_WORKER_LIST);
917         }
918 }
919
920
921
922
923
924 /*
925  * masterCC is the context we use when not attached to a session.  This
926  * function initializes it.
927  */
928 void InitializeMasterCC(void) {
929         memset(&masterCC, 0, sizeof(struct CitContext));
930         masterCC.internal_pgm = 1;
931         masterCC.cs_pid = 0;
932 }
933
934
935
936
937
938
939 /*
940  * Bind a thread to a context.  (It's inline merely to speed things up.)
941  */
942 INLINE void become_session(struct CitContext *which_con) {
943         pthread_setspecific(MyConKey, (void *)which_con );
944 }
945
946
947
948 /* 
949  * This loop just keeps going and going and going...
950  */     
951 void *worker_thread(void *arg) {
952         int i;
953         int highest;
954         struct CitContext *ptr;
955         struct CitContext *bind_me = NULL;
956         fd_set readfds;
957         int retval = 0;
958         struct CitContext *con= NULL;   /* Temporary context pointer */
959         struct ServiceFunctionHook *serviceptr;
960         int ssock;                      /* Descriptor for client socket */
961         struct timeval tv;
962         int force_purge = 0;
963         int m;
964
965         num_threads++;
966
967         cdb_allocate_tsd();
968
969         while (!time_to_die) {
970
971                 /* make doubly sure we're not holding any stale db handles
972                  * which might cause a deadlock.
973                  */
974                 cdb_check_handles();
975 do_select:      force_purge = 0;
976                 bind_me = NULL;         /* Which session shall we handle? */
977
978                 /* Initialize the fdset. */
979                 FD_ZERO(&readfds);
980                 highest = 0;
981
982                 begin_critical_section(S_SESSION_TABLE);
983                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
984                         if (ptr->state == CON_IDLE) {
985                                 FD_SET(ptr->client_socket, &readfds);
986                                 if (ptr->client_socket > highest)
987                                         highest = ptr->client_socket;
988                         }
989                         if ((bind_me == NULL) && (ptr->state == CON_READY)) {
990                                 bind_me = ptr;
991                                 ptr->state = CON_EXECUTING;
992                         }
993                 }
994                 end_critical_section(S_SESSION_TABLE);
995
996                 if (bind_me) {
997                         goto SKIP_SELECT;
998                 }
999
1000                 /* If we got this far, it means that there are no sessions
1001                  * which a previous thread marked for attention, so we go
1002                  * ahead and get ready to select().
1003                  */
1004
1005                 /* First, add the various master sockets to the fdset. */
1006                 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1007                 serviceptr = serviceptr->next ) {
1008                         m = serviceptr->msock;
1009                         FD_SET(m, &readfds);
1010                         if (m > highest) {
1011                                 highest = m;
1012                         }
1013                 }
1014
1015                 if (!time_to_die) {
1016                         tv.tv_sec = 1;          /* wake up every second if no input */
1017                         tv.tv_usec = 0;
1018                         retval = select(highest + 1, &readfds, NULL, NULL, &tv);
1019                 }
1020
1021                 if (time_to_die) return(NULL);
1022
1023                 /* Now figure out who made this select() unblock.
1024                  * First, check for an error or exit condition.
1025                  */
1026                 if (retval < 0) {
1027                         if (errno == EBADF) {
1028                                 lprintf(CTDL_NOTICE, "select() failed: (%s)\n",
1029                                         strerror(errno));
1030                                 goto do_select;
1031                         }
1032                         if (errno != EINTR) {
1033                                 lprintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1034                                 time_to_die = 1;
1035                         } else if (!time_to_die)
1036                                 goto do_select;
1037                 }
1038
1039                 /* Next, check to see if it's a new client connecting
1040                  * on a master socket.
1041                  */
1042                 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1043                      serviceptr = serviceptr->next ) {
1044
1045                         if (FD_ISSET(serviceptr->msock, &readfds)) {
1046                                 ssock = accept(serviceptr->msock, NULL, 0);
1047                                 if (ssock >= 0) {
1048                                         lprintf(CTDL_DEBUG,
1049                                                 "New client socket %d\n",
1050                                                 ssock);
1051
1052                                         /* New context will be created already
1053                                         * set up in the CON_EXECUTING state.
1054                                         */
1055                                         con = CreateNewContext();
1056
1057                                         /* Assign new socket number to it. */
1058                                         con->client_socket = ssock;
1059                                         con->h_command_function =
1060                                                 serviceptr->h_command_function;
1061                                         con->h_async_function =
1062                                                 serviceptr->h_async_function;
1063
1064                                         /* Determine whether local socket */
1065                                         if (serviceptr->sockpath != NULL)
1066                                                 con->is_local_socket = 1;
1067         
1068                                         /* Set the SO_REUSEADDR socket option */
1069                                         i = 1;
1070                                         setsockopt(ssock, SOL_SOCKET,
1071                                                 SO_REUSEADDR,
1072                                                 &i, sizeof(i));
1073
1074                                         become_session(con);
1075                                         begin_session(con);
1076                                         serviceptr->h_greeting_function();
1077                                         become_session(NULL);
1078                                         con->state = CON_IDLE;
1079                                         goto do_select;
1080                                 }
1081                         }
1082                 }
1083
1084                 /* It must be a client socket.  Find a context that has data
1085                  * waiting on its socket *and* is in the CON_IDLE state.  Any
1086                  * active sockets other than our chosen one are marked as
1087                  * CON_READY so the next thread that comes around can just bind
1088                  * to one without having to select() again.
1089                  */
1090                 begin_critical_section(S_SESSION_TABLE);
1091                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1092                         if ( (FD_ISSET(ptr->client_socket, &readfds))
1093                            && (ptr->state != CON_EXECUTING) ) {
1094                                 ptr->input_waiting = 1;
1095                                 if (!bind_me) {
1096                                         bind_me = ptr;  /* I choose you! */
1097                                         bind_me->state = CON_EXECUTING;
1098                                 }
1099                                 else {
1100                                         ptr->state = CON_READY;
1101                                 }
1102                         }
1103                 }
1104                 end_critical_section(S_SESSION_TABLE);
1105
1106 SKIP_SELECT:
1107                 /* We're bound to a session */
1108                 if (bind_me != NULL) {
1109                         become_session(bind_me);
1110
1111                         /* If the client has sent a command, execute it. */
1112                         if (CC->input_waiting) {
1113                                 CC->h_command_function();
1114                                 CC->input_waiting = 0;
1115                         }
1116
1117                         /* If there are asynchronous messages waiting and the
1118                          * client supports it, do those now */
1119                         if ((CC->is_async) && (CC->async_waiting)
1120                            && (CC->h_async_function != NULL)) {
1121                                 CC->h_async_function();
1122                                 CC->async_waiting = 0;
1123                         }
1124                         
1125                         force_purge = CC->kill_me;
1126                         become_session(NULL);
1127                         bind_me->state = CON_IDLE;
1128                 }
1129
1130                 dead_session_purge(force_purge);
1131                 do_housekeeping();
1132                 check_sched_shutdown();
1133         }
1134
1135         /* If control reaches this point, the server is shutting down */        
1136         return(NULL);
1137 }
1138
1139
1140
1141
1142 /*
1143  * SyslogFacility()
1144  * Translate text facility name to syslog.h defined value.
1145  */
1146 int SyslogFacility(char *name)
1147 {
1148         int i;
1149         struct
1150         {
1151                 int facility;
1152                 char *name;
1153         }   facTbl[] =
1154         {
1155                 {   LOG_KERN,   "kern"          },
1156                 {   LOG_USER,   "user"          },
1157                 {   LOG_MAIL,   "mail"          },
1158                 {   LOG_DAEMON, "daemon"        },
1159                 {   LOG_AUTH,   "auth"          },
1160                 {   LOG_SYSLOG, "syslog"        },
1161                 {   LOG_LPR,    "lpr"           },
1162                 {   LOG_NEWS,   "news"          },
1163                 {   LOG_UUCP,   "uucp"          },
1164                 {   LOG_LOCAL0, "local0"        },
1165                 {   LOG_LOCAL1, "local1"        },
1166                 {   LOG_LOCAL2, "local2"        },
1167                 {   LOG_LOCAL3, "local3"        },
1168                 {   LOG_LOCAL4, "local4"        },
1169                 {   LOG_LOCAL5, "local5"        },
1170                 {   LOG_LOCAL6, "local6"        },
1171                 {   LOG_LOCAL7, "local7"        },
1172                 {   0,            NULL          }
1173         };
1174         for(i = 0; facTbl[i].name != NULL; i++) {
1175                 if(!strcasecmp(name, facTbl[i].name))
1176                         return facTbl[i].facility;
1177         }
1178         enable_syslog = 0;
1179         return LOG_DAEMON;
1180 }
1181
1182
1183 /********** MEM CHEQQER ***********/
1184
1185 #ifdef DEBUG_MEMORY_LEAKS
1186
1187 #undef malloc
1188 #undef realloc
1189 #undef strdup
1190 #undef free
1191
1192 void *tracked_malloc(size_t size, char *file, int line) {
1193         struct igheap *thisheap;
1194         void *block;
1195
1196         block = malloc(size);
1197         if (block == NULL) return(block);
1198
1199         thisheap = malloc(sizeof(struct igheap));
1200         if (thisheap == NULL) {
1201                 free(block);
1202                 return(NULL);
1203         }
1204
1205         thisheap->block = block;
1206         strcpy(thisheap->file, file);
1207         thisheap->line = line;
1208         
1209         begin_critical_section(S_DEBUGMEMLEAKS);
1210         thisheap->next = igheap;
1211         igheap = thisheap;
1212         end_critical_section(S_DEBUGMEMLEAKS);
1213
1214         return(block);
1215 }
1216
1217
1218 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
1219         struct igheap *thisheap;
1220         void *block;
1221
1222         block = realloc(ptr, size);
1223         if (block == NULL) return(block);
1224
1225         thisheap = malloc(sizeof(struct igheap));
1226         if (thisheap == NULL) {
1227                 free(block);
1228                 return(NULL);
1229         }
1230
1231         thisheap->block = block;
1232         strcpy(thisheap->file, file);
1233         thisheap->line = line;
1234         
1235         begin_critical_section(S_DEBUGMEMLEAKS);
1236         thisheap->next = igheap;
1237         igheap = thisheap;
1238         end_critical_section(S_DEBUGMEMLEAKS);
1239
1240         return(block);
1241 }
1242
1243
1244
1245 void tracked_free(void *ptr) {
1246         struct igheap *thisheap;
1247         struct igheap *trash;
1248
1249         free(ptr);
1250
1251         if (igheap == NULL) return;
1252         begin_critical_section(S_DEBUGMEMLEAKS);
1253         for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1254                 if (thisheap->next != NULL) {
1255                         if (thisheap->next->block == ptr) {
1256                                 trash = thisheap->next;
1257                                 thisheap->next = thisheap->next->next;
1258                                 free(trash);
1259                         }
1260                 }
1261         }
1262         if (igheap->block == ptr) {
1263                 trash = igheap;
1264                 igheap = igheap->next;
1265                 free(trash);
1266         }
1267         end_critical_section(S_DEBUGMEMLEAKS);
1268 }
1269
1270 char *tracked_strdup(const char *s, char *file, int line) {
1271         char *ptr;
1272
1273         if (s == NULL) return(NULL);
1274         ptr = tracked_malloc(strlen(s) + 1, file, line);
1275         if (ptr == NULL) return(NULL);
1276         strncpy(ptr, s, strlen(s));
1277         return(ptr);
1278 }
1279
1280 void dump_heap(void) {
1281         struct igheap *thisheap;
1282
1283         for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1284                 lprintf(CTDL_CRIT, "UNFREED: %30s : %d\n",
1285                         thisheap->file, thisheap->line);
1286         }
1287 }
1288
1289 #endif /*  DEBUG_MEMORY_LEAKS */