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