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