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