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