]> code.citadel.org Git - citadel.git/blob - citadel/sysdep.c
Moved all of the background tasks back to the old EVT_TIMER style
[citadel.git] / citadel / sysdep.c
1 /*
2  * Citadel "system dependent" stuff.
3  *
4  * Here's where we (hopefully) have most parts of the Citadel server that
5  * would need to be altered to run the server in a non-POSIX environment.
6  * 
7  * If we ever port to a different platform and either have multiple
8  * variants of this file or simply load it up with #ifdefs.
9  *
10  * Copyright (c) 1987-2011 by the citadel.org team
11  *
12  * This program is open source software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 3 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25  */
26
27 #include "sysdep.h"
28 #include <stdlib.h>
29 #include <unistd.h>
30 #include <stdio.h>
31 #include <fcntl.h>
32 #include <ctype.h>
33 #include <signal.h>
34 #include <sys/types.h>
35 #include <sys/stat.h>
36 #include <sys/wait.h>
37 #include <sys/socket.h>
38 #include <syslog.h>
39 #include <sys/syslog.h>
40
41 #if TIME_WITH_SYS_TIME
42 # include <sys/time.h>
43 # include <time.h>
44 #else
45 # if HAVE_SYS_TIME_H
46 #  include <sys/time.h>
47 # else
48 #  include <time.h>
49 # endif
50 #endif
51
52 #include <limits.h>
53 #include <sys/resource.h>
54 #include <netinet/in.h>
55 #include <netinet/tcp.h>
56 #include <arpa/inet.h>
57 #include <netdb.h>
58 #include <sys/un.h>
59 #include <string.h>
60 #include <pwd.h>
61 #include <errno.h>
62 #include <stdarg.h>
63 #include <grp.h>
64 #define SHOW_ME_VAPPEND_PRINTF
65 #include <libcitadel.h>
66 #include "citadel.h"
67 #include "server.h"
68 #include "sysdep_decls.h"
69 #include "citserver.h"
70 #include "support.h"
71 #include "config.h"
72 #include "database.h"
73 #include "housekeeping.h"
74 #include "modules/crypto/serv_crypto.h" /* Needed for init_ssl, client_write_ssl, client_read_ssl, destruct_ssl */
75 #include "ecrash.h"
76 #include "context.h"
77
78 #ifdef HAVE_SYS_SELECT_H
79 #include <sys/select.h>
80 #endif
81
82 #ifndef HAVE_SNPRINTF
83 #include "snprintf.h"
84 #endif
85
86 #include "ctdl_module.h"
87 #include "threads.h"
88 #include "user_ops.h"
89 #include "control.h"
90
91
92 #ifdef DEBUG_MEMORY_LEAKS
93 struct igheap {
94         struct igheap *next;
95         char file[32];
96         int line;
97         void *block;
98 };
99
100 struct igheap *igheap = NULL;
101 #endif
102
103
104 /*
105  * Signal handler to shut down the server.
106  */
107
108 volatile int exit_signal = 0;
109 volatile int shutdown_and_halt = 0;
110 volatile int restart_server = 0;
111 volatile int running_as_daemon = 0;
112
113 static RETSIGTYPE signal_cleanup(int signum) {
114
115         if (CT)
116                 CT->signal = signum;
117         else
118         {
119                 syslog(LOG_DEBUG, "Caught signal %d; shutting down.\n", signum);
120                 exit_signal = signum;
121         }
122 }
123
124 static RETSIGTYPE signal_exit(int signum) {
125         exit(1);
126 }
127
128
129
130 /*
131  * Some initialization stuff...
132  */
133 void init_sysdep(void) {
134         sigset_t set;
135
136         /* Avoid vulnerabilities related to FD_SETSIZE if we can. */
137 #ifdef FD_SETSIZE
138 #ifdef RLIMIT_NOFILE
139         struct rlimit rl;
140         getrlimit(RLIMIT_NOFILE, &rl);
141         rl.rlim_cur = FD_SETSIZE;
142         rl.rlim_max = FD_SETSIZE;
143         setrlimit(RLIMIT_NOFILE, &rl);
144 #endif
145 #endif
146
147         /* If we've got OpenSSL, we're going to use it. */
148 #ifdef HAVE_OPENSSL
149         init_ssl();
150 #endif
151
152         /*
153          * Set up a place to put thread-specific data.
154          * We only need a single pointer per thread - it points to the
155          * CitContext structure (in the ContextList linked list) of the
156          * session to which the calling thread is currently bound.
157          */
158         if (citthread_key_create(&MyConKey, NULL) != 0) {
159                 syslog(LOG_CRIT, "Can't create TSD key: %s\n",
160                         strerror(errno));
161         }
162
163         /*
164          * The action for unexpected signals and exceptions should be to
165          * call signal_cleanup() to gracefully shut down the server.
166          */
167         sigemptyset(&set);
168         sigaddset(&set, SIGINT);                // intr = shutdown
169         sigaddset(&set, SIGHUP);
170         sigaddset(&set, SIGTERM);
171         sigprocmask(SIG_UNBLOCK, &set, NULL);
172
173         signal(SIGINT, signal_cleanup);         // intr = shutdown
174         signal(SIGHUP, signal_cleanup);
175         signal(SIGTERM, signal_cleanup);
176         signal(SIGUSR2, signal_exit);
177
178         /*
179          * Do not shut down the server on broken pipe signals, otherwise the
180          * whole Citadel service would come down whenever a single client
181          * socket breaks.
182          */
183         signal(SIGPIPE, SIG_IGN);
184 }
185
186
187 /* 
188  * This is a generic function to set up a master socket for listening on
189  * a TCP port.  The server shuts down if the bind fails.  (IPv4/IPv6 version)
190  *
191  * ip_addr      IP address to bind
192  * port_number  port number to bind
193  * queue_len    number of incoming connections to allow in the queue
194  */
195 int ctdl_tcp_server(char *ip_addr, int port_number, int queue_len, char *errormessage)
196 {
197         struct protoent *p;
198         struct sockaddr_in6 sin6;
199         struct sockaddr_in sin4;
200         int s, i, b;
201         int ip_version = 6;
202
203         memset(&sin6, 0, sizeof(sin6));
204         memset(&sin4, 0, sizeof(sin4));
205         sin6.sin6_family = AF_INET6;
206         sin4.sin_family = AF_INET;
207
208         if (    (ip_addr == NULL)                                                       /* any IPv6 */
209                 || (IsEmptyStr(ip_addr))
210                 || (!strcmp(ip_addr, "*"))
211         ) {
212                 ip_version = 6;
213                 sin6.sin6_addr = in6addr_any;
214         }
215         else if (!strcmp(ip_addr, "0.0.0.0"))                                           /* any IPv4 */
216         {
217                 ip_version = 4;
218                 sin4.sin_addr.s_addr = INADDR_ANY;
219         }
220         else if ((strchr(ip_addr, '.')) && (!strchr(ip_addr, ':')))                     /* specific IPv4 */
221         {
222                 ip_version = 4;
223                 if (inet_pton(AF_INET, ip_addr, &sin4.sin_addr) <= 0) {
224                         snprintf(errormessage, SIZ,
225                                  "Error binding to [%s] : %s", ip_addr, strerror(errno)
226                         );
227                         syslog(LOG_ALERT, "%s\n", errormessage);
228                         return (-1);
229                 }
230         }
231         else                                                                            /* specific IPv6 */
232         {
233                 ip_version = 6;
234                 if (inet_pton(AF_INET6, ip_addr, &sin6.sin6_addr) <= 0) {
235                         snprintf(errormessage, SIZ,
236                                  "Error binding to [%s] : %s", ip_addr, strerror(errno)
237                         );
238                         syslog(LOG_ALERT, "%s\n", errormessage);
239                         return (-1);
240                 }
241         }
242
243         if (port_number == 0) {
244                 snprintf(errormessage, SIZ,
245                          "Can't start: no port number specified."
246                 );
247                 syslog(LOG_ALERT, "%s\n", errormessage);
248                 return (-1);
249         }
250         sin6.sin6_port = htons((u_short) port_number);
251         sin4.sin_port = htons((u_short) port_number);
252
253         p = getprotobyname("tcp");
254
255         s = socket( ((ip_version == 6) ? PF_INET6 : PF_INET), SOCK_STREAM, (p->p_proto));
256         if (s < 0) {
257                 snprintf(errormessage, SIZ,
258                          "Can't create a listening socket: %s", strerror(errno)
259                 );
260                 syslog(LOG_ALERT, "%s\n", errormessage);
261                 return (-1);
262         }
263         /* Set some socket options that make sense. */
264         i = 1;
265         setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
266
267         if (ip_version == 6) {
268                 b = bind(s, (struct sockaddr *) &sin6, sizeof(sin6));
269         }
270         else {
271                 b = bind(s, (struct sockaddr *) &sin4, sizeof(sin4));
272         }
273
274         if (b < 0) {
275                 snprintf(errormessage, SIZ,
276                          "Can't bind: %s", strerror(errno)
277                 );
278                 syslog(LOG_ALERT, "%s\n", errormessage);
279                 return (-1);
280         }
281
282         fcntl(s, F_SETFL, O_NONBLOCK);
283
284         if (listen(s, ((queue_len >= 5) ? queue_len : 5) ) < 0) {
285                 snprintf(errormessage, SIZ,
286                          "Can't listen: %s", strerror(errno)
287                 );
288                 syslog(LOG_ALERT, "%s\n", errormessage);
289                 return (-1);
290         }
291         return (s);
292 }
293
294
295
296
297
298 /*
299  * Create a Unix domain socket and listen on it
300  */
301 int ctdl_uds_server(char *sockpath, int queue_len, char *errormessage)
302 {
303         struct sockaddr_un addr;
304         int s;
305         int i;
306         int actual_queue_len;
307 #ifdef HAVE_STRUCT_UCRED
308         int passcred = 1;
309 #endif
310
311         actual_queue_len = queue_len;
312         if (actual_queue_len < 5) actual_queue_len = 5;
313
314         i = unlink(sockpath);
315         if ((i != 0) && (errno != ENOENT)) {
316                 snprintf(errormessage, SIZ, "citserver: can't unlink %s: %s",
317                         sockpath, strerror(errno)
318                 );
319                 syslog(LOG_EMERG, "%s\n", errormessage);
320                 return(-1);
321         }
322
323         memset(&addr, 0, sizeof(addr));
324         addr.sun_family = AF_UNIX;
325         safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
326
327         s = socket(AF_UNIX, SOCK_STREAM, 0);
328         if (s < 0) {
329                 snprintf(errormessage, SIZ, 
330                          "citserver: Can't create a socket: %s",
331                          strerror(errno));
332                 syslog(LOG_EMERG, "%s\n", errormessage);
333                 return(-1);
334         }
335
336         if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
337                 snprintf(errormessage, SIZ, 
338                          "citserver: Can't bind: %s",
339                          strerror(errno));
340                 syslog(LOG_EMERG, "%s\n", errormessage);
341                 return(-1);
342         }
343
344         /* set to nonblock - we need this for some obscure situations */
345         if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
346                 snprintf(errormessage, SIZ, 
347                          "citserver: Can't set socket to non-blocking: %s",
348                          strerror(errno));
349                 syslog(LOG_EMERG, "%s\n", errormessage);
350                 close(s);
351                 return(-1);
352         }
353
354         if (listen(s, actual_queue_len) < 0) {
355                 snprintf(errormessage, SIZ, 
356                          "citserver: Can't listen: %s",
357                          strerror(errno));
358                 syslog(LOG_EMERG, "%s\n", errormessage);
359                 return(-1);
360         }
361
362 #ifdef HAVE_STRUCT_UCRED
363         setsockopt(s, SOL_SOCKET, SO_PASSCRED, &passcred, sizeof(passcred));
364 #endif
365
366         chmod(sockpath, S_ISGID|S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
367         return(s);
368 }
369
370
371
372 /*
373  * The following functions implement output buffering on operating systems which
374  * support it (such as Linux and various BSD flavors).
375  */
376 #ifndef HAVE_DARWIN
377 #ifdef TCP_CORK
378 #       define HAVE_TCP_BUFFERING
379 #else
380 #       ifdef TCP_NOPUSH
381 #               define HAVE_TCP_BUFFERING
382 #               define TCP_CORK TCP_NOPUSH
383 #       endif
384 #endif /* TCP_CORK */
385 #endif /* HAVE_DARWIN */
386
387 static unsigned on = 1, off = 0;
388
389 void buffer_output(void) {
390 #ifdef HAVE_TCP_BUFFERING
391 #ifdef HAVE_OPENSSL
392         if (!CC->redirect_ssl)
393 #endif
394                 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
395 #endif
396 }
397
398 void unbuffer_output(void) {
399 #ifdef HAVE_TCP_BUFFERING
400 #ifdef HAVE_OPENSSL
401         if (!CC->redirect_ssl)
402 #endif
403                 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
404 #endif
405 }
406
407 void flush_output(void) {
408 #ifdef HAVE_TCP_BUFFERING
409         struct CitContext *CCC = CC;
410         setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
411         setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
412 #endif
413 }
414
415 /*
416 static void flush_client_inbuf(void)
417 {
418         CitContext *CCC=CC;
419
420         FlushStrBuf(CCC->ReadBuf);
421         CCC->Pos = NULL;
422
423 }
424 */
425
426
427 /*
428  * client_close()       ...     close the client socket
429  */
430 void client_close(void) {
431         CitContext *CCC = CC;
432         int r;
433
434         if (!CCC) return;
435         if (CCC->client_socket < 0) return;
436         syslog(LOG_DEBUG, "Closing socket %d\n", CCC->client_socket);
437         r = close(CCC->client_socket);
438         if (!r) syslog(LOG_INFO, "close() failed: %s\n", strerror(errno));
439         CCC->client_socket = -1 ;
440 }
441
442
443
444
445 /*
446  * client_write()   ...    Send binary data to the client.
447  */
448 int client_write(const char *buf, int nbytes)
449 {
450         int bytes_written = 0;
451         int retval;
452 #ifndef HAVE_TCP_BUFFERING
453         int old_buffer_len = 0;
454 #endif
455         fd_set wset;
456         CitContext *Ctx;
457         int fdflags;
458
459         if (nbytes < 1) return(0);
460
461         Ctx = CC;
462
463 #ifdef BIGBAD_IODBG
464         {
465                 int rv = 0;
466                 char fn [SIZ];
467                 FILE *fd;
468                 
469                 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", Ctx->ServiceName, Ctx->cs_pid);
470                 
471                 fd = fopen(fn, "a+");
472                 fprintf(fd, "Sending: BufSize: %d BufContent: [",
473                         nbytes);
474                 rv = fwrite(buf, nbytes, 1, fd);
475                 fprintf(fd, "]\n");
476                 
477                         
478                 fclose(fd);
479         }
480 #endif
481 //      flush_client_inbuf();
482         if (Ctx->redirect_buffer != NULL) {
483                 StrBufAppendBufPlain(Ctx->redirect_buffer,
484                                      buf, nbytes, 0);
485                 return 0;
486         }
487
488 #ifdef HAVE_OPENSSL
489         if (Ctx->redirect_ssl) {
490                 client_write_ssl(buf, nbytes);
491                 return 0;
492         }
493 #endif
494         if (Ctx->client_socket == -1) return -1;
495
496         fdflags = fcntl(Ctx->client_socket, F_GETFL);
497
498         while ((bytes_written < nbytes) && (Ctx->client_socket != -1)){
499                 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
500                         FD_ZERO(&wset);
501                         FD_SET(Ctx->client_socket, &wset);
502                         if (select(1, NULL, &wset, NULL, NULL) == -1) {
503                                 if (errno == EINTR)
504                                 {
505                                         syslog(LOG_DEBUG, "client_write(%d bytes) select() interrupted.\n", nbytes-bytes_written);
506                                         if (CtdlThreadCheckStop()) {
507                                                 CC->kill_me = KILLME_SELECT_INTERRUPTED;
508                                                 return (-1);
509                                         } else {
510                                                 /* can't trust fd's and stuff so we need to re-create them */
511                                                 continue;
512                                         }
513                                 } else {
514                                         syslog(LOG_ERR,
515                                                 "client_write(%d bytes) select failed: %s (%d)\n",
516                                                 nbytes - bytes_written,
517                                                 strerror(errno), errno
518                                         );
519                                         cit_backtrace();
520                                         client_close();
521                                         Ctx->kill_me = KILLME_SELECT_FAILED;
522                                         return -1;
523                                 }
524                         }
525                 }
526
527                 retval = write(Ctx->client_socket, &buf[bytes_written], nbytes - bytes_written);
528                 if (retval < 1) {
529                         syslog(LOG_ERR,
530                                 "client_write(%d bytes) failed: %s (%d)\n",
531                                 nbytes - bytes_written,
532                                 strerror(errno), errno
533                         );
534                         cit_backtrace();
535                         client_close();
536                         // syslog(LOG_DEBUG, "Tried to send: %s",  &buf[bytes_written]);
537                         Ctx->kill_me = KILLME_WRITE_FAILED;
538                         return -1;
539                 }
540                 bytes_written = bytes_written + retval;
541         }
542         return 0;
543 }
544
545 void cputbuf(const StrBuf *Buf) {   
546         client_write(ChrPtr(Buf), StrLength(Buf)); 
547 }   
548
549
550 /*
551  * cprintf()    Send formatted printable data to the client.
552  *              Implemented in terms of client_write() so it's technically not sysdep...
553  */
554 void cprintf(const char *format, ...) {   
555         va_list arg_ptr;   
556         char buf[1024];
557    
558         va_start(arg_ptr, format);   
559         if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
560                 buf[sizeof buf - 2] = '\n';
561         client_write(buf, strlen(buf)); 
562         va_end(arg_ptr);
563 }   
564
565
566 /*
567  * Read data from the client socket.
568  *
569  * sock         socket fd to read from
570  * buf          buffer to read into 
571  * bytes        number of bytes to read
572  * timeout      Number of seconds to wait before timing out
573  *
574  * Possible return values:
575  *      1       Requested number of bytes has been read.
576  *      0       Request timed out.
577  *      -1      Connection is broken, or other error.
578  */
579 int client_read_blob(StrBuf *Target, int bytes, int timeout)
580 {
581         CitContext *CCC=CC;
582         const char *Error;
583         int retval = 0;
584
585 #ifdef HAVE_OPENSSL
586         if (CCC->redirect_ssl) {
587 #ifdef BIGBAD_IODBG
588                 int rv = 0;
589                 char fn [SIZ];
590                 FILE *fd;
591                 
592                 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
593                         
594                 fd = fopen(fn, "a+");
595                 fprintf(fd, "Reading BLOB: BufSize: %d ",
596                         bytes);
597                 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
598                 fprintf(fd, "]\n");
599                 
600                         
601                 fclose(fd);
602 #endif
603                 retval = client_read_sslblob(Target, bytes, timeout);
604                 if (retval < 0) {
605                         syslog(LOG_CRIT, 
606                                       "%s failed\n",
607                                       __FUNCTION__);
608                 }
609 #ifdef BIGBAD_IODBG
610                 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
611                 
612                 fd = fopen(fn, "a+");
613                 fprintf(fd, "Read: %d BufContent: [",
614                         StrLength(Target));
615                 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
616                 fprintf(fd, "]\n");
617                 
618                 
619                 fclose(fd);
620 #endif
621         }
622         else 
623 #endif
624         {
625 #ifdef BIGBAD_IODBG
626                 int rv = 0;
627                 char fn [SIZ];
628                 FILE *fd;
629                 
630                 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
631                         
632                 fd = fopen(fn, "a+");
633                 fprintf(fd, "Reading BLOB: BufSize: %d ",
634                         bytes);
635                 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
636                 fprintf(fd, "]\n");
637                 
638                         
639                 fclose(fd);
640 #endif
641                 retval = StrBufReadBLOBBuffered(Target, 
642                                                 CCC->ReadBuf,
643                                                 &CCC->Pos,
644                                                 &CCC->client_socket,
645                                                 1, 
646                                                 bytes,
647                                                 O_TERM,
648                                                 &Error);
649                 if (retval < 0) {
650                         syslog(LOG_CRIT, "%s failed: %s\n", __FUNCTION__, Error);
651                         client_close();
652                         return retval;
653                 }
654 #ifdef BIGBAD_IODBG
655                 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
656                 
657                 fd = fopen(fn, "a+");
658                 fprintf(fd, "Read: %d BufContent: [",
659                         StrLength(Target));
660                 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
661                 fprintf(fd, "]\n");
662                 fclose(fd);
663 #endif
664         }
665         return retval;
666 }
667
668
669 /*
670  * to make client_read_random_blob() more efficient, increase buffer size.
671  * just use in greeting function, else your buffer may be flushed
672  */
673 void client_set_inbound_buf(long N)
674 {
675         FlushStrBuf(CC->ReadBuf);
676         ReAdjustEmptyBuf(CC->ReadBuf, N * SIZ, N * SIZ);
677 }
678
679 int client_read_random_blob(StrBuf *Target, int timeout)
680 {
681         CitContext *CCC=CC;
682         int rc;
683
684         rc =  client_read_blob(Target, 1, timeout);
685         if (rc > 0)
686         {
687                 long len;
688                 const char *pch;
689                 
690                 len = StrLength(CCC->ReadBuf);
691                 pch = ChrPtr(CCC->ReadBuf);
692
693                 if (len > 0)
694                 {
695                         if (CCC->Pos != NULL) {
696                                 len -= CCC->Pos - pch;
697                                 pch = CCC->Pos;
698                         }
699                         StrBufAppendBufPlain(Target, pch, len, 0);
700                         FlushStrBuf(CCC->ReadBuf);
701                         CCC->Pos = NULL;
702 #ifdef BIGBAD_IODBG
703                         {
704                                 int rv = 0;
705                                 char fn [SIZ];
706                                 FILE *fd;
707                         
708                                 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
709                         
710                                 fd = fopen(fn, "a+");
711                                 fprintf(fd, "Read: BufSize: %d BufContent: [",
712                                         StrLength(Target));
713                                 rv = fwrite(ChrPtr(Target), StrLength(Target), 1, fd);
714                                 fprintf(fd, "]\n");
715                         
716                         
717                                 fclose(fd);
718                         }
719 #endif
720         
721                         return StrLength(Target);
722                 }
723                 return rc;
724         }
725         else
726                 return rc;
727 }
728
729 int client_read_to(char *buf, int bytes, int timeout)
730 {
731         CitContext *CCC=CC;
732         int rc;
733
734         rc = client_read_blob(CCC->MigrateBuf, bytes, timeout);
735         if (rc < 0)
736         {
737                 *buf = '\0';
738                 return rc;
739         }
740         else
741         {
742                 memcpy(buf, 
743                        ChrPtr(CCC->MigrateBuf),
744                        StrLength(CCC->MigrateBuf) + 1);
745                 FlushStrBuf(CCC->MigrateBuf);
746                 return rc;
747         }
748 }
749
750
751 int HaveMoreLinesWaiting(CitContext *CCC)
752 {
753         if ((CCC->kill_me != 0) || (
754             (CCC->Pos == NULL) && 
755             (StrLength(CCC->ReadBuf) == 0) && 
756             (CCC->client_socket != -1)) )
757                 return 0;
758         else
759                 return 1;
760 }
761
762
763 /*
764  * Read data from the client socket with default timeout.
765  * (This is implemented in terms of client_read_to() and could be
766  * justifiably moved out of sysdep.c)
767  */
768 INLINE int client_read(char *buf, int bytes)
769 {
770         return(client_read_to(buf, bytes, config.c_sleeping));
771 }
772
773 int CtdlClientGetLine(StrBuf *Target)
774 {
775         CitContext *CCC=CC;
776         const char *Error;
777         int rc;
778
779         FlushStrBuf(Target);
780 #ifdef HAVE_OPENSSL
781         if (CCC->redirect_ssl) {
782 #ifdef BIGBAD_IODBG
783                 char fn [SIZ];
784                 FILE *fd;
785                 int len = 0;
786                 int rlen = 0;
787                 int  nlen = 0;
788                 int nrlen = 0;
789                 const char *pch;
790
791                 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
792
793                 fd = fopen(fn, "a+");
794                 pch = ChrPtr(CCC->ReadBuf);
795                 len = StrLength(CCC->ReadBuf);
796                 if (CCC->Pos != NULL)
797                         rlen = CC->Pos - pch;
798                 else
799                         rlen = 0;
800
801 /*              fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
802                         len, rlen, pch);
803 */
804                 fprintf(fd, "\n\n\nSSL1: BufSize: %d BufPos: %d \n_____________________\n",
805                         len, rlen);
806 #endif
807                 rc = client_readline_sslbuffer(Target,
808                                                CCC->ReadBuf,
809                                                &CCC->Pos,
810                                                1);
811 #ifdef BIGBAD_IODBG
812                 pch = ChrPtr(CCC->ReadBuf);
813                 nlen = StrLength(CCC->ReadBuf);
814                 if (CCC->Pos != NULL)
815                         nrlen = CC->Pos - pch;
816                 else
817                         nrlen = 0;
818 /*
819                 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
820                         len, nlen, rlen, nrlen, pch);
821 */
822                 fprintf(fd, "\n\n\nSSL2: BufSize: was: %d is: %d BufPos: was: %d is: %d \n",
823                         len, nlen, rlen, nrlen);
824
825                 fprintf(fd, "SSL3: Read: BufSize: %d BufContent: [%s]\n\n*************\n",
826                         StrLength(Target), ChrPtr(Target));
827                 fclose(fd);
828
829                 if (rc < 0)
830                         syslog(LOG_CRIT, 
831                                       "%s failed\n",
832                                       __FUNCTION__);
833 #endif
834                 return rc;
835         }
836         else 
837 #endif
838         {
839 #ifdef BIGBAD_IODBG
840                 char fn [SIZ];
841                 FILE *fd;
842                 int len, rlen, nlen, nrlen;
843                 const char *pch;
844
845                 snprintf(fn, SIZ, "/tmp/foolog_%s.%d", CCC->ServiceName, CCC->cs_pid);
846
847                 fd = fopen(fn, "a+");
848                 pch = ChrPtr(CCC->ReadBuf);
849                 len = StrLength(CCC->ReadBuf);
850                 if (CCC->Pos != NULL)
851                         rlen = CC->Pos - pch;
852                 else
853                         rlen = 0;
854
855 /*              fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \nBufContent: [%s]\n\n_____________________\n",
856                         len, rlen, pch);
857 */
858                 fprintf(fd, "\n\n\nBufSize: %d BufPos: %d \n_____________________\n",
859                         len, rlen);
860 #endif
861                 rc = StrBufTCP_read_buffered_line_fast(Target, 
862                                                        CCC->ReadBuf,
863                                                        &CCC->Pos,
864                                                        &CCC->client_socket,
865                                                        5,
866                                                        1,
867                                                        &Error);
868
869 #ifdef BIGBAD_IODBG
870                 pch = ChrPtr(CCC->ReadBuf);
871                 nlen = StrLength(CCC->ReadBuf);
872                 if (CCC->Pos != NULL)
873                         nrlen = CC->Pos - pch;
874                 else
875                         nrlen = 0;
876 /*
877                 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \nBufContent: [%s]\n\n_____________________\n",
878                         len, nlen, rlen, nrlen, pch);
879 */
880                 fprintf(fd, "\n\n\nBufSize: was: %d is: %d BufPos: was: %d is: %d \n",
881                         len, nlen, rlen, nrlen);
882
883                 fprintf(fd, "Read: BufSize: %d BufContent: [%s]\n\n*************\n",
884                         StrLength(Target), ChrPtr(Target));
885                 fclose(fd);
886
887                 if ((rc < 0) && (Error != NULL))
888                         syslog(LOG_CRIT, 
889                                       "%s failed: %s\n",
890                                       __FUNCTION__,
891                                       Error);
892 #endif
893                 return rc;
894         }
895 }
896
897
898 /*
899  * client_getln()   ...   Get a LF-terminated line of text from the client.
900  * (This is implemented in terms of client_read() and could be
901  * justifiably moved out of sysdep.c)
902  */
903 int client_getln(char *buf, int bufsize)
904 {
905         int i, retval;
906         CitContext *CCC=CC;
907         const char *pCh;
908
909         retval = CtdlClientGetLine(CCC->MigrateBuf);
910         if (retval < 0)
911           return(retval >= 0);
912
913
914         i = StrLength(CCC->MigrateBuf);
915         pCh = ChrPtr(CCC->MigrateBuf);
916         /* Strip the trailing LF, and the trailing CR if present.
917          */
918         if (bufsize <= i)
919                 i = bufsize - 1;
920         while ( (i > 0)
921                 && ( (pCh[i - 1]==13)
922                      || ( pCh[i - 1]==10)) ) {
923                 i--;
924         }
925         memcpy(buf, pCh, i);
926         buf[i] = 0;
927
928         FlushStrBuf(CCC->MigrateBuf);
929         if (retval < 0) {
930                 safestrncpy(&buf[i], "000", bufsize - i);
931         }
932         return(retval >= 0);
933 }
934
935
936 /*
937  * Cleanup any contexts that are left lying around
938  */
939
940
941 void close_masters (void)
942 {
943         struct ServiceFunctionHook *serviceptr;
944         
945         /*
946          * close all protocol master sockets
947          */
948         for (serviceptr = ServiceHookTable; serviceptr != NULL;
949             serviceptr = serviceptr->next ) {
950
951                 if (serviceptr->tcp_port > 0)
952                 {
953                         syslog(LOG_INFO, "Closing listener on port %d\n",
954                                 serviceptr->tcp_port);
955                         serviceptr->tcp_port = 0;
956                 }
957                 
958                 if (serviceptr->sockpath != NULL)
959                         syslog(LOG_INFO, "Closing listener on '%s'\n",
960                                 serviceptr->sockpath);
961
962                 close(serviceptr->msock);
963                 /* If it's a Unix domain socket, remove the file. */
964                 if (serviceptr->sockpath != NULL) {
965                         unlink(serviceptr->sockpath);
966                         serviceptr->sockpath = NULL;
967                 }
968         }
969 }
970
971
972 /*
973  * The system-dependent part of master_cleanup() - close the master socket.
974  */
975 void sysdep_master_cleanup(void) {
976         
977         close_masters();
978         
979         context_cleanup();
980         
981 #ifdef HAVE_OPENSSL
982         destruct_ssl();
983 #endif
984         CtdlDestroyProtoHooks();
985         CtdlDestroyDeleteHooks();
986         CtdlDestroyXmsgHooks();
987         CtdlDestroyNetprocHooks();
988         CtdlDestroyUserHooks();
989         CtdlDestroyMessageHook();
990         CtdlDestroyCleanupHooks();
991         CtdlDestroyFixedOutputHooks();  
992         CtdlDestroySessionHooks();
993         CtdlDestroyServiceHook();
994         CtdlDestroyRoomHooks();
995         CtdlDestroySearchHooks();
996         #ifdef HAVE_BACKTRACE
997 ///     eCrash_Uninit();
998         #endif
999 }
1000
1001
1002
1003 pid_t current_child;
1004 void graceful_shutdown(int signum) {
1005         kill(current_child, signum);
1006         unlink(file_pid_file);
1007         exit(0);
1008 }
1009
1010 int nFireUps = 0;
1011 int nFireUpsNonRestart = 0;
1012 pid_t ForkedPid = 1;
1013
1014 /*
1015  * Start running as a daemon.
1016  */
1017 void start_daemon(int unused) {
1018         int status = 0;
1019         pid_t child = 0;
1020         FILE *fp;
1021         int do_restart = 0;
1022
1023         current_child = 0;
1024
1025         /* Close stdin/stdout/stderr and replace them with /dev/null.
1026          * We don't just call close() because we don't want these fd's
1027          * to be reused for other files.
1028          */
1029         if (chdir(ctdl_run_dir) != 0)
1030                 syslog(LOG_EMERG, 
1031                               "unable to change into directory [%s]: %s", 
1032                               ctdl_run_dir, strerror(errno));
1033
1034         child = fork();
1035         if (child != 0) {
1036                 exit(0);
1037         }
1038         
1039         signal(SIGHUP, SIG_IGN);
1040         signal(SIGINT, SIG_IGN);
1041         signal(SIGQUIT, SIG_IGN);
1042
1043         setsid();
1044         umask(0);
1045         if ((freopen("/dev/null", "r", stdin) != stdin) || 
1046             (freopen("/dev/null", "w", stdout) != stdout) || 
1047             (freopen("/dev/null", "w", stderr) != stderr))
1048                 syslog(LOG_EMERG, 
1049                               "unable to reopen stdin/out/err %s", 
1050                               strerror(errno));
1051                 
1052
1053         do {
1054                 current_child = fork();
1055
1056                 signal(SIGTERM, graceful_shutdown);
1057         
1058                 if (current_child < 0) {
1059                         perror("fork");
1060                         exit(errno);
1061                 }
1062         
1063                 else if (current_child == 0) {
1064                         return; /* continue starting citadel. */
1065                 }
1066         
1067                 else {
1068                         fp = fopen(file_pid_file, "w");
1069                         if (fp != NULL) {
1070                                 fprintf(fp, ""F_PID_T"\n", getpid());
1071                                 fclose(fp);
1072                         }
1073                         waitpid(current_child, &status, 0);
1074                 }
1075                 do_restart = 0;
1076                 nFireUpsNonRestart = nFireUps;
1077                 
1078                 /* Exit code 0 means the watcher should exit */
1079                 if (WIFEXITED(status) && (WEXITSTATUS(status) == CTDLEXIT_SHUTDOWN)) {
1080                         do_restart = 0;
1081                 }
1082
1083                 /* Exit code 101-109 means the watcher should exit */
1084                 else if (WIFEXITED(status) && (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109)) {
1085                         do_restart = 0;
1086                 }
1087
1088                 /* Any other exit code, or no exit code, means we should restart. */
1089                 else {
1090                         do_restart = 1;
1091                         nFireUps++;
1092                         ForkedPid = current_child;
1093                 }
1094
1095         } while (do_restart);
1096
1097         unlink(file_pid_file);
1098         exit(WEXITSTATUS(status));
1099 }
1100
1101
1102
1103 void checkcrash(void)
1104 {
1105         if (nFireUpsNonRestart != nFireUps)
1106         {
1107                 StrBuf *CrashMail;
1108
1109                 CrashMail = NewStrBuf();
1110                 syslog(LOG_ALERT, "Posting crash message\n");
1111                 StrBufPrintf(CrashMail, 
1112                         " \n"
1113                         " The Citadel server process (citserver) terminated unexpectedly."
1114                         "\n \n"
1115                         " This could be the result of a bug in the server program, or some external "
1116                         "factor.\n \n"
1117                         " You can obtain more information about this by enabling core dumps.\n \n"
1118                         " For more information, please see:\n \n"
1119                         " http://citadel.org/doku.php/faq:mastering_your_os:gdb#how.do.i.make.my.system.produce.core-files"
1120                         "\n \n"
1121
1122                         " If you have already done this, the core dump is likely to be found at %score.%d\n"
1123                         ,
1124                         ctdl_run_dir, ForkedPid);
1125                 CtdlAideMessage(ChrPtr(CrashMail), "Citadel server process terminated unexpectedly");
1126                 FreeStrBuf(&CrashMail);
1127         }
1128 }
1129
1130
1131 /*
1132  * Generic routine to convert a login name to a full name (gecos)
1133  * Returns nonzero if a conversion took place
1134  */
1135 int convert_login(char NameToConvert[]) {
1136         struct passwd *pw;
1137         int a;
1138
1139         pw = getpwnam(NameToConvert);
1140         if (pw == NULL) {
1141                 return(0);
1142         }
1143         else {
1144                 strcpy(NameToConvert, pw->pw_gecos);
1145                 for (a=0; a<strlen(NameToConvert); ++a) {
1146                         if (NameToConvert[a] == ',') NameToConvert[a] = 0;
1147                 }
1148                 return(1);
1149         }
1150 }
1151
1152
1153
1154 /* 
1155  * This loop just keeps going and going and going...
1156  */
1157 void *worker_thread(void *arg) {
1158         int highest;
1159         CitContext *ptr;
1160         CitContext *bind_me = NULL;
1161         fd_set readfds;
1162         int retval = 0;
1163         struct timeval tv;
1164         int force_purge = 0;
1165         
1166
1167         while (!CtdlThreadCheckStop()) {
1168
1169                 /* make doubly sure we're not holding any stale db handles
1170                  * which might cause a deadlock.
1171                  */
1172                 cdb_check_handles();
1173 do_select:      force_purge = 0;
1174                 bind_me = NULL;         /* Which session shall we handle? */
1175
1176                 /* Initialize the fdset. */
1177                 FD_ZERO(&readfds);
1178                 highest = 0;
1179
1180                 begin_critical_section(S_SESSION_TABLE);
1181                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1182                         /* Don't select on dead sessions, only truly idle ones */
1183                         if (    (ptr->state == CON_IDLE)
1184                                 && (ptr->kill_me == 0)
1185                                 && (ptr->client_socket != -1)
1186                         ) {
1187                                 FD_SET(ptr->client_socket, &readfds);
1188                                 if (ptr->client_socket > highest)
1189                                         highest = ptr->client_socket;
1190                         }
1191                         if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1192                                 bind_me = ptr;
1193                                 ptr->state = CON_EXECUTING;
1194                                 break;
1195                         }
1196                         if ((bind_me == NULL) && (ptr->state == CON_GREETING)) {
1197                                 bind_me = ptr;
1198                                 ptr->state = CON_STARTING;
1199                                 break;
1200                         }
1201                 }
1202                 end_critical_section(S_SESSION_TABLE);
1203
1204                 if (bind_me) {
1205                         goto SKIP_SELECT;
1206                 }
1207
1208                 /* If we got this far, it means that there are no sessions
1209                  * which a previous thread marked for attention, so we go
1210                  * ahead and get ready to select().
1211                  */
1212
1213                 if (!CtdlThreadCheckStop()) {
1214                         tv.tv_sec = 1;          /* wake up every second if no input */
1215                         tv.tv_usec = 0;
1216                         retval = CtdlThreadSelect(highest + 1, &readfds, NULL, NULL, &tv);
1217                 }
1218                 else
1219                         return NULL;
1220
1221                 /* Now figure out who made this select() unblock.
1222                  * First, check for an error or exit condition.
1223                  */
1224                 if (retval < 0) {
1225                         if (errno == EBADF) {
1226                                 syslog(LOG_NOTICE, "select() failed: (%s)\n",
1227                                         strerror(errno));
1228                                 goto do_select;
1229                         }
1230                         if (errno != EINTR) {
1231                                 syslog(LOG_EMERG, "Exiting (%s)\n", strerror(errno));
1232                                 CtdlThreadStopAll();
1233                                 continue;
1234                         } else {
1235                                 syslog(LOG_DEBUG, "Interrupted CtdlThreadSelect.\n");
1236                                 if (CtdlThreadCheckStop()) return(NULL);
1237                                 goto do_select;
1238                         }
1239                 }
1240                 else if(retval == 0) {
1241                         if (CtdlThreadCheckStop()) return(NULL);
1242                 }
1243
1244                 /* It must be a client socket.  Find a context that has data
1245                  * waiting on its socket *and* is in the CON_IDLE state.  Any
1246                  * active sockets other than our chosen one are marked as
1247                  * CON_READY so the next thread that comes around can just bind
1248                  * to one without having to select() again.
1249                  */
1250                 begin_critical_section(S_SESSION_TABLE);
1251                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1252                         int checkfd = ptr->client_socket;
1253                         if ((checkfd != -1) && (ptr->state == CON_IDLE) ){
1254                                 if (FD_ISSET(checkfd, &readfds)) {
1255                                         ptr->input_waiting = 1;
1256                                         if (!bind_me) {
1257                                                 bind_me = ptr;  /* I choose you! */
1258                                                 bind_me->state = CON_EXECUTING;
1259                                         }
1260                                         else {
1261                                                 ptr->state = CON_READY;
1262                                         }
1263                                 } else if ((ptr->is_async) && (ptr->async_waiting) && (ptr->h_async_function)) {
1264                                         if (!bind_me) {
1265                                                 bind_me = ptr;  /* I choose you! */
1266                                                 bind_me->state = CON_EXECUTING;
1267                                         }
1268                                         else {
1269                                                 ptr->state = CON_READY;
1270                                         }
1271                                 }
1272                         }
1273                 }
1274                 end_critical_section(S_SESSION_TABLE);
1275
1276 SKIP_SELECT:
1277                 /* We're bound to a session */
1278                 if (bind_me != NULL) {
1279                         become_session(bind_me);
1280
1281                         if (bind_me->state == CON_STARTING) {
1282                                 bind_me->state = CON_EXECUTING;
1283                                 begin_session(bind_me);
1284                                 bind_me->h_greeting_function();
1285                         }
1286                         /* If the client has sent a command, execute it. */
1287                         if (CC->input_waiting) {
1288                                 CC->h_command_function();
1289
1290                                 while (HaveMoreLinesWaiting(CC))
1291                                        CC->h_command_function();
1292
1293                                 CC->input_waiting = 0;
1294                         }
1295
1296                         /* If there are asynchronous messages waiting and the
1297                          * client supports it, do those now */
1298                         if ((CC->is_async) && (CC->async_waiting)
1299                            && (CC->h_async_function != NULL)) {
1300                                 CC->h_async_function();
1301                                 CC->async_waiting = 0;
1302                         }
1303                         
1304                         force_purge = CC->kill_me;
1305                         become_session(NULL);
1306                         bind_me->state = CON_IDLE;
1307                 }
1308
1309                 dead_session_purge(force_purge);
1310                 do_housekeeping();
1311         }
1312         /* If control reaches this point, the server is shutting down */        
1313         return(NULL);
1314 }
1315
1316
1317
1318
1319 /*
1320  * A function to handle selecting on master sockets.
1321  * In other words it handles new connections.
1322  * It is a thread.
1323  */
1324 void *select_on_master (void *arg)
1325 {
1326         struct ServiceFunctionHook *serviceptr;
1327         fd_set master_fds;
1328         int highest;
1329         struct timeval tv;
1330         int ssock;                      /* Descriptor for client socket */
1331         CitContext *con= NULL;  /* Temporary context pointer */
1332         int m;
1333         int i;
1334         int retval;
1335         struct CitContext select_on_master_CC;
1336
1337         CtdlFillSystemContext(&select_on_master_CC, "select_on_master");
1338         citthread_setspecific(MyConKey, (void *)&select_on_master_CC);
1339
1340         while (!CtdlThreadCheckStop()) {
1341                 /* Initialize the fdset. */
1342                 FD_ZERO(&master_fds);
1343                 highest = 0;
1344
1345                 /* First, add the various master sockets to the fdset. */
1346                 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1347                 serviceptr = serviceptr->next ) {
1348                         m = serviceptr->msock;
1349                         FD_SET(m, &master_fds);
1350                         if (m > highest) {
1351                                 highest = m;
1352                         }
1353                 }
1354
1355                 if (!CtdlThreadCheckStop()) {
1356                         tv.tv_sec = 60;         /* wake up every second if no input */
1357                         tv.tv_usec = 0;
1358                         retval = CtdlThreadSelect(highest + 1, &master_fds, NULL, NULL, &tv);
1359                 }
1360                 else
1361                         return NULL;
1362
1363                 /* Now figure out who made this select() unblock.
1364                  * First, check for an error or exit condition.
1365                  */
1366                 if (retval < 0) {
1367                         if (errno == EBADF) {
1368                                 syslog(LOG_NOTICE, "select() failed: (%s)\n",
1369                                         strerror(errno));
1370                                 continue;
1371                         }
1372                         if (errno != EINTR) {
1373                                 syslog(LOG_EMERG, "Exiting (%s)\n", strerror(errno));
1374                                 CtdlThreadStopAll();
1375                         } else {
1376                                 syslog(LOG_DEBUG, "Interrupted CtdlThreadSelect.\n");
1377                                 if (CtdlThreadCheckStop()) return(NULL);
1378                                 continue;
1379                         }
1380                 }
1381                 else if(retval == 0) {
1382                         if (CtdlThreadCheckStop()) return(NULL);
1383                         continue;
1384                 }
1385                 /* Next, check to see if it's a new client connecting
1386                  * on a master socket.
1387                  */
1388                 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1389                      serviceptr = serviceptr->next ) {
1390
1391                         if (FD_ISSET(serviceptr->msock, &master_fds)) {
1392                                 ssock = accept(serviceptr->msock, NULL, 0);
1393                                 if (ssock >= 0) {
1394                                         syslog(LOG_DEBUG, "New client socket %d\n", ssock);
1395
1396                                         /* The master socket is non-blocking but the client
1397                                          * sockets need to be blocking, otherwise certain
1398                                          * operations barf on FreeBSD.  Not a fatal error.
1399                                          */
1400                                         if (fcntl(ssock, F_SETFL, 0) < 0) {
1401                                                 syslog(LOG_EMERG,
1402                                                         "citserver: Can't set socket to blocking: %s\n",
1403                                                         strerror(errno));
1404                                         }
1405
1406                                         /* New context will be created already
1407                                          * set up in the CON_EXECUTING state.
1408                                          */
1409                                         con = CreateNewContext();
1410
1411                                         /* Assign our new socket number to it. */
1412                                         con->client_socket = ssock;
1413                                         con->h_command_function = serviceptr->h_command_function;
1414                                         con->h_async_function = serviceptr->h_async_function;
1415                                         con->h_greeting_function = serviceptr->h_greeting_function;
1416                                         con->ServiceName = serviceptr->ServiceName;
1417                                         
1418                                         /* Determine whether it's a local socket */
1419                                         if (serviceptr->sockpath != NULL) {
1420                                                 con->is_local_socket = 1;
1421                                         }
1422         
1423                                         /* Set the SO_REUSEADDR socket option */
1424                                         i = 1;
1425                                         setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
1426                                         con->state = CON_GREETING;
1427                                         retval--;
1428                                         if (retval == 0)
1429                                                 break;
1430                                 }
1431                         }
1432                 }
1433         }
1434         CtdlClearSystemContext();
1435
1436         return NULL;
1437 }
1438
1439
1440
1441 /*
1442  * SyslogFacility()
1443  * Translate text facility name to syslog.h defined value.
1444  */
1445 int SyslogFacility(char *name)
1446 {
1447         int i;
1448         struct
1449         {
1450                 int facility;
1451                 char *name;
1452         }   facTbl[] =
1453         {
1454                 {   LOG_KERN,   "kern"          },
1455                 {   LOG_USER,   "user"          },
1456                 {   LOG_MAIL,   "mail"          },
1457                 {   LOG_DAEMON, "daemon"        },
1458                 {   LOG_AUTH,   "auth"          },
1459                 {   LOG_SYSLOG, "syslog"        },
1460                 {   LOG_LPR,    "lpr"           },
1461                 {   LOG_NEWS,   "news"          },
1462                 {   LOG_UUCP,   "uucp"          },
1463                 {   LOG_LOCAL0, "local0"        },
1464                 {   LOG_LOCAL1, "local1"        },
1465                 {   LOG_LOCAL2, "local2"        },
1466                 {   LOG_LOCAL3, "local3"        },
1467                 {   LOG_LOCAL4, "local4"        },
1468                 {   LOG_LOCAL5, "local5"        },
1469                 {   LOG_LOCAL6, "local6"        },
1470                 {   LOG_LOCAL7, "local7"        },
1471                 {   0,            NULL          }
1472         };
1473         for(i = 0; facTbl[i].name != NULL; i++) {
1474                 if(!strcasecmp(name, facTbl[i].name))
1475                         return facTbl[i].facility;
1476         }
1477         return LOG_DAEMON;
1478 }
1479
1480
1481 /********** MEM CHEQQER ***********/
1482
1483 #ifdef DEBUG_MEMORY_LEAKS
1484
1485 #undef malloc
1486 #undef realloc
1487 #undef strdup
1488 #undef free
1489
1490 void *tracked_malloc(size_t size, char *file, int line) {
1491         struct igheap *thisheap;
1492         void *block;
1493
1494         block = malloc(size);
1495         if (block == NULL) return(block);
1496
1497         thisheap = malloc(sizeof(struct igheap));
1498         if (thisheap == NULL) {
1499                 free(block);
1500                 return(NULL);
1501         }
1502
1503         thisheap->block = block;
1504         strcpy(thisheap->file, file);
1505         thisheap->line = line;
1506         
1507         begin_critical_section(S_DEBUGMEMLEAKS);
1508         thisheap->next = igheap;
1509         igheap = thisheap;
1510         end_critical_section(S_DEBUGMEMLEAKS);
1511
1512         return(block);
1513 }
1514
1515
1516 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
1517         struct igheap *thisheap;
1518         void *block;
1519
1520         block = realloc(ptr, size);
1521         if (block == NULL) return(block);
1522
1523         thisheap = malloc(sizeof(struct igheap));
1524         if (thisheap == NULL) {
1525                 free(block);
1526                 return(NULL);
1527         }
1528
1529         thisheap->block = block;
1530         strcpy(thisheap->file, file);
1531         thisheap->line = line;
1532         
1533         begin_critical_section(S_DEBUGMEMLEAKS);
1534         thisheap->next = igheap;
1535         igheap = thisheap;
1536         end_critical_section(S_DEBUGMEMLEAKS);
1537
1538         return(block);
1539 }
1540
1541
1542
1543 void tracked_free(void *ptr) {
1544         struct igheap *thisheap;
1545         struct igheap *trash;
1546
1547         free(ptr);
1548
1549         if (igheap == NULL) return;
1550         begin_critical_section(S_DEBUGMEMLEAKS);
1551         for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1552                 if (thisheap->next != NULL) {
1553                         if (thisheap->next->block == ptr) {
1554                                 trash = thisheap->next;
1555                                 thisheap->next = thisheap->next->next;
1556                                 free(trash);
1557                         }
1558                 }
1559         }
1560         if (igheap->block == ptr) {
1561                 trash = igheap;
1562                 igheap = igheap->next;
1563                 free(trash);
1564         }
1565         end_critical_section(S_DEBUGMEMLEAKS);
1566 }
1567
1568 char *tracked_strdup(const char *s, char *file, int line) {
1569         char *ptr;
1570
1571         if (s == NULL) return(NULL);
1572         ptr = tracked_malloc(strlen(s) + 1, file, line);
1573         if (ptr == NULL) return(NULL);
1574         strncpy(ptr, s, strlen(s));
1575         return(ptr);
1576 }
1577
1578 void dump_heap(void) {
1579         struct igheap *thisheap;
1580
1581         for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1582                 syslog(LOG_CRIT, "UNFREED: %30s : %d\n",
1583                         thisheap->file, thisheap->line);
1584         }
1585 }
1586
1587 #endif /*  DEBUG_MEMORY_LEAKS */