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