* create format strings different for solaris
[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 "serv_extensions.h"
58 #include "sysdep_decls.h"
59 #include "citserver.h"
60 #include "support.h"
61 #include "config.h"
62 #include "database.h"
63 #include "housekeeping.h"
64 #include "tools.h"
65 #include "serv_crypto.h"
66 #include "serv_fulltext.h"
67
68 #ifdef HAVE_SYS_SELECT_H
69 #include <sys/select.h>
70 #endif
71
72 #ifndef HAVE_SNPRINTF
73 #include "snprintf.h"
74 #endif
75
76
77 #ifdef DEBUG_MEMORY_LEAKS
78 struct igheap {
79         struct igheap *next;
80         char file[32];
81         int line;
82         void *block;
83 };
84
85 struct igheap *igheap = NULL;
86 #endif
87
88
89 pthread_mutex_t Critters[MAX_SEMAPHORES];       /* Things needing locking */
90 pthread_key_t MyConKey;                         /* TSD key for MyContext() */
91
92 int verbosity = DEFAULT_VERBOSITY;              /* Logging level */
93
94 struct CitContext masterCC;
95 time_t last_purge = 0;                          /* Last dead session purge */
96 static int num_threads = 0;                     /* Current number of threads */
97 int num_sessions = 0;                           /* Current number of sessions */
98 pthread_t indexer_thread_tid;
99 pthread_t checkpoint_thread_tid;
100
101 int syslog_facility = LOG_DAEMON;
102 int enable_syslog = 0;
103 extern int running_as_daemon;
104
105 void DestroyWorkerList(void);
106
107 /*
108  * lprintf()  ...   Write logging information
109  */
110 void lprintf(enum LogLevel loglevel, const char *format, ...) {   
111         va_list arg_ptr;
112
113         if (enable_syslog) {
114                 va_start(arg_ptr, format);
115                         vsyslog((syslog_facility | loglevel), format, arg_ptr);
116                 va_end(arg_ptr);
117         }
118
119         /* stderr output code */
120         if (enable_syslog || running_as_daemon) return;
121
122         /* if we run in forground and syslog is disabled, log to terminal */
123         if (loglevel <= verbosity) { 
124                 struct timeval tv;
125                 struct tm tim;
126                 time_t unixtime;
127
128                 gettimeofday(&tv, NULL);
129                 /* Promote to time_t; types differ on some OSes (like darwin) */
130                 unixtime = tv.tv_sec;
131                 localtime_r(&unixtime, &tim);
132                 if (CC->cs_pid != 0) {
133                         fprintf(stderr,
134                                 "%04d/%02d/%02d %2d:%02d:%02d.%06ld [%3d] ",
135                                 tim.tm_year + 1900, tim.tm_mon + 1,
136                                 tim.tm_mday, tim.tm_hour, tim.tm_min,
137                                 tim.tm_sec, (long)tv.tv_usec,
138                                 CC->cs_pid);
139                 } else {
140                         fprintf(stderr,
141                                 "%04d/%02d/%02d %2d:%02d:%02d.%06ld ",
142                                 tim.tm_year + 1900, tim.tm_mon + 1,
143                                 tim.tm_mday, tim.tm_hour, tim.tm_min,
144                                 tim.tm_sec, (long)tv.tv_usec);
145                 }
146                 va_start(arg_ptr, format);   
147                         vfprintf(stderr, format, arg_ptr);   
148                 va_end(arg_ptr);   
149                 fflush(stderr);
150         }
151 }   
152
153
154
155 /*
156  * Signal handler to shut down the server.
157  */
158
159 volatile int time_to_die = 0;
160 volatile int shutdown_and_halt = 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         pthread_attr_destroy(&attr);
1017 }
1018
1019
1020
1021 /*
1022  * Purge all sessions which have the 'kill_me' flag set.
1023  * This function has code to prevent it from running more than once every
1024  * few seconds, because running it after every single unbind would waste a lot
1025  * of CPU time and keep the context list locked too much.  To force it to run
1026  * anyway, set "force" to nonzero.
1027  *
1028  *
1029  * After that's done, we raise the size of the worker thread pool
1030  * if such an action is appropriate.
1031  */
1032 void dead_session_purge(int force) {
1033         struct CitContext *ptr;         /* general-purpose utility pointer */
1034         struct CitContext *rem = NULL;  /* list of sessions to be destroyed */
1035
1036         if (force == 0) {
1037                 if ( (time(NULL) - last_purge) < 5 ) {
1038                         return; /* Too soon, go away */
1039                 }
1040         }
1041         time(&last_purge);
1042
1043         begin_critical_section(S_SESSION_TABLE);
1044         for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1045                 if ( (ptr->state == CON_IDLE) && (ptr->kill_me) ) {
1046
1047                         /* Remove the session from the active list */
1048                         if (ptr->prev) {
1049                                 ptr->prev->next = ptr->next;
1050                         }
1051                         else {
1052                                 ContextList = ptr->next;
1053                         }
1054                         if (ptr->next) {
1055                                 ptr->next->prev = ptr->prev;
1056                         }
1057
1058                         --num_sessions;
1059
1060                         /* And put it on our to-be-destroyed list */
1061                         ptr->next = rem;
1062                         rem = ptr;
1063
1064                 }
1065         }
1066         end_critical_section(S_SESSION_TABLE);
1067
1068         /* Now that we no longer have the session list locked, we can take
1069          * our time and destroy any sessions on the to-be-killed list, which
1070          * is allocated privately on this thread's stack.
1071          */
1072         while (rem != NULL) {
1073                 lprintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
1074                 RemoveContext(rem);
1075                 ptr = rem;
1076                 rem = rem->next;
1077                 free(ptr);
1078         }
1079
1080         /* Raise the size of the worker thread pool if necessary. */
1081         if ( (num_sessions > num_threads)
1082            && (num_threads < config.c_max_workers) ) {
1083                 begin_critical_section(S_WORKER_LIST);
1084                 create_worker();
1085                 end_critical_section(S_WORKER_LIST);
1086         }
1087 }
1088
1089
1090
1091
1092
1093 /*
1094  * masterCC is the context we use when not attached to a session.  This
1095  * function initializes it.
1096  */
1097 void InitializeMasterCC(void) {
1098         memset(&masterCC, 0, sizeof(struct CitContext));
1099         masterCC.internal_pgm = 1;
1100         masterCC.cs_pid = 0;
1101 }
1102
1103
1104
1105
1106
1107
1108 /*
1109  * Bind a thread to a context.  (It's inline merely to speed things up.)
1110  */
1111 INLINE void become_session(struct CitContext *which_con) {
1112         pthread_setspecific(MyConKey, (void *)which_con );
1113 }
1114
1115
1116
1117 /* 
1118  * This loop just keeps going and going and going...
1119  */     
1120 void *worker_thread(void *arg) {
1121         int i;
1122         int highest;
1123         struct CitContext *ptr;
1124         struct CitContext *bind_me = NULL;
1125         fd_set readfds;
1126         int retval = 0;
1127         struct CitContext *con= NULL;   /* Temporary context pointer */
1128         struct ServiceFunctionHook *serviceptr;
1129         int ssock;                      /* Descriptor for client socket */
1130         struct timeval tv;
1131         int force_purge = 0;
1132         int m;
1133
1134         num_threads++;
1135
1136         cdb_allocate_tsd();
1137
1138         while (!time_to_die) {
1139
1140                 /* make doubly sure we're not holding any stale db handles
1141                  * which might cause a deadlock.
1142                  */
1143                 cdb_check_handles();
1144 do_select:      force_purge = 0;
1145                 bind_me = NULL;         /* Which session shall we handle? */
1146
1147                 /* Initialize the fdset. */
1148                 FD_ZERO(&readfds);
1149                 highest = 0;
1150
1151                 begin_critical_section(S_SESSION_TABLE);
1152                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1153                         if (ptr->state == CON_IDLE) {
1154                                 FD_SET(ptr->client_socket, &readfds);
1155                                 if (ptr->client_socket > highest)
1156                                         highest = ptr->client_socket;
1157                         }
1158                         if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1159                                 bind_me = ptr;
1160                                 ptr->state = CON_EXECUTING;
1161                         }
1162                 }
1163                 end_critical_section(S_SESSION_TABLE);
1164
1165                 if (bind_me) {
1166                         goto SKIP_SELECT;
1167                 }
1168
1169                 /* If we got this far, it means that there are no sessions
1170                  * which a previous thread marked for attention, so we go
1171                  * ahead and get ready to select().
1172                  */
1173
1174                 /* First, add the various master sockets to the fdset. */
1175                 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1176                 serviceptr = serviceptr->next ) {
1177                         m = serviceptr->msock;
1178                         FD_SET(m, &readfds);
1179                         if (m > highest) {
1180                                 highest = m;
1181                         }
1182                 }
1183
1184                 if (!time_to_die) {
1185                         tv.tv_sec = 1;          /* wake up every second if no input */
1186                         tv.tv_usec = 0;
1187                         retval = select(highest + 1, &readfds, NULL, NULL, &tv);
1188                 }
1189
1190                 if (time_to_die) return(NULL);
1191
1192                 /* Now figure out who made this select() unblock.
1193                  * First, check for an error or exit condition.
1194                  */
1195                 if (retval < 0) {
1196                         if (errno == EBADF) {
1197                                 lprintf(CTDL_NOTICE, "select() failed: (%s)\n",
1198                                         strerror(errno));
1199                                 goto do_select;
1200                         }
1201                         if (errno != EINTR) {
1202                                 lprintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1203                                 time_to_die = 1;
1204                         } else if (!time_to_die)
1205                                 goto do_select;
1206                 }
1207
1208                 /* Next, check to see if it's a new client connecting
1209                  * on a master socket.
1210                  */
1211                 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1212                      serviceptr = serviceptr->next ) {
1213
1214                         if (FD_ISSET(serviceptr->msock, &readfds)) {
1215                                 ssock = accept(serviceptr->msock, NULL, 0);
1216                                 if (ssock >= 0) {
1217                                         lprintf(CTDL_DEBUG,
1218                                                 "New client socket %d\n",
1219                                                 ssock);
1220
1221                                         /* The master socket is non-blocking but the client
1222                                          * sockets need to be blocking, otherwise certain
1223                                          * operations barf on FreeBSD.  Not a fatal error.
1224                                          */
1225                                         if (fcntl(ssock, F_SETFL, 0) < 0) {
1226                                                 lprintf(CTDL_EMERG,
1227                                                         "citserver: Can't set socket to blocking: %s\n",
1228                                                         strerror(errno));
1229                                         }
1230
1231                                         /* New context will be created already
1232                                          * set up in the CON_EXECUTING state.
1233                                          */
1234                                         con = CreateNewContext();
1235
1236                                         /* Assign our new socket number to it. */
1237                                         con->client_socket = ssock;
1238                                         con->h_command_function =
1239                                                 serviceptr->h_command_function;
1240                                         con->h_async_function =
1241                                                 serviceptr->h_async_function;
1242
1243                                         /* Determine whether it's a local socket */
1244                                         if (serviceptr->sockpath != NULL)
1245                                                 con->is_local_socket = 1;
1246         
1247                                         /* Set the SO_REUSEADDR socket option */
1248                                         i = 1;
1249                                         setsockopt(ssock, SOL_SOCKET,
1250                                                 SO_REUSEADDR,
1251                                                 &i, sizeof(i));
1252
1253                                         become_session(con);
1254                                         begin_session(con);
1255                                         serviceptr->h_greeting_function();
1256                                         become_session(NULL);
1257                                         con->state = CON_IDLE;
1258                                         goto do_select;
1259                                 }
1260                         }
1261                 }
1262
1263                 /* It must be a client socket.  Find a context that has data
1264                  * waiting on its socket *and* is in the CON_IDLE state.  Any
1265                  * active sockets other than our chosen one are marked as
1266                  * CON_READY so the next thread that comes around can just bind
1267                  * to one without having to select() again.
1268                  */
1269                 begin_critical_section(S_SESSION_TABLE);
1270                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1271                         if ( (FD_ISSET(ptr->client_socket, &readfds))
1272                            && (ptr->state != CON_EXECUTING) ) {
1273                                 ptr->input_waiting = 1;
1274                                 if (!bind_me) {
1275                                         bind_me = ptr;  /* I choose you! */
1276                                         bind_me->state = CON_EXECUTING;
1277                                 }
1278                                 else {
1279                                         ptr->state = CON_READY;
1280                                 }
1281                         }
1282                 }
1283                 end_critical_section(S_SESSION_TABLE);
1284
1285 SKIP_SELECT:
1286                 /* We're bound to a session */
1287                 if (bind_me != NULL) {
1288                         become_session(bind_me);
1289
1290                         /* If the client has sent a command, execute it. */
1291                         if (CC->input_waiting) {
1292                                 CC->h_command_function();
1293                                 CC->input_waiting = 0;
1294                         }
1295
1296                         /* If there are asynchronous messages waiting and the
1297                          * client supports it, do those now */
1298                         if ((CC->is_async) && (CC->async_waiting)
1299                            && (CC->h_async_function != NULL)) {
1300                                 CC->h_async_function();
1301                                 CC->async_waiting = 0;
1302                         }
1303                         
1304                         force_purge = CC->kill_me;
1305                         become_session(NULL);
1306                         bind_me->state = CON_IDLE;
1307                 }
1308
1309                 dead_session_purge(force_purge);
1310                 do_housekeeping();
1311                 check_sched_shutdown();
1312         }
1313         if (con != NULL) free (con);//// TODO: could this harm other threads? 
1314         /* If control reaches this point, the server is shutting down */        
1315         return(NULL);
1316 }
1317
1318
1319
1320
1321 /*
1322  * SyslogFacility()
1323  * Translate text facility name to syslog.h defined value.
1324  */
1325 int SyslogFacility(char *name)
1326 {
1327         int i;
1328         struct
1329         {
1330                 int facility;
1331                 char *name;
1332         }   facTbl[] =
1333         {
1334                 {   LOG_KERN,   "kern"          },
1335                 {   LOG_USER,   "user"          },
1336                 {   LOG_MAIL,   "mail"          },
1337                 {   LOG_DAEMON, "daemon"        },
1338                 {   LOG_AUTH,   "auth"          },
1339                 {   LOG_SYSLOG, "syslog"        },
1340                 {   LOG_LPR,    "lpr"           },
1341                 {   LOG_NEWS,   "news"          },
1342                 {   LOG_UUCP,   "uucp"          },
1343                 {   LOG_LOCAL0, "local0"        },
1344                 {   LOG_LOCAL1, "local1"        },
1345                 {   LOG_LOCAL2, "local2"        },
1346                 {   LOG_LOCAL3, "local3"        },
1347                 {   LOG_LOCAL4, "local4"        },
1348                 {   LOG_LOCAL5, "local5"        },
1349                 {   LOG_LOCAL6, "local6"        },
1350                 {   LOG_LOCAL7, "local7"        },
1351                 {   0,            NULL          }
1352         };
1353         for(i = 0; facTbl[i].name != NULL; i++) {
1354                 if(!strcasecmp(name, facTbl[i].name))
1355                         return facTbl[i].facility;
1356         }
1357         enable_syslog = 0;
1358         return LOG_DAEMON;
1359 }
1360
1361
1362 /********** MEM CHEQQER ***********/
1363
1364 #ifdef DEBUG_MEMORY_LEAKS
1365
1366 #undef malloc
1367 #undef realloc
1368 #undef strdup
1369 #undef free
1370
1371 void *tracked_malloc(size_t size, char *file, int line) {
1372         struct igheap *thisheap;
1373         void *block;
1374
1375         block = malloc(size);
1376         if (block == NULL) return(block);
1377
1378         thisheap = malloc(sizeof(struct igheap));
1379         if (thisheap == NULL) {
1380                 free(block);
1381                 return(NULL);
1382         }
1383
1384         thisheap->block = block;
1385         strcpy(thisheap->file, file);
1386         thisheap->line = line;
1387         
1388         begin_critical_section(S_DEBUGMEMLEAKS);
1389         thisheap->next = igheap;
1390         igheap = thisheap;
1391         end_critical_section(S_DEBUGMEMLEAKS);
1392
1393         return(block);
1394 }
1395
1396
1397 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
1398         struct igheap *thisheap;
1399         void *block;
1400
1401         block = realloc(ptr, size);
1402         if (block == NULL) return(block);
1403
1404         thisheap = malloc(sizeof(struct igheap));
1405         if (thisheap == NULL) {
1406                 free(block);
1407                 return(NULL);
1408         }
1409
1410         thisheap->block = block;
1411         strcpy(thisheap->file, file);
1412         thisheap->line = line;
1413         
1414         begin_critical_section(S_DEBUGMEMLEAKS);
1415         thisheap->next = igheap;
1416         igheap = thisheap;
1417         end_critical_section(S_DEBUGMEMLEAKS);
1418
1419         return(block);
1420 }
1421
1422
1423
1424 void tracked_free(void *ptr) {
1425         struct igheap *thisheap;
1426         struct igheap *trash;
1427
1428         free(ptr);
1429
1430         if (igheap == NULL) return;
1431         begin_critical_section(S_DEBUGMEMLEAKS);
1432         for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1433                 if (thisheap->next != NULL) {
1434                         if (thisheap->next->block == ptr) {
1435                                 trash = thisheap->next;
1436                                 thisheap->next = thisheap->next->next;
1437                                 free(trash);
1438                         }
1439                 }
1440         }
1441         if (igheap->block == ptr) {
1442                 trash = igheap;
1443                 igheap = igheap->next;
1444                 free(trash);
1445         }
1446         end_critical_section(S_DEBUGMEMLEAKS);
1447 }
1448
1449 char *tracked_strdup(const char *s, char *file, int line) {
1450         char *ptr;
1451
1452         if (s == NULL) return(NULL);
1453         ptr = tracked_malloc(strlen(s) + 1, file, line);
1454         if (ptr == NULL) return(NULL);
1455         strncpy(ptr, s, strlen(s));
1456         return(ptr);
1457 }
1458
1459 void dump_heap(void) {
1460         struct igheap *thisheap;
1461
1462         for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1463                 lprintf(CTDL_CRIT, "UNFREED: %30s : %d\n",
1464                         thisheap->file, thisheap->line);
1465         }
1466 }
1467
1468 #endif /*  DEBUG_MEMORY_LEAKS */