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