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