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