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