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