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