* optimize SMTP in, first step:
[citadel.git] / citadel / sysdep.c
1 /*
2  * $Id$
3  *
4  * Citadel "system dependent" stuff.
5  * See COPYING 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 #include <libcitadel.h>
53 #include "citadel.h"
54 #include "server.h"
55 #include "sysdep_decls.h"
56 #include "citserver.h"
57 #include "support.h"
58 #include "config.h"
59 #include "database.h"
60 #include "housekeeping.h"
61 #include "modules/crypto/serv_crypto.h" /* Needed for init_ssl, client_write_ssl, client_read_ssl, destruct_ssl */
62 #include "ecrash.h"
63 #include "context.h"
64
65 #ifdef HAVE_SYS_SELECT_H
66 #include <sys/select.h>
67 #endif
68
69 #ifndef HAVE_SNPRINTF
70 #include "snprintf.h"
71 #endif
72
73 #include "ctdl_module.h"
74 #include "threads.h"
75 #include "user_ops.h"
76 #include "control.h"
77
78
79 #ifdef DEBUG_MEMORY_LEAKS
80 struct igheap {
81         struct igheap *next;
82         char file[32];
83         int line;
84         void *block;
85 };
86
87 struct igheap *igheap = NULL;
88 #endif
89
90
91 int verbosity = DEFAULT_VERBOSITY;              /* Logging level */
92
93 int syslog_facility = LOG_DAEMON;
94 int enable_syslog = 0;
95
96
97 /*
98  * CtdlLogPrintf()  ...   Write logging information
99  */
100 void CtdlLogPrintf(enum LogLevel loglevel, const char *format, ...) {   
101         va_list arg_ptr;
102         va_start(arg_ptr, format);
103         vCtdlLogPrintf(loglevel, format, arg_ptr);
104         va_end(arg_ptr);
105 }
106
107 void vCtdlLogPrintf(enum LogLevel loglevel, const char *format, va_list arg_ptr)
108 {
109         char buf[SIZ], buf2[SIZ];
110
111         if (enable_syslog) {
112                 vsyslog((syslog_facility | loglevel), format, arg_ptr);
113         }
114
115         /* stderr output code */
116         if (enable_syslog || running_as_daemon) return;
117
118         /* if we run in forground and syslog is disabled, log to terminal */
119         if (loglevel <= verbosity) { 
120                 struct timeval tv;
121                 struct tm tim;
122                 time_t unixtime;
123                 CitContext *CCC = CC;
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 ((CCC != NULL) && (CCC->cs_pid != 0)) {
130                         sprintf(buf,
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                                 CCC->cs_pid);
136                 } else {
137                         sprintf(buf,
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                 vsnprintf(buf2, SIZ, format, arg_ptr);   
144
145                 fprintf(stderr, "%s%s", buf, buf2);
146                 fflush(stderr);
147         }
148 }   
149
150
151
152 /*
153  * Signal handler to shut down the server.
154  */
155
156 volatile int exit_signal = 0;
157 volatile int shutdown_and_halt = 0;
158 volatile int restart_server = 0;
159 volatile int running_as_daemon = 0;
160
161 static RETSIGTYPE signal_cleanup(int signum) {
162
163         if (CT)
164                 CT->signal = signum;
165         else
166         {
167                 CtdlLogPrintf(CTDL_DEBUG, "Caught signal %d; shutting down.\n", signum);
168                 exit_signal = signum;
169         }
170 }
171
172
173
174 /*
175  * Some initialization stuff...
176  */
177 void init_sysdep(void) {
178         sigset_t set;
179
180         /* Avoid vulnerabilities related to FD_SETSIZE if we can. */
181 #ifdef FD_SETSIZE
182 #ifdef RLIMIT_NOFILE
183         struct rlimit rl;
184         getrlimit(RLIMIT_NOFILE, &rl);
185         rl.rlim_cur = FD_SETSIZE;
186         rl.rlim_max = FD_SETSIZE;
187         setrlimit(RLIMIT_NOFILE, &rl);
188 #endif
189 #endif
190
191         /* If we've got OpenSSL, we're going to use it. */
192 #ifdef HAVE_OPENSSL
193         init_ssl();
194 #endif
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 (citthread_key_create(&MyConKey, NULL) != 0) {
203                 CtdlLogPrintf(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
240 /*
241  * This is a generic function to set up a master socket for listening on
242  * a TCP port.  The server shuts down if the bind fails.
243  *
244  */
245 int ig_tcp_server(char *ip_addr, int port_number, int queue_len, char **errormessage)
246 {
247         struct sockaddr_in sin;
248         int s, i;
249         int actual_queue_len;
250
251         actual_queue_len = queue_len;
252         if (actual_queue_len < 5) actual_queue_len = 5;
253
254         memset(&sin, 0, sizeof(sin));
255         sin.sin_family = AF_INET;
256         sin.sin_port = htons((u_short)port_number);
257         if (ip_addr == NULL) {
258                 sin.sin_addr.s_addr = INADDR_ANY;
259         }
260         else {
261                 sin.sin_addr.s_addr = inet_addr(ip_addr);
262         }
263                                                                                 
264         if (sin.sin_addr.s_addr == !INADDR_ANY) {
265                 sin.sin_addr.s_addr = INADDR_ANY;
266         }
267
268         s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
269
270         if (s < 0) {
271                 *errormessage = (char*) malloc(SIZ + 1);
272                 snprintf(*errormessage, SIZ, 
273                                  "citserver: Can't create a socket: %s",
274                                  strerror(errno));
275                 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
276                 return(-1);
277         }
278
279         i = 1;
280         setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
281
282         if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
283                 *errormessage = (char*) malloc(SIZ + 1);
284                 snprintf(*errormessage, SIZ, 
285                                  "citserver: Can't bind: %s",
286                                  strerror(errno));
287                 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
288                 close(s);
289                 return(-1);
290         }
291
292         /* set to nonblock - we need this for some obscure situations */
293         if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
294                 *errormessage = (char*) malloc(SIZ + 1);
295                 snprintf(*errormessage, SIZ, 
296                                  "citserver: Can't set socket to non-blocking: %s",
297                                  strerror(errno));
298                 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
299                 close(s);
300                 return(-1);
301         }
302
303         if (listen(s, actual_queue_len) < 0) {
304                 *errormessage = (char*) malloc(SIZ + 1);
305                 snprintf(*errormessage, SIZ, 
306                                  "citserver: Can't listen: %s",
307                                  strerror(errno));
308                 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
309                 close(s);
310                 return(-1);
311         }
312
313         return(s);
314 }
315
316
317
318 /*
319  * Create a Unix domain socket and listen on it
320  */
321 int ig_uds_server(char *sockpath, int queue_len, char **errormessage)
322 {
323         struct sockaddr_un addr;
324         int s;
325         int i;
326         int actual_queue_len;
327 #ifdef HAVE_STRUCT_UCRED
328         int passcred = 1;
329 #endif
330
331         actual_queue_len = queue_len;
332         if (actual_queue_len < 5) actual_queue_len = 5;
333
334         i = unlink(sockpath);
335         if ((i != 0) && (errno != ENOENT)) {
336                 *errormessage = (char*) malloc(SIZ + 1);
337                 snprintf(*errormessage, SIZ, "citserver: can't unlink %s: %s",
338                         sockpath, strerror(errno));
339                 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
340                 return(-1);
341         }
342
343         memset(&addr, 0, sizeof(addr));
344         addr.sun_family = AF_UNIX;
345         safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
346
347         s = socket(AF_UNIX, SOCK_STREAM, 0);
348         if (s < 0) {
349                 *errormessage = (char*) malloc(SIZ + 1);
350                 snprintf(*errormessage, SIZ, 
351                          "citserver: Can't create a socket: %s",
352                          strerror(errno));
353                 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
354                 return(-1);
355         }
356
357         if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
358                 *errormessage = (char*) malloc(SIZ + 1);
359                 snprintf(*errormessage, SIZ, 
360                          "citserver: Can't bind: %s",
361                          strerror(errno));
362                 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
363                 return(-1);
364         }
365
366         /* set to nonblock - we need this for some obscure situations */
367         if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
368                 *errormessage = (char*) malloc(SIZ + 1);
369                 snprintf(*errormessage, SIZ, 
370                          "citserver: Can't set socket to non-blocking: %s",
371                          strerror(errno));
372                 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
373                 close(s);
374                 return(-1);
375         }
376
377         if (listen(s, actual_queue_len) < 0) {
378                 *errormessage = (char*) malloc(SIZ + 1);
379                 snprintf(*errormessage, SIZ, 
380                          "citserver: Can't listen: %s",
381                          strerror(errno));
382                 CtdlLogPrintf(CTDL_EMERG, "%s\n", *errormessage);
383                 return(-1);
384         }
385
386 #ifdef HAVE_STRUCT_UCRED
387         setsockopt(s, SOL_SOCKET, SO_PASSCRED, &passcred, sizeof(passcred));
388 #endif
389
390         chmod(sockpath, S_ISGID|S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
391         return(s);
392 }
393
394
395
396 /*
397  * The following functions implement output buffering on operating systems which
398  * support it (such as Linux and various BSD flavors).
399  */
400 #ifndef HAVE_DARWIN
401 #ifdef TCP_CORK
402 #       define HAVE_TCP_BUFFERING
403 #else
404 #       ifdef TCP_NOPUSH
405 #               define HAVE_TCP_BUFFERING
406 #               define TCP_CORK TCP_NOPUSH
407 #       endif
408 #endif /* TCP_CORK */
409 #endif /* HAVE_DARWIN */
410
411 static unsigned on = 1, off = 0;
412
413 void buffer_output(void) {
414 #ifdef HAVE_TCP_BUFFERING
415 #ifdef HAVE_OPENSSL
416         if (!CC->redirect_ssl)
417 #endif
418                 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
419 #endif
420 }
421
422 void unbuffer_output(void) {
423 #ifdef HAVE_TCP_BUFFERING
424 #ifdef HAVE_OPENSSL
425         if (!CC->redirect_ssl)
426 #endif
427                 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
428 #endif
429 }
430
431 void flush_output(void) {
432 #ifdef HAVE_TCP_BUFFERING
433         struct CitContext *CCC = CC;
434         setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
435         setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
436 #endif
437 }
438
439
440
441 /*
442  * client_write()   ...    Send binary data to the client.
443  */
444 int client_write(const char *buf, int nbytes)
445 {
446         int bytes_written = 0;
447         int retval;
448 #ifndef HAVE_TCP_BUFFERING
449         int old_buffer_len = 0;
450 #endif
451         fd_set wset;
452         CitContext *Ctx;
453         int fdflags;
454
455         Ctx = CC;
456         if (Ctx->redirect_buffer != NULL) {
457                 if ((Ctx->redirect_len + nbytes + 2) >= Ctx->redirect_alloc) {
458                         Ctx->redirect_alloc = (Ctx->redirect_alloc * 2) + nbytes;
459                         Ctx->redirect_buffer = realloc(Ctx->redirect_buffer,
460                                                 Ctx->redirect_alloc);
461                 }
462                 memcpy(&Ctx->redirect_buffer[Ctx->redirect_len], buf, nbytes);
463                 Ctx->redirect_len += nbytes;
464                 Ctx->redirect_buffer[Ctx->redirect_len] = 0;
465                 return 0;
466         }
467
468 #ifdef HAVE_OPENSSL
469         if (Ctx->redirect_ssl) {
470                 client_write_ssl(buf, nbytes);
471                 return 0;
472         }
473 #endif
474
475         fdflags = fcntl(Ctx->client_socket, F_GETFL);
476
477         while (bytes_written < nbytes) {
478                 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
479                         FD_ZERO(&wset);
480                         FD_SET(Ctx->client_socket, &wset);
481                         if (select(1, NULL, &wset, NULL, NULL) == -1) {
482                                 if (errno == EINTR)
483                                 {
484                                         CtdlLogPrintf(CTDL_DEBUG, "client_write(%d bytes) select() interrupted.\n", nbytes-bytes_written);
485                                         if (CtdlThreadCheckStop()) {
486                                                 CC->kill_me = 1;
487                                                 return (-1);
488                                         } else {
489                                                 /* can't trust fd's and stuff so we need to re-create them */
490                                                 continue;
491                                         }
492                                 } else {
493                                         CtdlLogPrintf(CTDL_ERR,
494                                                 "client_write(%d bytes) select failed: %s (%d)\n",
495                                                 nbytes - bytes_written,
496                                                 strerror(errno), errno);
497                                         cit_backtrace();
498                                         Ctx->kill_me = 1;
499                                         return -1;
500                                 }
501                         }
502                 }
503
504                 retval = write(Ctx->client_socket, &buf[bytes_written],
505                         nbytes - bytes_written);
506                 if (retval < 1) {
507                         CtdlLogPrintf(CTDL_ERR,
508                                 "client_write(%d bytes) failed: %s (%d)\n",
509                                 nbytes - bytes_written,
510                                 strerror(errno), errno);
511                         cit_backtrace();
512                         // CtdlLogPrintf(CTDL_DEBUG, "Tried to send: %s",  &buf[bytes_written]);
513                         Ctx->kill_me = 1;
514                         return -1;
515                 }
516                 bytes_written = bytes_written + retval;
517         }
518         return 0;
519 }
520
521 void cputbuf(const StrBuf *Buf) {   
522         client_write(ChrPtr(Buf), StrLength(Buf)); 
523 }   
524
525
526 /*
527  * cprintf()    Send formatted printable data to the client.
528  *              Implemented in terms of client_write() so it's technically not sysdep...
529  */
530 void cprintf(const char *format, ...) {   
531         va_list arg_ptr;   
532         char buf[1024];
533    
534         va_start(arg_ptr, format);   
535         if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
536                 buf[sizeof buf - 2] = '\n';
537         client_write(buf, strlen(buf)); 
538         va_end(arg_ptr);
539 }   
540
541
542 /*
543  * Read data from the client socket.
544  * Return values are:
545  *      1       Requested number of bytes has been read.
546  *      0       Request timed out.
547  *      -1      The socket is broken.
548  * If the socket breaks, the session will be terminated.
549  */
550 INLINE int client_read_backend(char *buf, int bytes, int timeout, CitContext *CCC)
551 {
552         int len,rlen;
553         fd_set rfds;
554         int fd;
555         struct timeval tv;
556         int retval;
557
558 #ifdef HAVE_OPENSSL
559         if (CCC->redirect_ssl) {
560                 return (client_read_ssl(buf, bytes, timeout));
561         }
562 #endif
563         len = 0;
564         fd = CCC->client_socket;
565         while(len<bytes) {
566                 FD_ZERO(&rfds);
567                 FD_SET(fd, &rfds);
568                 tv.tv_sec = timeout;
569                 tv.tv_usec = 0;
570
571                 retval = select( (fd)+1, 
572                                  &rfds, NULL, NULL, &tv);
573                 if (retval < 0)
574                 {
575                         if (errno == EINTR)
576                         {
577                                 CtdlLogPrintf(CTDL_DEBUG, "Interrupted select() in client_read_to().\n");
578                                 if (CtdlThreadCheckStop()) {
579                                         CC->kill_me = 1;
580                                         return (-1);
581                                 } else {
582                                         /* can't trust fd's and stuff so we need to re-create them */
583                                         continue;
584                                 }
585                         }
586                         else {
587                                 CtdlLogPrintf(CTDL_DEBUG, "Failed select() in client_read_to().\n");
588                                 CCC->kill_me = 1;
589                                 return (-1);
590                         }
591                 }
592
593                 if (FD_ISSET(fd, &rfds) == 0) {
594                         return(0);
595                 }
596
597                 rlen = read(fd, &buf[len], bytes-len);
598                 if (rlen<1) {
599                         /* The socket has been disconnected! */
600                         CCC->kill_me = 1;
601                         return(-1);
602                 }
603                 len = len + rlen;
604         }
605         return(1);
606 }
607
608
609 int client_read_to(char *buf, int bytes, int timeout)
610 {
611         return client_read_backend(buf, bytes, timeout, CC);
612 }
613
614 /*
615  * Read data from the client socket with default timeout.
616  * (This is implemented in terms of client_read_to() and could be
617  * justifiably moved out of sysdep.c)
618  */
619 INLINE int client_read(char *buf, int bytes)
620 {
621         return(client_read_to(buf, bytes, config.c_sleeping));
622 }
623
624
625 /*
626  * client_getln()   ...   Get a LF-terminated line of text from the client.
627  * (This is implemented in terms of client_read() and could be
628  * justifiably moved out of sysdep.c)
629  */
630 int client_getln(char *buf, int bufsize)
631 {
632         int i, retval;
633         CitContext *CCC=CC;
634
635         /* Read one character at a time.
636          */
637         for (i = 0;;i++) {
638                 retval = client_read_backend(&buf[i], 1, config.c_sleeping, CCC);
639                 if (retval != 1 || buf[i] == '\n' || i == (bufsize-1))
640                         break;
641         }
642
643         /* If we got a long line, discard characters until the newline.
644          */
645         if (i == (bufsize-1))
646                 while (buf[i] != '\n' && retval == 1)
647                         retval = client_read(&buf[i], 1);
648
649         /* Strip the trailing LF, and the trailing CR if present.
650          */
651         buf[i] = 0;
652         while ( (i > 0)
653                 && ( (buf[i - 1]==13)
654                      || ( buf[i - 1]==10)) ) {
655                 i--;
656                 buf[i] = 0;
657         }
658         if (retval < 0) safestrncpy(&buf[i], "000", bufsize - i);
659         return(retval);
660 }
661
662
663 /*
664  * Cleanup any contexts that are left lying around
665  */
666
667
668 void close_masters (void)
669 {
670         struct ServiceFunctionHook *serviceptr;
671         
672         /*
673          * close all protocol master sockets
674          */
675         for (serviceptr = ServiceHookTable; serviceptr != NULL;
676             serviceptr = serviceptr->next ) {
677
678                 if (serviceptr->tcp_port > 0)
679                 {
680                         CtdlLogPrintf(CTDL_INFO, "Closing listener on port %d\n",
681                                 serviceptr->tcp_port);
682                         serviceptr->tcp_port = 0;
683                 }
684                 
685                 if (serviceptr->sockpath != NULL)
686                         CtdlLogPrintf(CTDL_INFO, "Closing listener on '%s'\n",
687                                 serviceptr->sockpath);
688
689                 close(serviceptr->msock);
690                 /* If it's a Unix domain socket, remove the file. */
691                 if (serviceptr->sockpath != NULL) {
692                         unlink(serviceptr->sockpath);
693                         serviceptr->sockpath = NULL;
694                 }
695         }
696 }
697
698
699 /*
700  * The system-dependent part of master_cleanup() - close the master socket.
701  */
702 void sysdep_master_cleanup(void) {
703         
704         close_masters();
705         
706         context_cleanup();
707         
708 #ifdef HAVE_OPENSSL
709         destruct_ssl();
710 #endif
711         CtdlDestroyProtoHooks();
712         CtdlDestroyDeleteHooks();
713         CtdlDestroyXmsgHooks();
714         CtdlDestroyNetprocHooks();
715         CtdlDestroyUserHooks();
716         CtdlDestroyMessageHook();
717         CtdlDestroyCleanupHooks();
718         CtdlDestroyFixedOutputHooks();  
719         CtdlDestroySessionHooks();
720         CtdlDestroyServiceHook();
721         CtdlDestroyRoomHooks();
722         #ifdef HAVE_BACKTRACE
723 ///     eCrash_Uninit();
724         #endif
725 }
726
727
728
729 pid_t current_child;
730 void graceful_shutdown(int signum) {
731         kill(current_child, signum);
732         unlink(file_pid_file);
733         exit(0);
734 }
735
736 int nFireUps = 0;
737 int nFireUpsNonRestart = 0;
738 pid_t ForkedPid = 1;
739
740 /*
741  * Start running as a daemon.
742  */
743 void start_daemon(int unused) {
744         int status = 0;
745         pid_t child = 0;
746         FILE *fp;
747         int do_restart = 0;
748
749         current_child = 0;
750
751         /* Close stdin/stdout/stderr and replace them with /dev/null.
752          * We don't just call close() because we don't want these fd's
753          * to be reused for other files.
754          */
755         if (chdir(ctdl_run_dir) != 0)
756                 CtdlLogPrintf(CTDL_EMERG, 
757                               "unable to change into directory [%s]: %s", 
758                               ctdl_run_dir, strerror(errno));
759
760         child = fork();
761         if (child != 0) {
762                 exit(0);
763         }
764         
765         signal(SIGHUP, SIG_IGN);
766         signal(SIGINT, SIG_IGN);
767         signal(SIGQUIT, SIG_IGN);
768
769         setsid();
770         umask(0);
771         if ((freopen("/dev/null", "r", stdin) != stdin) || 
772             (freopen("/dev/null", "w", stdout) != stdout) || 
773             (freopen("/dev/null", "w", stderr) != stderr))
774                 CtdlLogPrintf(CTDL_EMERG, 
775                               "unable to reopen stdin/out/err %s", 
776                               strerror(errno));
777                 
778
779         do {
780                 current_child = fork();
781
782                 signal(SIGTERM, graceful_shutdown);
783         
784                 if (current_child < 0) {
785                         perror("fork");
786                         exit(errno);
787                 }
788         
789                 else if (current_child == 0) {
790                         return; /* continue starting citadel. */
791                 }
792         
793                 else {
794                         fp = fopen(file_pid_file, "w");
795                         if (fp != NULL) {
796                                 fprintf(fp, ""F_PID_T"\n", getpid());
797                                 fclose(fp);
798                         }
799                         waitpid(current_child, &status, 0);
800                 }
801                 do_restart = 0;
802                 nFireUpsNonRestart = nFireUps;
803                 
804                 /* Exit code 0 means the watcher should exit */
805                 if (WIFEXITED(status) && (WEXITSTATUS(status) == CTDLEXIT_SHUTDOWN)) {
806                         do_restart = 0;
807                 }
808
809                 /* Exit code 101-109 means the watcher should exit */
810                 else if (WIFEXITED(status) && (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109)) {
811                         do_restart = 0;
812                 }
813
814                 /* Any other exit code, or no exit code, means we should restart. */
815                 else {
816                         do_restart = 1;
817                         nFireUps++;
818                         ForkedPid = current_child;
819                 }
820
821         } while (do_restart);
822
823         unlink(file_pid_file);
824         exit(WEXITSTATUS(status));
825 }
826
827
828
829 void checkcrash(void)
830 {
831         if (nFireUpsNonRestart != nFireUps)
832         {
833                 StrBuf *CrashMail;
834
835                 CrashMail = NewStrBuf();
836                 CtdlLogPrintf(CTDL_ALERT, "Posting crash message\n");
837                 StrBufPrintf(CrashMail, 
838                         " \n"
839                         " The Citadel server process (citserver) terminated unexpectedly."
840                         "\n \n"
841                         " This could be the result of a bug in the server program, or some external "
842                         "factor.\n \n"
843                         " You can obtain more information about this by enabling core dumps.\n \n"
844                         " For more information, please see:\n \n"
845                         " http://citadel.org/doku.php/faq:mastering_your_os:gdb#how.do.i.make.my.system.produce.core-files"
846                         "\n \n"
847 "http://www.4players.de/4players.php/walkthrough/Wii/9298/24733/Die_Chroniken_von_Narnia_Prinz_Kaspian_von_Narnia.html"
848
849                         " If you have already done this, the core dump is likely to be found at %score.%d\n"
850                         ,
851                         ctdl_run_dir, ForkedPid);
852                 CtdlAideMessage(ChrPtr(CrashMail), "Citadel server process terminated unexpectedly");
853                 FreeStrBuf(&CrashMail);
854         }
855 }
856
857
858 /*
859  * Generic routine to convert a login name to a full name (gecos)
860  * Returns nonzero if a conversion took place
861  */
862 int convert_login(char NameToConvert[]) {
863         struct passwd *pw;
864         int a;
865
866         pw = getpwnam(NameToConvert);
867         if (pw == NULL) {
868                 return(0);
869         }
870         else {
871                 strcpy(NameToConvert, pw->pw_gecos);
872                 for (a=0; a<strlen(NameToConvert); ++a) {
873                         if (NameToConvert[a] == ',') NameToConvert[a] = 0;
874                 }
875                 return(1);
876         }
877 }
878
879
880
881 /* 
882  * This loop just keeps going and going and going...
883  */
884 /*
885  * FIXME:
886  * This current implimentation of worker_thread creates a bottle neck in several situations
887  * The first thing to remember is that a single thread can handle more than one connection at a time.
888  * More threads mean less memory for the system to run in.
889  * So for efficiency we want every thread to be doing something useful or waiting in the main loop for
890  * something to happen anywhere.
891  * This current implimentation requires worker threads to wait in other locations, after it has
892  * been committed to a single connection which is very wasteful.
893  * As an extreme case consider this:
894  * A slow client connects and this slow client sends only one character each second.
895  * With this current implimentation a single worker thread is dispatched to handle that connection
896  * until such times as the client timeout expires, an error occurs on the socket or the client
897  * completes its transmission.
898  * THIS IS VERY BAD since that thread could have handled a read from many more clients in each one
899  * second interval between chars.
900  *
901  * It is my intention to re-write this code and the associated client_getln, client_read functions
902  * to allow any thread to read data on behalf of any connection (context).
903  * To do this I intend to have this main loop read chars into a buffer stored in the context.
904  * Once the correct criteria for a full buffer is met then we will dispatch a thread to 
905  * process it.
906  * This worker thread loop also needs to be able to handle binary data.
907  */
908  
909 void *worker_thread(void *arg) {
910         int highest;
911         CitContext *ptr;
912         CitContext *bind_me = NULL;
913         fd_set readfds;
914         int retval = 0;
915         struct timeval tv;
916         int force_purge = 0;
917         
918
919         while (!CtdlThreadCheckStop()) {
920
921                 /* make doubly sure we're not holding any stale db handles
922                  * which might cause a deadlock.
923                  */
924                 cdb_check_handles();
925 do_select:      force_purge = 0;
926                 bind_me = NULL;         /* Which session shall we handle? */
927
928                 /* Initialize the fdset. */
929                 FD_ZERO(&readfds);
930                 highest = 0;
931
932                 begin_critical_section(S_SESSION_TABLE);
933                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
934                         /* Dont select on dead sessions only truly idle ones */
935                         if ((ptr->state == CON_IDLE) && (CC->kill_me == 0)) {
936                                 FD_SET(ptr->client_socket, &readfds);
937                                 if (ptr->client_socket > highest)
938                                         highest = ptr->client_socket;
939                         }
940                         if ((bind_me == NULL) && (ptr->state == CON_READY)) {
941                                 bind_me = ptr;
942                                 ptr->state = CON_EXECUTING;
943                                 break;
944                         }
945                         if ((bind_me == NULL) && (ptr->state == CON_GREETING)) {
946                                 bind_me = ptr;
947                                 ptr->state = CON_STARTING;
948                                 break;
949                         }
950                 }
951                 end_critical_section(S_SESSION_TABLE);
952
953                 if (bind_me) {
954                         goto SKIP_SELECT;
955                 }
956
957                 /* If we got this far, it means that there are no sessions
958                  * which a previous thread marked for attention, so we go
959                  * ahead and get ready to select().
960                  */
961
962                 if (!CtdlThreadCheckStop()) {
963                         tv.tv_sec = 1;          /* wake up every second if no input */
964                         tv.tv_usec = 0;
965                         retval = CtdlThreadSelect(highest + 1, &readfds, NULL, NULL, &tv);
966                 }
967                 else
968                         return NULL;
969
970                 /* Now figure out who made this select() unblock.
971                  * First, check for an error or exit condition.
972                  */
973                 if (retval < 0) {
974                         if (errno == EBADF) {
975                                 CtdlLogPrintf(CTDL_NOTICE, "select() failed: (%s)\n",
976                                         strerror(errno));
977                                 goto do_select;
978                         }
979                         if (errno != EINTR) {
980                                 CtdlLogPrintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
981                                 CtdlThreadStopAll();
982                                 continue;
983                         } else {
984                                 CtdlLogPrintf(CTDL_DEBUG, "Interrupted CtdlThreadSelect.\n");
985                                 if (CtdlThreadCheckStop()) return(NULL);
986                                 goto do_select;
987                         }
988                 }
989                 else if(retval == 0) {
990                         if (CtdlThreadCheckStop()) return(NULL);
991                 }
992
993                 /* It must be a client socket.  Find a context that has data
994                  * waiting on its socket *and* is in the CON_IDLE state.  Any
995                  * active sockets other than our chosen one are marked as
996                  * CON_READY so the next thread that comes around can just bind
997                  * to one without having to select() again.
998                  */
999                 begin_critical_section(S_SESSION_TABLE);
1000                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1001                         if ( (FD_ISSET(ptr->client_socket, &readfds))
1002                            && (ptr->state == CON_IDLE) ) {
1003                                 ptr->input_waiting = 1;
1004                                 if (!bind_me) {
1005                                         bind_me = ptr;  /* I choose you! */
1006                                         bind_me->state = CON_EXECUTING;
1007                                 }
1008                                 else {
1009                                         ptr->state = CON_READY;
1010                                 }
1011                         }
1012                 }
1013                 end_critical_section(S_SESSION_TABLE);
1014
1015 SKIP_SELECT:
1016                 /* We're bound to a session */
1017                 if (bind_me != NULL) {
1018                         become_session(bind_me);
1019
1020                         if (bind_me->state == CON_STARTING) {
1021                                 bind_me->state = CON_EXECUTING;
1022                                 begin_session(bind_me);
1023                                 bind_me->h_greeting_function();
1024                         }
1025                         /* If the client has sent a command, execute it. */
1026                         if (CC->input_waiting) {
1027                                 CC->h_command_function();
1028                                 CC->input_waiting = 0;
1029                         }
1030
1031                         /* If there are asynchronous messages waiting and the
1032                          * client supports it, do those now */
1033                         if ((CC->is_async) && (CC->async_waiting)
1034                            && (CC->h_async_function != NULL)) {
1035                                 CC->h_async_function();
1036                                 CC->async_waiting = 0;
1037                         }
1038                         
1039                         force_purge = CC->kill_me;
1040                         become_session(NULL);
1041                         bind_me->state = CON_IDLE;
1042                 }
1043
1044                 dead_session_purge(force_purge);
1045                 do_housekeeping();
1046         }
1047         /* If control reaches this point, the server is shutting down */        
1048         return(NULL);
1049 }
1050
1051
1052
1053
1054 /*
1055  * A function to handle selecting on master sockets.
1056  * In other words it handles new connections.
1057  * It is a thread.
1058  */
1059 void *select_on_master (void *arg)
1060 {
1061         struct ServiceFunctionHook *serviceptr;
1062         fd_set master_fds;
1063         int highest;
1064         struct timeval tv;
1065         int ssock;                      /* Descriptor for client socket */
1066         CitContext *con= NULL;  /* Temporary context pointer */
1067         int m;
1068         int i;
1069         int retval;
1070
1071         while (!CtdlThreadCheckStop()) {
1072                 /* Initialize the fdset. */
1073                 FD_ZERO(&master_fds);
1074                 highest = 0;
1075
1076                 /* First, add the various master sockets to the fdset. */
1077                 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1078                 serviceptr = serviceptr->next ) {
1079                         m = serviceptr->msock;
1080                         FD_SET(m, &master_fds);
1081                         if (m > highest) {
1082                                 highest = m;
1083                         }
1084                 }
1085
1086                 if (!CtdlThreadCheckStop()) {
1087                         tv.tv_sec = 60;         /* wake up every second if no input */
1088                         tv.tv_usec = 0;
1089                         retval = CtdlThreadSelect(highest + 1, &master_fds, NULL, NULL, &tv);
1090                 }
1091                 else
1092                         return NULL;
1093
1094                 /* Now figure out who made this select() unblock.
1095                  * First, check for an error or exit condition.
1096                  */
1097                 if (retval < 0) {
1098                         if (errno == EBADF) {
1099                                 CtdlLogPrintf(CTDL_NOTICE, "select() failed: (%s)\n",
1100                                         strerror(errno));
1101                                 continue;
1102                         }
1103                         if (errno != EINTR) {
1104                                 CtdlLogPrintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1105                                 CtdlThreadStopAll();
1106                         } else {
1107                                 CtdlLogPrintf(CTDL_DEBUG, "Interrupted CtdlThreadSelect.\n");
1108                                 if (CtdlThreadCheckStop()) return(NULL);
1109                                 continue;
1110                         }
1111                 }
1112                 else if(retval == 0) {
1113                         if (CtdlThreadCheckStop()) return(NULL);
1114                         continue;
1115                 }
1116                 /* Next, check to see if it's a new client connecting
1117                  * on a master socket.
1118                  */
1119                 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1120                      serviceptr = serviceptr->next ) {
1121
1122                         if (FD_ISSET(serviceptr->msock, &master_fds)) {
1123                                 ssock = accept(serviceptr->msock, NULL, 0);
1124                                 if (ssock >= 0) {
1125                                         CtdlLogPrintf(CTDL_DEBUG,
1126                                                 "New client socket %d\n",
1127                                                 ssock);
1128
1129                                         /* The master socket is non-blocking but the client
1130                                          * sockets need to be blocking, otherwise certain
1131                                          * operations barf on FreeBSD.  Not a fatal error.
1132                                          */
1133                                         if (fcntl(ssock, F_SETFL, 0) < 0) {
1134                                                 CtdlLogPrintf(CTDL_EMERG,
1135                                                         "citserver: Can't set socket to blocking: %s\n",
1136                                                         strerror(errno));
1137                                         }
1138
1139                                         /* New context will be created already
1140                                          * set up in the CON_EXECUTING state.
1141                                          */
1142                                         con = CreateNewContext();
1143
1144                                         /* Assign our new socket number to it. */
1145                                         con->client_socket = ssock;
1146                                         con->h_command_function =
1147                                                 serviceptr->h_command_function;
1148                                         con->h_async_function =
1149                                                 serviceptr->h_async_function;
1150                                         con->h_greeting_function = serviceptr->h_greeting_function;
1151                                         con->ServiceName =
1152                                                 serviceptr->ServiceName;
1153                                         
1154                                         /* Determine whether it's a local socket */
1155                                         if (serviceptr->sockpath != NULL)
1156                                                 con->is_local_socket = 1;
1157         
1158                                         /* Set the SO_REUSEADDR socket option */
1159                                         i = 1;
1160                                         setsockopt(ssock, SOL_SOCKET,
1161                                                 SO_REUSEADDR,
1162                                                 &i, sizeof(i));
1163
1164                                         con->state = CON_GREETING;
1165
1166                                         retval--;
1167                                         if (retval == 0)
1168                                                 break;
1169                                 }
1170                         }
1171                 }
1172         }
1173         return NULL;
1174 }
1175
1176
1177
1178 /*
1179  * SyslogFacility()
1180  * Translate text facility name to syslog.h defined value.
1181  */
1182 int SyslogFacility(char *name)
1183 {
1184         int i;
1185         struct
1186         {
1187                 int facility;
1188                 char *name;
1189         }   facTbl[] =
1190         {
1191                 {   LOG_KERN,   "kern"          },
1192                 {   LOG_USER,   "user"          },
1193                 {   LOG_MAIL,   "mail"          },
1194                 {   LOG_DAEMON, "daemon"        },
1195                 {   LOG_AUTH,   "auth"          },
1196                 {   LOG_SYSLOG, "syslog"        },
1197                 {   LOG_LPR,    "lpr"           },
1198                 {   LOG_NEWS,   "news"          },
1199                 {   LOG_UUCP,   "uucp"          },
1200                 {   LOG_LOCAL0, "local0"        },
1201                 {   LOG_LOCAL1, "local1"        },
1202                 {   LOG_LOCAL2, "local2"        },
1203                 {   LOG_LOCAL3, "local3"        },
1204                 {   LOG_LOCAL4, "local4"        },
1205                 {   LOG_LOCAL5, "local5"        },
1206                 {   LOG_LOCAL6, "local6"        },
1207                 {   LOG_LOCAL7, "local7"        },
1208                 {   0,            NULL          }
1209         };
1210         for(i = 0; facTbl[i].name != NULL; i++) {
1211                 if(!strcasecmp(name, facTbl[i].name))
1212                         return facTbl[i].facility;
1213         }
1214         enable_syslog = 0;
1215         return LOG_DAEMON;
1216 }
1217
1218
1219 /********** MEM CHEQQER ***********/
1220
1221 #ifdef DEBUG_MEMORY_LEAKS
1222
1223 #undef malloc
1224 #undef realloc
1225 #undef strdup
1226 #undef free
1227
1228 void *tracked_malloc(size_t size, char *file, int line) {
1229         struct igheap *thisheap;
1230         void *block;
1231
1232         block = malloc(size);
1233         if (block == NULL) return(block);
1234
1235         thisheap = malloc(sizeof(struct igheap));
1236         if (thisheap == NULL) {
1237                 free(block);
1238                 return(NULL);
1239         }
1240
1241         thisheap->block = block;
1242         strcpy(thisheap->file, file);
1243         thisheap->line = line;
1244         
1245         begin_critical_section(S_DEBUGMEMLEAKS);
1246         thisheap->next = igheap;
1247         igheap = thisheap;
1248         end_critical_section(S_DEBUGMEMLEAKS);
1249
1250         return(block);
1251 }
1252
1253
1254 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
1255         struct igheap *thisheap;
1256         void *block;
1257
1258         block = realloc(ptr, size);
1259         if (block == NULL) return(block);
1260
1261         thisheap = malloc(sizeof(struct igheap));
1262         if (thisheap == NULL) {
1263                 free(block);
1264                 return(NULL);
1265         }
1266
1267         thisheap->block = block;
1268         strcpy(thisheap->file, file);
1269         thisheap->line = line;
1270         
1271         begin_critical_section(S_DEBUGMEMLEAKS);
1272         thisheap->next = igheap;
1273         igheap = thisheap;
1274         end_critical_section(S_DEBUGMEMLEAKS);
1275
1276         return(block);
1277 }
1278
1279
1280
1281 void tracked_free(void *ptr) {
1282         struct igheap *thisheap;
1283         struct igheap *trash;
1284
1285         free(ptr);
1286
1287         if (igheap == NULL) return;
1288         begin_critical_section(S_DEBUGMEMLEAKS);
1289         for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1290                 if (thisheap->next != NULL) {
1291                         if (thisheap->next->block == ptr) {
1292                                 trash = thisheap->next;
1293                                 thisheap->next = thisheap->next->next;
1294                                 free(trash);
1295                         }
1296                 }
1297         }
1298         if (igheap->block == ptr) {
1299                 trash = igheap;
1300                 igheap = igheap->next;
1301                 free(trash);
1302         }
1303         end_critical_section(S_DEBUGMEMLEAKS);
1304 }
1305
1306 char *tracked_strdup(const char *s, char *file, int line) {
1307         char *ptr;
1308
1309         if (s == NULL) return(NULL);
1310         ptr = tracked_malloc(strlen(s) + 1, file, line);
1311         if (ptr == NULL) return(NULL);
1312         strncpy(ptr, s, strlen(s));
1313         return(ptr);
1314 }
1315
1316 void dump_heap(void) {
1317         struct igheap *thisheap;
1318
1319         for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1320                 CtdlLogPrintf(CTDL_CRIT, "UNFREED: %30s : %d\n",
1321                         thisheap->file, thisheap->line);
1322         }
1323 }
1324
1325 #endif /*  DEBUG_MEMORY_LEAKS */