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