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