0420bc6c168a2b8e1937be9304f77eb5388b3542
[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 static void flush_client_inbuf(void)
440 {
441         CitContext *CCC=CC;
442
443         FlushStrBuf(CCC->ReadBuf);
444         CCC->Pos = NULL;
445
446 }
447
448 /*
449  * client_write()   ...    Send binary data to the client.
450  */
451 int client_write(const char *buf, int nbytes)
452 {
453         int bytes_written = 0;
454         int retval;
455 #ifndef HAVE_TCP_BUFFERING
456         int old_buffer_len = 0;
457 #endif
458         fd_set wset;
459         CitContext *Ctx;
460         int fdflags;
461
462         flush_client_inbuf();
463         Ctx = CC;
464         if (Ctx->redirect_buffer != NULL) {
465                 if ((Ctx->redirect_len + nbytes + 2) >= Ctx->redirect_alloc) {
466                         Ctx->redirect_alloc = (Ctx->redirect_alloc * 2) + nbytes;
467                         Ctx->redirect_buffer = realloc(Ctx->redirect_buffer,
468                                                 Ctx->redirect_alloc);
469                 }
470                 memcpy(&Ctx->redirect_buffer[Ctx->redirect_len], buf, nbytes);
471                 Ctx->redirect_len += nbytes;
472                 Ctx->redirect_buffer[Ctx->redirect_len] = 0;
473                 return 0;
474         }
475
476 #ifdef HAVE_OPENSSL
477         if (Ctx->redirect_ssl) {
478                 client_write_ssl(buf, nbytes);
479                 return 0;
480         }
481 #endif
482
483         fdflags = fcntl(Ctx->client_socket, F_GETFL);
484
485         while (bytes_written < nbytes) {
486                 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
487                         FD_ZERO(&wset);
488                         FD_SET(Ctx->client_socket, &wset);
489                         if (select(1, NULL, &wset, NULL, NULL) == -1) {
490                                 if (errno == EINTR)
491                                 {
492                                         CtdlLogPrintf(CTDL_DEBUG, "client_write(%d bytes) select() interrupted.\n", nbytes-bytes_written);
493                                         if (CtdlThreadCheckStop()) {
494                                                 CC->kill_me = 1;
495                                                 return (-1);
496                                         } else {
497                                                 /* can't trust fd's and stuff so we need to re-create them */
498                                                 continue;
499                                         }
500                                 } else {
501                                         CtdlLogPrintf(CTDL_ERR,
502                                                 "client_write(%d bytes) select failed: %s (%d)\n",
503                                                 nbytes - bytes_written,
504                                                 strerror(errno), errno);
505                                         cit_backtrace();
506                                         Ctx->kill_me = 1;
507                                         return -1;
508                                 }
509                         }
510                 }
511
512                 retval = write(Ctx->client_socket, &buf[bytes_written],
513                         nbytes - bytes_written);
514                 if (retval < 1) {
515                         CtdlLogPrintf(CTDL_ERR,
516                                 "client_write(%d bytes) failed: %s (%d)\n",
517                                 nbytes - bytes_written,
518                                 strerror(errno), errno);
519                         cit_backtrace();
520                         // CtdlLogPrintf(CTDL_DEBUG, "Tried to send: %s",  &buf[bytes_written]);
521                         Ctx->kill_me = 1;
522                         return -1;
523                 }
524                 bytes_written = bytes_written + retval;
525         }
526         return 0;
527 }
528
529 void cputbuf(const StrBuf *Buf) {   
530         client_write(ChrPtr(Buf), StrLength(Buf)); 
531 }   
532
533
534 /*
535  * cprintf()    Send formatted printable data to the client.
536  *              Implemented in terms of client_write() so it's technically not sysdep...
537  */
538 void cprintf(const char *format, ...) {   
539         va_list arg_ptr;   
540         char buf[1024];
541    
542         va_start(arg_ptr, format);   
543         if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
544                 buf[sizeof buf - 2] = '\n';
545         client_write(buf, strlen(buf)); 
546         va_end(arg_ptr);
547 }   
548
549
550 /*
551  * Read data from the client socket.
552  *
553  * sock         socket fd to read from
554  * buf          buffer to read into 
555  * bytes        number of bytes to read
556  * timeout      Number of seconds to wait before timing out
557  *
558  * Possible return values:
559  *      1       Requested number of bytes has been read.
560  *      0       Request timed out.
561  *      -1      Connection is broken, or other error.
562  */
563 int client_read_blob(StrBuf *Target, int bytes, int timeout)
564 {
565         CitContext *CCC=CC;
566         const char *Error;
567         int retval = 0;
568
569 #ifdef HAVE_OPENSSL
570         if (CCC->redirect_ssl) {
571                 retval = client_read_sslblob(Target, bytes, timeout);
572         }
573         else 
574 #endif
575
576                 retval = StrBufReadBLOBBuffered(Target, 
577                                                 CCC->ReadBuf,
578                                                 &CCC->Pos,
579                                                 &CCC->client_socket,
580                                                 1, 
581                                                 bytes,
582                                                 O_TERM,
583                                                 &Error);
584         if (retval < 0) {
585                 CtdlLogPrintf(CTDL_CRIT, 
586                               "%s failed: %s\n",
587                               __FUNCTION__,
588                               Error);
589         }
590         return retval;
591 }
592
593 int client_read_to(char *buf, int bytes, int timeout)
594 {
595         CitContext *CCC=CC;
596         int rc;
597
598         rc = client_read_blob(CCC->MigrateBuf, bytes, timeout);
599         if (rc < 0)
600         {
601                 *buf = '\0';
602                 return rc;
603         }
604         else
605         {
606                 memcpy(buf, 
607                        ChrPtr(CCC->MigrateBuf),
608                        StrLength(CCC->MigrateBuf) + 1);
609                 FlushStrBuf(CCC->MigrateBuf);
610                 return rc;
611         }
612 }
613
614
615 int HaveMoreLinesWaiting(CitContext *CCC)
616 {
617         if ((CCC->Pos == NULL) && (StrLength(CCC->ReadBuf) == 0))
618                 return 0;
619         else
620                 return 1;
621 }
622
623
624 /*
625  * Read data from the client socket with default timeout.
626  * (This is implemented in terms of client_read_to() and could be
627  * justifiably moved out of sysdep.c)
628  */
629 INLINE int client_read(char *buf, int bytes)
630 {
631         return(client_read_to(buf, bytes, config.c_sleeping));
632 }
633
634 int CtdlClientGetLine(StrBuf *Target)
635 {
636         CitContext *CCC=CC;
637         const char *Error;
638         int rc;
639
640 #ifdef HAVE_OPENSSL
641         if (CCC->redirect_ssl) {
642                 return client_readline_sslbuffer(Target,
643                                                  CCC->ReadBuf,
644                                                  1);
645         }
646         else 
647 #endif
648         {
649                 rc = StrBufTCP_read_buffered_line_fast(Target, 
650                                                        CCC->ReadBuf,
651                                                        &CCC->Pos,
652                                                        &CCC->client_socket,
653                                                        5,
654                                                        1,
655                                                        &Error);
656                 if ((rc < 0) && (Error != NULL))
657                         CtdlLogPrintf(CTDL_CRIT, 
658                                       "%s failed: %s\n",
659                                       __FUNCTION__,
660                                       Error);
661                 return rc;
662         }
663 }
664
665
666 /*
667  * client_getln()   ...   Get a LF-terminated line of text from the client.
668  * (This is implemented in terms of client_read() and could be
669  * justifiably moved out of sysdep.c)
670  */
671 int client_getln(char *buf, int bufsize)
672 {
673         int i, retval;
674         CitContext *CCC=CC;
675         const char *pCh;
676
677         retval = CtdlClientGetLine(CCC->MigrateBuf);
678
679         i = StrLength(CCC->MigrateBuf);
680         pCh = ChrPtr(CCC->MigrateBuf);
681         /* Strip the trailing LF, and the trailing CR if present.
682          */
683         if (bufsize <= i)
684                 i = bufsize - 1;
685         while ( (i > 0)
686                 && ( (pCh[i - 1]==13)
687                      || ( pCh[i - 1]==10)) ) {
688                 i--;
689         }
690         memcpy(buf, pCh, i);
691         buf[i] = 0;
692
693         FlushStrBuf(CCC->MigrateBuf);
694         if (retval < 0) {
695                 safestrncpy(&buf[i], "000", bufsize - i);
696         }
697         return(retval >= 0);
698 }
699
700
701 /*
702  * Cleanup any contexts that are left lying around
703  */
704
705
706 void close_masters (void)
707 {
708         struct ServiceFunctionHook *serviceptr;
709         
710         /*
711          * close all protocol master sockets
712          */
713         for (serviceptr = ServiceHookTable; serviceptr != NULL;
714             serviceptr = serviceptr->next ) {
715
716                 if (serviceptr->tcp_port > 0)
717                 {
718                         CtdlLogPrintf(CTDL_INFO, "Closing listener on port %d\n",
719                                 serviceptr->tcp_port);
720                         serviceptr->tcp_port = 0;
721                 }
722                 
723                 if (serviceptr->sockpath != NULL)
724                         CtdlLogPrintf(CTDL_INFO, "Closing listener on '%s'\n",
725                                 serviceptr->sockpath);
726
727                 close(serviceptr->msock);
728                 /* If it's a Unix domain socket, remove the file. */
729                 if (serviceptr->sockpath != NULL) {
730                         unlink(serviceptr->sockpath);
731                         serviceptr->sockpath = NULL;
732                 }
733         }
734 }
735
736
737 /*
738  * The system-dependent part of master_cleanup() - close the master socket.
739  */
740 void sysdep_master_cleanup(void) {
741         
742         close_masters();
743         
744         context_cleanup();
745         
746 #ifdef HAVE_OPENSSL
747         destruct_ssl();
748 #endif
749         CtdlDestroyProtoHooks();
750         CtdlDestroyDeleteHooks();
751         CtdlDestroyXmsgHooks();
752         CtdlDestroyNetprocHooks();
753         CtdlDestroyUserHooks();
754         CtdlDestroyMessageHook();
755         CtdlDestroyCleanupHooks();
756         CtdlDestroyFixedOutputHooks();  
757         CtdlDestroySessionHooks();
758         CtdlDestroyServiceHook();
759         CtdlDestroyRoomHooks();
760         #ifdef HAVE_BACKTRACE
761 ///     eCrash_Uninit();
762         #endif
763 }
764
765
766
767 pid_t current_child;
768 void graceful_shutdown(int signum) {
769         kill(current_child, signum);
770         unlink(file_pid_file);
771         exit(0);
772 }
773
774 int nFireUps = 0;
775 int nFireUpsNonRestart = 0;
776 pid_t ForkedPid = 1;
777
778 /*
779  * Start running as a daemon.
780  */
781 void start_daemon(int unused) {
782         int status = 0;
783         pid_t child = 0;
784         FILE *fp;
785         int do_restart = 0;
786
787         current_child = 0;
788
789         /* Close stdin/stdout/stderr and replace them with /dev/null.
790          * We don't just call close() because we don't want these fd's
791          * to be reused for other files.
792          */
793         if (chdir(ctdl_run_dir) != 0)
794                 CtdlLogPrintf(CTDL_EMERG, 
795                               "unable to change into directory [%s]: %s", 
796                               ctdl_run_dir, strerror(errno));
797
798         child = fork();
799         if (child != 0) {
800                 exit(0);
801         }
802         
803         signal(SIGHUP, SIG_IGN);
804         signal(SIGINT, SIG_IGN);
805         signal(SIGQUIT, SIG_IGN);
806
807         setsid();
808         umask(0);
809         if ((freopen("/dev/null", "r", stdin) != stdin) || 
810             (freopen("/dev/null", "w", stdout) != stdout) || 
811             (freopen("/dev/null", "w", stderr) != stderr))
812                 CtdlLogPrintf(CTDL_EMERG, 
813                               "unable to reopen stdin/out/err %s", 
814                               strerror(errno));
815                 
816
817         do {
818                 current_child = fork();
819
820                 signal(SIGTERM, graceful_shutdown);
821         
822                 if (current_child < 0) {
823                         perror("fork");
824                         exit(errno);
825                 }
826         
827                 else if (current_child == 0) {
828                         return; /* continue starting citadel. */
829                 }
830         
831                 else {
832                         fp = fopen(file_pid_file, "w");
833                         if (fp != NULL) {
834                                 fprintf(fp, ""F_PID_T"\n", getpid());
835                                 fclose(fp);
836                         }
837                         waitpid(current_child, &status, 0);
838                 }
839                 do_restart = 0;
840                 nFireUpsNonRestart = nFireUps;
841                 
842                 /* Exit code 0 means the watcher should exit */
843                 if (WIFEXITED(status) && (WEXITSTATUS(status) == CTDLEXIT_SHUTDOWN)) {
844                         do_restart = 0;
845                 }
846
847                 /* Exit code 101-109 means the watcher should exit */
848                 else if (WIFEXITED(status) && (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109)) {
849                         do_restart = 0;
850                 }
851
852                 /* Any other exit code, or no exit code, means we should restart. */
853                 else {
854                         do_restart = 1;
855                         nFireUps++;
856                         ForkedPid = current_child;
857                 }
858
859         } while (do_restart);
860
861         unlink(file_pid_file);
862         exit(WEXITSTATUS(status));
863 }
864
865
866
867 void checkcrash(void)
868 {
869         if (nFireUpsNonRestart != nFireUps)
870         {
871                 StrBuf *CrashMail;
872
873                 CrashMail = NewStrBuf();
874                 CtdlLogPrintf(CTDL_ALERT, "Posting crash message\n");
875                 StrBufPrintf(CrashMail, 
876                         " \n"
877                         " The Citadel server process (citserver) terminated unexpectedly."
878                         "\n \n"
879                         " This could be the result of a bug in the server program, or some external "
880                         "factor.\n \n"
881                         " You can obtain more information about this by enabling core dumps.\n \n"
882                         " For more information, please see:\n \n"
883                         " http://citadel.org/doku.php/faq:mastering_your_os:gdb#how.do.i.make.my.system.produce.core-files"
884                         "\n \n"
885
886                         " If you have already done this, the core dump is likely to be found at %score.%d\n"
887                         ,
888                         ctdl_run_dir, ForkedPid);
889                 CtdlAideMessage(ChrPtr(CrashMail), "Citadel server process terminated unexpectedly");
890                 FreeStrBuf(&CrashMail);
891         }
892 }
893
894
895 /*
896  * Generic routine to convert a login name to a full name (gecos)
897  * Returns nonzero if a conversion took place
898  */
899 int convert_login(char NameToConvert[]) {
900         struct passwd *pw;
901         int a;
902
903         pw = getpwnam(NameToConvert);
904         if (pw == NULL) {
905                 return(0);
906         }
907         else {
908                 strcpy(NameToConvert, pw->pw_gecos);
909                 for (a=0; a<strlen(NameToConvert); ++a) {
910                         if (NameToConvert[a] == ',') NameToConvert[a] = 0;
911                 }
912                 return(1);
913         }
914 }
915
916
917
918 /* 
919  * This loop just keeps going and going and going...
920  */
921 /*
922  * FIXME:
923  * This current implimentation of worker_thread creates a bottle neck in several situations
924  * The first thing to remember is that a single thread can handle more than one connection at a time.
925  * More threads mean less memory for the system to run in.
926  * So for efficiency we want every thread to be doing something useful or waiting in the main loop for
927  * something to happen anywhere.
928  * This current implimentation requires worker threads to wait in other locations, after it has
929  * been committed to a single connection which is very wasteful.
930  * As an extreme case consider this:
931  * A slow client connects and this slow client sends only one character each second.
932  * With this current implimentation a single worker thread is dispatched to handle that connection
933  * until such times as the client timeout expires, an error occurs on the socket or the client
934  * completes its transmission.
935  * THIS IS VERY BAD since that thread could have handled a read from many more clients in each one
936  * second interval between chars.
937  *
938  * It is my intention to re-write this code and the associated client_getln, client_read functions
939  * to allow any thread to read data on behalf of any connection (context).
940  * To do this I intend to have this main loop read chars into a buffer stored in the context.
941  * Once the correct criteria for a full buffer is met then we will dispatch a thread to 
942  * process it.
943  * This worker thread loop also needs to be able to handle binary data.
944  */
945  
946 void *worker_thread(void *arg) {
947         int highest;
948         CitContext *ptr;
949         CitContext *bind_me = NULL;
950         fd_set readfds;
951         int retval = 0;
952         struct timeval tv;
953         int force_purge = 0;
954         
955
956         while (!CtdlThreadCheckStop()) {
957
958                 /* make doubly sure we're not holding any stale db handles
959                  * which might cause a deadlock.
960                  */
961                 cdb_check_handles();
962 do_select:      force_purge = 0;
963                 bind_me = NULL;         /* Which session shall we handle? */
964
965                 /* Initialize the fdset. */
966                 FD_ZERO(&readfds);
967                 highest = 0;
968
969                 begin_critical_section(S_SESSION_TABLE);
970                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
971                         /* Dont select on dead sessions only truly idle ones */
972                         if ((ptr->state == CON_IDLE) && (CC->kill_me == 0)) {
973                                 FD_SET(ptr->client_socket, &readfds);
974                                 if (ptr->client_socket > highest)
975                                         highest = ptr->client_socket;
976                         }
977                         if ((bind_me == NULL) && (ptr->state == CON_READY)) {
978                                 bind_me = ptr;
979                                 ptr->state = CON_EXECUTING;
980                                 break;
981                         }
982                         if ((bind_me == NULL) && (ptr->state == CON_GREETING)) {
983                                 bind_me = ptr;
984                                 ptr->state = CON_STARTING;
985                                 break;
986                         }
987                 }
988                 end_critical_section(S_SESSION_TABLE);
989
990                 if (bind_me) {
991                         goto SKIP_SELECT;
992                 }
993
994                 /* If we got this far, it means that there are no sessions
995                  * which a previous thread marked for attention, so we go
996                  * ahead and get ready to select().
997                  */
998
999                 if (!CtdlThreadCheckStop()) {
1000                         tv.tv_sec = 1;          /* wake up every second if no input */
1001                         tv.tv_usec = 0;
1002                         retval = CtdlThreadSelect(highest + 1, &readfds, NULL, NULL, &tv);
1003                 }
1004                 else
1005                         return NULL;
1006
1007                 /* Now figure out who made this select() unblock.
1008                  * First, check for an error or exit condition.
1009                  */
1010                 if (retval < 0) {
1011                         if (errno == EBADF) {
1012                                 CtdlLogPrintf(CTDL_NOTICE, "select() failed: (%s)\n",
1013                                         strerror(errno));
1014                                 goto do_select;
1015                         }
1016                         if (errno != EINTR) {
1017                                 CtdlLogPrintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1018                                 CtdlThreadStopAll();
1019                                 continue;
1020                         } else {
1021                                 CtdlLogPrintf(CTDL_DEBUG, "Interrupted CtdlThreadSelect.\n");
1022                                 if (CtdlThreadCheckStop()) return(NULL);
1023                                 goto do_select;
1024                         }
1025                 }
1026                 else if(retval == 0) {
1027                         if (CtdlThreadCheckStop()) return(NULL);
1028                 }
1029
1030                 /* It must be a client socket.  Find a context that has data
1031                  * waiting on its socket *and* is in the CON_IDLE state.  Any
1032                  * active sockets other than our chosen one are marked as
1033                  * CON_READY so the next thread that comes around can just bind
1034                  * to one without having to select() again.
1035                  */
1036                 begin_critical_section(S_SESSION_TABLE);
1037                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1038                         if ( (FD_ISSET(ptr->client_socket, &readfds))
1039                            && (ptr->state == CON_IDLE) ) {
1040                                 ptr->input_waiting = 1;
1041                                 if (!bind_me) {
1042                                         bind_me = ptr;  /* I choose you! */
1043                                         bind_me->state = CON_EXECUTING;
1044                                 }
1045                                 else {
1046                                         ptr->state = CON_READY;
1047                                 }
1048                         }
1049                 }
1050                 end_critical_section(S_SESSION_TABLE);
1051
1052 SKIP_SELECT:
1053                 /* We're bound to a session */
1054                 if (bind_me != NULL) {
1055                         become_session(bind_me);
1056
1057                         if (bind_me->state == CON_STARTING) {
1058                                 bind_me->state = CON_EXECUTING;
1059                                 begin_session(bind_me);
1060                                 bind_me->h_greeting_function();
1061                         }
1062                         /* If the client has sent a command, execute it. */
1063                         if (CC->input_waiting) {
1064                                 CC->h_command_function();
1065
1066                                 while (HaveMoreLinesWaiting(CC))
1067                                        CC->h_command_function();
1068
1069                                 CC->input_waiting = 0;
1070                         }
1071
1072                         /* If there are asynchronous messages waiting and the
1073                          * client supports it, do those now */
1074                         if ((CC->is_async) && (CC->async_waiting)
1075                            && (CC->h_async_function != NULL)) {
1076                                 CC->h_async_function();
1077                                 CC->async_waiting = 0;
1078                         }
1079                         
1080                         force_purge = CC->kill_me;
1081                         become_session(NULL);
1082                         bind_me->state = CON_IDLE;
1083                 }
1084
1085                 dead_session_purge(force_purge);
1086                 do_housekeeping();
1087         }
1088         /* If control reaches this point, the server is shutting down */        
1089         return(NULL);
1090 }
1091
1092
1093
1094
1095 /*
1096  * A function to handle selecting on master sockets.
1097  * In other words it handles new connections.
1098  * It is a thread.
1099  */
1100 void *select_on_master (void *arg)
1101 {
1102         struct ServiceFunctionHook *serviceptr;
1103         fd_set master_fds;
1104         int highest;
1105         struct timeval tv;
1106         int ssock;                      /* Descriptor for client socket */
1107         CitContext *con= NULL;  /* Temporary context pointer */
1108         int m;
1109         int i;
1110         int retval;
1111
1112         while (!CtdlThreadCheckStop()) {
1113                 /* Initialize the fdset. */
1114                 FD_ZERO(&master_fds);
1115                 highest = 0;
1116
1117                 /* First, add the various master sockets to the fdset. */
1118                 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1119                 serviceptr = serviceptr->next ) {
1120                         m = serviceptr->msock;
1121                         FD_SET(m, &master_fds);
1122                         if (m > highest) {
1123                                 highest = m;
1124                         }
1125                 }
1126
1127                 if (!CtdlThreadCheckStop()) {
1128                         tv.tv_sec = 60;         /* wake up every second if no input */
1129                         tv.tv_usec = 0;
1130                         retval = CtdlThreadSelect(highest + 1, &master_fds, NULL, NULL, &tv);
1131                 }
1132                 else
1133                         return NULL;
1134
1135                 /* Now figure out who made this select() unblock.
1136                  * First, check for an error or exit condition.
1137                  */
1138                 if (retval < 0) {
1139                         if (errno == EBADF) {
1140                                 CtdlLogPrintf(CTDL_NOTICE, "select() failed: (%s)\n",
1141                                         strerror(errno));
1142                                 continue;
1143                         }
1144                         if (errno != EINTR) {
1145                                 CtdlLogPrintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1146                                 CtdlThreadStopAll();
1147                         } else {
1148                                 CtdlLogPrintf(CTDL_DEBUG, "Interrupted CtdlThreadSelect.\n");
1149                                 if (CtdlThreadCheckStop()) return(NULL);
1150                                 continue;
1151                         }
1152                 }
1153                 else if(retval == 0) {
1154                         if (CtdlThreadCheckStop()) return(NULL);
1155                         continue;
1156                 }
1157                 /* Next, check to see if it's a new client connecting
1158                  * on a master socket.
1159                  */
1160                 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1161                      serviceptr = serviceptr->next ) {
1162
1163                         if (FD_ISSET(serviceptr->msock, &master_fds)) {
1164                                 ssock = accept(serviceptr->msock, NULL, 0);
1165                                 if (ssock >= 0) {
1166                                         CtdlLogPrintf(CTDL_DEBUG,
1167                                                 "New client socket %d\n",
1168                                                 ssock);
1169
1170                                         /* The master socket is non-blocking but the client
1171                                          * sockets need to be blocking, otherwise certain
1172                                          * operations barf on FreeBSD.  Not a fatal error.
1173                                          */
1174                                         if (fcntl(ssock, F_SETFL, 0) < 0) {
1175                                                 CtdlLogPrintf(CTDL_EMERG,
1176                                                         "citserver: Can't set socket to blocking: %s\n",
1177                                                         strerror(errno));
1178                                         }
1179
1180                                         /* New context will be created already
1181                                          * set up in the CON_EXECUTING state.
1182                                          */
1183                                         con = CreateNewContext();
1184
1185                                         /* Assign our new socket number to it. */
1186                                         con->client_socket = ssock;
1187                                         con->h_command_function =
1188                                                 serviceptr->h_command_function;
1189                                         con->h_async_function =
1190                                                 serviceptr->h_async_function;
1191                                         con->h_greeting_function = serviceptr->h_greeting_function;
1192                                         con->ServiceName =
1193                                                 serviceptr->ServiceName;
1194                                         
1195                                         /* Determine whether it's a local socket */
1196                                         if (serviceptr->sockpath != NULL)
1197                                                 con->is_local_socket = 1;
1198         
1199                                         /* Set the SO_REUSEADDR socket option */
1200                                         i = 1;
1201                                         setsockopt(ssock, SOL_SOCKET,
1202                                                 SO_REUSEADDR,
1203                                                 &i, sizeof(i));
1204
1205                                         con->state = CON_GREETING;
1206
1207                                         retval--;
1208                                         if (retval == 0)
1209                                                 break;
1210                                 }
1211                         }
1212                 }
1213         }
1214         return NULL;
1215 }
1216
1217
1218
1219 /*
1220  * SyslogFacility()
1221  * Translate text facility name to syslog.h defined value.
1222  */
1223 int SyslogFacility(char *name)
1224 {
1225         int i;
1226         struct
1227         {
1228                 int facility;
1229                 char *name;
1230         }   facTbl[] =
1231         {
1232                 {   LOG_KERN,   "kern"          },
1233                 {   LOG_USER,   "user"          },
1234                 {   LOG_MAIL,   "mail"          },
1235                 {   LOG_DAEMON, "daemon"        },
1236                 {   LOG_AUTH,   "auth"          },
1237                 {   LOG_SYSLOG, "syslog"        },
1238                 {   LOG_LPR,    "lpr"           },
1239                 {   LOG_NEWS,   "news"          },
1240                 {   LOG_UUCP,   "uucp"          },
1241                 {   LOG_LOCAL0, "local0"        },
1242                 {   LOG_LOCAL1, "local1"        },
1243                 {   LOG_LOCAL2, "local2"        },
1244                 {   LOG_LOCAL3, "local3"        },
1245                 {   LOG_LOCAL4, "local4"        },
1246                 {   LOG_LOCAL5, "local5"        },
1247                 {   LOG_LOCAL6, "local6"        },
1248                 {   LOG_LOCAL7, "local7"        },
1249                 {   0,            NULL          }
1250         };
1251         for(i = 0; facTbl[i].name != NULL; i++) {
1252                 if(!strcasecmp(name, facTbl[i].name))
1253                         return facTbl[i].facility;
1254         }
1255         enable_syslog = 0;
1256         return LOG_DAEMON;
1257 }
1258
1259
1260 /********** MEM CHEQQER ***********/
1261
1262 #ifdef DEBUG_MEMORY_LEAKS
1263
1264 #undef malloc
1265 #undef realloc
1266 #undef strdup
1267 #undef free
1268
1269 void *tracked_malloc(size_t size, char *file, int line) {
1270         struct igheap *thisheap;
1271         void *block;
1272
1273         block = malloc(size);
1274         if (block == NULL) return(block);
1275
1276         thisheap = malloc(sizeof(struct igheap));
1277         if (thisheap == NULL) {
1278                 free(block);
1279                 return(NULL);
1280         }
1281
1282         thisheap->block = block;
1283         strcpy(thisheap->file, file);
1284         thisheap->line = line;
1285         
1286         begin_critical_section(S_DEBUGMEMLEAKS);
1287         thisheap->next = igheap;
1288         igheap = thisheap;
1289         end_critical_section(S_DEBUGMEMLEAKS);
1290
1291         return(block);
1292 }
1293
1294
1295 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
1296         struct igheap *thisheap;
1297         void *block;
1298
1299         block = realloc(ptr, size);
1300         if (block == NULL) return(block);
1301
1302         thisheap = malloc(sizeof(struct igheap));
1303         if (thisheap == NULL) {
1304                 free(block);
1305                 return(NULL);
1306         }
1307
1308         thisheap->block = block;
1309         strcpy(thisheap->file, file);
1310         thisheap->line = line;
1311         
1312         begin_critical_section(S_DEBUGMEMLEAKS);
1313         thisheap->next = igheap;
1314         igheap = thisheap;
1315         end_critical_section(S_DEBUGMEMLEAKS);
1316
1317         return(block);
1318 }
1319
1320
1321
1322 void tracked_free(void *ptr) {
1323         struct igheap *thisheap;
1324         struct igheap *trash;
1325
1326         free(ptr);
1327
1328         if (igheap == NULL) return;
1329         begin_critical_section(S_DEBUGMEMLEAKS);
1330         for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1331                 if (thisheap->next != NULL) {
1332                         if (thisheap->next->block == ptr) {
1333                                 trash = thisheap->next;
1334                                 thisheap->next = thisheap->next->next;
1335                                 free(trash);
1336                         }
1337                 }
1338         }
1339         if (igheap->block == ptr) {
1340                 trash = igheap;
1341                 igheap = igheap->next;
1342                 free(trash);
1343         }
1344         end_critical_section(S_DEBUGMEMLEAKS);
1345 }
1346
1347 char *tracked_strdup(const char *s, char *file, int line) {
1348         char *ptr;
1349
1350         if (s == NULL) return(NULL);
1351         ptr = tracked_malloc(strlen(s) + 1, file, line);
1352         if (ptr == NULL) return(NULL);
1353         strncpy(ptr, s, strlen(s));
1354         return(ptr);
1355 }
1356
1357 void dump_heap(void) {
1358         struct igheap *thisheap;
1359
1360         for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1361                 CtdlLogPrintf(CTDL_CRIT, "UNFREED: %30s : %d\n",
1362                         thisheap->file, thisheap->line);
1363         }
1364 }
1365
1366 #endif /*  DEBUG_MEMORY_LEAKS */