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