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