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