* cleanup ourselfs on exit.
[citadel.git] / citadel / sysdep.c
1 /*
2  * $Id$
3  *
4  * Citadel "system dependent" stuff.
5  * See copyright.txt for copyright information.
6  *
7  * Here's where we (hopefully) have most parts of the Citadel server that
8  * would need to be altered to run the server in a non-POSIX environment.
9  * 
10  * If we ever port to a different platform and either have multiple
11  * variants of this file or simply load it up with #ifdefs.
12  *
13  */
14
15 #include "sysdep.h"
16 #include <stdlib.h>
17 #include <unistd.h>
18 #include <stdio.h>
19 #include <fcntl.h>
20 #include <ctype.h>
21 #include <signal.h>
22 #include <sys/types.h>
23 #include <sys/stat.h>
24 #include <sys/wait.h>
25 #include <sys/socket.h>
26 #include <sys/syslog.h>
27
28 #if TIME_WITH_SYS_TIME
29 # include <sys/time.h>
30 # include <time.h>
31 #else
32 # if HAVE_SYS_TIME_H
33 #  include <sys/time.h>
34 # else
35 #  include <time.h>
36 # endif
37 #endif
38
39 #include <limits.h>
40 #include <sys/resource.h>
41 #include <netinet/in.h>
42 #include <netinet/tcp.h>
43 #include <arpa/inet.h>
44 #include <netdb.h>
45 #include <sys/un.h>
46 #include <string.h>
47 #include <pwd.h>
48 #include <errno.h>
49 #include <stdarg.h>
50 #include <grp.h>
51 #ifdef HAVE_PTHREAD_H
52 #include <pthread.h>
53 #endif
54 #include "citadel.h"
55 #include "server.h"
56 #include "serv_extensions.h"
57 #include "sysdep_decls.h"
58 #include "citserver.h"
59 #include "support.h"
60 #include "config.h"
61 #include "database.h"
62 #include "housekeeping.h"
63 #include "tools.h"
64 #include "serv_crypto.h"
65 #include "serv_fulltext.h"
66
67 #ifdef HAVE_SYS_SELECT_H
68 #include <sys/select.h>
69 #endif
70
71 #ifndef HAVE_SNPRINTF
72 #include "snprintf.h"
73 #endif
74
75
76 #ifdef DEBUG_MEMORY_LEAKS
77 struct igheap {
78         struct igheap *next;
79         char file[32];
80         int line;
81         void *block;
82 };
83
84 struct igheap *igheap = NULL;
85 #endif
86
87
88 pthread_mutex_t Critters[MAX_SEMAPHORES];       /* Things needing locking */
89 pthread_key_t MyConKey;                         /* TSD key for MyContext() */
90
91 int verbosity = DEFAULT_VERBOSITY;              /* Logging level */
92
93 struct CitContext masterCC;
94 time_t last_purge = 0;                          /* Last dead session purge */
95 static int num_threads = 0;                     /* Current number of threads */
96 int num_sessions = 0;                           /* Current number of sessions */
97 pthread_t indexer_thread_tid;
98 pthread_t checkpoint_thread_tid;
99
100 int syslog_facility = LOG_DAEMON;
101 int enable_syslog = 0;
102 extern int running_as_daemon;
103
104 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_NONE) {
294                 sin.sin_addr.s_addr = INADDR_ANY;
295         }
296
297         s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
298
299         if (s < 0) {
300                 *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         /*
725          * close all protocol master sockets
726          */
727         for (serviceptr = ServiceHookTable; serviceptr != NULL;
728             serviceptr = serviceptr->next ) {
729
730                 if (serviceptr->tcp_port > 0)
731                         lprintf(CTDL_INFO, "Closing listener on port %d\n",
732                                 serviceptr->tcp_port);
733
734                 if (serviceptr->sockpath != NULL)
735                         lprintf(CTDL_INFO, "Closing listener on '%s'\n",
736                                 serviceptr->sockpath);
737
738                 close(serviceptr->msock);
739
740                 /* If it's a Unix domain socket, remove the file. */
741                 if (serviceptr->sockpath != NULL) {
742                         unlink(serviceptr->sockpath);
743                 }
744         }
745 #ifdef HAVE_OPENSSL
746         destruct_ssl();
747 #endif
748         CtdlDestroyProtoHooks();
749         CtdlDestroyDeleteHooks();
750         CtdlDestroyXmsgHooks();
751         CtdlDestroyNetprocHooks();
752         CtdlDestroyUserHooks();
753         CtdlDestroyMessageHook();
754         CtdlDestroyCleanupHooks();
755         CtdlDestroyFixedOutputHooks();  
756         CtdlDestroySessionHooks();
757         CtdlDestroyServiceHook();
758         DestroyWorkerList();
759 }
760
761
762
763
764 /*
765  * Terminate another session.
766  * (This could justifiably be moved out of sysdep.c because it
767  * no longer does anything that is system-dependent.)
768  */
769 void kill_session(int session_to_kill) {
770         struct CitContext *ptr;
771
772         begin_critical_section(S_SESSION_TABLE);
773         for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
774                 if (ptr->cs_pid == session_to_kill) {
775                         ptr->kill_me = 1;
776                 }
777         }
778         end_critical_section(S_SESSION_TABLE);
779 }
780
781 pid_t current_child;
782 void graceful_shutdown(int signum) {
783         kill(current_child, signum);
784         unlink(file_pid_file);
785         exit(0);
786 }
787
788
789 /*
790  * Start running as a daemon.
791  */
792 void start_daemon(int unused) {
793         int status = 0;
794         pid_t child = 0;
795         FILE *fp;
796         int do_restart = 0;
797
798         current_child = 0;
799
800         /* Close stdin/stdout/stderr and replace them with /dev/null.
801          * We don't just call close() because we don't want these fd's
802          * to be reused for other files.
803          */
804         chdir(ctdl_run_dir);
805
806         child = fork();
807         if (child != 0) {
808                 exit(0);
809         }
810         
811         signal(SIGHUP, SIG_IGN);
812         signal(SIGINT, SIG_IGN);
813         signal(SIGQUIT, SIG_IGN);
814
815         setsid();
816         umask(0);
817         freopen("/dev/null", "r", stdin);
818         freopen("/dev/null", "w", stdout);
819         freopen("/dev/null", "w", stderr);
820
821         do {
822                 current_child = fork();
823
824                 signal(SIGTERM, graceful_shutdown);
825         
826                 if (current_child < 0) {
827                         perror("fork");
828                         exit(errno);
829                 }
830         
831                 else if (current_child == 0) {
832                         return; /* continue starting citadel. */
833                 }
834         
835                 else {
836                         fp = fopen(file_pid_file, "w");
837                         if (fp != NULL) {
838                                 fprintf(fp, "%d\n", child);
839                                 fclose(fp);
840                         }
841                         waitpid(current_child, &status, 0);
842                 }
843
844                 do_restart = 0;
845
846                 /* Did the main process exit with an actual exit code? */
847                 if (WIFEXITED(status)) {
848
849                         /* Exit code 0 means the watcher should exit */
850                         if (WEXITSTATUS(status) == 0) {
851                                 do_restart = 0;
852                         }
853
854                         /* Exit code 101-109 means the watcher should exit */
855                         else if ( (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109) ) {
856                                 do_restart = 0;
857                         }
858
859                         /* Any other exit code means we should restart. */
860                         else {
861                                 do_restart = 1;
862                         }
863                 }
864
865                 /* Any other type of termination (signals, etc.) should also restart. */
866                 else {
867                         do_restart = 1;
868                 }
869
870         } while (do_restart);
871
872         unlink(file_pid_file);
873         exit(WEXITSTATUS(status));
874 }
875
876
877
878 /*
879  * Generic routine to convert a login name to a full name (gecos)
880  * Returns nonzero if a conversion took place
881  */
882 int convert_login(char NameToConvert[]) {
883         struct passwd *pw;
884         int a;
885
886         pw = getpwnam(NameToConvert);
887         if (pw == NULL) {
888                 return(0);
889         }
890         else {
891                 strcpy(NameToConvert, pw->pw_gecos);
892                 for (a=0; a<strlen(NameToConvert); ++a) {
893                         if (NameToConvert[a] == ',') NameToConvert[a] = 0;
894                 }
895                 return(1);
896         }
897 }
898
899 struct worker_node *worker_list = NULL;
900
901
902 /*
903  * create a worker thread. this function must always be called from within
904  * an S_WORKER_LIST critical section!
905  */
906 void create_worker(void) {
907         int ret;
908         struct worker_node *n;
909         pthread_attr_t attr;
910
911         n = malloc(sizeof(struct worker_node));
912         if (n == NULL) {
913                 lprintf(CTDL_EMERG, "can't allocate worker_node, exiting\n");
914                 time_to_die = -1;
915                 return;
916         }
917
918         if ((ret = pthread_attr_init(&attr))) {
919                 lprintf(CTDL_EMERG, "pthread_attr_init: %s\n", strerror(ret));
920                 time_to_die = -1;
921                 return;
922         }
923
924         /* Our per-thread stacks need to be bigger than the default size,
925          * otherwise the MIME parser crashes on FreeBSD, and the IMAP service
926          * crashes on 64-bit Linux.
927          */
928         if ((ret = pthread_attr_setstacksize(&attr, THREADSTACKSIZE))) {
929                 lprintf(CTDL_EMERG, "pthread_attr_setstacksize: %s\n",
930                         strerror(ret));
931                 time_to_die = -1;
932                 pthread_attr_destroy(&attr);
933                 return;
934         }
935
936         if ((ret = pthread_create(&n->tid, &attr, worker_thread, NULL) != 0))
937         {
938
939                 lprintf(CTDL_ALERT, "Can't create worker thread: %s\n",
940                         strerror(ret));
941         }
942
943         n->next = worker_list;
944         worker_list = n;
945         pthread_attr_destroy(&attr);
946 }
947
948 void DestroyWorkerList(void)
949 {
950         struct worker_node *cur, *p;
951         cur = worker_list;
952         while (cur != NULL)
953         {
954                 p = cur->next;
955                 free (cur);
956                 cur = p;
957         }
958         worker_list = NULL;
959 }
960
961 /*
962  * Create the indexer thread and begin its operation.
963  * Then create the checkpoint thread and begin its operation.
964  */
965 void create_maintenance_threads(void) {
966         int ret;
967         pthread_attr_t attr;
968
969         if ((ret = pthread_attr_init(&attr))) {
970                 lprintf(CTDL_EMERG, "pthread_attr_init: %s\n", strerror(ret));
971                 time_to_die = -1;
972                 return;
973         }
974
975         /* Our per-thread stacks need to be bigger than the default size,
976          * otherwise the MIME parser crashes on FreeBSD, and the IMAP service
977          * crashes on 64-bit Linux.
978          */
979         if ((ret = pthread_attr_setstacksize(&attr, THREADSTACKSIZE))) {
980                 lprintf(CTDL_EMERG, "pthread_attr_setstacksize: %s\n",
981                         strerror(ret));
982                 time_to_die = -1;
983                 pthread_attr_destroy(&attr);
984                 return;
985         }
986
987         if ((ret = pthread_create(&indexer_thread_tid, &attr, indexer_thread, NULL) != 0)) {
988                 lprintf(CTDL_ALERT, "Can't create thread: %s\n", strerror(ret));
989         }
990
991         if ((ret = pthread_create(&checkpoint_thread_tid, &attr, checkpoint_thread, NULL) != 0)) {
992                 lprintf(CTDL_ALERT, "Can't create thread: %s\n", strerror(ret));
993         }
994
995         pthread_attr_destroy(&attr);
996 }
997
998
999
1000 /*
1001  * Purge all sessions which have the 'kill_me' flag set.
1002  * This function has code to prevent it from running more than once every
1003  * few seconds, because running it after every single unbind would waste a lot
1004  * of CPU time and keep the context list locked too much.  To force it to run
1005  * anyway, set "force" to nonzero.
1006  *
1007  *
1008  * After that's done, we raise the size of the worker thread pool
1009  * if such an action is appropriate.
1010  */
1011 void dead_session_purge(int force) {
1012         struct CitContext *ptr;         /* general-purpose utility pointer */
1013         struct CitContext *rem = NULL;  /* list of sessions to be destroyed */
1014
1015         if (force == 0) {
1016                 if ( (time(NULL) - last_purge) < 5 ) {
1017                         return; /* Too soon, go away */
1018                 }
1019         }
1020         time(&last_purge);
1021
1022         begin_critical_section(S_SESSION_TABLE);
1023         for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1024                 if ( (ptr->state == CON_IDLE) && (ptr->kill_me) ) {
1025
1026                         /* Remove the session from the active list */
1027                         if (ptr->prev) {
1028                                 ptr->prev->next = ptr->next;
1029                         }
1030                         else {
1031                                 ContextList = ptr->next;
1032                         }
1033                         if (ptr->next) {
1034                                 ptr->next->prev = ptr->prev;
1035                         }
1036
1037                         --num_sessions;
1038
1039                         /* And put it on our to-be-destroyed list */
1040                         ptr->next = rem;
1041                         rem = ptr;
1042
1043                 }
1044         }
1045         end_critical_section(S_SESSION_TABLE);
1046
1047         /* Now that we no longer have the session list locked, we can take
1048          * our time and destroy any sessions on the to-be-killed list, which
1049          * is allocated privately on this thread's stack.
1050          */
1051         while (rem != NULL) {
1052                 lprintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
1053                 RemoveContext(rem);
1054                 ptr = rem;
1055                 rem = rem->next;
1056                 free(ptr);
1057         }
1058
1059         /* Raise the size of the worker thread pool if necessary. */
1060         if ( (num_sessions > num_threads)
1061            && (num_threads < config.c_max_workers) ) {
1062                 begin_critical_section(S_WORKER_LIST);
1063                 create_worker();
1064                 end_critical_section(S_WORKER_LIST);
1065         }
1066 }
1067
1068
1069
1070
1071
1072 /*
1073  * masterCC is the context we use when not attached to a session.  This
1074  * function initializes it.
1075  */
1076 void InitializeMasterCC(void) {
1077         memset(&masterCC, 0, sizeof(struct CitContext));
1078         masterCC.internal_pgm = 1;
1079         masterCC.cs_pid = 0;
1080 }
1081
1082
1083
1084
1085
1086
1087 /*
1088  * Bind a thread to a context.  (It's inline merely to speed things up.)
1089  */
1090 INLINE void become_session(struct CitContext *which_con) {
1091         pthread_setspecific(MyConKey, (void *)which_con );
1092 }
1093
1094
1095
1096 /* 
1097  * This loop just keeps going and going and going...
1098  */     
1099 void *worker_thread(void *arg) {
1100         int i;
1101         int highest;
1102         struct CitContext *ptr;
1103         struct CitContext *bind_me = NULL;
1104         fd_set readfds;
1105         int retval = 0;
1106         struct CitContext *con= NULL;   /* Temporary context pointer */
1107         struct ServiceFunctionHook *serviceptr;
1108         int ssock;                      /* Descriptor for client socket */
1109         struct timeval tv;
1110         int force_purge = 0;
1111         int m;
1112
1113         num_threads++;
1114
1115         cdb_allocate_tsd();
1116
1117         while (!time_to_die) {
1118
1119                 /* make doubly sure we're not holding any stale db handles
1120                  * which might cause a deadlock.
1121                  */
1122                 cdb_check_handles();
1123 do_select:      force_purge = 0;
1124                 bind_me = NULL;         /* Which session shall we handle? */
1125
1126                 /* Initialize the fdset. */
1127                 FD_ZERO(&readfds);
1128                 highest = 0;
1129
1130                 begin_critical_section(S_SESSION_TABLE);
1131                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1132                         if (ptr->state == CON_IDLE) {
1133                                 FD_SET(ptr->client_socket, &readfds);
1134                                 if (ptr->client_socket > highest)
1135                                         highest = ptr->client_socket;
1136                         }
1137                         if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1138                                 bind_me = ptr;
1139                                 ptr->state = CON_EXECUTING;
1140                         }
1141                 }
1142                 end_critical_section(S_SESSION_TABLE);
1143
1144                 if (bind_me) {
1145                         goto SKIP_SELECT;
1146                 }
1147
1148                 /* If we got this far, it means that there are no sessions
1149                  * which a previous thread marked for attention, so we go
1150                  * ahead and get ready to select().
1151                  */
1152
1153                 /* First, add the various master sockets to the fdset. */
1154                 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1155                 serviceptr = serviceptr->next ) {
1156                         m = serviceptr->msock;
1157                         FD_SET(m, &readfds);
1158                         if (m > highest) {
1159                                 highest = m;
1160                         }
1161                 }
1162
1163                 if (!time_to_die) {
1164                         tv.tv_sec = 1;          /* wake up every second if no input */
1165                         tv.tv_usec = 0;
1166                         retval = select(highest + 1, &readfds, NULL, NULL, &tv);
1167                 }
1168
1169                 if (time_to_die) return(NULL);
1170
1171                 /* Now figure out who made this select() unblock.
1172                  * First, check for an error or exit condition.
1173                  */
1174                 if (retval < 0) {
1175                         if (errno == EBADF) {
1176                                 lprintf(CTDL_NOTICE, "select() failed: (%s)\n",
1177                                         strerror(errno));
1178                                 goto do_select;
1179                         }
1180                         if (errno != EINTR) {
1181                                 lprintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1182                                 time_to_die = 1;
1183                         } else if (!time_to_die)
1184                                 goto do_select;
1185                 }
1186
1187                 /* Next, check to see if it's a new client connecting
1188                  * on a master socket.
1189                  */
1190                 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1191                      serviceptr = serviceptr->next ) {
1192
1193                         if (FD_ISSET(serviceptr->msock, &readfds)) {
1194                                 ssock = accept(serviceptr->msock, NULL, 0);
1195                                 if (ssock >= 0) {
1196                                         lprintf(CTDL_DEBUG,
1197                                                 "New client socket %d\n",
1198                                                 ssock);
1199
1200                                         /* The master socket is non-blocking but the client
1201                                          * sockets need to be blocking, otherwise certain
1202                                          * operations barf on FreeBSD.  Not a fatal error.
1203                                          */
1204                                         if (fcntl(ssock, F_SETFL, 0) < 0) {
1205                                                 lprintf(CTDL_EMERG,
1206                                                         "citserver: Can't set socket to blocking: %s\n",
1207                                                         strerror(errno));
1208                                         }
1209
1210                                         /* New context will be created already
1211                                          * set up in the CON_EXECUTING state.
1212                                          */
1213                                         con = CreateNewContext();
1214
1215                                         /* Assign our new socket number to it. */
1216                                         con->client_socket = ssock;
1217                                         con->h_command_function =
1218                                                 serviceptr->h_command_function;
1219                                         con->h_async_function =
1220                                                 serviceptr->h_async_function;
1221
1222                                         /* Determine whether it's a local socket */
1223                                         if (serviceptr->sockpath != NULL)
1224                                                 con->is_local_socket = 1;
1225         
1226                                         /* Set the SO_REUSEADDR socket option */
1227                                         i = 1;
1228                                         setsockopt(ssock, SOL_SOCKET,
1229                                                 SO_REUSEADDR,
1230                                                 &i, sizeof(i));
1231
1232                                         become_session(con);
1233                                         begin_session(con);
1234                                         serviceptr->h_greeting_function();
1235                                         become_session(NULL);
1236                                         con->state = CON_IDLE;
1237                                         goto do_select;
1238                                 }
1239                         }
1240                 }
1241
1242                 /* It must be a client socket.  Find a context that has data
1243                  * waiting on its socket *and* is in the CON_IDLE state.  Any
1244                  * active sockets other than our chosen one are marked as
1245                  * CON_READY so the next thread that comes around can just bind
1246                  * to one without having to select() again.
1247                  */
1248                 begin_critical_section(S_SESSION_TABLE);
1249                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1250                         if ( (FD_ISSET(ptr->client_socket, &readfds))
1251                            && (ptr->state != CON_EXECUTING) ) {
1252                                 ptr->input_waiting = 1;
1253                                 if (!bind_me) {
1254                                         bind_me = ptr;  /* I choose you! */
1255                                         bind_me->state = CON_EXECUTING;
1256                                 }
1257                                 else {
1258                                         ptr->state = CON_READY;
1259                                 }
1260                         }
1261                 }
1262                 end_critical_section(S_SESSION_TABLE);
1263
1264 SKIP_SELECT:
1265                 /* We're bound to a session */
1266                 if (bind_me != NULL) {
1267                         become_session(bind_me);
1268
1269                         /* If the client has sent a command, execute it. */
1270                         if (CC->input_waiting) {
1271                                 CC->h_command_function();
1272                                 CC->input_waiting = 0;
1273                         }
1274
1275                         /* If there are asynchronous messages waiting and the
1276                          * client supports it, do those now */
1277                         if ((CC->is_async) && (CC->async_waiting)
1278                            && (CC->h_async_function != NULL)) {
1279                                 CC->h_async_function();
1280                                 CC->async_waiting = 0;
1281                         }
1282                         
1283                         force_purge = CC->kill_me;
1284                         become_session(NULL);
1285                         bind_me->state = CON_IDLE;
1286                 }
1287
1288                 dead_session_purge(force_purge);
1289                 do_housekeeping();
1290                 check_sched_shutdown();
1291         }
1292         if (con != NULL) free (con);//// TODO: could this harm other threads? 
1293         /* If control reaches this point, the server is shutting down */        
1294         return(NULL);
1295 }
1296
1297
1298
1299
1300 /*
1301  * SyslogFacility()
1302  * Translate text facility name to syslog.h defined value.
1303  */
1304 int SyslogFacility(char *name)
1305 {
1306         int i;
1307         struct
1308         {
1309                 int facility;
1310                 char *name;
1311         }   facTbl[] =
1312         {
1313                 {   LOG_KERN,   "kern"          },
1314                 {   LOG_USER,   "user"          },
1315                 {   LOG_MAIL,   "mail"          },
1316                 {   LOG_DAEMON, "daemon"        },
1317                 {   LOG_AUTH,   "auth"          },
1318                 {   LOG_SYSLOG, "syslog"        },
1319                 {   LOG_LPR,    "lpr"           },
1320                 {   LOG_NEWS,   "news"          },
1321                 {   LOG_UUCP,   "uucp"          },
1322                 {   LOG_LOCAL0, "local0"        },
1323                 {   LOG_LOCAL1, "local1"        },
1324                 {   LOG_LOCAL2, "local2"        },
1325                 {   LOG_LOCAL3, "local3"        },
1326                 {   LOG_LOCAL4, "local4"        },
1327                 {   LOG_LOCAL5, "local5"        },
1328                 {   LOG_LOCAL6, "local6"        },
1329                 {   LOG_LOCAL7, "local7"        },
1330                 {   0,            NULL          }
1331         };
1332         for(i = 0; facTbl[i].name != NULL; i++) {
1333                 if(!strcasecmp(name, facTbl[i].name))
1334                         return facTbl[i].facility;
1335         }
1336         enable_syslog = 0;
1337         return LOG_DAEMON;
1338 }
1339
1340
1341 /********** MEM CHEQQER ***********/
1342
1343 #ifdef DEBUG_MEMORY_LEAKS
1344
1345 #undef malloc
1346 #undef realloc
1347 #undef strdup
1348 #undef free
1349
1350 void *tracked_malloc(size_t size, char *file, int line) {
1351         struct igheap *thisheap;
1352         void *block;
1353
1354         block = malloc(size);
1355         if (block == NULL) return(block);
1356
1357         thisheap = malloc(sizeof(struct igheap));
1358         if (thisheap == NULL) {
1359                 free(block);
1360                 return(NULL);
1361         }
1362
1363         thisheap->block = block;
1364         strcpy(thisheap->file, file);
1365         thisheap->line = line;
1366         
1367         begin_critical_section(S_DEBUGMEMLEAKS);
1368         thisheap->next = igheap;
1369         igheap = thisheap;
1370         end_critical_section(S_DEBUGMEMLEAKS);
1371
1372         return(block);
1373 }
1374
1375
1376 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
1377         struct igheap *thisheap;
1378         void *block;
1379
1380         block = realloc(ptr, size);
1381         if (block == NULL) return(block);
1382
1383         thisheap = malloc(sizeof(struct igheap));
1384         if (thisheap == NULL) {
1385                 free(block);
1386                 return(NULL);
1387         }
1388
1389         thisheap->block = block;
1390         strcpy(thisheap->file, file);
1391         thisheap->line = line;
1392         
1393         begin_critical_section(S_DEBUGMEMLEAKS);
1394         thisheap->next = igheap;
1395         igheap = thisheap;
1396         end_critical_section(S_DEBUGMEMLEAKS);
1397
1398         return(block);
1399 }
1400
1401
1402
1403 void tracked_free(void *ptr) {
1404         struct igheap *thisheap;
1405         struct igheap *trash;
1406
1407         free(ptr);
1408
1409         if (igheap == NULL) return;
1410         begin_critical_section(S_DEBUGMEMLEAKS);
1411         for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1412                 if (thisheap->next != NULL) {
1413                         if (thisheap->next->block == ptr) {
1414                                 trash = thisheap->next;
1415                                 thisheap->next = thisheap->next->next;
1416                                 free(trash);
1417                         }
1418                 }
1419         }
1420         if (igheap->block == ptr) {
1421                 trash = igheap;
1422                 igheap = igheap->next;
1423                 free(trash);
1424         }
1425         end_critical_section(S_DEBUGMEMLEAKS);
1426 }
1427
1428 char *tracked_strdup(const char *s, char *file, int line) {
1429         char *ptr;
1430
1431         if (s == NULL) return(NULL);
1432         ptr = tracked_malloc(strlen(s) + 1, file, line);
1433         if (ptr == NULL) return(NULL);
1434         strncpy(ptr, s, strlen(s));
1435         return(ptr);
1436 }
1437
1438 void dump_heap(void) {
1439         struct igheap *thisheap;
1440
1441         for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1442                 lprintf(CTDL_CRIT, "UNFREED: %30s : %d\n",
1443                         thisheap->file, thisheap->line);
1444         }
1445 }
1446
1447 #endif /*  DEBUG_MEMORY_LEAKS */