sd: remove 'ssd' driver support
[unleashed/tickless.git] / usr / src / cmd / syslogd / syslogd.c
blob99fdec47b832b570e241ef4ac7491a23d47dd833
1 /*
2 * CDDL HEADER START
4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or http://www.opensolaris.org/os/licensing.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
19 * CDDL HEADER END
22 * Copyright 2008 Sun Microsystems, Inc. All rights reserved.
23 * Use is subject to license terms.
24 * Copyright 2012 Milan Jurik. All rights reserved.
25 * Copyright (c) 2013 Gary Mills
29 * Copyright (c) 1984, 1986, 1987, 1988, 1989 AT&T
30 * All Rights Reserved
34 * University Copyright- Copyright (c) 1982, 1986, 1988
35 * The Regents of the University of California
36 * All Rights Reserved
38 * University Acknowledgment- Portions of this document are derived from
39 * software developed by the University of California, Berkeley, and its
40 * contributors.
44 * syslogd -- log system messages
46 * This program implements a system log. It takes a series of lines.
47 * Each line may have a priority, signified as "<n>" as
48 * the first characters of the line. If this is
49 * not present, a default priority is used.
51 * To kill syslogd, send a signal 15 (terminate). A signal 1 (hup) will
52 * cause it to reconfigure.
54 * Defined Constants:
56 * MAXLINE -- the maximimum line length that can be handled.
57 * DEFUPRI -- the default priority for user messages.
58 * DEFSPRI -- the default priority for kernel messages.
62 #include <unistd.h>
63 #include <note.h>
64 #include <errno.h>
65 #include <sys/types.h>
66 #include <stdio.h>
67 #include <stdio_ext.h>
68 #include <stdlib.h>
69 #include <ctype.h>
70 #include <signal.h>
71 #include <string.h>
72 #include <strings.h>
73 #include <libscf.h>
74 #include <netconfig.h>
75 #include <netdir.h>
76 #include <pwd.h>
77 #include <sys/socket.h>
78 #include <tiuser.h>
79 #include <utmpx.h>
80 #include <limits.h>
81 #include <pthread.h>
82 #include <fcntl.h>
83 #include <stropts.h>
84 #include <assert.h>
85 #include <sys/statvfs.h>
87 #include <sys/param.h>
88 #include <sys/sysmacros.h>
89 #include <sys/syslog.h>
90 #include <sys/strlog.h>
91 #include <sys/stat.h>
92 #include <sys/time.h>
93 #include <sys/utsname.h>
94 #include <sys/poll.h>
95 #include <sys/wait.h>
96 #include <sys/resource.h>
97 #include <sys/mman.h>
98 #include <sys/note.h>
99 #include <door.h>
101 #include <wchar.h>
102 #include <locale.h>
103 #include <stdarg.h>
105 #include "dataq.h"
106 #include "conf.h"
107 #include "syslogd.h"
109 #define DOORFILE "/var/run/syslog_door"
110 #define RELATIVE_DOORFILE "../var/run/syslog_door"
111 #define OLD_DOORFILE "/etc/.syslog_door"
113 #define PIDFILE "/var/run/syslog.pid"
114 #define RELATIVE_PIDFILE "../var/run/syslog.pid"
115 #define OLD_PIDFILE "/etc/syslog.pid"
117 static char *LogName = "/dev/log";
118 static char *ConfFile = "/etc/syslog.conf";
119 static char ctty[] = "/dev/console";
120 static char sysmsg[] = "/dev/sysmsg";
121 static int DoorFd = -1;
122 static int DoorCreated = 0;
123 static int PidfileCreated = 0;
124 static char *DoorFileName = DOORFILE;
125 static char *PidFileName = PIDFILE;
128 * configuration file directives
131 static struct code PriNames[] = {
132 "panic", LOG_EMERG,
133 "emerg", LOG_EMERG,
134 "alert", LOG_ALERT,
135 "crit", LOG_CRIT,
136 "err", LOG_ERR,
137 "error", LOG_ERR,
138 "warn", LOG_WARNING,
139 "warning", LOG_WARNING,
140 "notice", LOG_NOTICE,
141 "info", LOG_INFO,
142 "debug", LOG_DEBUG,
143 "none", NOPRI,
144 NULL, -1
147 static struct code FacNames[] = {
148 "kern", LOG_KERN,
149 "user", LOG_USER,
150 "mail", LOG_MAIL,
151 "daemon", LOG_DAEMON,
152 "auth", LOG_AUTH,
153 "security", LOG_AUTH,
154 "mark", LOG_MARK,
155 "syslog", LOG_SYSLOG,
156 "lpr", LOG_LPR,
157 "news", LOG_NEWS,
158 "uucp", LOG_UUCP,
159 "altcron", LOG_ALTCRON,
160 "authpriv", LOG_AUTHPRIV,
161 "ftp", LOG_FTP,
162 "ntp", LOG_NTP,
163 "audit", LOG_AUDIT,
164 "console", LOG_CONSOLE,
165 "cron", LOG_CRON,
166 "local0", LOG_LOCAL0,
167 "local1", LOG_LOCAL1,
168 "local2", LOG_LOCAL2,
169 "local3", LOG_LOCAL3,
170 "local4", LOG_LOCAL4,
171 "local5", LOG_LOCAL5,
172 "local6", LOG_LOCAL6,
173 "local7", LOG_LOCAL7,
174 NULL, -1
177 static char *TypeNames[7] = {
178 "UNUSED", "FILE", "TTY", "CONSOLE",
179 "FORW", "USERS", "WALL"
183 * we allocate our own thread stacks so we can create them
184 * without the MAP_NORESERVE option. We need to be sure
185 * we have stack space even if the machine runs out of swap
188 #define DEFAULT_STACKSIZE (100 * 1024) /* 100 k stack */
189 #define DEFAULT_REDZONESIZE (8 * 1024) /* 8k redzone */
191 static pthread_mutex_t wmp = PTHREAD_MUTEX_INITIALIZER; /* wallmsg lock */
193 static pthread_mutex_t cft = PTHREAD_MUTEX_INITIALIZER;
194 static int conf_threads = 0;
196 static pthread_mutex_t hup_lock = PTHREAD_MUTEX_INITIALIZER;
197 static pthread_cond_t hup_done = PTHREAD_COND_INITIALIZER;
199 static pthread_mutex_t logerror_lock = PTHREAD_MUTEX_INITIALIZER;
201 #define HUP_ACCEPTABLE 0x0000 /* can start SIGHUP process */
202 #define HUP_INPROGRESS 0x0001 /* SIGHUP process in progress */
203 #define HUP_COMPLETED 0x0002 /* SIGHUP process completed */
204 #define HUP_SUSP_LOGMSG_REQD 0x1000 /* request to suspend */
205 #define HUP_LOGMSG_SUSPENDED 0x2000 /* logmsg is suspended */
206 static int hup_state = HUP_ACCEPTABLE;
208 static size_t stacksize; /* thread stack size */
209 static size_t redzonesize; /* thread stack redzone size */
210 static char *stack_ptr; /* ptr to allocated stacks */
211 static char *cstack_ptr; /* ptr to conf_thr stacks */
213 static time_t start_time;
215 static pthread_t sys_thread; /* queues messages from us */
216 static pthread_t net_thread; /* queues messages from the net */
217 static pthread_t log_thread; /* message processing thread */
218 static pthread_t hnl_thread; /* hostname lookup thread */
220 static dataq_t inputq; /* the input queue */
221 static dataq_t tmpq; /* temporary queue for err msg */
222 static dataq_t hnlq; /* hostname lookup queue */
224 static struct filed fallback[2];
225 static struct filed *Files;
226 static int nlogs;
227 static int Debug; /* debug flag */
228 static host_list_t LocalHostName; /* our hostname */
229 static host_list_t NullHostName; /* in case of lookup failure */
230 static int debuglev = 1; /* debug print level */
231 static int interrorlog; /* internal error logging */
233 static int MarkInterval = 20; /* interval between marks (mins) */
234 static int Marking = 0; /* non-zero if marking some file */
235 static int Ninputs = 0; /* number of network inputs */
236 static int curalarm = 0; /* current timeout value (secs) */
237 static int sys_msg_count = 0; /* total msgs rcvd from local log */
238 static int sys_init_msg_count = 0; /* initially received */
239 static int net_msg_count = 0; /* total msgs rcvd from net */
241 static struct pollfd Pfd; /* Pollfd for local the log device */
242 static struct pollfd *Nfd; /* Array of pollfds for udp ports */
243 static struct netconfig *Ncf;
244 static struct netbuf **Myaddrs;
245 static struct t_unitdata **Udp;
246 static struct t_uderr **Errp;
247 static int turnoff = 0;
248 static int shutting_down;
250 /* for managing door server threads */
251 static pthread_mutex_t door_server_cnt_lock = PTHREAD_MUTEX_INITIALIZER;
252 static uint_t door_server_cnt = 0;
253 static pthread_attr_t door_thr_attr;
255 static struct hostname_cache **hnc_cache;
256 static pthread_mutex_t hnc_mutex = PTHREAD_MUTEX_INITIALIZER;
257 static size_t hnc_size = DEF_HNC_SIZE;
258 static unsigned int hnc_ttl = DEF_HNC_TTL;
260 #define DPRINT0(d, m) if ((Debug) && debuglev >= (d)) \
261 (void) fprintf(stderr, m)
262 #define DPRINT1(d, m, a) if ((Debug) && debuglev >= (d)) \
263 (void) fprintf(stderr, m, a)
264 #define DPRINT2(d, m, a, b) if ((Debug) && debuglev >= (d)) \
265 (void) fprintf(stderr, m, a, b)
266 #define DPRINT3(d, m, a, b, c) if ((Debug) && debuglev >= (d)) \
267 (void) fprintf(stderr, m, a, b, c)
268 #define DPRINT4(d, m, a, b, c, e) if ((Debug) && debuglev >= (d)) \
269 (void) fprintf(stderr, m, a, b, c, e)
270 #define MALLOC_FAIL(x) \
271 logerror("malloc failed: " x)
272 #define MALLOC_FAIL_EXIT \
273 logerror("malloc failed - fatal"); \
274 exit(1)
277 #define MAILCMD "mailx -s \"syslogd shut down\" root"
280 * Number of seconds to wait before giving up on threads that won't
281 * shutdown: (that's right, 10 minutes!)
283 #define LOOP_MAX (10 * 60)
286 * Interval(sec) to check the status of output queue while processing
287 * HUP signal.
289 #define LOOP_INTERVAL (15)
292 main(int argc, char **argv)
294 int i;
295 char *pstr;
296 int sig, fd;
297 int tflag = 0, Tflag = 0;
298 sigset_t sigs, allsigs;
299 struct rlimit rlim;
300 char *debugstr;
301 int mcount = 0;
302 struct sigaction act;
303 pthread_t mythreadno = 0;
304 char cbuf [30];
305 struct stat sb;
307 #ifdef DEBUG
308 #define DEBUGDIR "/var/tmp"
309 if (chdir(DEBUGDIR))
310 DPRINT2(1, "main(%u): Unable to cd to %s\n", mythreadno,
311 DEBUGDIR);
312 #endif /* DEBUG */
314 (void) setlocale(LC_ALL, "");
316 if ((debugstr = getenv("SYSLOGD_DEBUG")) != NULL)
317 if ((debuglev = atoi(debugstr)) == 0)
318 debuglev = 1;
320 #if ! defined(TEXT_DOMAIN) /* should be defined by cc -D */
321 #define TEXT_DOMAIN "SYS_TEST"
322 #endif
323 (void) textdomain(TEXT_DOMAIN);
325 (void) time(&start_time);
327 if (lstat("/var/run", &sb) != 0 || !(S_ISDIR(sb.st_mode))) {
328 DoorFileName = OLD_DOORFILE;
329 PidFileName = OLD_PIDFILE;
332 properties();
334 while ((i = getopt(argc, argv, "df:p:m:tT")) != EOF) {
335 switch (i) {
336 case 'f': /* configuration file */
337 ConfFile = optarg;
338 break;
340 case 'd': /* debug */
341 Debug++;
342 break;
344 case 'p': /* path */
345 LogName = optarg;
346 break;
348 case 'm': /* mark interval */
349 for (pstr = optarg; *pstr; pstr++) {
350 if (! (isdigit(*pstr))) {
351 (void) fprintf(stderr,
352 "Illegal interval\n");
353 usage();
356 MarkInterval = atoi(optarg);
357 if (MarkInterval < 1 || MarkInterval > INT_MAX) {
358 (void) fprintf(stderr,
359 "Interval must be between 1 and %d\n",
360 INT_MAX);
361 usage();
363 break;
364 case 't': /* turn off remote reception */
365 tflag++;
366 turnoff++;
367 break;
368 case 'T': /* turn on remote reception */
369 Tflag++;
370 turnoff = 0;
371 break;
372 default:
373 usage();
377 if (optind < argc)
378 usage();
380 if (tflag && Tflag) {
381 (void) fprintf(stderr, "specify only one of -t and -T\n");
382 usage();
386 * close all fd's except 0-2
389 closefrom(3);
391 if (!Debug) {
392 if (fork())
393 return (0);
394 (void) close(0);
395 (void) open("/", O_RDONLY);
396 (void) dup2(0, 1);
397 (void) dup2(0, 2);
398 untty();
401 if (Debug) {
402 mythreadno = pthread_self();
406 * DO NOT call logerror() until tmpq is initialized.
408 disable_errorlog();
411 * ensure that file descriptor limit is "high enough"
413 (void) getrlimit(RLIMIT_NOFILE, &rlim);
414 if (rlim.rlim_cur < rlim.rlim_max)
415 rlim.rlim_cur = rlim.rlim_max;
416 if (setrlimit(RLIMIT_NOFILE, &rlim) < 0)
417 logerror("Unable to increase file descriptor limit.");
418 (void) enable_extended_FILE_stdio(-1, -1);
420 /* block all signals from all threads initially */
421 (void) sigfillset(&allsigs);
422 (void) pthread_sigmask(SIG_BLOCK, &allsigs, NULL);
424 DPRINT2(1, "main(%u): Started at time %s", mythreadno,
425 ctime_r(&start_time, cbuf));
427 init(); /* read configuration, start threads */
429 DPRINT1(1, "main(%u): off & running....\n", mythreadno);
431 /* now set up to catch signals we care about */
433 (void) sigemptyset(&sigs);
434 (void) sigaddset(&sigs, SIGHUP); /* reconfigure */
435 (void) sigaddset(&sigs, SIGALRM); /* mark & flush timer */
436 (void) sigaddset(&sigs, SIGTERM); /* exit */
437 (void) sigaddset(&sigs, SIGINT); /* exit if debugging */
438 (void) sigaddset(&sigs, SIGQUIT); /* exit if debugging */
439 (void) sigaddset(&sigs, SIGPIPE); /* catch & discard */
440 (void) sigaddset(&sigs, SIGUSR1); /* dump debug stats */
443 * We must set up to catch these signals, even though sigwait
444 * will get them before the isr does. Setting SA_SIGINFO ensures
445 * that signals will be enqueued.
448 act.sa_flags = SA_SIGINFO;
449 act.sa_sigaction = signull;
451 (void) sigaction(SIGHUP, &act, NULL);
452 (void) sigaction(SIGALRM, &act, NULL);
453 (void) sigaction(SIGTERM, &act, NULL);
454 (void) sigaction(SIGINT, &act, NULL);
455 (void) sigaction(SIGQUIT, &act, NULL);
456 (void) sigaction(SIGPIPE, &act, NULL);
457 (void) sigaction(SIGUSR1, &act, NULL);
459 /* we now turn into the signal handling thread */
461 DPRINT1(2, "main(%u): now handling signals\n", mythreadno);
462 for (;;) {
463 (void) sigwait(&sigs, &sig);
464 DPRINT2(2, "main(%u): received signal %d\n", mythreadno, sig);
465 switch (sig) {
466 case SIGALRM:
467 DPRINT1(1, "main(%u): Got SIGALRM\n",
468 mythreadno);
469 flushmsg(NOCOPY);
470 if (Marking && (++mcount % MARKCOUNT == 0)) {
471 if (logmymsg(LOG_INFO, "-- MARK --",
472 ADDDATE|MARK|NOCOPY, 0) == -1) {
473 MALLOC_FAIL(
474 "dropping MARK message");
477 mcount = 0;
479 curalarm = MarkInterval * 60 / MARKCOUNT;
480 (void) alarm((unsigned)curalarm);
481 DPRINT2(2, "main(%u): Next alarm in %d "
482 "seconds\n", mythreadno, curalarm);
483 break;
484 case SIGHUP:
485 DPRINT1(1, "main(%u): got SIGHUP - "
486 "reconfiguring\n", mythreadno);
488 reconfigure();
490 DPRINT1(1, "main(%u): done processing SIGHUP\n",
491 mythreadno);
492 break;
493 case SIGQUIT:
494 case SIGINT:
495 if (!Debug) {
496 /* allow these signals if debugging */
497 break;
499 /* FALLTHROUGH */
500 case SIGTERM:
501 DPRINT2(1, "main(%u): going down on signal %d\n",
502 mythreadno, sig);
503 (void) alarm(0);
504 flushmsg(0);
505 errno = 0;
506 t_errno = 0;
507 logerror("going down on signal %d", sig);
508 disable_errorlog(); /* force msg to console */
509 (void) shutdown_msg(); /* stop threads */
510 shutdown_input();
511 close_door();
512 delete_doorfiles();
513 return (0);
514 case SIGUSR1: /* secret debug dump mode */
515 /* if in debug mode, use stdout */
517 if (Debug) {
518 dumpstats(STDOUT_FILENO);
519 break;
521 /* otherwise dump to a debug file */
522 if ((fd = open(DEBUGFILE,
523 (O_WRONLY|O_CREAT|O_TRUNC|O_EXCL),
524 0644)) < 0)
525 break;
526 dumpstats(fd);
527 (void) close(fd);
528 break;
529 default:
530 DPRINT2(2, "main(%u): unexpected signal %d\n",
531 mythreadno, sig);
532 break;
538 * Attempts to open the local log device
539 * and return a file descriptor.
541 static int
542 openklog(char *name, int mode)
544 int fd;
545 struct strioctl str;
546 pthread_t mythreadno;
548 if (Debug) {
549 mythreadno = pthread_self();
552 if ((fd = open(name, mode)) < 0) {
553 logerror("cannot open %s", name);
554 DPRINT3(1, "openklog(%u): cannot create %s (%d)\n",
555 mythreadno, name, errno);
556 return (-1);
558 str.ic_cmd = I_CONSLOG;
559 str.ic_timout = 0;
560 str.ic_len = 0;
561 str.ic_dp = NULL;
562 if (ioctl(fd, I_STR, &str) < 0) {
563 logerror("cannot register to log console messages");
564 DPRINT2(1, "openklog(%u): cannot register to log "
565 "console messages (%d)\n", mythreadno, errno);
566 return (-1);
568 return (fd);
573 * Open the log device, and pull up all pending messages.
575 static void
576 prepare_sys_poll()
578 int nfds, funix;
580 if ((funix = openklog(LogName, O_RDONLY)) < 0) {
581 logerror("can't open kernel log device - fatal");
582 exit(1);
585 Pfd.fd = funix;
586 Pfd.events = POLLIN;
588 for (;;) {
589 nfds = poll(&Pfd, 1, 0);
590 if (nfds <= 0) {
591 if (sys_init_msg_count > 0)
592 flushmsg(SYNC_FILE);
593 break;
596 if (Pfd.revents & POLLIN) {
597 getkmsg(0);
598 } else if (Pfd.revents & (POLLNVAL|POLLHUP|POLLERR)) {
599 logerror("kernel log driver poll error");
600 break;
607 * this thread listens to the local stream log driver for log messages
608 * generated by this host, formats them, and queues them to the logger
609 * thread.
611 /*ARGSUSED*/
612 static void *
613 sys_poll(void *ap)
615 int nfds;
616 static int klogerrs = 0;
617 pthread_t mythreadno;
619 if (Debug) {
620 mythreadno = pthread_self();
623 DPRINT1(1, "sys_poll(%u): sys_thread started\n", mythreadno);
626 * Process messages, blocking on poll because timeout is set
627 * to INFTIM. When poll returns with a message, call getkmsg
628 * to pull up one message from the log driver and enqueue it
629 * with the sync flag set.
632 sys_init_msg_count = 0;
634 for (;;) {
635 errno = 0;
636 t_errno = 0;
638 nfds = poll(&Pfd, 1, INFTIM);
640 if (nfds == 0)
641 continue;
643 if (nfds < 0) {
644 if (errno != EINTR)
645 logerror("poll");
646 continue;
648 if (Pfd.revents & POLLIN) {
649 getkmsg(INFTIM);
650 } else {
651 if (shutting_down) {
652 pthread_exit(0);
654 if (Pfd.revents & (POLLNVAL|POLLHUP|POLLERR)) {
655 logerror("kernel log driver poll error");
656 (void) close(Pfd.fd);
657 Pfd.fd = -1;
661 while (Pfd.fd == -1 && klogerrs++ < 10) {
662 Pfd.fd = openklog(LogName, O_RDONLY);
664 if (klogerrs >= 10) {
665 logerror("can't reopen kernel log device - fatal");
666 exit(1);
669 /*NOTREACHED*/
670 return (NULL);
674 * Pull up one message from log driver.
676 static void
677 getkmsg(int timeout)
679 int flags = 0, i;
680 char *lastline;
681 struct strbuf ctl, dat;
682 struct log_ctl hdr;
683 char buf[MAXLINE+1];
684 size_t buflen;
685 size_t len;
686 char tmpbuf[MAXLINE+1];
687 pthread_t mythreadno;
689 if (Debug) {
690 mythreadno = pthread_self();
693 dat.maxlen = MAXLINE;
694 dat.buf = buf;
695 ctl.maxlen = sizeof (struct log_ctl);
696 ctl.buf = (caddr_t)&hdr;
698 while ((i = getmsg(Pfd.fd, &ctl, &dat, &flags)) == MOREDATA) {
699 lastline = &dat.buf[dat.len];
700 *lastline = '\0';
702 DPRINT2(5, "getkmsg:(%u): getmsg: dat.len = %d\n",
703 mythreadno, dat.len);
704 buflen = strlen(buf);
705 len = findnl_bkwd(buf, buflen);
707 (void) memcpy(tmpbuf, buf, len);
708 tmpbuf[len] = '\0';
711 * Format sys will enqueue the log message.
712 * Set the sync flag if timeout != 0, which
713 * means that we're done handling all the
714 * initial messages ready during startup.
716 if (timeout == 0) {
717 formatsys(&hdr, tmpbuf, 0);
718 sys_init_msg_count++;
719 } else {
720 formatsys(&hdr, tmpbuf, 1);
722 sys_msg_count++;
724 if (len != buflen) {
725 /* If anything remains in buf */
726 size_t remlen;
728 if (buf[len] == '\n') {
729 /* skip newline */
730 len++;
734 * Move the remaining bytes to
735 * the beginnning of buf.
738 remlen = buflen - len;
739 (void) memcpy(buf, &buf[len], remlen);
740 dat.maxlen = MAXLINE - remlen;
741 dat.buf = &buf[remlen];
742 } else {
743 dat.maxlen = MAXLINE;
744 dat.buf = buf;
748 if (i == 0 && dat.len > 0) {
749 dat.buf[dat.len] = '\0';
751 * Format sys will enqueue the log message.
752 * Set the sync flag if timeout != 0, which
753 * means that we're done handling all the
754 * initial messages ready during startup.
756 DPRINT2(5, "getkmsg(%u): getmsg: dat.maxlen = %d\n",
757 mythreadno, dat.maxlen);
758 DPRINT2(5, "getkmsg(%u): getmsg: dat.len = %d\n",
759 mythreadno, dat.len);
760 DPRINT2(5, "getkmsg(%u): getmsg: strlen(dat.buf) = %d\n",
761 mythreadno, strlen(dat.buf));
762 DPRINT2(5, "getkmsg(%u): getmsg: dat.buf = \"%s\"\n",
763 mythreadno, dat.buf);
764 DPRINT2(5, "getkmsg(%u): buf len = %d\n",
765 mythreadno, strlen(buf));
766 if (timeout == 0) {
767 formatsys(&hdr, buf, 0);
768 sys_init_msg_count++;
769 } else {
770 formatsys(&hdr, buf, 1);
772 sys_msg_count++;
773 } else if (i < 0 && errno != EINTR) {
774 if (!shutting_down) {
775 logerror("kernel log driver read error");
777 (void) close(Pfd.fd);
778 Pfd.fd = -1;
783 * this thread polls all the network interfaces for syslog messages
784 * forwarded to us, tags them with the hostname they are received
785 * from, and queues them to the logger thread.
787 /*ARGSUSED*/
788 static void *
789 net_poll(void *ap)
791 int nfds, i;
792 int flags = 0;
793 struct t_unitdata *udp;
794 struct t_uderr *errp;
795 char buf[MAXLINE+1];
796 char *uap;
797 log_message_t *mp;
798 host_info_t *hinfo;
799 pthread_t mythreadno;
801 if (Debug) {
802 mythreadno = pthread_self();
805 DPRINT1(1, "net_poll(%u): net_thread started\n", mythreadno);
807 _NOTE(NOW_INVISIBLE_TO_OTHER_THREADS(*mp))
809 for (;;) {
810 errno = 0;
811 t_errno = 0;
812 nfds = poll(Nfd, Ninputs, -1);
813 if (nfds == 0)
814 continue;
816 if (nfds < 0) {
817 if (errno != EINTR)
818 logerror("poll");
819 continue;
821 for (i = 0; nfds > 0 && i < Ninputs; i++) {
822 if ((Nfd[i].revents & POLLIN) == 0) {
823 if (shutting_down) {
824 pthread_exit(0);
826 if (Nfd[i].revents &
827 (POLLNVAL|POLLHUP|POLLERR)) {
828 logerror("POLLNVAL|POLLHUP|POLLERR");
829 (void) t_close(Nfd[i].fd);
830 Nfd[i].fd = -1;
831 nfds--;
833 continue;
836 udp = Udp[i];
837 udp->udata.buf = buf;
838 udp->udata.maxlen = MAXLINE;
839 udp->udata.len = 0;
840 flags = 0;
841 if (t_rcvudata(Nfd[i].fd, udp, &flags) < 0) {
842 errp = Errp[i];
843 if (t_errno == TLOOK) {
844 if (t_rcvuderr(Nfd[i].fd, errp) < 0) {
845 if (!shutting_down) {
846 logerror("t_rcvuderr");
848 (void) t_close(Nfd[i].fd);
849 Nfd[i].fd = -1;
851 } else {
852 if (!shutting_down) {
853 logerror("t_rcvudata");
855 (void) t_close(Nfd[i].fd);
856 Nfd[i].fd = -1;
858 nfds--;
859 if (shutting_down) {
860 pthread_exit(0);
862 continue;
864 nfds--;
866 if (udp->udata.len == 0) {
867 if (Debug) {
868 uap = NULL;
869 if (udp->addr.len > 0) {
870 uap = taddr2uaddr(&Ncf[i],
871 &udp->addr);
873 DPRINT2(1, "net_poll(%u):"
874 " received empty packet"
875 " from %s\n", mythreadno,
876 uap ? uap : "<unknown>");
877 free(uap);
879 continue; /* No data */
881 if (udp->addr.len == 0) {
883 * The previous message was larger than
884 * MAXLINE, and T_MORE should have been set.
885 * Further data needs to be discarded as
886 * we've already received MAXLINE.
888 DPRINT1(1, "net_poll(%u): discarding packet "
889 "exceeds max line size\n", mythreadno);
890 continue;
893 net_msg_count++;
895 if ((mp = new_msg()) == NULL) {
896 MALLOC_FAIL("dropping message from "
897 "remote");
898 continue;
901 buf[udp->udata.len] = '\0';
902 formatnet(&udp->udata, mp);
904 if (Debug) {
905 uap = taddr2uaddr(&Ncf[i], &udp->addr);
906 DPRINT2(1, "net_poll(%u): received message"
907 " from %s\n", mythreadno,
908 uap ? uap : "<unknown>");
909 free(uap);
911 if ((hinfo = malloc(sizeof (*hinfo))) == NULL ||
912 (hinfo->addr.buf =
913 malloc(udp->addr.len)) == NULL) {
914 MALLOC_FAIL("dropping message from "
915 "remote");
916 if (hinfo) {
917 free(hinfo);
919 free_msg(mp);
920 continue;
923 hinfo->ncp = &Ncf[i];
924 hinfo->addr.len = udp->addr.len;
925 (void) memcpy(hinfo->addr.buf, udp->addr.buf,
926 udp->addr.len);
927 mp->ptr = hinfo;
928 if (dataq_enqueue(&hnlq, (void *)mp) == -1) {
929 MALLOC_FAIL("dropping message from "
930 "remote");
931 free_msg(mp);
932 free(hinfo->addr.buf);
933 free(hinfo);
934 continue;
936 DPRINT3(5, "net_poll(%u): enqueued msg %p "
937 "on queue %p\n", mythreadno, (void *)mp,
938 (void *)&hnlq);
941 /*NOTREACHED*/
942 return (NULL);
945 static void
946 usage(void)
948 (void) fprintf(stderr,
949 "usage: syslogd [-d] [-t|-T] [-mmarkinterval] [-ppath]"
950 " [-fconffile]\n");
951 exit(1);
954 static void
955 untty(void)
957 if (!Debug)
958 (void) setsid();
962 * generate a log message internally. The original version of syslogd
963 * simply called logmsg directly, but because everything is now based
964 * on message passing, we need an internal way to generate and queue
965 * log messages from within syslogd itself.
967 static int
968 logmymsg(int pri, char *msg, int flags, int pending)
970 log_message_t *mp;
971 pthread_t mythreadno;
972 dataq_t *qptr;
974 if (Debug) {
975 mythreadno = pthread_self();
978 if ((mp = new_msg()) == NULL) {
979 return (-1);
982 _NOTE(NOW_INVISIBLE_TO_OTHER_THREADS(*mp))
983 mp->pri = pri;
984 mp->hlp = &LocalHostName;
985 (void) strlcpy(mp->msg, msg, MAXLINE+1);
986 mp->flags = flags;
987 (void) time(&mp->ts);
989 qptr = pending ? &tmpq : &inputq;
990 if (dataq_enqueue(qptr, (void *)mp) == -1) {
991 free_msg(mp);
992 return (-1);
995 DPRINT3(5, "logmymsg(%u): enqueued msg %p on queue %p\n",
996 mythreadno, (void *)mp, (void *)qptr);
997 DPRINT2(5, "logmymsg(%u): Message content: %s\n", mythreadno, msg);
998 return (0);
1002 * Generate an internal shutdown message
1004 static int
1005 shutdown_msg(void)
1007 pthread_t mythreadno;
1008 log_message_t *mp;
1010 if (Debug) {
1011 mythreadno = pthread_self();
1014 if ((mp = new_msg()) == NULL) {
1015 return (-1);
1018 _NOTE(NOW_INVISIBLE_TO_OTHER_THREADS(*mp));
1019 mp->flags = SHUTDOWN;
1020 mp->hlp = &LocalHostName;
1022 if (dataq_enqueue(&inputq, (void *)mp) == -1) {
1023 free_msg(mp);
1024 return (-1);
1027 DPRINT3(5, "shutdown_msg(%u): enqueued msg %p on queue %p\n",
1028 mythreadno, (void *)mp, (void *)&inputq);
1029 return (0);
1033 * Generate an internal flush message
1035 static void
1036 flushmsg(int flags)
1038 log_message_t *mp;
1039 pthread_t mythreadno;
1041 if (Debug) {
1042 mythreadno = pthread_self();
1045 if ((mp = new_msg()) == NULL) {
1046 MALLOC_FAIL("dropping flush msg");
1047 return;
1050 _NOTE(NOW_INVISIBLE_TO_OTHER_THREADS(*mp));
1051 mp->flags = FLUSHMSG | flags;
1052 mp->hlp = &LocalHostName;
1054 if (dataq_enqueue(&inputq, (void *)mp) == -1) {
1055 free_msg(mp);
1056 MALLOC_FAIL("dropping flush msg");
1057 return;
1060 DPRINT4(5, "flush_msg(%u): enqueued msg %p on queue %p, flags "
1061 "0x%x\n", mythreadno, (void *)mp, (void *)&inputq, flags);
1065 * Do some processing on messages received from the net
1067 static void
1068 formatnet(struct netbuf *nbp, log_message_t *mp)
1070 char *p;
1071 int pri;
1072 pthread_t mythreadno;
1074 if (Debug) {
1075 mythreadno = pthread_self();
1078 DPRINT2(5, "formatnet(%u): called for msg %p\n", mythreadno,
1079 (void *)mp);
1081 mp->flags = NETWORK;
1082 (void) time(&mp->ts);
1084 /* test for special codes */
1085 pri = DEFUPRI;
1086 p = nbp->buf;
1087 DPRINT2(9, "formatnet(%u): Message content:\n>%s<\n", mythreadno,
1089 if (*p == '<' && isdigit(*(p+1))) {
1090 pri = 0;
1091 while (isdigit(*++p))
1092 pri = 10 * pri + (*p - '0');
1093 if (*p == '>')
1094 ++p;
1095 if (pri <= 0 || pri >= (LOG_NFACILITIES << 3))
1096 pri = DEFUPRI;
1099 mp->pri = pri;
1100 (void) strlcpy(mp->msg, p, MAXLINE+1);
1104 * Do some processing on messages generated by this host
1105 * and then enqueue the log message.
1107 static void
1108 formatsys(struct log_ctl *lp, char *msg, int sync)
1110 char *p, *q;
1111 char line[MAXLINE + 1];
1112 size_t msglen;
1113 log_message_t *mp;
1114 char cbuf[30];
1115 pthread_t mythreadno;
1117 if (Debug) {
1118 mythreadno = pthread_self();
1121 DPRINT3(3, "formatsys(%u): log_ctl.mid = %d, log_ctl.sid = %d\n",
1122 mythreadno, lp->mid, lp->sid);
1123 DPRINT2(9, "formatsys(%u): Message Content:\n>%s<\n", mythreadno,
1124 msg);
1126 /* msglen includes the null termination */
1127 msglen = strlen(msg) + 1;
1129 for (p = msg; *p != '\0'; ) {
1130 size_t linelen;
1131 size_t len;
1134 * Allocate a log_message_t structure.
1135 * We should do it here since a single message (msg)
1136 * could be composed of many lines.
1138 _NOTE(NOW_INVISIBLE_TO_OTHER_THREADS(*mp));
1140 if ((mp = new_msg()) == NULL) {
1141 MALLOC_FAIL("dropping message");
1143 * Should bail out from the loop.
1145 break;
1148 mp->flags &= ~NETWORK;
1149 mp->hlp = &LocalHostName;
1150 mp->ts = lp->ttime;
1151 if (lp->flags & SL_LOGONLY)
1152 mp->flags |= IGN_CONS;
1153 if (lp->flags & SL_CONSONLY)
1154 mp->flags |= IGN_FILE;
1156 /* extract facility */
1157 if ((lp->pri & LOG_FACMASK) == LOG_KERN) {
1158 (void) sprintf(line, "%.15s ",
1159 ctime_r(&mp->ts, cbuf) + 4);
1160 } else {
1161 (void) sprintf(line, "");
1164 linelen = strlen(line);
1165 q = line + linelen;
1167 DPRINT2(5, "formatsys(%u): msglen = %d\n", mythreadno, msglen);
1168 len = copynl_frwd(q, MAXLINE + 1 - linelen, p, msglen);
1169 DPRINT2(5, "formatsys(%u): len (copynl_frwd) = %d\n",
1170 mythreadno, len);
1172 p += len;
1173 msglen -= len;
1175 if (*p == '\n') {
1176 /* skip newline */
1177 p++;
1180 if (sync && ((lp->pri & LOG_FACMASK) == LOG_KERN))
1181 mp->flags |= SYNC_FILE; /* fsync file after write */
1183 if (len != 0) {
1184 (void) strlcpy(mp->msg, line, MAXLINE+1);
1185 mp->pri = lp->pri;
1187 if (dataq_enqueue(&inputq, (void *)mp) == -1) {
1188 free_msg(mp);
1189 MALLOC_FAIL("dropping message");
1190 break;
1193 DPRINT3(5, "formatsys(%u): sys_thread enqueued msg "
1194 "%p on queue %p\n", mythreadno, (void *)mp,
1195 (void *)&inputq);
1196 } else
1197 free_msg(mp);
1202 * Log a message to the appropriate log files, users, etc. based on
1203 * the priority.
1205 /*ARGSUSED*/
1206 static void *
1207 logmsg(void *ap)
1209 struct filed *f;
1210 int fac, prilev, flags, refcnt;
1211 int fake_shutdown, skip_shutdown;
1212 log_message_t *mp, *save_mp;
1213 pthread_t mythreadno;
1215 if (Debug) {
1216 mythreadno = pthread_self();
1219 DPRINT1(1, "logmsg(%u): msg dispatcher started\n", mythreadno);
1221 fake_shutdown = skip_shutdown = 0;
1222 save_mp = NULL;
1223 for (;;) {
1224 if (save_mp) {
1226 * If we have set aside a message in order to fake a
1227 * SHUTDOWN, use that message before picking from the
1228 * queue again.
1230 mp = save_mp;
1231 save_mp = NULL;
1232 } else {
1233 (void) dataq_dequeue(&inputq, (void **)&mp, 0);
1235 _NOTE(NOW_INVISIBLE_TO_OTHER_THREADS(*mp))
1236 DPRINT3(5, "logmsg(%u): msg dispatcher dequeued %p from "
1237 "queue %p\n", mythreadno, (void *)mp,
1238 (void *)&inputq);
1241 * In most cases, if the message traffic is low, logmsg() wakes
1242 * up when it receives the SHUTDOWN msg, and will sleep until
1243 * HUP process is complete. However, if the inputq is too
1244 * long, logmsg() may not receive SHUTDOWN before reconfigure()
1245 * releases the logger fds, filed and logit threads. That, in
1246 * turn, will cause logmsg to refer to invalid fileds.
1248 * logmsg() needs to respond to the SHUTDOWN message within
1249 * LOOP_INTERVAL seconds when reconfigure() enqueues it. It
1250 * does so in most cases. When it does not respond in time,
1251 * logmsg() needs to be in suspended state immediately, since
1252 * filed may have been invalidated. reconfigure() will set the
1253 * HUP_SUSP_LOGMSG_REQD bit in hup_state and wait another
1254 * LOOP_INTERVAL seconds before proceeding.
1256 * When HUP_SUSP_LOGMSG_REQD is set, we will create a fake
1257 * SHUTDOWN message, and dispatch it to the various logit
1258 * threads, and logmsg() itself will suspend. In order to
1259 * ignore the real SHUTDOWN which will arrive later, we keep a
1260 * counter (skip_shutdown) and decrement it when the SHUTDOWN
1261 * message arrives.
1263 if ((hup_state & HUP_SUSP_LOGMSG_REQD) &&
1264 (mp->flags & SHUTDOWN) == 0) {
1265 DPRINT1(3, "logmsg(%u): suspend request\n",
1266 mythreadno);
1268 save_mp = mp;
1270 /* create a fake SHUTDOWN msg */
1271 if ((mp = new_msg()) == NULL) {
1272 MALLOC_FAIL("dropping message");
1273 if (mp->flags & SHUTDOWN) {
1274 (void) logerror_to_console(1,
1275 "unable to shutdown "
1276 "logger thread");
1278 continue;
1280 mp->flags = SHUTDOWN;
1281 mp->hlp = &LocalHostName;
1282 fake_shutdown = 1;
1283 skip_shutdown++;
1284 DPRINT2(3, "logmsg(%u): pending SHUTDOWN %d\n",
1285 mythreadno, skip_shutdown);
1289 * is it a shutdown or flush message ?
1291 if ((mp->flags & SHUTDOWN) || (mp->flags & FLUSHMSG)) {
1292 (void) pthread_mutex_lock(&mp->msg_mutex);
1294 if ((mp->flags & SHUTDOWN) &&
1295 !fake_shutdown && skip_shutdown > 0) {
1296 skip_shutdown--;
1297 (void) pthread_mutex_unlock(&mp->msg_mutex);
1298 free_msg(mp);
1299 DPRINT2(3, "logmsg(%u): released late "
1300 "arrived SHUTDOWN. pending %d\n",
1301 mythreadno, skip_shutdown);
1302 continue;
1305 for (f = Files; f < &Files[nlogs]; f++) {
1306 (void) pthread_mutex_lock(&f->filed_mutex);
1308 if (f->f_type == F_UNUSED) {
1309 (void) pthread_mutex_unlock(
1310 &f->filed_mutex);
1311 continue;
1314 f->f_queue_count++;
1315 mp->refcnt++;
1317 if (dataq_enqueue(&f->f_queue,
1318 (void *)mp) == -1) {
1319 f->f_queue_count--;
1320 mp->refcnt--;
1321 (void) pthread_mutex_unlock(
1322 &f->filed_mutex);
1323 MALLOC_FAIL("dropping message");
1325 if (mp->flags & SHUTDOWN) {
1326 (void) logerror_to_console(1,
1327 "unable to shutdown "
1328 "logger thread");
1331 continue;
1333 DPRINT3(5, "logmsg(%u): enqueued msg %p "
1334 "on queue %p\n", mythreadno,
1335 (void *)mp, (void *)&f->f_queue);
1336 (void) pthread_mutex_unlock(&f->filed_mutex);
1340 * flags value needs to be saved because mp may
1341 * have been freed before SHUTDOWN test below.
1343 flags = mp->flags;
1344 refcnt = mp->refcnt;
1346 (void) pthread_mutex_unlock(&mp->msg_mutex);
1347 if (refcnt == 0)
1348 free_msg(mp);
1350 if (flags & SHUTDOWN) {
1351 (void) pthread_mutex_lock(&hup_lock);
1352 while (hup_state != HUP_COMPLETED) {
1353 hup_state |= HUP_LOGMSG_SUSPENDED;
1354 (void) pthread_cond_wait(&hup_done,
1355 &hup_lock);
1356 hup_state &= ~HUP_LOGMSG_SUSPENDED;
1358 hup_state = HUP_ACCEPTABLE;
1359 (void) pthread_mutex_unlock(&hup_lock);
1360 fake_shutdown = 0;
1362 continue;
1366 * Check to see if msg looks non-standard.
1368 if ((int)strlen(mp->msg) < 16 || mp->msg[3] != ' ' ||
1369 mp->msg[6] != ' ' || mp->msg[9] != ':' ||
1370 mp->msg[12] != ':' || mp->msg[15] != ' ')
1371 mp->flags |= ADDDATE;
1373 /* extract facility and priority level */
1374 fac = (mp->pri & LOG_FACMASK) >> 3;
1375 if (mp->flags & MARK)
1376 fac = LOG_NFACILITIES;
1377 prilev = mp->pri & LOG_PRIMASK;
1379 DPRINT3(3, "logmsg(%u): fac = %d, pri = %d\n",
1380 mythreadno, fac, prilev);
1383 * Because different devices log at different speeds,
1384 * it's important to hold the mutex for the current
1385 * message until it's been enqueued to all log files,
1386 * so the reference count is accurate before any
1387 * of the log threads can decrement it.
1389 _NOTE(NOW_VISIBLE_TO_OTHER_THREADS(*mp))
1390 _NOTE(COMPETING_THREADS_NOW)
1391 (void) pthread_mutex_lock(&mp->msg_mutex);
1393 for (f = Files; f < &Files[nlogs]; f++) {
1394 /* skip messages that are incorrect priority */
1395 if (f->f_pmask[fac] < (unsigned)prilev ||
1396 f->f_pmask[fac] == NOPRI)
1397 continue;
1398 if (f->f_queue_count > Q_HIGHWATER_MARK) {
1399 DPRINT4(5, "logmsg(%u): Dropping message "
1400 "%p on file %p, count = %d\n",
1401 mythreadno, (void *)mp, (void *)f,
1402 f->f_queue_count);
1403 continue;
1407 * Need to grab filed_mutex before testing the f_type.
1408 * Otherwise logit() may set F_UNUSED after the test
1409 * below, and start pulling out the pending messages.
1412 (void) pthread_mutex_lock(&f->filed_mutex);
1414 if (f->f_type == F_UNUSED ||
1415 (f->f_type == F_FILE && (mp->flags & IGN_FILE)) ||
1416 (f->f_type == F_CONSOLE &&
1417 (mp->flags & IGN_CONS))) {
1418 (void) pthread_mutex_unlock(&f->filed_mutex);
1419 continue;
1422 f->f_queue_count++;
1423 mp->refcnt++;
1425 if (dataq_enqueue(&f->f_queue, (void *)mp) == -1) {
1426 f->f_queue_count--;
1427 mp->refcnt--;
1428 (void) pthread_mutex_unlock(&f->filed_mutex);
1429 MALLOC_FAIL("dropping message");
1430 continue;
1433 DPRINT3(5, "logmsg(%u): enqueued msg %p on queue "
1434 "%p\n", mythreadno, (void *)mp,
1435 (void *)&f->f_queue);
1436 (void) pthread_mutex_unlock(&f->filed_mutex);
1438 refcnt = mp->refcnt;
1439 (void) pthread_mutex_unlock(&mp->msg_mutex);
1440 if (refcnt == 0)
1441 free_msg(mp);
1443 /*NOTREACHED*/
1444 return (NULL);
1448 * function to actually write the log message to the selected file.
1449 * each file has a logger thread that runs this routine. The function
1450 * is called with a pointer to its file structure.
1452 static void *
1453 logit(void *ap)
1455 struct filed *f = ap;
1456 log_message_t *mp;
1457 int forwardingloop = 0;
1458 const char *errmsg = "logit(%u): %s to %s forwarding loop detected\n";
1459 int i, currofst, prevofst, refcnt;
1460 host_list_t *hlp;
1462 assert(f != NULL);
1464 DPRINT4(5, "logit(%u): logger started for \"%s\" (queue %p, filed "
1465 "%p)\n", f->f_thread, f->f_un.f_fname, (void *)&f->f_queue,
1466 (void *)f);
1467 _NOTE(COMPETING_THREADS_NOW);
1469 while (f->f_type != F_UNUSED) {
1470 (void) dataq_dequeue(&f->f_queue, (void **)&mp, 0);
1471 DPRINT3(5, "logit(%u): logger dequeued msg %p from queue "
1472 "%p\n", f->f_thread, (void *)mp, (void *)&f->f_queue);
1473 (void) pthread_mutex_lock(&f->filed_mutex);
1474 assert(f->f_queue_count > 0);
1475 f->f_queue_count--;
1476 (void) pthread_mutex_unlock(&f->filed_mutex);
1477 assert(mp->refcnt > 0);
1480 * is it a shutdown message ?
1482 if (mp->flags & SHUTDOWN) {
1483 (void) pthread_mutex_lock(&mp->msg_mutex);
1484 refcnt = --mp->refcnt;
1485 (void) pthread_mutex_unlock(&mp->msg_mutex);
1486 if (refcnt == 0)
1487 free_msg(mp);
1488 break;
1492 * Is it a logsync message?
1494 if ((mp->flags & (FLUSHMSG | LOGSYNC)) ==
1495 (FLUSHMSG | LOGSYNC)) {
1496 if (f->f_type != F_FILE)
1497 goto out; /* nothing to do */
1498 (void) close(f->f_file);
1499 f->f_file = open64(f->f_un.f_fname,
1500 O_WRONLY|O_APPEND|O_NOCTTY);
1501 if (f->f_file < 0) {
1502 f->f_type = F_UNUSED;
1503 logerror(f->f_un.f_fname);
1504 f->f_stat.errs++;
1506 goto out;
1510 * If the message flags include both flush and sync,
1511 * then just sync the file out to disk if appropriate.
1513 if ((mp->flags & (FLUSHMSG | SYNC_FILE)) ==
1514 (FLUSHMSG | SYNC_FILE)) {
1515 if (f->f_type == F_FILE) {
1516 DPRINT2(5, "logit(%u): got FLUSH|SYNC "
1517 "for filed %p\n", f->f_thread,
1518 (void *)f);
1519 (void) fsync(f->f_file);
1521 goto out;
1525 * Otherwise if it's a standard flush message, write
1526 * out any saved messages to the file.
1528 if ((mp->flags & FLUSHMSG) && (f->f_prevcount > 0)) {
1529 set_flush_msg(f);
1530 writemsg(SAVED, f);
1531 goto out;
1534 (void) strlcpy(f->f_current.msg, mp->msg, MAXLINE+1);
1535 (void) strlcpy(f->f_current.host, mp->hlp->hl_hosts[0],
1536 SYS_NMLN);
1537 f->f_current.pri = mp->pri;
1538 f->f_current.flags = mp->flags;
1539 f->f_current.time = mp->ts;
1540 f->f_msgflag &= ~CURRENT_VALID;
1541 hlp = mp->hlp;
1543 prevofst = (f->f_prevmsg.flags & ADDDATE) ? 0 : 16;
1544 currofst = (f->f_current.flags & ADDDATE) ? 0 : 16;
1546 if (f->f_type == F_FORW) {
1548 * Should not forward MARK messages, as they are
1549 * not defined outside of the current system.
1552 if (mp->flags & MARK) {
1553 DPRINT1(1, "logit(%u): cannot forward "
1554 "Mark\n", f->f_thread);
1555 goto out;
1559 * can not forward message if we do
1560 * not have a host to forward to
1562 if (hlp == (host_list_t *)NULL)
1563 goto out;
1565 * a forwarding loop is created on machines
1566 * with multiple interfaces because the
1567 * network address of the sender is different
1568 * to the receiver even though it is the
1569 * same machine. Instead, if the
1570 * hostname the source and target are
1571 * the same the message if thrown away
1573 forwardingloop = 0;
1574 for (i = 0; i < hlp->hl_cnt; i++) {
1575 if (strcmp(hlp->hl_hosts[i],
1576 f->f_un.f_forw.f_hname) == 0) {
1577 DPRINT3(1, errmsg, f->f_thread,
1578 f->f_un.f_forw.f_hname,
1579 hlp->hl_hosts[i]);
1580 forwardingloop = 1;
1581 break;
1585 if (forwardingloop == 1) {
1586 f->f_stat.cantfwd++;
1587 goto out;
1591 f->f_msgflag |= CURRENT_VALID;
1593 /* check for dup message */
1594 if (f->f_type != F_FORW &&
1595 (f->f_msgflag & OLD_VALID) &&
1596 prevofst == currofst &&
1597 (strcmp(f->f_prevmsg.msg + prevofst,
1598 f->f_current.msg + currofst) == 0) &&
1599 (strcmp(f->f_prevmsg.host,
1600 f->f_current.host) == 0)) {
1601 /* a dup */
1602 DPRINT2(2, "logit(%u): msg is dup - %p\n",
1603 f->f_thread, (void *)mp);
1604 if (currofst == 16) {
1605 (void) strncpy(f->f_prevmsg.msg,
1606 f->f_current.msg, 15); /* update time */
1608 f->f_prevcount++;
1609 f->f_stat.dups++;
1610 f->f_stat.total++;
1611 f->f_msgflag &= ~CURRENT_VALID;
1612 } else {
1613 /* new: mark or prior dups exist */
1614 if (f->f_current.flags & MARK || f->f_prevcount > 0) {
1615 if (f->f_prevcount > 0 && f->f_type != F_FORW) {
1616 set_flush_msg(f);
1617 if (f->f_msgflag & OLD_VALID) {
1618 writemsg(SAVED, f);
1621 if (f->f_msgflag & CURRENT_VALID)
1622 writemsg(CURRENT, f);
1623 if (!(mp->flags & NOCOPY))
1624 copy_msg(f);
1625 if (f->f_current.flags & MARK) {
1626 DPRINT2(2, "logit(%u): msg is "
1627 "mark - %p)\n", f->f_thread,
1628 (void *)mp);
1629 f->f_msgflag &= ~OLD_VALID;
1630 } else {
1631 DPRINT2(2, "logit(%u): saving "
1632 "message - %p\n", f->f_thread,
1633 (void *)mp);
1635 f->f_stat.total++;
1636 } else { /* new message */
1637 DPRINT2(2, "logit(%u): msg is new "
1638 "- %p\n", f->f_thread, (void *)mp);
1639 writemsg(CURRENT, f);
1640 if (!(mp->flags & NOCOPY))
1641 copy_msg(f);
1642 f->f_stat.total++;
1646 * if message refcnt goes to zero after we decrement
1647 * it here, we are the last consumer of the message,
1648 * and we should free it. We need to hold the lock
1649 * between decrementing the count and checking for
1650 * zero so another thread doesn't beat us to it.
1652 out:
1653 (void) pthread_mutex_lock(&mp->msg_mutex);
1654 refcnt = --mp->refcnt;
1655 (void) pthread_mutex_unlock(&mp->msg_mutex);
1656 if (refcnt == 0)
1657 free_msg(mp);
1659 /* register our exit */
1662 * Pull out all pending messages, if they exist.
1665 (void) pthread_mutex_lock(&f->filed_mutex);
1667 while (f->f_queue_count > 0) {
1668 (void) dataq_dequeue(&f->f_queue, (void **)&mp, 0);
1669 DPRINT3(5, "logit(%u): logger dequeued msg %p from queue "
1670 "%p\n",
1671 f->f_thread, (void *)mp, (void *)&f->f_queue);
1672 (void) pthread_mutex_lock(&mp->msg_mutex);
1673 refcnt = --mp->refcnt;
1674 (void) pthread_mutex_unlock(&mp->msg_mutex);
1675 if (refcnt == 0)
1676 free_msg(mp);
1677 f->f_queue_count--;
1680 (void) pthread_mutex_unlock(&f->filed_mutex);
1682 if (f->f_type != F_USERS && f->f_type != F_WALL &&
1683 f->f_type != F_UNUSED) {
1684 if (f->f_type == F_FORW)
1685 (void) t_close(f->f_file);
1686 else
1687 (void) close(f->f_file);
1691 * Since f_type may have been changed before this point, we need
1692 * to test orig_type.
1694 if (f->f_orig_type == F_FORW) {
1695 free(f->f_un.f_forw.f_addr.buf);
1698 f->f_type = F_UNUSED;
1699 (void) pthread_mutex_lock(&cft);
1700 --conf_threads;
1701 (void) pthread_mutex_unlock(&cft);
1702 DPRINT1(5, "logit(%u): logging thread exited\n", f->f_thread);
1703 return (NULL);
1707 * change the previous message to a flush message, stating how
1708 * many repeats occurred since the last flush
1710 static void
1711 set_flush_msg(struct filed *f)
1713 char tbuf[10];
1714 int prevofst = (f->f_prevmsg.flags & ADDDATE) ? 0 : 16;
1716 if (f->f_prevcount == 1)
1717 (void) strncpy(tbuf, "time", sizeof (tbuf));
1718 else
1719 (void) strncpy(tbuf, "times", sizeof (tbuf));
1721 (void) snprintf(f->f_prevmsg.msg+prevofst,
1722 sizeof (f->f_prevmsg.msg) - prevofst,
1723 "last message repeated %d %s", f->f_prevcount, tbuf);
1724 f->f_prevcount = 0;
1725 f->f_msgflag |= OLD_VALID;
1730 * the actual writing of the message is broken into a separate function
1731 * because each file has a current and saved message associated with
1732 * it (for duplicate message detection). It is necessary to be able
1733 * to write either the saved message or the current message.
1735 static void
1736 writemsg(int selection, struct filed *f)
1738 char *cp, *p;
1739 int pri;
1740 int flags;
1741 int l;
1742 time_t ts;
1743 struct t_unitdata ud;
1744 char *eomp, *eomp2, *from, *text, *msg;
1745 char line[MAXLINE*2];
1746 char head[MAXLINE+1];
1747 char tmpbuf[MAXLINE+1];
1748 char cbuf[30];
1749 char *filtered;
1750 char *msgid_start, *msgid_end;
1751 pthread_t mythreadno;
1752 size_t hlen, filter_len;
1754 if (Debug) {
1755 mythreadno = pthread_self();
1758 switch (selection) {
1759 default:
1760 case CURRENT: /* print current message */
1761 msg = f->f_current.msg;
1762 from = f->f_current.host;
1763 pri = f->f_current.pri;
1764 flags = f->f_current.flags;
1765 ts = f->f_current.time;
1766 f->f_msgflag &= ~CURRENT_VALID;
1767 break;
1768 case SAVED: /* print saved message */
1769 msg = f->f_prevmsg.msg;
1770 from = f->f_prevmsg.host;
1771 pri = f->f_prevmsg.pri;
1772 flags = f->f_prevmsg.flags;
1773 ts = f->f_prevmsg.time;
1774 f->f_msgflag &= ~OLD_VALID;
1775 break;
1778 if (msg[0] == '\0')
1779 return;
1781 cp = line;
1783 if (flags & ADDDATE)
1784 (void) strncpy(cp, ctime_r(&ts, cbuf) + 4, 15);
1785 else
1786 (void) strncpy(cp, msg, 15);
1788 line[15] = '\0';
1789 (void) strcat(cp, " ");
1790 (void) strcat(cp, from);
1791 (void) strcat(cp, " ");
1792 text = cp + strlen(cp);
1794 if (flags & ADDDATE)
1795 (void) strcat(cp, msg);
1796 else
1797 (void) strcat(cp, msg+16);
1798 DPRINT2(5, "writemsg(%u): text = \"%s\"\n", mythreadno, text);
1800 errno = 0;
1801 t_errno = 0;
1802 switch (f->f_type) {
1803 case F_UNUSED:
1804 DPRINT1(1, "writemsg(%u): UNUSED\n", mythreadno);
1805 break;
1806 case F_FORW:
1807 DPRINT4(1, "writemsg(%u): Logging msg '%s' to %s %s\n",
1808 mythreadno, msg, TypeNames[f->f_type],
1809 f->f_un.f_forw.f_hname);
1811 hlen = snprintf(head, sizeof (head),
1812 "<%d>%.15s ", pri, cp);
1814 DPRINT2(5, "writemsg(%u): head = \"%s\"\n", mythreadno, head);
1815 DPRINT2(5, "writemsg(%u): hlen = %d\n", mythreadno, hlen);
1817 l = strlen(text);
1818 p = text;
1820 DPRINT2(5, "writemsg(%u): text = \"%s\"\n", mythreadno, text);
1821 DPRINT2(5, "writemsg(%u): strlen(text) = %d\n", mythreadno, l);
1823 (void) strncpy(tmpbuf, head, hlen);
1825 while (l > 0) {
1826 size_t len;
1828 len = copy_frwd(tmpbuf + hlen, sizeof (tmpbuf) - hlen,
1829 p, l);
1831 DPRINT2(5, "writemsg(%u): tmpbuf = \"%s\"\n",
1832 mythreadno, tmpbuf);
1833 DPRINT2(5, "writemsg(%u): len = %d\n", mythreadno,
1834 len);
1835 DPRINT2(5, "writemsg(%u): strlen(tmpbuf) = %d\n",
1836 mythreadno, strlen(tmpbuf));
1838 ud.opt.buf = NULL;
1839 ud.opt.len = 0;
1840 ud.udata.buf = tmpbuf;
1841 ud.udata.len = len + hlen;
1842 ud.addr.maxlen = f->f_un.f_forw.f_addr.maxlen;
1843 ud.addr.buf = f->f_un.f_forw.f_addr.buf;
1844 ud.addr.len = f->f_un.f_forw.f_addr.len;
1845 if (t_sndudata(f->f_file, &ud) < 0) {
1846 if ((hup_state & HUP_INPROGRESS) &&
1847 f->f_type == F_UNUSED) {
1848 break;
1850 (void) t_close(f->f_file);
1851 f->f_type = F_UNUSED;
1852 logerror("t_sndudata");
1855 * Since it has already failed, it's not worth
1856 * continuing output from the middle of
1857 * message string.
1859 break;
1861 p += len;
1862 l -= len;
1864 break;
1865 case F_CONSOLE:
1866 case F_TTY:
1867 case F_FILE:
1868 case F_USERS:
1869 case F_WALL:
1870 DPRINT4(1, "writemsg(%u): Logging msg '%s' to %s %s\n",
1871 mythreadno, msg, TypeNames[f->f_type],
1872 ((f->f_type == F_USERS) || (f->f_type == F_WALL)) ?
1873 "" : f->f_un.f_fname);
1875 * filter the string in preparation for writing it
1876 * save the original for possible forwarding.
1877 * In case every byte in cp is a control character,
1878 * allocates large enough buffer for filtered.
1881 filter_len = strlen(cp) * 4 + 1;
1882 filtered = (char *)malloc(filter_len);
1883 if (!filtered) {
1884 MALLOC_FAIL("dropping message");
1885 /* seems we can just return */
1886 return;
1888 DPRINT3(5, "writemsg(%u): "
1889 "filtered allocated (%p: %d bytes)\n",
1890 mythreadno, (void *)filtered, filter_len);
1891 /* -3 : we may add "\r\n" to ecomp(filtered) later */
1892 filter_string(cp, filtered, filter_len - 3);
1894 DPRINT2(5, "writemsg(%u): strlen(filtered) = %d\n",
1895 mythreadno, strlen(filtered));
1897 * If we're writing to the console, strip out the message ID
1898 * to reduce visual clutter.
1900 if ((msgid_start = strstr(filtered, "[ID ")) != NULL &&
1901 (msgid_end = strstr(msgid_start, "] ")) != NULL &&
1902 f->f_type == F_CONSOLE)
1903 (void) strcpy(msgid_start, msgid_end + 2);
1905 eomp = filtered + strlen(filtered);
1907 if ((f->f_type == F_USERS) || (f->f_type == F_WALL)) {
1908 /* CSTYLED */
1909 (void) strcat(eomp, "\r\n"); /*lint !e669*/
1911 * Since wallmsg messes with utmpx we need
1912 * to guarantee single threadedness...
1914 (void) pthread_mutex_lock(&wmp);
1915 wallmsg(f, from, filtered);
1916 (void) pthread_mutex_unlock(&wmp);
1919 * The contents of filtered have been copied
1920 * out to the struct walldev. We should free it here.
1923 free(filtered);
1925 /* exiting the switch */
1926 break;
1927 } else if (f->f_type != F_FILE) {
1928 /* CSTYLED */
1929 (void) strncpy(eomp, "\r\n", 3); /*lint !e669*/
1930 } else {
1931 if ((eomp2 = strchr(filtered, '\r')) != NULL) {
1932 (void) strncpy(eomp2, "\n", 2);
1933 } else {
1934 /* CSTYLED */
1935 (void) strncpy(eomp, "\n", 2); /*lint !e669*/
1938 if (write(f->f_file, filtered, strlen(filtered)) < 0) {
1939 int e = errno;
1941 if ((hup_state & HUP_INPROGRESS) &&
1942 f->f_type == F_UNUSED) {
1943 free(filtered);
1944 break;
1946 (void) close(f->f_file);
1948 * Check for EBADF on TTY's due
1949 * to vhangup() XXX
1951 if (e == EBADF && f->f_type != F_FILE) {
1952 f->f_file = open(f->f_un.f_fname,
1953 O_WRONLY|O_APPEND|O_NOCTTY);
1954 if (f->f_file < 0) {
1955 f->f_type = F_UNUSED;
1956 logerror(f->f_un.f_fname);
1957 f->f_stat.errs++;
1959 untty();
1960 } else {
1961 f->f_type = F_UNUSED;
1962 f->f_stat.errs++;
1963 errno = e;
1964 logerror(f->f_un.f_fname);
1966 } else if (flags & SYNC_FILE)
1967 if (((pri & LOG_FACMASK) >> 3) == LOG_KERN)
1968 (void) fsync(f->f_file);
1970 DPRINT2(5, "writemsg(%u): freeing filtered (%p)\n",
1971 mythreadno, (void *)filtered);
1973 free(filtered);
1974 break;
1979 * WALLMSG -- Write a message to the world at large
1981 * Write the specified message to either the entire
1982 * world, or a list of approved users.
1984 static void
1985 wallmsg(struct filed *f, char *from, char *msg)
1987 int i;
1988 size_t len, clen;
1989 char *buf = NULL;
1990 struct utmpx *utxp;
1991 time_t now;
1992 char line[512], dev[100];
1993 char cp[MAXLINE+1];
1994 struct stat statbuf;
1995 walldev_t *w;
1996 char cbuf[30];
1997 pthread_t mythreadno;
1999 if (Debug) {
2000 mythreadno = pthread_self();
2003 if (access(UTMPX_FILE, R_OK) != 0 || stat(UTMPX_FILE, &statbuf) != 0) {
2004 logerror(UTMPX_FILE);
2005 return;
2006 } else if (statbuf.st_uid != 0 || (statbuf.st_mode & 07777) != 0644) {
2007 (void) snprintf(line, sizeof (line), "%s %s", UTMPX_FILE,
2008 "not owned by root or not mode 644.\n"
2009 "This file must be owned by root "
2010 "and not writable by\n"
2011 "anyone other than root. This alert is being "
2012 "dropped because of\n"
2013 "this problem.");
2014 logerror(line);
2015 return;
2018 if (f->f_type == F_WALL) {
2019 (void) time(&now);
2020 len = snprintf(line, sizeof (line),
2021 "\r\n\7Message from syslogd@%s "
2022 "at %.24s ...\r\n", from, ctime_r(&now, cbuf));
2023 len += strlen(msg + 16);
2024 buf = (char *)malloc(len + 1);
2025 if (!buf) {
2026 MALLOC_FAIL("dropping message");
2027 return;
2029 DPRINT3(5, "wallmsg(%u): buf allocated (%p: %d bytes)\n",
2030 mythreadno, (void *)buf, len + 1);
2031 (void) strcpy(buf, line);
2032 (void) strcat(buf, msg + 16);
2033 clen = copy_frwd(cp, sizeof (cp), buf, len);
2034 DPRINT2(5, "wallmsg(%u): clen = %d\n",
2035 mythreadno, clen);
2036 DPRINT2(5, "wallmsg(%u): freeing buf (%p)\n",
2037 mythreadno, (void *)buf);
2038 free(buf);
2039 } else {
2040 clen = copy_frwd(cp, sizeof (cp), msg, strlen(msg));
2041 DPRINT2(5, "wallmsg(%u): clen = %d\n",
2042 mythreadno, clen);
2044 /* scan the user login file */
2045 setutxent();
2046 while ((utxp = getutxent()) != NULL) {
2047 /* is this slot used? */
2048 if (utxp->ut_name[0] == '\0' ||
2049 utxp->ut_line[0] == '\0' ||
2050 utxp->ut_type != USER_PROCESS)
2051 continue;
2052 /* should we send the message to this user? */
2053 if (f->f_type == F_USERS) {
2054 for (i = 0; i < MAXUNAMES; i++) {
2055 if (!f->f_un.f_uname[i][0]) {
2056 i = MAXUNAMES;
2057 break;
2059 if (strncmp(f->f_un.f_uname[i],
2060 utxp->ut_name, UNAMESZ) == 0)
2061 break;
2063 if (i >= MAXUNAMES)
2064 continue;
2067 /* compute the device name */
2068 if (utxp->ut_line[0] == '/') {
2069 (void) strncpy(dev, utxp->ut_line, UDEVSZ);
2070 } else {
2071 (void) strcpy(dev, "/dev/");
2072 (void) strncat(dev, utxp->ut_line, UDEVSZ);
2074 DPRINT2(1, "wallmsg(%u): write to '%s'\n", mythreadno,
2075 dev);
2077 if ((w = malloc(sizeof (walldev_t))) != NULL) {
2078 int rc;
2079 (void) pthread_attr_init(&w->thread_attr);
2080 (void) pthread_attr_setdetachstate(&w->thread_attr,
2081 PTHREAD_CREATE_DETACHED);
2082 (void) strncpy(w->dev, dev, PATH_MAX);
2083 (void) strncpy(w->msg, cp, MAXLINE+1);
2084 (void) strncpy(w->ut_name, utxp->ut_name,
2085 sizeof (w->ut_name));
2087 if ((rc = pthread_create(&w->thread, &w->thread_attr,
2088 writetodev, (void *) w)) != 0) {
2089 DPRINT2(5, "wallmsg(%u): wallmsg thread "
2090 "create failed rc = %d\n",
2091 mythreadno, rc);
2092 free(w);
2093 break;
2095 } else {
2096 MALLOC_FAIL("dropping message to user");
2099 /* close the user login file */
2100 endutxent();
2104 * Each time we need to write to a tty device (a potentially expensive
2105 * or long-running operation) this routine gets called as a new
2106 * detached, unbound thread. This allows writes to many devices
2107 * to proceed nearly in parallel, without having to resort to
2108 * asynchronous I/O or forking.
2110 static void *
2111 writetodev(void *ap)
2113 walldev_t *w = ap;
2114 int ttyf;
2115 int len;
2116 struct stat statb;
2117 struct passwd pw, *pwp;
2118 char pwbuf[MAXLINE];
2119 pthread_t mythreadno;
2121 if (Debug) {
2122 mythreadno = pthread_self();
2125 DPRINT1(1, "writetodev(%u): Device writer thread started\n",
2126 mythreadno);
2128 len = strlen(w->msg);
2130 ttyf = open(w->dev, O_WRONLY|O_NOCTTY|O_NDELAY);
2131 if (ttyf >= 0) {
2132 if (fstat(ttyf, &statb) != 0) {
2133 DPRINT2(1, "writetodev(%u): Can't stat '%s'\n",
2134 mythreadno, w->dev);
2135 errno = 0;
2136 logerror("Can't stat '%s'", w->dev);
2137 } else if (!(statb.st_mode & S_IWRITE)) {
2138 DPRINT2(1, "writetodev(%u): Can't write to "
2139 "'%s'\n", mythreadno, w->dev);
2140 } else if (!isatty(ttyf)) {
2141 DPRINT2(1, "writetodev(%u): '%s' not a tty\n",
2142 mythreadno, w->dev);
2144 * We might hit dtremote here. Don't generate
2145 * error message.
2147 } else if (getpwuid_r(statb.st_uid, &pw, pwbuf,
2148 sizeof (pwbuf), &pwp) != 0) {
2149 DPRINT2(1, "writetodev(%u): Can't determine owner "
2150 "of '%s'\n", mythreadno, w->dev);
2151 errno = 0;
2152 logerror("Can't determine owner of '%s'", w->dev);
2153 } else if (strncmp(pw.pw_name, w->ut_name, UNAMESZ) != 0) {
2154 DPRINT2(1, "writetodev(%u): Bad terminal owner '%s'"
2155 "\n", mythreadno, w->dev);
2156 errno = 0;
2157 logerror("%s %s owns '%s' %s %.*s",
2158 "Bad terminal owner;", pw.pw_name, w->dev,
2159 "but utmpx says", UNAMESZ, w->ut_name);
2160 } else if (write(ttyf, w->msg, len) != len) {
2161 DPRINT2(1, "writetodev(%u): Write failed to "
2162 "'%s'\n", mythreadno, w->dev);
2163 errno = 0;
2164 logerror("Write failed to '%s'", w->dev);
2167 DPRINT2(1, "writetodev(%u): write to '%s' succeeded\n",
2168 mythreadno, w->dev);
2170 (void) close(ttyf);
2171 } else {
2172 DPRINT2(1, "writetodev(%u): Can't open '%s'\n",
2173 mythreadno, w->dev);
2176 (void) pthread_attr_destroy(&w->thread_attr);
2177 free(w);
2179 DPRINT1(1, "writetodev(%u): Device writer thread exiting\n",
2180 mythreadno);
2182 pthread_exit(0);
2183 return (NULL);
2184 /*NOTREACHED*/
2188 * Return a printable representation of a host address. If unable to
2189 * look up hostname, format the numeric address for display instead.
2191 * First calls hnc_lookup to see if there is valid cache entry for
2192 * given network address. If it failed, cvthname looks up hostname,
2193 * and push the results into the hostname cache.
2195 static host_list_t *
2196 cvthname(struct netbuf *nbp, struct netconfig *ncp, char *failsafe_addr)
2198 int i;
2199 host_list_t *h;
2200 struct nd_hostservlist *hsp;
2201 struct nd_hostserv *hspp;
2202 pthread_t mythreadno;
2203 int hindex;
2204 char *uap;
2206 if (Debug) {
2207 mythreadno = pthread_self();
2210 if (Debug)
2211 uap = taddr2uaddr(ncp, nbp);
2213 DPRINT2(2, "cvthname(%u): looking up hostname for %s\n",
2214 mythreadno, uap ? uap : "<unknown>");
2216 if ((h = hnc_lookup(nbp, ncp, &hindex)) != NULL) {
2217 DPRINT4(2, "cvthname(%u): Cache found %p for %s (%s)\n",
2218 mythreadno, (void *)h, uap ? uap : "<unknown>",
2219 h->hl_hosts[0]);
2220 return (h);
2222 DPRINT2(2, "cvthname(%u): No cache found for %s\n",
2223 mythreadno, uap ? uap : "<unknown>");
2225 if (Debug)
2226 free(uap);
2228 if (ncp->nc_semantics != NC_TPI_CLTS) {
2229 return (NULL);
2232 /* memory allocation failure here is fatal */
2233 if ((h = malloc(sizeof (host_list_t))) == NULL) {
2234 MALLOC_FAIL("host name conversion");
2235 return (NULL);
2238 if (netdir_getbyaddr(ncp, &hsp, nbp) == 0) {
2239 if (hsp->h_cnt <= 0) {
2240 out: netdir_free((void *)hsp, ND_HOSTSERVLIST);
2241 free(h);
2242 return (NULL);
2245 hspp = hsp->h_hostservs;
2246 h->hl_cnt = hsp->h_cnt;
2247 h->hl_hosts = (char **)malloc(sizeof (char *) * (h->hl_cnt));
2248 if (h->hl_hosts == NULL) {
2249 MALLOC_FAIL("host name conversion");
2250 goto out;
2253 DPRINT2(2, "cvthname(%u): Found %d hostnames\n",
2254 mythreadno, h->hl_cnt);
2255 for (i = 0; i < h->hl_cnt; i++) {
2256 h->hl_hosts[i] = (char *)
2257 malloc(sizeof (char) * (strlen(hspp->h_host) + 1));
2258 if (h->hl_hosts[i] == NULL) {
2259 int j;
2260 for (j = 0; j < i; j++) {
2261 free(h->hl_hosts[j]);
2263 free(h->hl_hosts);
2264 MALLOC_FAIL("host name conversion");
2265 goto out;
2267 (void) strcpy(h->hl_hosts[i], hspp->h_host);
2268 hspp++;
2270 netdir_free((void *)hsp, ND_HOSTSERVLIST);
2271 } else { /* unknown address */
2272 h->hl_cnt = 1;
2273 h->hl_hosts = (char **)malloc(sizeof (char *));
2274 if (h->hl_hosts == NULL) {
2275 free(h);
2276 MALLOC_FAIL("host name conversion");
2277 return (NULL);
2279 h->hl_hosts[0] = (char *)malloc(strlen(failsafe_addr) + 3);
2280 if (h->hl_hosts[0] == NULL) {
2281 free(h->hl_hosts);
2282 free(h);
2283 MALLOC_FAIL("host name conversion");
2284 return (NULL);
2286 /*LINTED*/
2287 (void) sprintf(h->hl_hosts[0], "[%s]", failsafe_addr);
2288 DPRINT2(1, "cvthname(%u): Hostname lookup failed "
2289 "- using address %s instead\n",
2290 mythreadno, h->hl_hosts[0]);
2293 h->hl_refcnt = 1;
2294 if (pthread_mutex_init(&h->hl_mutex, NULL) != 0) {
2295 logerror("pthread_mutex_init failed");
2296 /* This host_list won't be shared by the cache. */
2297 return (h);
2299 hnc_register(nbp, ncp, h, hindex);
2300 DPRINT3(2, "cvthname(%u): returning %p for %s\n",
2301 mythreadno, (void *)h, h->hl_hosts[0]);
2302 return (h);
2306 * Print syslogd errors some place. Need to be careful here, because
2307 * this routine is called at times when we're not initialized and
2308 * ready to log messages...in this case, fall back to using the console.
2310 void
2311 logerror(const char *type, ...)
2313 char buf[MAXLINE+1];
2314 pthread_t mythreadno;
2315 int flag;
2316 va_list ap;
2318 if (Debug) {
2319 mythreadno = pthread_self();
2322 va_start(ap, type);
2323 logerror_format(type, buf, ap);
2324 va_end(ap);
2325 DPRINT2(1, "logerror(%u): %s\n", mythreadno, buf);
2327 (void) pthread_mutex_lock(&logerror_lock);
2328 if (!interrorlog) {
2329 flag = 0;
2330 if (logerror_to_console(1, buf) == 0) {
2331 /* has written to the console */
2332 flag = IGN_CONS;
2334 (void) logmymsg(LOG_SYSLOG|LOG_ERR, buf, ADDDATE|flag, 1);
2335 } else {
2336 if (logmymsg(LOG_SYSLOG|LOG_ERR, buf, ADDDATE, 0) == -1) {
2337 (void) logerror_to_console(1, buf);
2340 (void) pthread_mutex_unlock(&logerror_lock);
2342 errno = 0;
2343 t_errno = 0;
2346 static void
2347 logerror_format(const char *type, char *buf, va_list ap)
2349 char tmpbuf[MAXLINE + 1];
2350 pthread_t mythreadno;
2352 if (Debug) {
2353 mythreadno = pthread_self();
2356 (void) vsnprintf(tmpbuf, MAXLINE, type, ap);
2358 if (t_errno == 0 || t_errno == TSYSERR) {
2359 char *errstr;
2361 if (errno == 0) {
2362 (void) snprintf(buf, MAXLINE, "syslogd: %.*s",
2363 MAXLINE, tmpbuf);
2364 } else if ((errstr = strerror(errno)) == NULL) {
2365 (void) snprintf(buf, MAXLINE, "syslogd: %s: error"
2366 " %d", tmpbuf, errno);
2367 } else {
2368 (void) snprintf(buf, MAXLINE, "syslogd: %s: %s",
2369 tmpbuf, errstr);
2371 } else {
2372 if (t_errno > t_nerr) {
2373 (void) snprintf(buf, MAXLINE, "syslogd: %s:"
2374 " t_error %d", tmpbuf, t_errno);
2375 } else {
2376 (void) snprintf(buf, MAXLINE, "syslogd: %s: %s",
2377 tmpbuf, t_errlist[t_errno]);
2381 DPRINT2(5, "logerror_format(%u): out %s\n", mythreadno, buf);
2384 static int
2385 logerror_to_console(int nonblock, const char *buf)
2387 int cfd, modes;
2388 pthread_t mythreadno;
2389 int ret = 0, len;
2390 char tmpbuf[MAXLINE + 1];
2392 if (Debug) {
2393 mythreadno = pthread_self();
2396 DPRINT2(1, "logerror_to_console(%u): %s\n", mythreadno, buf);
2399 * must use open here instead of fopen, because
2400 * we need the O_NOCTTY behavior - otherwise we
2401 * could hang the console at boot time
2404 modes = (nonblock) ?
2405 O_WRONLY|O_APPEND|O_NOCTTY|O_NONBLOCK :
2406 O_WRONLY|O_APPEND|O_NOCTTY;
2408 if (((cfd = open(sysmsg, modes)) >= 0) ||
2409 ((cfd = open(ctty, modes)) >= 0)) {
2410 (void) snprintf(tmpbuf, MAXLINE, "%s\n", buf);
2411 len = strlen(tmpbuf);
2412 if (write(cfd, tmpbuf, len) != len) {
2413 ret = 1;
2415 (void) close(cfd);
2416 } else {
2417 ret = 1;
2419 /* punt */
2420 DPRINT1(1, "logerror_console(%u): can't open console\n",
2421 mythreadno);
2423 return (ret);
2427 * copy current message to saved message in filed structure.
2429 static void
2430 copy_msg(struct filed *f)
2432 (void) strlcpy(f->f_prevmsg.msg, f->f_current.msg, MAXLINE+1);
2433 (void) strlcpy(f->f_prevmsg.host, f->f_current.host, SYS_NMLN);
2434 f->f_prevmsg.pri = f->f_current.pri;
2435 f->f_prevmsg.flags = f->f_current.flags;
2436 f->f_prevmsg.time = f->f_current.time;
2437 f->f_msgflag |= OLD_VALID;
2442 * function to free a host_list_t struct that was allocated
2443 * out of cvthname(). There is a special case where we don't
2444 * free the hostname list in LocalHostName, because that's
2445 * our own addresses, and we just want to have to look it
2446 * up once and save it. Also don't free it if it's
2447 * NullHostName, because that's a special one we use if
2448 * name service lookup fails.
2450 * By having hostname cache, now host_list_t will be shared
2451 * by messages and hostname cache. hl_refcnt is used for
2452 * the purpose.
2454 static void
2455 freehl(host_list_t *h)
2457 int i, refcnt;
2458 pthread_t mythreadno;
2460 if (Debug) {
2461 mythreadno = pthread_self();
2464 DPRINT2(2, "freehl(%u): releasing %p\n", mythreadno, (void *)h);
2466 if (h == NULL || h == &LocalHostName || h == &NullHostName) {
2467 return;
2470 (void) pthread_mutex_lock(&h->hl_mutex);
2471 refcnt = --h->hl_refcnt;
2472 (void) pthread_mutex_unlock(&h->hl_mutex);
2474 if (refcnt != 0) {
2475 DPRINT3(5, "freehl(%u): %p has reference %d\n",
2476 mythreadno, (void *)h, refcnt);
2477 return;
2480 (void) pthread_mutex_destroy(&h->hl_mutex);
2482 DPRINT2(5, "freehl(%u): freeing %p\n", mythreadno, (void *)h);
2484 for (i = 0; i < h->hl_cnt; i++) {
2485 free(h->hl_hosts[i]);
2488 free(h->hl_hosts);
2489 free(h);
2493 * Create the door file and the pid file in /var/run. If the filesystem
2494 * containing /etc is writable, create symlinks /etc/.syslog_door and
2495 * /etc/syslog.pid to them. On systems that do not support /var/run, create
2496 * /etc/.syslog_door and /etc/syslog.pid directly.
2498 * Note: it is not considered fatal to fail to create the pid file or its
2499 * symlink. Attempts to use them in the usual way will fail, of course, but
2500 * syslogd will function nicely without it (not so for the door file).
2503 static void
2504 open_door(void)
2506 struct stat buf;
2507 door_info_t info;
2508 char line[MAXLINE+1];
2509 pthread_t mythreadno;
2510 int err;
2512 if (Debug) {
2513 mythreadno = pthread_self();
2517 * first see if another syslogd is running by trying
2518 * a door call - if it succeeds, there is already
2519 * a syslogd process active
2522 if (!DoorCreated) {
2523 int door;
2525 if ((door = open(DoorFileName, O_RDONLY)) >= 0) {
2526 DPRINT2(5, "open_door(%u): %s opened "
2527 "successfully\n", mythreadno, DoorFileName);
2529 if (door_info(door, &info) >= 0) {
2530 DPRINT2(5, "open_door(%u): "
2531 "door_info:info.di_target = %ld\n",
2532 mythreadno, info.di_target);
2534 if (info.di_target > 0) {
2535 (void) sprintf(line, "syslogd pid %ld"
2536 " already running. Cannot "
2537 "start another syslogd pid %ld",
2538 info.di_target, getpid());
2539 DPRINT2(5, "open_door(%u): error: "
2540 "%s\n", mythreadno, line);
2541 errno = 0;
2542 logerror(line);
2543 exit(1);
2547 (void) close(door);
2548 } else {
2549 if (lstat(DoorFileName, &buf) < 0) {
2550 err = errno;
2552 DPRINT3(5, "open_door(%u): lstat() of %s "
2553 "failed, errno=%d\n",
2554 mythreadno, DoorFileName, err);
2556 if ((door = creat(DoorFileName, 0644)) < 0) {
2557 err = errno;
2558 (void) snprintf(line, sizeof (line),
2559 "creat() of %s failed - fatal",
2560 DoorFileName);
2561 DPRINT3(1, "open_door(%u): error: %s, "
2562 "errno=%d\n", mythreadno, line,
2563 err);
2564 errno = err;
2565 logerror(line);
2566 delete_doorfiles();
2567 exit(1);
2570 (void) fchmod(door,
2571 S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
2573 DPRINT2(5, "open_door(%u): creat() of %s "
2574 "succeeded\n", mythreadno,
2575 DoorFileName);
2577 (void) close(door);
2581 if (strcmp(DoorFileName, DOORFILE) == 0) {
2582 if (lstat(OLD_DOORFILE, &buf) == 0) {
2583 DPRINT2(5, "open_door(%u): lstat() of %s "
2584 "succeeded\n", mythreadno,
2585 OLD_DOORFILE);
2587 if (S_ISDIR(buf.st_mode)) {
2588 (void) snprintf(line, sizeof (line),
2589 "%s is a directory - fatal",
2590 OLD_DOORFILE);
2591 DPRINT2(1, "open_door(%u): error: "
2592 "%s\n", mythreadno, line);
2593 errno = 0;
2594 logerror(line);
2595 delete_doorfiles();
2596 exit(1);
2599 DPRINT2(5, "open_door(%u): %s is not a "
2600 "directory\n",
2601 mythreadno, OLD_DOORFILE);
2603 if (unlink(OLD_DOORFILE) < 0) {
2604 err = errno;
2605 (void) snprintf(line, sizeof (line),
2606 "unlink() of %s failed",
2607 OLD_DOORFILE);
2608 DPRINT2(5, "open_door(%u): %s\n",
2609 mythreadno, line);
2611 if (err != EROFS) {
2612 DPRINT3(1, "open_door(%u): "
2613 "error: %s, "
2614 "errno=%d\n",
2615 mythreadno, line, err);
2616 (void) strcat(line, " - fatal");
2617 errno = err;
2618 logerror(line);
2619 delete_doorfiles();
2620 exit(1);
2623 DPRINT1(5, "open_door(%u): unlink "
2624 "failure OK on RO file "
2625 "system\n", mythreadno);
2627 } else {
2628 DPRINT2(5, "open_door(%u): file %s doesn't "
2629 "exist\n", mythreadno, OLD_DOORFILE);
2632 if (symlink(RELATIVE_DOORFILE, OLD_DOORFILE) < 0) {
2633 err = errno;
2634 (void) snprintf(line, sizeof (line),
2635 "symlink %s -> %s failed", OLD_DOORFILE,
2636 RELATIVE_DOORFILE);
2637 DPRINT2(5, "open_door(%u): %s\n", mythreadno,
2638 line);
2640 if (err != EROFS) {
2641 DPRINT3(1, "open_door(%u): error: %s, "
2642 "errno=%d\n", mythreadno, line,
2643 err);
2644 errno = err;
2645 (void) strcat(line, " - fatal");
2646 logerror(line);
2647 delete_doorfiles();
2648 exit(1);
2651 DPRINT1(5, "open_door(%u): symlink failure OK "
2652 "on RO file system\n", mythreadno);
2653 } else {
2654 DPRINT3(5, "open_door(%u): symlink %s -> %s "
2655 "succeeded\n", mythreadno,
2656 OLD_DOORFILE, RELATIVE_DOORFILE);
2660 if ((DoorFd = door_create(server, 0,
2661 DOOR_REFUSE_DESC | DOOR_NO_CANCEL)) < 0) {
2662 err = errno;
2663 (void) sprintf(line, "door_create() failed - fatal");
2664 DPRINT3(1, "open_door(%u): error: %s, errno=%d\n",
2665 mythreadno, line, err);
2666 errno = err;
2667 logerror(line);
2668 delete_doorfiles();
2669 exit(1);
2671 (void) door_setparam(DoorFd, DOOR_PARAM_DATA_MAX, 0);
2672 DPRINT2(5, "open_door(%u): door_create() succeeded, "
2673 "DoorFd=%d\n", mythreadno, DoorFd);
2675 DoorCreated = 1;
2678 (void) fdetach(DoorFileName); /* just in case... */
2680 (void) door_server_create(door_server_pool);
2682 if (fattach(DoorFd, DoorFileName) < 0) {
2683 err = errno;
2684 (void) snprintf(line, sizeof (line), "fattach() of fd"
2685 " %d to %s failed - fatal", DoorFd, DoorFileName);
2686 DPRINT3(1, "open_door(%u): error: %s, errno=%d\n", mythreadno,
2687 line, err);
2688 errno = err;
2689 logerror(line);
2690 delete_doorfiles();
2691 exit(1);
2694 DPRINT2(5, "open_door(%u): attached server() to %s\n", mythreadno,
2695 DoorFileName);
2698 * create pidfile anyway, so those using it to control
2699 * syslogd (with kill `cat /etc/syslog.pid` perhaps)
2700 * don't get broken.
2703 if (!PidfileCreated) {
2704 int pidfd;
2706 PidfileCreated = 1;
2708 if ((pidfd = open(PidFileName, O_RDWR|O_CREAT|O_TRUNC, 0644))
2709 < 0) {
2710 err = errno;
2711 (void) snprintf(line, sizeof (line),
2712 "open() of %s failed", PidFileName);
2713 DPRINT3(1, "open_door(%u): warning: %s, errno=%d\n",
2714 mythreadno, line, err);
2715 errno = err;
2716 logerror(line);
2717 return;
2720 (void) fchmod(pidfd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
2721 (void) sprintf(line, "%ld\n", getpid());
2723 if (write(pidfd, line, strlen(line)) < 0) {
2724 err = errno;
2725 (void) snprintf(line, sizeof (line),
2726 "write to %s on fd %d failed", PidFileName, pidfd);
2727 DPRINT3(1, "open_door(%u): warning: %s, errno=%d\n",
2728 mythreadno, line, err);
2729 errno = err;
2730 logerror(line);
2731 return;
2734 (void) close(pidfd);
2736 DPRINT2(5, "open_door(%u): %s created\n",
2737 mythreadno, PidFileName);
2739 if (strcmp(PidFileName, PIDFILE) == 0) {
2740 if (lstat(OLD_PIDFILE, &buf) == 0) {
2741 DPRINT2(5, "open_door(%u): lstat() of %s "
2742 "succeded\n", mythreadno, OLD_PIDFILE);
2744 if (S_ISDIR(buf.st_mode)) {
2745 (void) snprintf(line, sizeof (line),
2746 "file %s is a directory",
2747 OLD_PIDFILE);
2748 DPRINT2(1, "open_door(%u): warning: "
2749 "%s\n", mythreadno, line);
2750 errno = 0;
2751 logerror(line);
2752 return;
2755 if (unlink(OLD_PIDFILE) < 0) {
2756 err = errno;
2757 (void) snprintf(line, sizeof (line),
2758 "unlink() of %s failed",
2759 OLD_PIDFILE);
2760 DPRINT2(5, "open_door(%u): %s\n",
2761 mythreadno, line);
2763 if (err != EROFS) {
2764 DPRINT3(1, "open_door (%u): "
2765 "warning: %s, "
2766 "errno=%d\n",
2767 mythreadno, line, err);
2768 errno = err;
2769 logerror(line);
2770 return;
2773 DPRINT1(5, "open_door(%u): unlink "
2774 "failure OK on RO file "
2775 "system\n", mythreadno);
2777 } else {
2778 DPRINT2(5, "open_door(%u): file %s doesn't "
2779 "exist\n", mythreadno, OLD_PIDFILE);
2782 if (symlink(RELATIVE_PIDFILE, OLD_PIDFILE) < 0) {
2783 err = errno;
2784 (void) snprintf(line, sizeof (line),
2785 "symlink %s -> %s failed", OLD_PIDFILE,
2786 RELATIVE_PIDFILE);
2787 DPRINT2(5, "open_door(%u): %s\n", mythreadno,
2788 line);
2790 if (err != EROFS) {
2791 DPRINT3(1, "open_door(%u): warning: "
2792 "%s, errno=%d\n", mythreadno,
2793 line, err);
2794 errno = err;
2795 logerror(line);
2796 return;
2799 DPRINT1(5, "open_door(%u): symlink failure OK "
2800 "on RO file system\n", mythreadno);
2801 return;
2804 DPRINT3(5, "open_door(%u): symlink %s -> %s "
2805 "succeeded\n", mythreadno, OLD_PIDFILE,
2806 RELATIVE_PIDFILE);
2812 * the 'server' function that we export via the door. It does
2813 * nothing but return.
2815 /*ARGSUSED*/
2816 static void
2817 server(void *cookie, char *argp, size_t arg_size,
2818 door_desc_t *dp, uint_t n)
2820 (void) door_return(NULL, 0, NULL, 0);
2821 /* NOTREACHED */
2824 /*ARGSUSED*/
2825 static void *
2826 create_door_thr(void *arg)
2828 (void) pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
2829 (void) door_return(NULL, 0, NULL, 0);
2832 * If there is an error in door_return(), it will return here and
2833 * the thread will exit. Hence we need to decrement door_server_cnt.
2835 (void) pthread_mutex_lock(&door_server_cnt_lock);
2836 door_server_cnt--;
2837 (void) pthread_mutex_unlock(&door_server_cnt_lock);
2838 return (NULL);
2842 * Max number of door server threads for syslogd. Since door is used
2843 * to check the health of syslogd, we don't need large number of
2844 * server threads.
2846 #define MAX_DOOR_SERVER_THR 3
2849 * Manage door server thread pool.
2851 /*ARGSUSED*/
2852 static void
2853 door_server_pool(door_info_t *dip)
2855 (void) pthread_mutex_lock(&door_server_cnt_lock);
2856 if (door_server_cnt <= MAX_DOOR_SERVER_THR &&
2857 pthread_create(NULL, &door_thr_attr, create_door_thr, NULL) == 0) {
2858 door_server_cnt++;
2859 (void) pthread_mutex_unlock(&door_server_cnt_lock);
2860 return;
2863 (void) pthread_mutex_unlock(&door_server_cnt_lock);
2867 * checkm4 - used to verify that the external utilities that
2868 * syslogd depends on are where we expect them to be.
2869 * Returns 0 if all utilities are found, > 0 if any are missing.
2870 * Also logs errors so user knows what's missing
2872 static int
2873 checkm4(void)
2875 int notfound = 0;
2876 int saverrno;
2877 pthread_t mythreadno;
2879 if (Debug) {
2880 mythreadno = pthread_self();
2883 if (access("/usr/ccs/bin/m4", X_OK) < 0) {
2884 saverrno = errno;
2885 logerror("/usr/ccs/bin/m4");
2886 DPRINT2(1, "checkm4(%u): /usr/ccs/bin/m4 - access "
2887 "returned %d\n", mythreadno, saverrno);
2888 notfound++;
2891 return (notfound);
2895 * INIT -- Initialize syslogd from configuration table, start up
2896 * input and logger threads. This routine is called only once.
2898 static void
2899 init(void)
2901 struct utsname *up;
2902 pthread_attr_t sys_attr, net_attr, log_attr, hnl_attr;
2903 int nthread;
2904 pthread_t mythreadno;
2906 if (Debug) {
2907 mythreadno = pthread_self();
2910 DPRINT1(2, "init(%u): initializing\n", mythreadno);
2912 /* hand-craft a host_list_t entry for our local host name */
2913 if ((up = malloc(sizeof (struct utsname))) == NULL) {
2914 MALLOC_FAIL_EXIT;
2916 (void) uname(up);
2917 LocalHostName.hl_cnt = 1;
2918 if ((LocalHostName.hl_hosts = malloc(sizeof (char *))) == NULL) {
2919 MALLOC_FAIL_EXIT;
2921 if ((LocalHostName.hl_hosts[0] = strdup(up->nodename)) == NULL) {
2922 free(LocalHostName.hl_hosts);
2923 MALLOC_FAIL_EXIT;
2925 free(up);
2926 /* also hand craft one for use if name resolution fails */
2927 NullHostName.hl_cnt = 1;
2928 if ((NullHostName.hl_hosts = malloc(sizeof (char *))) == NULL) {
2929 MALLOC_FAIL_EXIT;
2931 if ((NullHostName.hl_hosts[0] = strdup("name lookup failed")) == NULL) {
2932 MALLOC_FAIL_EXIT;
2935 hnc_init(0);
2938 * Note that getnets will allocate network resources, but won't be
2939 * binding UDP port. This is because, there could be a race
2940 * condition between door. If we bind here, one syslogd could grab
2941 * UDP port first, but later another syslogd could take over without
2942 * getting UDP port but grab the door file. The 2nd syslogd could
2943 * continue to run without listening network.
2944 * bindnet() will be called after door was successfully opened.
2946 getnets();
2949 * Start up configured theads
2951 conf_init();
2954 * allocate thread stacks for the persistant threads
2956 nthread = (turnoff == 0) ? 4 : 2;
2958 if ((stack_ptr = alloc_stacks(nthread)) == NULL) {
2959 logerror("alloc_stacks failed - fatal");
2960 exit(1);
2963 if (Debug) {
2964 dumpstats(STDOUT_FILENO);
2967 (void) dataq_init(&inputq); /* init the input queue */
2969 if (pthread_attr_init(&sys_attr) != 0 ||
2970 pthread_attr_init(&log_attr) != 0 ||
2971 pthread_attr_init(&net_attr) != 0 ||
2972 pthread_attr_init(&hnl_attr) != 0 ||
2973 pthread_attr_init(&door_thr_attr) != 0) {
2974 logerror("pthread_attr_init failed - fatal");
2975 exit(1);
2978 (void) pthread_attr_setscope(&sys_attr, PTHREAD_SCOPE_PROCESS);
2979 (void) pthread_attr_setscope(&log_attr, PTHREAD_SCOPE_PROCESS);
2980 (void) pthread_attr_setscope(&net_attr, PTHREAD_SCOPE_PROCESS);
2981 (void) pthread_attr_setscope(&hnl_attr, PTHREAD_SCOPE_PROCESS);
2982 (void) pthread_attr_setscope(&door_thr_attr, PTHREAD_SCOPE_SYSTEM);
2983 (void) pthread_attr_setdetachstate(&door_thr_attr,
2984 PTHREAD_CREATE_DETACHED);
2986 /* 1: logmsg thread */
2987 (void) pthread_attr_setstacksize(&log_attr, stacksize);
2988 (void) pthread_attr_setstackaddr(&log_attr, stack_ptr);
2989 stack_ptr += stacksize + redzonesize;
2990 if (pthread_create(&log_thread, &log_attr, logmsg, NULL) != 0) {
2991 logerror("pthread_create failed - fatal");
2992 exit(1);
2996 * open the log device, and pull up all pending message
2997 * from the log driver.
2999 prepare_sys_poll();
3002 * Now we can deliver the pending internal error messages.
3004 enable_errorlog();
3006 /* 2: sys_poll thread */
3007 (void) pthread_attr_setstacksize(&sys_attr, stacksize);
3008 (void) pthread_attr_setstackaddr(&sys_attr, stack_ptr);
3009 stack_ptr += stacksize + redzonesize;
3010 if (pthread_create(&sys_thread, &sys_attr, sys_poll, NULL) != 0) {
3011 logerror("pthread_create failed - fatal");
3012 exit(1);
3016 * We've started the sys_poll() and logmsg() threads. Now we are ready
3017 * to open the door. This cannot happen before spawning sys_poll(),
3018 * because after opening the door, syslog() will no longer take care of
3019 * LOG_CONS. Therefor, we should pull up all pending log messages and
3020 * activate sys_poll() before opening the door, so that log driver
3021 * won't drop messages.
3023 open_door();
3025 DPRINT1(1, "init(%u): accepting messages from local system\n",
3026 mythreadno);
3028 if (turnoff == 0) {
3029 /* init the hostname lookup queue */
3030 (void) dataq_init(&hnlq);
3032 /* 3: hostname lookup thread */
3033 (void) pthread_attr_setstacksize(&hnl_attr, stacksize);
3034 (void) pthread_attr_setstackaddr(&hnl_attr, stack_ptr);
3035 stack_ptr += stacksize + redzonesize;
3036 if (pthread_create(&hnl_thread, &hnl_attr,
3037 hostname_lookup, NULL) != 0) {
3038 logerror("pthread_create failed - fatal");
3039 exit(1);
3042 /* 4: net_poll thread */
3043 (void) pthread_attr_setstacksize(&net_attr, stacksize);
3044 (void) pthread_attr_setstackaddr(&net_attr, stack_ptr);
3045 stack_ptr += stacksize + redzonesize;
3047 /* grab UDP port */
3048 bindnet();
3050 if (pthread_create(&net_thread, &net_attr, net_poll,
3051 NULL) != 0) {
3052 logerror("pthread_create failed - fatal");
3053 exit(1);
3055 DPRINT1(1, "init(%u): accepting messages from remote\n",
3056 mythreadno);
3059 (void) pthread_attr_destroy(&sys_attr);
3060 (void) pthread_attr_destroy(&net_attr);
3061 (void) pthread_attr_destroy(&log_attr);
3062 (void) pthread_attr_destroy(&hnl_attr);
3064 curalarm = MarkInterval * 60 / MARKCOUNT;
3065 (void) alarm((unsigned)curalarm);
3066 DPRINT2(2, "init(%u): Next alarm in %d seconds\n",
3067 mythreadno, curalarm);
3068 DPRINT1(1, "init(%u): syslogd: started\n", mythreadno);
3072 * will print a bunch of debugging stats on 'fd'
3074 static void
3075 dumpstats(int fd)
3077 FILE *out;
3078 struct filed *f;
3079 int i;
3080 char users[1024];
3081 char cbuf[30];
3082 char *dashes = "------------------------";
3083 static int conversion_printed;
3085 if ((out = fdopen(fd, "w+")) == NULL)
3086 return;
3088 (void) fprintf(out, "\nSyslogd started: %s",
3089 ctime_r(&start_time, cbuf));
3090 (void) fprintf(out, "Input message count: system %d, network %d\n",
3091 sys_msg_count, net_msg_count);
3092 (void) fprintf(out, "# Outputs: %d\n\n", nlogs);
3094 (void) fprintf(out, "%s priority = [file, facility] %s\n\n",
3095 dashes, dashes);
3097 for (i = 0; i < LOG_NFACILITIES + 1; i++) {
3098 (void) fprintf(out, "%d ", i / 10);
3100 (void) fprintf(out, "\n");
3101 for (i = 0; i < LOG_NFACILITIES + 1; i++) {
3102 (void) fprintf(out, "%d ", i % 10);
3104 (void) fprintf(out, "\n");
3105 for (i = 0; i < LOG_NFACILITIES + 1; i++) {
3106 (void) fprintf(out, "--");
3108 (void) fprintf(out, "\n");
3110 for (f = Files; f < &Files[nlogs]; f++) {
3111 for (i = 0; i < LOG_NFACILITIES + 1; i++) {
3112 if (f->f_pmask[i] == NOPRI)
3113 (void) fprintf(out, "X ");
3114 else
3115 (void) fprintf(out, "%d ",
3116 f->f_pmask[i]);
3118 (void) fprintf(out, "%s: ", TypeNames[f->f_type]);
3119 switch (f->f_type) {
3120 case F_FILE:
3121 case F_TTY:
3122 case F_CONSOLE:
3123 (void) fprintf(out, "%s", f->f_un.f_fname);
3124 break;
3125 case F_FORW:
3126 (void) fprintf(out, "%s", f->f_un.f_forw.f_hname);
3127 break;
3128 case F_USERS:
3129 for (i = 0; i < MAXUNAMES &&
3130 *f->f_un.f_uname[i]; i++) {
3131 if (!i)
3132 (void) fprintf(out, "%s",
3133 f->f_un.f_uname[i]);
3134 else
3135 (void) fprintf(out, ", %s",
3136 f->f_un.f_uname[i]);
3138 break;
3140 (void) fprintf(out, "\n");
3143 if (!conversion_printed) {
3144 (void) fprintf(out, "\nFacilities:\n");
3146 for (i = 0; FacNames[i].c_val != -1; i++) {
3147 (void) fprintf(out, " [%02d] %s: %3d\n", i,
3148 FacNames[i].c_name, FacNames[i].c_val);
3151 (void) fprintf(out, "\nPriorities:\n");
3153 for (i = 0; PriNames[i].c_val != -1; i++) {
3154 (void) fprintf(out, " [%02d] %s: %3d\n", i,
3155 PriNames[i].c_name, PriNames[i].c_val);
3158 conversion_printed = 1;
3161 (void) fprintf(out, "\n\n\n\t\tPer File Statistics\n");
3162 (void) fprintf(out, "%-24s\tTot\tDups\tNofwd\tErrs\n", "File");
3163 (void) fprintf(out, "%-24s\t---\t----\t-----\t----\n", "----");
3164 for (f = Files; f < &Files[nlogs]; f++) {
3165 switch (f->f_type) {
3166 case F_FILE:
3167 case F_TTY:
3168 case F_CONSOLE:
3169 (void) fprintf(out, "%-24s", f->f_un.f_fname);
3170 break;
3171 case F_WALL:
3172 (void) fprintf(out, "%-24s", TypeNames[f->f_type]);
3173 break;
3174 case F_FORW:
3175 (void) fprintf(out, "%-24s", f->f_un.f_forw.f_hname);
3176 break;
3177 case F_USERS:
3178 for (i = 0; i < MAXUNAMES &&
3179 *f->f_un.f_uname[i]; i++) {
3180 if (!i)
3181 (void) strcpy(users,
3182 f->f_un.f_uname[i]);
3183 else {
3184 (void) strcat(users, ",");
3185 (void) strcat(users,
3186 f->f_un.f_uname[i]);
3189 (void) fprintf(out, "%-24s", users);
3190 break;
3192 (void) fprintf(out, "\t%d\t%d\t%d\t%d\n",
3193 f->f_stat.total, f->f_stat.dups,
3194 f->f_stat.cantfwd, f->f_stat.errs);
3196 (void) fprintf(out, "\n\n");
3197 if (Debug && fd == 1)
3198 return;
3199 (void) fclose(out);
3203 * conf_init - This routine is code seperated from the
3204 * init routine in order to be re-callable when we get
3205 * a SIGHUP signal.
3207 static void
3208 conf_init(void)
3210 char *p;
3211 int i;
3212 struct filed *f;
3213 char *m4argv[4];
3214 int m4argc = 0;
3215 conf_t cf;
3216 pthread_t mythreadno;
3218 if (Debug) {
3219 mythreadno = pthread_self();
3222 DPRINT1(2, "conf_init(%u): starting logger threads\n",
3223 mythreadno);
3225 m4argv[m4argc++] = "m4";
3227 if (amiloghost() == 1) {
3228 DPRINT1(1, "conf_init(%u): I am loghost\n", mythreadno);
3229 m4argv[m4argc++] = "-DLOGHOST=1";
3232 m4argv[m4argc++] = ConfFile;
3233 m4argv[m4argc] = NULL;
3236 * Make sure the configuration file and m4 exist, and then parse
3237 * the configuration file with m4. If any of these fail, resort
3238 * to our hardcoded fallback configuration.
3241 if (access(ConfFile, R_OK) == -1) {
3242 DPRINT2(1, "conf_init(%u): %s does not exist\n", mythreadno,
3243 ConfFile);
3244 logerror("can't open configuration file");
3245 /* CSTYLED */
3246 Files = (struct filed *) &fallback; /*lint !e545 */
3247 cfline("*.ERR\t/dev/sysmsg", 0, &Files[0]);
3248 cfline("*.PANIC\t*", 0, &Files[1]);
3249 nlogs = 2;
3250 goto nofile;
3253 if (checkm4() != 0 || conf_open(&cf, "/usr/ccs/bin/m4", m4argv) == -1) {
3254 DPRINT2(1, "conf_init(%u): cannot open %s\n", mythreadno,
3255 ConfFile);
3256 /* CSTYLED */
3257 Files = (struct filed *) &fallback; /*lint !e545 */
3258 cfline("*.ERR\t/dev/sysmsg", 0, &Files[0]);
3259 cfline("*.PANIC\t*", 0, &Files[1]);
3260 nlogs = 2;
3261 goto nofile;
3264 /* Count the number of lines which are not blanks or comments */
3265 nlogs = 0;
3266 while ((p = conf_read(&cf)) != NULL) {
3267 if (p[0] != '\0' && p[0] != '#')
3268 nlogs++;
3271 Files = (struct filed *)malloc(sizeof (struct filed) * nlogs);
3273 if (!Files) {
3274 DPRINT1(1, "conf_init(%u): malloc failed - can't "
3275 "allocate 'Files' array\n", mythreadno);
3276 MALLOC_FAIL("loading minimum configuration");
3277 /* CSTYLED */
3278 Files = (struct filed *) &fallback; /*lint !e545 */
3279 cfline("*.ERR\t/dev/sysmsg", 0, &Files[0]);
3280 cfline("*.PANIC\t*", 0, &Files[1]);
3281 nlogs = 2;
3282 conf_close(&cf);
3283 goto nofile;
3287 * Foreach line in the conf table, open that file.
3289 conf_rewind(&cf);
3290 f = Files;
3291 i = 0;
3292 while (((p = conf_read(&cf)) != NULL) && (f < &Files[nlogs])) {
3293 i++;
3294 /* check for end-of-section */
3295 if (p[0] == '\0' || p[0] == '#')
3296 continue;
3298 cfline(p, i, f);
3299 if (f->f_type == F_UNUSED)
3300 nlogs--;
3301 else
3302 f++;
3305 conf_close(&cf);
3308 * See if marks are to be written to any files. If so, set up a
3309 * timeout for marks.
3311 nofile:
3312 Marking = 0;
3315 * allocate thread stacks - one for each logger thread.
3317 if ((cstack_ptr = alloc_stacks(nlogs)) == NULL) {
3318 logerror("alloc_stacks failed - fatal");
3319 exit(1);
3322 /* And now one thread for each configured file */
3323 for (f = Files; f < &Files[nlogs]; f++) {
3324 if (filed_init(f) != 0) {
3325 logerror("pthread_create failed - fatal");
3326 exit(1);
3329 (void) pthread_mutex_lock(&cft);
3330 ++conf_threads;
3331 (void) pthread_mutex_unlock(&cft);
3333 if (f->f_type != F_UNUSED &&
3334 f->f_pmask[LOG_NFACILITIES] != NOPRI)
3335 Marking = 1;
3340 * filed init - initialize fields in a file descriptor struct
3341 * this is called before multiple threads are running, so no mutex
3342 * needs to be held at this time.
3344 static int
3345 filed_init(struct filed *f)
3347 pthread_attr_t stack_attr;
3348 pthread_t mythreadno;
3350 if (Debug) {
3351 mythreadno = pthread_self();
3354 if (pthread_mutex_init(&f->filed_mutex, NULL) != 0) {
3355 logerror("pthread_mutex_init failed");
3356 return (-1);
3359 DPRINT2(5, "filed_init(%u): dataq_init for queue %p\n",
3360 mythreadno, (void *)&f->f_queue);
3361 (void) dataq_init(&f->f_queue);
3363 if (pthread_attr_init(&stack_attr) != 0) {
3364 logerror("pthread_attr_init failed");
3365 return (-1);
3368 (void) pthread_attr_setstacksize(&stack_attr, stacksize);
3369 (void) pthread_attr_setstackaddr(&stack_attr, cstack_ptr);
3370 cstack_ptr += stacksize + redzonesize;
3372 f->f_msgflag = 0;
3373 f->f_prevmsg.msg[0] = '\0';
3374 f->f_prevmsg.flags = 0;
3375 f->f_prevmsg.pri = 0;
3376 f->f_prevmsg.host[0] = '\0';
3378 f->f_current.msg[0] = '\0';
3379 f->f_current.flags = 0;
3380 f->f_current.pri = 0;
3381 f->f_current.host[0] = '\0';
3383 f->f_prevcount = 0;
3385 f->f_stat.flag = 0;
3386 f->f_stat.total = 0;
3387 f->f_stat.dups = 0;
3388 f->f_stat.cantfwd = 0;
3389 f->f_stat.errs = 0;
3391 if (pthread_create(&f->f_thread, NULL, logit, (void *)f) != 0) {
3392 logerror("pthread_create failed");
3393 (void) pthread_attr_destroy(&stack_attr);
3394 return (-1);
3397 (void) pthread_attr_destroy(&stack_attr);
3398 return (0);
3403 * Crack a configuration file line
3405 static void
3406 cfline(char *line, int lineno, struct filed *f)
3408 char *p;
3409 char *q;
3410 int i;
3411 char *bp;
3412 int pri;
3413 char buf[MAXLINE];
3414 char ebuf[SYS_NMLN+1+40];
3415 mode_t fmode, omode = O_WRONLY|O_APPEND|O_NOCTTY;
3416 struct stat64 sbuf;
3417 pthread_t mythreadno;
3419 if (Debug) {
3420 mythreadno = pthread_self();
3423 DPRINT2(1, "cfline(%u): (%s)\n", mythreadno, line);
3425 errno = 0; /* keep errno related stuff out of logerror messages */
3427 /* clear out file entry */
3428 bzero((char *)f, sizeof (*f));
3429 for (i = 0; i <= LOG_NFACILITIES; i++)
3430 f->f_pmask[i] = NOPRI;
3432 /* scan through the list of selectors */
3433 for (p = line; *p && *p != '\t'; ) {
3435 /* find the end of this facility name list */
3436 for (q = p; *q && *q != '\t' && *q++ != '.'; )
3437 continue;
3439 /* collect priority name */
3440 for (bp = buf; *q && !strchr("\t,;", *q); )
3441 *bp++ = *q++;
3442 *bp = '\0';
3444 /* skip cruft */
3445 while (strchr(", ;", *q))
3446 q++;
3448 /* decode priority name */
3449 pri = decode(buf, PriNames);
3450 if (pri < 0) {
3451 logerror("line %d: unknown priority name \"%s\"",
3452 lineno, buf);
3453 return;
3456 /* scan facilities */
3457 while (*p && !strchr("\t.;", *p)) {
3458 for (bp = buf; *p && !strchr("\t,;.", *p); )
3459 *bp++ = *p++;
3460 *bp = '\0';
3461 if (*buf == '*')
3462 for (i = 0; i < LOG_NFACILITIES; i++)
3463 f->f_pmask[i] = (uchar_t)pri;
3464 else {
3465 i = decode(buf, FacNames);
3466 if (i < 0) {
3467 logerror("line %d: unknown facility"
3468 " name \"%s\"", lineno, buf);
3469 return;
3471 f->f_pmask[i >> 3] = (uchar_t)pri;
3473 while (*p == ',' || *p == ' ')
3474 p++;
3477 p = q;
3480 /* skip to action part */
3481 while (*p == '\t' || *p == ' ')
3482 p++;
3484 switch (*p) {
3485 case '\0':
3486 errno = 0;
3487 logerror("line %d: no action part", lineno);
3488 break;
3490 case '@':
3491 (void) strlcpy(f->f_un.f_forw.f_hname, ++p, SYS_NMLN);
3492 if (logforward(f, ebuf, sizeof (ebuf)) != 0) {
3493 logerror("line %d: %s", lineno, ebuf);
3494 break;
3496 f->f_type = F_FORW;
3497 break;
3499 case '/':
3500 (void) strlcpy(f->f_un.f_fname, p, MAXPATHLEN);
3501 if (stat64(p, &sbuf) < 0) {
3502 logerror(p);
3503 break;
3506 * don't block trying to open a pipe
3507 * with no reader on the other end
3509 fmode = 0; /* reset each pass */
3510 if (S_ISFIFO(sbuf.st_mode))
3511 fmode = O_NONBLOCK;
3513 f->f_file = open64(p, omode|fmode);
3514 if (f->f_file < 0) {
3515 if (fmode && errno == ENXIO) {
3516 errno = 0;
3517 logerror("%s - no reader", p);
3518 } else
3519 logerror(p);
3520 break;
3524 * Fifos are initially opened NONBLOCK
3525 * to insure we don't hang, but once
3526 * we are open, we need to change the
3527 * behavior back to blocking, otherwise
3528 * we may get write errors, and the log
3529 * will get closed down the line.
3531 if (S_ISFIFO(sbuf.st_mode))
3532 (void) fcntl(f->f_file, F_SETFL, omode);
3534 if (isatty(f->f_file)) {
3535 f->f_type = F_TTY;
3536 untty();
3537 } else
3538 f->f_type = F_FILE;
3540 if ((strcmp(p, ctty) == 0) || (strcmp(p, sysmsg) == 0))
3541 f->f_type = F_CONSOLE;
3542 break;
3544 case '*':
3545 f->f_type = F_WALL;
3546 break;
3548 default:
3549 for (i = 0; i < MAXUNAMES && *p; i++) {
3550 for (q = p; *q && *q != ','; )
3551 q++;
3552 (void) strlcpy(f->f_un.f_uname[i], p, UNAMESZ);
3553 if ((q - p) > UNAMESZ)
3554 f->f_un.f_uname[i][UNAMESZ] = '\0';
3555 else
3556 f->f_un.f_uname[i][q - p] = '\0';
3557 while (*q == ',' || *q == ' ')
3558 q++;
3559 p = q;
3561 f->f_type = F_USERS;
3562 break;
3564 f->f_orig_type = f->f_type;
3569 * Decode a symbolic name to a numeric value
3571 static int
3572 decode(char *name, struct code *codetab)
3574 struct code *c;
3575 char *p;
3576 char buf[40];
3578 if (isdigit(*name))
3579 return (atoi(name));
3581 (void) strncpy(buf, name, sizeof (buf) - 1);
3582 for (p = buf; *p; p++)
3583 if (isupper(*p))
3584 *p = tolower(*p);
3585 for (c = codetab; c->c_name; c++)
3586 if (!(strcmp(buf, c->c_name)))
3587 return (c->c_val);
3589 return (-1);
3592 static int
3593 ismyaddr(struct netbuf *nbp)
3595 int i;
3597 if (nbp == NULL)
3598 return (0);
3600 for (i = 1; i < Ninputs; i++) {
3601 if (same_addr(nbp, Myaddrs[i]))
3602 return (1);
3604 return (0);
3607 static void
3608 getnets(void)
3610 struct nd_hostserv hs;
3611 struct netconfig *ncp;
3612 struct nd_addrlist *nap;
3613 struct netbuf *nbp;
3614 int i, inputs;
3615 void *handle;
3616 char *uap;
3617 pthread_t mythreadno;
3619 if (Debug) {
3620 mythreadno = pthread_self();
3623 if (turnoff) {
3624 DPRINT1(1, "getnets(%u): network is being turned off\n",
3625 mythreadno);
3626 return;
3629 hs.h_host = HOST_SELF;
3630 hs.h_serv = "syslog";
3632 if ((handle = setnetconfig()) == NULL) {
3633 return;
3636 while ((ncp = getnetconfig(handle)) != NULL) {
3637 if (ncp->nc_semantics != NC_TPI_CLTS) {
3638 continue;
3641 if (netdir_getbyname(ncp, &hs, &nap) != 0) {
3642 continue;
3645 if (nap == NULL || nap->n_cnt <= 0) {
3646 DPRINT1(1, "getnets(%u): found no address\n",
3647 mythreadno);
3648 netdir_free((void *)nap, ND_ADDRLIST);
3649 continue;
3652 if (Debug) {
3653 DPRINT2(1, "getnets(%u): found %d addresses",
3654 mythreadno, nap->n_cnt);
3655 DPRINT0(1, ", they are: ");
3656 nbp = nap->n_addrs;
3658 for (i = 0; i < nap->n_cnt; i++) {
3659 if ((uap = taddr2uaddr(ncp, nbp)) != NULL) {
3660 DPRINT1(1, "%s ", uap);
3661 free(uap);
3663 nbp++;
3666 DPRINT0(1, "\n");
3669 inputs = Ninputs + nap->n_cnt;
3671 Nfd = reallocarray(Nfd, inputs, sizeof (struct pollfd));
3672 Ncf = reallocarray(Ncf, inputs, sizeof (struct netconfig));
3673 Myaddrs = reallocarray(Myaddrs, inputs,
3674 sizeof (struct netbuf *));
3675 Udp = reallocarray(Udp, inputs, sizeof (struct t_unitdata *));
3676 Errp = reallocarray(Errp, inputs, sizeof (struct t_uderr *));
3679 * all malloc failures here are fatal
3681 if (Nfd == NULL || Ncf == NULL || Myaddrs == NULL ||
3682 Udp == NULL || Errp == NULL) {
3683 MALLOC_FAIL_EXIT;
3686 nbp = nap->n_addrs;
3688 for (i = 0; i < nap->n_cnt; i++, nbp++) {
3689 char ebuf[128];
3691 if (addnet(ncp, nbp) == 0) {
3692 /* no error */
3693 continue;
3696 (void) strcpy(ebuf, "Unable to configure syslog port");
3698 if ((uap = taddr2uaddr(ncp, nbp)) != NULL) {
3699 size_t l = strlen(ebuf);
3700 (void) snprintf(ebuf + l, sizeof (ebuf) - l,
3701 " for %s", uap);
3704 DPRINT2(1, "getnets(%u): %s",
3705 mythreadno, ebuf);
3707 if (uap) {
3708 free(uap);
3711 logerror(ebuf);
3713 * Here maybe syslogd can quit. However, syslogd
3714 * has been ignoring this error and keep running.
3715 * So we won't break it.
3719 netdir_free((void *)nap, ND_ADDRLIST);
3722 (void) endnetconfig(handle);
3726 * Open the network device, and allocate necessary resources.
3727 * Myaddrs will also be filled, so that we can call ismyaddr() before
3728 * being bound to the network.
3730 static int
3731 addnet(struct netconfig *ncp, struct netbuf *nbp)
3733 int fd;
3734 struct netbuf *bp;
3736 fd = t_open(ncp->nc_device, O_RDWR, NULL);
3738 if (fd < 0) {
3739 return (1);
3742 (void) memcpy(&Ncf[Ninputs], ncp, sizeof (struct netconfig));
3744 /*LINTED*/
3745 Udp[Ninputs] = (struct t_unitdata *)t_alloc(fd, T_UNITDATA, T_ADDR);
3747 if (Udp[Ninputs] == NULL) {
3748 (void) t_close(fd);
3749 return (1);
3752 /*LINTED*/
3753 Errp[Ninputs] = (struct t_uderr *)t_alloc(fd, T_UDERROR, T_ADDR);
3755 if (Errp[Ninputs] == NULL) {
3756 (void) t_close(fd);
3757 (void) t_free((char *)Udp[Ninputs], T_UNITDATA);
3758 return (1);
3761 if ((bp = malloc(sizeof (struct netbuf))) == NULL ||
3762 (bp->buf = malloc(nbp->len)) == NULL) {
3763 MALLOC_FAIL("allocating address buffer");
3764 (void) t_close(fd);
3765 (void) t_free((char *)Udp[Ninputs], T_UNITDATA);
3766 (void) t_free((char *)Errp[Ninputs], T_UDERROR);
3768 if (bp) {
3769 free(bp);
3772 return (1);
3775 bp->len = nbp->len;
3776 (void) memcpy(bp->buf, nbp->buf, nbp->len);
3777 Myaddrs[Ninputs] = bp;
3779 Nfd[Ninputs].fd = fd;
3780 Nfd[Ninputs].events = POLLIN;
3781 Ninputs++;
3782 return (0);
3786 * Allocate UDP buffer to minimize packet loss.
3788 static void
3789 set_udp_buffer(int fd)
3791 struct t_optmgmt req, resp;
3792 struct opthdr *opt;
3793 size_t optsize, bsize = 256 * 1024;
3794 pthread_t mythreadno;
3796 if (Debug) {
3797 mythreadno = pthread_self();
3800 optsize = sizeof (struct opthdr) + sizeof (int);
3801 if ((opt = malloc(optsize)) == NULL) {
3802 MALLOC_FAIL("will have no udp buffer");
3803 return;
3805 opt->level = SOL_SOCKET;
3806 opt->name = SO_RCVBUF;
3807 opt->len = sizeof (int);
3808 *(int *)(opt + 1) = bsize;
3810 req.flags = T_NEGOTIATE;
3811 req.opt.len = optsize;
3812 req.opt.buf = (char *)opt;
3814 resp.flags = 0;
3815 resp.opt.maxlen = optsize;
3816 resp.opt.buf = (char *)opt;
3818 while (t_optmgmt(fd, &req, &resp) == -1 || resp.flags != T_SUCCESS) {
3819 if (t_errno != TSYSERR || errno != ENOBUFS) {
3820 bsize = 0;
3821 break;
3823 bsize >>= 1;
3824 if (bsize < 8192) {
3825 break;
3827 *(int *)(opt + 1) = bsize;
3829 if (bsize == 0) {
3830 logerror("failed to allocate UDP buffer");
3832 DPRINT3(1, "set_udp_buffer(%u): allocate %d for fd %d\n",
3833 mythreadno, bsize, fd);
3834 free(opt);
3838 * Attach the network, and allocate UDP buffer for the interface.
3840 static void
3841 bindnet(void)
3843 struct t_bind bind, *bound;
3844 int cnt, i;
3845 char *uap;
3846 pthread_t mythreadno;
3848 if (Debug) {
3849 mythreadno = pthread_self();
3852 cnt = 0;
3854 while (cnt < Ninputs) {
3855 char ebuf[128];
3857 /*LINTED*/
3858 bound = (struct t_bind *)t_alloc(Nfd[cnt].fd, T_BIND, T_ADDR);
3859 bind.addr = *Myaddrs[cnt];
3860 bind.qlen = 0;
3862 if (t_bind(Nfd[cnt].fd, &bind, bound) == 0) {
3863 if (same_addr(&bind.addr, &bound->addr)) {
3864 (void) t_free((char *)bound, T_BIND);
3865 set_udp_buffer(Nfd[cnt].fd);
3866 cnt++;
3867 continue;
3871 /* failed to bind port */
3872 (void) t_free((char *)bound, T_BIND);
3874 (void) strcpy(ebuf, "Unable to bind syslog port");
3876 uap = taddr2uaddr(&Ncf[cnt], Myaddrs[cnt]);
3877 if (uap) {
3878 i = strlen(ebuf);
3879 (void) snprintf(ebuf + i, sizeof (ebuf) - i,
3880 " for %s", uap);
3883 DPRINT2(1, "bindnet(%u): failed to bind port (%s)\n",
3884 mythreadno, uap ? uap : "<unknown>");
3886 if (uap) {
3887 free(uap);
3890 errno = 0;
3891 logerror(ebuf);
3893 (void) t_close(Nfd[cnt].fd);
3894 free(Myaddrs[cnt]->buf);
3895 free(Myaddrs[cnt]);
3896 (void) t_free((char *)Udp[cnt], T_UNITDATA);
3897 (void) t_free((char *)Errp[cnt], T_UDERROR);
3899 for (i = cnt; i < (Ninputs-1); i++) {
3900 Nfd[i] = Nfd[i + 1];
3901 Ncf[i] = Ncf[i + 1];
3902 Myaddrs[i] = Myaddrs[i + 1];
3903 Udp[i] = Udp[i + 1];
3904 Errp[i] = Errp[i + 1];
3907 Ninputs--;
3911 static int
3912 logforward(struct filed *f, char *ebuf, size_t elen)
3914 struct nd_hostserv hs;
3915 struct netbuf *nbp;
3916 struct netconfig *ncp;
3917 struct nd_addrlist *nap;
3918 void *handle;
3919 char *hp;
3921 hp = f->f_un.f_forw.f_hname;
3922 hs.h_host = hp;
3923 hs.h_serv = "syslog";
3925 if ((handle = setnetconfig()) == NULL) {
3926 (void) strlcpy(ebuf,
3927 "unable to rewind the netconfig database", elen);
3928 errno = 0;
3929 return (-1);
3931 nap = NULL;
3932 while ((ncp = getnetconfig(handle)) != NULL) {
3933 if (ncp->nc_semantics == NC_TPI_CLTS) {
3934 if (netdir_getbyname(ncp, &hs, &nap) == 0) {
3935 if (!nap)
3936 continue;
3937 nbp = nap->n_addrs;
3938 break;
3942 if (ncp == NULL) {
3943 (void) endnetconfig(handle);
3944 (void) snprintf(ebuf, elen,
3945 "WARNING: %s could not be resolved", hp);
3946 errno = 0;
3947 return (-1);
3949 if (nap == NULL) {
3950 (void) endnetconfig(handle);
3951 (void) snprintf(ebuf, elen, "unknown host %s", hp);
3952 errno = 0;
3953 return (-1);
3955 /* CSTYLED */
3956 if (ismyaddr(nbp)) { /*lint !e644 */
3957 netdir_free((void *)nap, ND_ADDRLIST);
3958 (void) endnetconfig(handle);
3959 (void) snprintf(ebuf, elen,
3960 "host %s is this host - logging loop", hp);
3961 errno = 0;
3962 return (-1);
3964 f->f_un.f_forw.f_addr.buf = malloc(nbp->len);
3965 if (f->f_un.f_forw.f_addr.buf == NULL) {
3966 netdir_free((void *)nap, ND_ADDRLIST);
3967 (void) endnetconfig(handle);
3968 (void) strlcpy(ebuf, "malloc failed", elen);
3969 return (-1);
3971 bcopy(nbp->buf, f->f_un.f_forw.f_addr.buf, nbp->len);
3972 f->f_un.f_forw.f_addr.len = nbp->len;
3973 f->f_file = t_open(ncp->nc_device, O_RDWR, NULL);
3974 if (f->f_file < 0) {
3975 netdir_free((void *)nap, ND_ADDRLIST);
3976 (void) endnetconfig(handle);
3977 free(f->f_un.f_forw.f_addr.buf);
3978 (void) strlcpy(ebuf, "t_open", elen);
3979 return (-1);
3981 netdir_free((void *)nap, ND_ADDRLIST);
3982 (void) endnetconfig(handle);
3983 if (t_bind(f->f_file, NULL, NULL) < 0) {
3984 (void) strlcpy(ebuf, "t_bind", elen);
3985 free(f->f_un.f_forw.f_addr.buf);
3986 (void) t_close(f->f_file);
3987 return (-1);
3989 return (0);
3992 static int
3993 amiloghost(void)
3995 struct nd_hostserv hs;
3996 struct netconfig *ncp;
3997 struct nd_addrlist *nap;
3998 struct netbuf *nbp;
3999 int i, fd;
4000 void *handle;
4001 char *uap;
4002 struct t_bind bind, *bound;
4003 pthread_t mythreadno;
4005 if (Debug) {
4006 mythreadno = pthread_self();
4010 * we need to know if we are running on the loghost. This is
4011 * checked by binding to the address associated with "loghost"
4012 * and "syslogd" service over the connectionless transport
4014 hs.h_host = "loghost";
4015 hs.h_serv = "syslog";
4017 if ((handle = setnetconfig()) == NULL) {
4018 return (0);
4021 while ((ncp = getnetconfig(handle)) != NULL) {
4022 if (ncp->nc_semantics != NC_TPI_CLTS) {
4023 continue;
4026 if (netdir_getbyname(ncp, &hs, &nap) != 0) {
4027 continue;
4030 if (nap == NULL) {
4031 continue;
4034 nbp = nap->n_addrs;
4036 for (i = 0; i < nap->n_cnt; i++) {
4037 if ((uap = taddr2uaddr(ncp, nbp)) != NULL) {
4038 DPRINT2(1, "amiloghost(%u): testing %s\n",
4039 mythreadno, uap);
4042 free(uap);
4044 fd = t_open(ncp->nc_device, O_RDWR, NULL);
4046 if (fd < 0) {
4047 netdir_free((void *)nap, ND_ADDRLIST);
4048 (void) endnetconfig(handle);
4049 return (0);
4052 /*LINTED*/
4053 bound = (struct t_bind *)t_alloc(fd, T_BIND, T_ADDR);
4054 bind.addr = *nbp;
4055 bind.qlen = 0;
4057 if (t_bind(fd, &bind, bound) == 0) {
4058 (void) t_close(fd);
4059 (void) t_free((char *)bound, T_BIND);
4060 netdir_free((void *)nap, ND_ADDRLIST);
4061 (void) endnetconfig(handle);
4062 return (1);
4063 } else {
4064 (void) t_close(fd);
4065 (void) t_free((char *)bound, T_BIND);
4068 nbp++;
4071 netdir_free((void *)nap, ND_ADDRLIST);
4074 (void) endnetconfig(handle);
4075 return (0);
4079 same_addr(struct netbuf *na, struct netbuf *nb)
4081 char *a, *b;
4082 size_t n;
4084 assert(na->buf != NULL && nb->buf != NULL);
4086 if (na->len != nb->len) {
4087 return (0);
4090 a = na->buf;
4091 b = nb->buf;
4092 n = nb->len;
4094 while (n-- > 0) {
4095 if (*a++ != *b++) {
4096 return (0);
4100 return (1);
4104 * allocates a new message structure, initializes it
4105 * and returns a pointer to it
4107 static log_message_t *
4108 new_msg(void)
4110 log_message_t *lm;
4111 pthread_t mythreadno;
4113 if (Debug) {
4114 mythreadno = pthread_self();
4117 if ((lm = malloc(sizeof (log_message_t))) == NULL)
4118 return ((log_message_t *)NULL);
4120 _NOTE(NOW_INVISIBLE_TO_OTHER_THREADS(*lm))
4122 if (pthread_mutex_init(&lm->msg_mutex, NULL) != 0)
4123 return ((log_message_t *)NULL);
4124 lm->refcnt = 0;
4125 lm->pri = 0;
4126 lm->flags = 0;
4127 lm->hlp = NULL;
4128 lm->msg[0] = '\0';
4129 lm->ptr = NULL;
4131 DPRINT2(3, "new_msg(%u): creating msg %p\n", mythreadno, (void *)lm);
4132 return (lm);
4136 * frees a message structure - should only be called if
4137 * the refcount is 0
4139 static void
4140 free_msg(log_message_t *lm)
4142 pthread_t mythreadno;
4144 if (Debug) {
4145 mythreadno = pthread_self();
4148 assert(lm != NULL && lm->refcnt == 0);
4149 if (lm->hlp != NULL)
4150 freehl(lm->hlp);
4151 DPRINT2(3, "free_msg(%u): freeing msg %p\n", mythreadno, (void *)lm);
4152 free(lm);
4156 * Make sure that the message makes sense in the current locale, and
4157 * does not contain stray control characters.
4159 static void
4160 filter_string(char *mbstr, char *filtered, size_t max)
4162 size_t cs = 0;
4163 size_t mb_cur_max;
4164 unsigned char *p = (unsigned char *)mbstr;
4165 pthread_t mythreadno = 0;
4167 if (Debug) {
4168 mythreadno = pthread_self();
4171 assert(mbstr != NULL && filtered != NULL);
4174 * Since the access to MB_CUR_MAX is expensive (because
4175 * MB_CUR_MAX lives in a global area), it should be
4176 * restrained for the better performance.
4178 mb_cur_max = (size_t)MB_CUR_MAX;
4179 if (mb_cur_max > 1) {
4180 /* multibyte locale */
4181 int mlen;
4182 wchar_t wc;
4184 while (*p != '\0') {
4185 if ((mlen = mbtowc(&wc, (char *)p,
4186 mb_cur_max)) == -1) {
4188 * Invalid byte sequence found.
4190 * try to print one byte
4191 * in ASCII format.
4193 DPRINT2(9, "filter_string(%u): Invalid "
4194 "MB sequence: %ld\n", mythreadno,
4195 wc);
4197 if (!putctrlc(*p++, &filtered, &cs, max)) {
4198 /* not enough buffer */
4199 goto end;
4200 } else {
4201 continue;
4203 } else {
4205 * Since *p is not a null byte here,
4206 * mbtowc should have never returned 0.
4208 * A valid wide character found.
4211 if (wc != L'\t' && iswcntrl(wc)) {
4213 * non-tab, non-newline, and
4214 * control character found.
4216 * try to print this wide character
4217 * in ASCII-format.
4219 char *q = filtered;
4221 DPRINT2(9, "filter_string(%u): MB"
4222 " control character: %ld\n",
4223 mythreadno, wc);
4225 while (mlen--) {
4226 if (!putctrlc(*p++, &filtered,
4227 &cs, max)) {
4229 * not enough buffer in
4230 * filtered
4232 * cancel already
4233 * stored bytes in
4234 * filtered for this
4235 * wide character.
4237 filtered = q;
4238 goto end;
4241 continue;
4242 } else {
4244 * tab, newline, or non-control
4245 * character found.
4247 if (cs + mlen < max) {
4248 /* enough buffer */
4249 cs += mlen;
4250 while (mlen--) {
4251 *filtered++ = *p++;
4253 continue;
4254 } else {
4255 /* not enough buffer */
4256 goto end;
4261 } else {
4262 /* singlebyte locale */
4264 while (*p != '\0') {
4265 if (*p != '\t' && iscntrl(*p)) {
4267 * non-tab, non-newline,
4268 * and control character found.
4270 * try to print this singlebyte character
4271 * in ASCII format.
4273 DPRINT2(9, "filter_string(%u): control "
4274 "character: %d\n", mythreadno, *p);
4276 if (!putctrlc(*p++, &filtered, &cs, max)) {
4277 /* not enough buffer */
4278 goto end;
4279 } else {
4280 continue;
4282 } else if (*p != '\t' && !isprint(*p)) {
4284 * non-tab and non printable character found
4285 * this check is required for the C locale
4287 DPRINT2(9, "filter_string(%u): non-printable "
4288 "character: %d\n", mythreadno, *p);
4289 if (!putctrlc(*p++, &filtered, &cs, max)) {
4290 /* not enough buffer */
4291 goto end;
4292 } else {
4293 continue;
4295 } else {
4297 * tab, newline, non-control character, or
4298 * printable found.
4300 if (cs + 1 < max) {
4301 *filtered++ = *p++;
4302 cs++;
4303 continue;
4304 } else {
4305 /* not enough buffer */
4306 goto end;
4312 end:
4313 *filtered = '\0';
4315 if (cs >= 2 &&
4316 filtered[-2] == '\\' && filtered[-1] == 'n') {
4317 filtered[-2] = '\0';
4321 static char *
4322 alloc_stacks(int numstacks)
4324 size_t pagesize, mapsize;
4325 char *stack_top;
4326 char *addr;
4327 int i;
4329 pagesize = (size_t)sysconf(_SC_PAGESIZE);
4331 * stacksize and redzonesize are global so threads
4332 * can be created elsewhere and refer to the sizes
4334 stacksize = (size_t)roundup(sysconf(_SC_THREAD_STACK_MIN) +
4335 DEFAULT_STACKSIZE, pagesize);
4336 redzonesize = (size_t)roundup(DEFAULT_REDZONESIZE, pagesize);
4339 * allocate an additional "redzonesize" chunk in addition
4340 * to what we require, so we can create a redzone at the
4341 * bottom of the last stack as well.
4343 mapsize = redzonesize + numstacks * (stacksize + redzonesize);
4344 stack_top = mmap(NULL, mapsize, PROT_READ|PROT_WRITE,
4345 MAP_PRIVATE|MAP_ANON, -1, 0);
4346 if (stack_top == MAP_FAILED)
4347 return (NULL);
4349 addr = stack_top;
4351 * this loop is intentionally <= instead of <, so we can
4352 * protect the redzone at the bottom of the last stack
4354 for (i = 0; i <= numstacks; i++) {
4355 (void) mprotect(addr, redzonesize, PROT_NONE);
4356 addr += stacksize + redzonesize;
4358 return ((char *)(stack_top + redzonesize));
4361 static void
4362 dealloc_stacks(int numstacks)
4364 size_t pagesize, mapsize;
4366 pagesize = (size_t)sysconf(_SC_PAGESIZE);
4368 stacksize = (size_t)roundup(sysconf(_SC_THREAD_STACK_MIN) +
4369 DEFAULT_STACKSIZE, pagesize);
4371 redzonesize = (size_t)roundup(DEFAULT_REDZONESIZE, pagesize);
4373 mapsize = redzonesize + numstacks * (stacksize + redzonesize);
4374 (void) munmap(cstack_ptr - mapsize, mapsize);
4377 static void
4378 filed_destroy(struct filed *f)
4380 (void) dataq_destroy(&f->f_queue);
4381 (void) pthread_mutex_destroy(&f->filed_mutex);
4384 static void
4385 close_door(void)
4387 pthread_t mythreadno;
4389 if (Debug) {
4390 mythreadno = pthread_self();
4393 (void) fdetach(DoorFileName);
4395 DPRINT2(5, "close_door(%u): detached server() from %s\n",
4396 mythreadno, DoorFileName);
4399 static void
4400 delete_doorfiles(void)
4402 pthread_t mythreadno;
4403 struct stat sb;
4404 int err;
4405 char line[MAXLINE+1];
4407 if (Debug) {
4408 mythreadno = pthread_self();
4412 if (lstat(DoorFileName, &sb) == 0 && !S_ISDIR(sb.st_mode)) {
4413 if (unlink(DoorFileName) < 0) {
4414 err = errno;
4415 (void) snprintf(line, sizeof (line),
4416 "unlink() of %s failed - fatal", DoorFileName);
4417 errno = err;
4418 logerror(line);
4419 DPRINT3(1, "delete_doorfiles(%u): error: %s, "
4420 "errno=%d\n", mythreadno, line, err);
4421 exit(1);
4424 DPRINT2(5, "delete_doorfiles(%u): deleted %s\n",
4425 mythreadno, DoorFileName);
4428 if (strcmp(DoorFileName, DOORFILE) == 0) {
4429 if (lstat(OLD_DOORFILE, &sb) == 0 && !S_ISDIR(sb.st_mode)) {
4430 if (unlink(OLD_DOORFILE) < 0) {
4431 err = errno;
4432 (void) snprintf(line, sizeof (line),
4433 "unlink() of %s failed", OLD_DOORFILE);
4434 DPRINT2(5, "delete_doorfiles(%u): %s\n",
4435 mythreadno, line);
4437 if (err != EROFS) {
4438 errno = err;
4439 (void) strlcat(line, " - fatal",
4440 sizeof (line));
4441 logerror(line);
4442 DPRINT3(1, "delete_doorfiles(%u): "
4443 "error: %s, errno=%d\n",
4444 mythreadno, line, err);
4445 exit(1);
4448 DPRINT1(5, "delete_doorfiles(%u): unlink() "
4449 "failure OK on RO file system\n",
4450 mythreadno);
4453 DPRINT2(5, "delete_doorfiles(%u): deleted %s\n",
4454 mythreadno, OLD_DOORFILE);
4458 if (lstat(PidFileName, &sb) == 0 && !S_ISDIR(sb.st_mode)) {
4459 if (unlink(PidFileName) < 0) {
4460 err = errno;
4461 (void) snprintf(line, sizeof (line),
4462 "unlink() of %s failed - fatal", PidFileName);
4463 errno = err;
4464 logerror(line);
4465 DPRINT3(1, "delete_doorfiles(%u): error: %s, "
4466 "errno=%d\n", mythreadno, line, err);
4467 exit(1);
4470 DPRINT2(5, "delete_doorfiles(%u): deleted %s\n", mythreadno,
4471 PidFileName);
4474 if (strcmp(PidFileName, PIDFILE) == 0) {
4475 if (lstat(OLD_PIDFILE, &sb) == 0 && !S_ISDIR(sb.st_mode)) {
4476 if (unlink(OLD_PIDFILE) < 0) {
4477 err = errno;
4478 (void) snprintf(line, sizeof (line),
4479 "unlink() of %s failed", OLD_PIDFILE);
4480 DPRINT2(5, "delete_doorfiles(%u): %s, \n",
4481 mythreadno, line);
4483 if (err != EROFS) {
4484 errno = err;
4485 (void) strlcat(line, " - fatal",
4486 sizeof (line));
4487 logerror(line);
4488 DPRINT3(1, "delete_doorfiles(%u): "
4489 "error: %s, errno=%d\n",
4490 mythreadno, line, err);
4491 exit(1);
4494 DPRINT1(5, "delete_doorfiles(%u): unlink "
4495 "failure OK on RO file system\n",
4496 mythreadno);
4499 DPRINT2(5, "delete_doorfiles(%u): deleted %s\n",
4500 mythreadno, OLD_PIDFILE);
4504 if (DoorFd != -1) {
4505 (void) door_revoke(DoorFd);
4508 DPRINT2(1, "delete_doorfiles(%u): revoked door: DoorFd=%d\n",
4509 mythreadno, DoorFd);
4513 /*ARGSUSED*/
4514 static void
4515 signull(int sig, siginfo_t *sip, void *utp)
4517 DPRINT1(1, "signull(%u): THIS CALL SHOULD NEVER HAPPEN\n",
4518 pthread_self());
4520 * Do nothing, as this is a place-holder used in conjunction with
4521 * sigaction()/sigwait() to ensure that the proper disposition is
4522 * given to the signals we handle in main().
4527 * putctrlc returns zero, if failed due to not enough buffer.
4528 * Otherwise, putctrlc returns non-zero.
4530 * c: a byte to print in ASCII format
4531 * **buf: a pointer to the pointer to the output buffer.
4532 * *cl: current length of characters in the output buffer
4533 * max: maximum length of the buffer
4536 static int
4537 putctrlc(int c, char **buf, size_t *cl, size_t max)
4539 char *p = *buf;
4541 if (c == '\n') {
4542 if (*cl + 2 < max) {
4543 *p++ = '\\';
4544 *p++ = 'n';
4545 *cl += 2;
4546 *buf = p;
4547 return (2);
4548 } else {
4549 return (0);
4551 } else if (c < 0200) {
4552 /* ascii control character */
4553 if (*cl + 2 < max) {
4554 *p++ = '^';
4555 *p++ = c ^ 0100;
4556 *cl += 2;
4557 *buf = p;
4558 return (2);
4559 } else {
4560 return (0);
4562 } else {
4563 if (*cl + 4 < max) {
4564 *p++ = '\\';
4565 *p++ = ((c >> 6) & 07) + '0';
4566 *p++ = ((c >> 3) & 07) + '0';
4567 *p++ = (c & 07) + '0';
4568 *cl += 4;
4569 *buf = p;
4570 return (4);
4571 } else {
4572 return (0);
4578 * findnl_bkwd:
4579 * Scans each character in buf until it finds the last newline in buf,
4580 * or the scanned character becomes the last COMPLETE character in buf.
4581 * Returns the number of scanned bytes.
4583 * buf - pointer to a buffer containing the message string
4584 * len - the length of the buffer
4586 size_t
4587 findnl_bkwd(const char *buf, const size_t len)
4589 const char *p;
4590 size_t mb_cur_max;
4591 pthread_t mythreadno;
4593 if (Debug) {
4594 mythreadno = pthread_self();
4597 if (len == 0) {
4598 return (0);
4601 mb_cur_max = MB_CUR_MAX;
4603 if (mb_cur_max == 1) {
4604 /* single-byte locale */
4605 for (p = buf + len - 1; p != buf; p--) {
4606 if (*p == '\n') {
4607 return ((size_t)(p - buf));
4610 return ((size_t)len);
4611 } else {
4612 /* multi-byte locale */
4613 int mlen;
4614 const char *nl;
4615 size_t rem;
4617 p = buf;
4618 nl = NULL;
4619 for (rem = len; rem >= mb_cur_max; ) {
4620 mlen = mblen(p, mb_cur_max);
4621 if (mlen == -1) {
4623 * Invalid character found.
4625 DPRINT1(9, "findnl_bkwd(%u): Invalid MB "
4626 "sequence\n", mythreadno);
4628 * handle as a single byte character.
4630 p++;
4631 rem--;
4632 } else {
4634 * It's guaranteed that *p points to
4635 * the 1st byte of a multibyte character.
4637 if (*p == '\n') {
4638 nl = p;
4640 p += mlen;
4641 rem -= mlen;
4644 if (nl) {
4645 return ((size_t)(nl - buf));
4648 * no newline nor null byte found.
4649 * Also it's guaranteed that *p points to
4650 * the 1st byte of a (multibyte) character
4651 * at this point.
4653 return (len - rem);
4658 * copynl_frwd:
4659 * Scans each character in buf and copies the scanned character to obuf
4660 * until it finds a null byte or a newline, or
4661 * the number of the remaining bytes in obuf gets to exceed obuflen
4662 * if copying the scanned character to obuf.
4663 * Returns the number of scanned bytes.
4665 * obuf - buffer to be copied the scanned character
4666 * obuflen - the size of obuf
4667 * buf - pointer to a buffer containing the message string
4668 * len - the length of the buffer
4670 size_t
4671 copynl_frwd(char *obuf, const size_t obuflen,
4672 const char *buf, const size_t len)
4674 const char *p;
4675 char *q = obuf;
4676 size_t olen = 0;
4677 size_t mb_cur_max;
4678 pthread_t mythreadno;
4680 if (Debug) {
4681 mythreadno = pthread_self();
4684 if (len == 0) {
4685 return (0);
4688 mb_cur_max = MB_CUR_MAX;
4690 if (mb_cur_max == 1) {
4691 /* single-byte locale */
4692 for (p = buf; *p; ) {
4693 if (obuflen > olen + 1) {
4694 if (*p != '\n') {
4695 *q++ = *p++;
4696 olen++;
4697 } else {
4698 *q = '\0';
4699 return ((size_t)(p - buf));
4701 } else {
4702 *q = '\0';
4703 return ((size_t)(p - buf));
4706 *q = '\0';
4707 return ((size_t)(p - buf));
4708 } else {
4709 /* multi-byte locale */
4710 int mlen;
4712 for (p = buf; *p; ) {
4713 mlen = mblen(p, mb_cur_max);
4714 if (mlen == -1) {
4716 * Invalid character found.
4718 DPRINT1(9, "copynl_frwd(%u): Invalid MB "
4719 "sequence\n", mythreadno);
4721 * handle as a single byte character.
4723 if (obuflen > olen + 1) {
4724 *q++ = *p++;
4725 olen++;
4726 } else {
4727 *q = '\0';
4728 return ((size_t)(p - buf));
4730 } else {
4732 * It's guaranteed that *p points to
4733 * the 1st byte of a multibyte character.
4735 if (*p == '\n') {
4736 *q = '\0';
4737 return ((size_t)(p - buf));
4739 if (obuflen > olen + mlen) {
4740 int n;
4741 for (n = 0; n < mlen; n++) {
4742 *q++ = *p++;
4744 olen += mlen;
4745 } else {
4746 *q = '\0';
4747 return ((size_t)(p - buf));
4752 * no newline nor null byte found.
4753 * Also it's guaranteed that *p points to
4754 * the 1st byte of a (multibyte) character
4755 * at this point.
4757 *q = '\0';
4758 return ((size_t)(p - buf));
4763 * copy_frwd:
4764 * Scans each character in buf and copies the scanned character to obuf
4765 * until the number of the remaining bytes in obuf gets to exceed obuflen
4766 * if copying the scanned character to obuf.
4767 * Returns the number of scanned (copied) bytes.
4769 * obuf - buffer to be copied the scanned character
4770 * obuflen - the size of obuf
4771 * buf - pointer to a buffer containing the message string
4772 * len - the length of the buffer
4774 size_t
4775 copy_frwd(char *obuf, const size_t obuflen,
4776 const char *buf, const size_t len)
4778 const char *p;
4779 char *q = obuf;
4780 size_t olen = 0;
4781 size_t mb_cur_max;
4782 pthread_t mythreadno;
4784 if (Debug) {
4785 mythreadno = pthread_self();
4788 if (len == 0) {
4789 return (0);
4792 mb_cur_max = MB_CUR_MAX;
4794 if (mb_cur_max == 1) {
4795 /* single-byte locale */
4796 if (obuflen > len) {
4797 (void) memcpy(obuf, buf, len);
4798 obuf[len] = '\0';
4799 return ((size_t)len);
4800 } else {
4801 (void) memcpy(obuf, buf, obuflen - 1);
4802 obuf[obuflen - 1] = '\0';
4803 return (obuflen - 1);
4805 } else {
4806 /* multi-byte locale */
4807 int mlen;
4809 for (p = buf; *p; ) {
4810 mlen = mblen(p, mb_cur_max);
4811 if (mlen == -1) {
4813 * Invalid character found.
4815 DPRINT1(9, "copy_frwd(%u): Invalid MB "
4816 "sequence\n", mythreadno);
4818 * handle as a single byte character.
4820 if (obuflen > olen + 1) {
4821 *q++ = *p++;
4822 olen++;
4823 } else {
4824 *q = '\0';
4825 return ((size_t)(p - buf));
4827 } else {
4828 if (obuflen > olen + mlen) {
4829 int n;
4830 for (n = 0; n < mlen; n++) {
4831 *q++ = *p++;
4833 olen += mlen;
4834 } else {
4835 *q = '\0';
4836 return ((size_t)(p - buf));
4840 *q = '\0';
4841 return ((size_t)(p - buf));
4846 * properties:
4847 * Get properties from SMF framework.
4849 static void
4850 properties(void)
4852 scf_simple_prop_t *prop;
4853 uint8_t *bool;
4855 if ((prop = scf_simple_prop_get(NULL, NULL, "config",
4856 "log_from_remote")) != NULL) {
4857 if ((bool = scf_simple_prop_next_boolean(prop)) != NULL) {
4858 if (*bool == 0)
4859 turnoff = 1; /* log_from_remote = false */
4860 else
4861 turnoff = 0; /* log_from_remote = true */
4863 scf_simple_prop_free(prop);
4864 DPRINT1(1, "properties: setting turnoff to %s\n",
4865 turnoff ? "true" : "false");
4870 * close all the input devices.
4872 static void
4873 shutdown_input(void)
4875 int cnt;
4877 shutting_down = 1;
4879 for (cnt = 0; cnt < Ninputs; cnt++) {
4880 (void) t_close(Nfd[cnt].fd);
4883 (void) close(Pfd.fd);
4887 * This is for the one thread that dedicates to resolve the
4888 * hostname. This will get the messages from net_poll() through
4889 * hnlq, and resolve the hostname, and push the messages back
4890 * into the inputq.
4892 /*ARGSUSED*/
4893 static void *
4894 hostname_lookup(void *ap)
4896 char *uap;
4897 log_message_t *mp;
4898 host_info_t *hip;
4899 char failsafe_addr[SYS_NMLN + 1];
4900 pthread_t mythreadno;
4902 if (Debug) {
4903 mythreadno = pthread_self();
4906 DPRINT1(1, "hostname_lookup(%u): hostname_lookup started\n",
4907 mythreadno);
4909 for (;;) {
4910 (void) dataq_dequeue(&hnlq, (void **)&mp, 0);
4912 DPRINT3(5, "hostname_lookup(%u): dequeued msg %p"
4913 " from queue %p\n", mythreadno, (void *)mp,
4914 (void *)&hnlq);
4916 hip = (host_info_t *)mp->ptr;
4917 if ((uap = taddr2uaddr(hip->ncp, &hip->addr)) != NULL) {
4918 (void) strlcpy(failsafe_addr, uap, SYS_NMLN);
4919 free(uap);
4920 } else {
4921 (void) strlcpy(failsafe_addr, "<unknown>", SYS_NMLN);
4924 mp->hlp = cvthname(&hip->addr, hip->ncp, failsafe_addr);
4926 if (mp->hlp == NULL) {
4927 mp->hlp = &NullHostName;
4930 free(hip->addr.buf);
4931 free(hip);
4932 mp->ptr = NULL;
4934 if (dataq_enqueue(&inputq, (void *)mp) == -1) {
4935 MALLOC_FAIL("dropping message from remote");
4936 free_msg(mp);
4937 continue;
4940 DPRINT3(5, "hostname_lookup(%u): enqueued msg %p on queue "
4941 "%p\n", mythreadno, (void *)mp, (void *)&inputq);
4944 /*NOTREACHED*/
4945 return (NULL);
4949 * Does all HUP(re-configuration) process.
4951 static void
4952 reconfigure()
4954 int cnt, loop, drops;
4955 int really_stuck;
4956 int console_stuck = 0;
4957 struct filed *f;
4958 char buf[LINE_MAX];
4959 struct utsname up;
4960 char cbuf[30];
4961 time_t tim;
4962 pthread_t mythreadno;
4964 if (Debug) {
4965 mythreadno = pthread_self();
4968 /* If we get here then we must need to regen */
4969 flushmsg(0);
4971 if (logmymsg(LOG_SYSLOG|LOG_INFO, "syslogd: configuration restart",
4972 ADDDATE, 0) == -1) {
4973 MALLOC_FAIL("dropping message");
4977 * make sure the logmsg thread is not in the waiting state.
4978 * Otherwise, changing hup_state will prevent the logmsg thread
4979 * getting out from the waiting loop.
4982 if (Debug) {
4983 tim = time(NULL);
4984 DPRINT2(3, "reconfigure(%u): %.15s: awaiting logmsg()"
4985 " moving to the safe place\n",
4986 mythreadno, ctime_r(&tim, cbuf)+4);
4989 for (loop = 0; loop < LOOP_MAX; loop++) {
4990 /* we don't need the mutex to read */
4991 if (hup_state == HUP_ACCEPTABLE)
4992 break;
4993 (void) sleep(1);
4995 if (hup_state != HUP_ACCEPTABLE) {
4996 goto thread_stuck;
4999 if (Debug) {
5000 tim = time(NULL);
5001 DPRINT2(3, "reconfigure(%u): %.15s: logmsg() will accept HUP\n",
5002 mythreadno, ctime_r(&tim, cbuf)+4);
5006 * Prevent logging until we are truly done processing the HUP
5008 (void) pthread_mutex_lock(&hup_lock);
5009 hup_state = HUP_INPROGRESS;
5010 (void) pthread_mutex_unlock(&hup_lock);
5013 * We will be going into a critical state. Any error message
5014 * from syslogd needs to be dumped to the console by default
5015 * immediately. Also, those error messages are quened in a temporary
5016 * queue to be able to post into the regular stream later.
5018 disable_errorlog();
5020 if (Debug) {
5021 tim = time(NULL);
5022 DPRINT2(3, "reconfigure(%u): %.15s: sending SHUTDOWN\n",
5023 mythreadno, ctime_r(&tim, cbuf)+4);
5026 /* stop configured threads */
5027 if (shutdown_msg() == -1) {
5029 * No memory, message will be dumped to the console.
5031 MALLOC_FAIL("unable to restart syslogd");
5032 goto out;
5035 /* make sure logmsg() is in suspended state */
5036 for (loop = 0; loop < LOOP_INTERVAL; loop++) {
5037 if (hup_state & HUP_LOGMSG_SUSPENDED)
5038 break;
5039 (void) sleep(1);
5042 if ((hup_state & HUP_LOGMSG_SUSPENDED) == 0) {
5043 if (Debug) {
5044 tim = time(NULL);
5045 DPRINT2(3, "reconfigure(%u): %.15s: logmsg() does not "
5046 "stop. enforcing\n",
5047 mythreadno, ctime_r(&tim, cbuf)+4);
5050 /* probably we have too long input queue, or really stuck */
5051 (void) pthread_mutex_lock(&hup_lock);
5052 hup_state |= HUP_SUSP_LOGMSG_REQD;
5053 (void) pthread_mutex_unlock(&hup_lock);
5055 for (loop = 0; loop < LOOP_MAX; loop++) {
5056 if (hup_state & HUP_LOGMSG_SUSPENDED)
5057 break;
5058 (void) sleep(1);
5060 if ((hup_state & HUP_LOGMSG_SUSPENDED) == 0) {
5061 if (Debug) {
5062 tim = time(NULL);
5063 DPRINT2(3, "reconfigure(%u): %.15s: logmsg()"
5064 " does not stop. give up\n",
5065 mythreadno, ctime_r(&tim, cbuf)+4);
5067 logerror("could not suspend logmsg - fatal");
5068 goto thread_stuck;
5072 if (Debug) {
5073 tim = time(NULL);
5074 DPRINT2(3, "reconfigure(%u): %.15s: logmsg() suspended\n",
5075 mythreadno, ctime_r(&tim, cbuf)+4);
5079 * Will wait for LOOP_MAX secs with watching queue lengths for the
5080 * each logger threads. If they have backlogs, and no change in the
5081 * length of queue found in 30 seconds, those will be counted as
5082 * "really stuck".
5083 * If all running logger threads become "really stuck" state, there
5084 * should be no worth waiting for them to quit.
5085 * In that case, we will go ahead and close out file descriptors to
5086 * have them pull out from hanging system call, and give them a last
5087 * chance(LOOP_INTERVAL sec) to quit.
5090 if (Debug) {
5091 tim = time(NULL);
5092 DPRINT2(3, "reconfigure(%u): %.15s: awaiting logit() to be"
5093 " shutdown\n", mythreadno, ctime_r(&tim, cbuf)+4);
5096 cnt = 0;
5097 really_stuck = 0;
5098 while (cnt < (LOOP_MAX/LOOP_INTERVAL) &&
5099 conf_threads > really_stuck) {
5101 /* save initial queue count */
5102 for (f = Files; f < &Files[nlogs]; f++) {
5103 f->f_prev_queue_count = (f->f_type == F_UNUSED) ?
5104 -1 : f->f_queue_count;
5107 for (loop = 0; loop < LOOP_INTERVAL; loop++) {
5108 if (conf_threads == 0)
5109 break;
5110 (void) sleep(1);
5113 if (conf_threads == 0)
5114 break;
5116 if (Debug) {
5117 tim = time(NULL);
5118 DPRINT3(3, "reconfigure(%u): %.15s: "
5119 "%d threads are still alive.\n",
5120 mythreadno, ctime_r(&tim, cbuf)+4,
5121 conf_threads);
5124 really_stuck = 0;
5125 for (f = Files; f < &Files[nlogs]; f++) {
5126 if (f->f_type == F_UNUSED) {
5127 f->f_prev_queue_count = -1;
5128 continue;
5130 if (f->f_prev_queue_count == f->f_queue_count) {
5131 really_stuck++;
5132 f->f_prev_queue_count = 1;
5133 DPRINT2(3, "reconfigure(%u): "
5134 "tid=%d is really stuck.\n",
5135 mythreadno, f->f_thread);
5136 } else {
5137 f->f_prev_queue_count = 0;
5138 DPRINT2(3, "reconfigure(%u): "
5139 "tid=%d is still active.\n",
5140 mythreadno, f->f_thread);
5144 * Here we have one of following values in the
5145 * f_prev_queue_count:
5146 * 0: logger thread is still actively working.
5147 * 1: logger thread is really stuck.
5148 * -1: logger thread has already died.
5151 cnt++;
5154 if (Debug) {
5155 tim = time(NULL);
5156 DPRINT2(3, "reconfigure(%u): %.15s:"
5157 " complete awaiting logit()\n",
5158 mythreadno, ctime_r(&tim, cbuf)+4);
5159 DPRINT3(3, "reconfigure(%u): %d threads alive."
5160 " %d threads stuck\n",
5161 mythreadno, conf_threads, really_stuck);
5165 * Still running? If so, mark it as UNUSED, and close
5166 * the fd so that logger threads can bail out from the loop.
5168 drops = 0;
5169 if (conf_threads) {
5170 for (f = Files; f < &Files[nlogs]; f++) {
5171 if (f->f_type == F_CONSOLE &&
5172 f->f_prev_queue_count == 1) {
5173 /* console is really stuck */
5174 console_stuck = 1;
5176 if (f->f_type == F_USERS || f->f_type == F_WALL ||
5177 f->f_type == F_UNUSED)
5178 continue;
5179 cnt = f->f_queue_count;
5180 drops += (cnt > 0) ? cnt - 1: 0;
5181 f->f_type = F_UNUSED;
5183 if (f->f_orig_type == F_FORW)
5184 (void) t_close(f->f_file);
5185 else
5186 (void) close(f->f_file);
5189 if (Debug) {
5190 tim = time(NULL);
5191 DPRINT1(3, "reconfigure(%u): terminating logit()\n",
5192 mythreadno);
5195 /* last chance to exit */
5196 for (loop = 0; loop < LOOP_MAX; loop++) {
5197 if (conf_threads == 0)
5198 break;
5199 (void) sleep(1);
5202 if (Debug) {
5203 tim = time(NULL);
5204 DPRINT3(3, "reconfigure(%u): %.15s: %d alive\n",
5205 mythreadno, ctime_r(&tim, cbuf)+4,
5206 conf_threads);
5210 if (conf_threads == 0 && drops) {
5211 errno = 0;
5212 logerror("Could not completely output pending messages"
5213 " while preparing re-configuration");
5214 logerror("discarded %d messages and restart configuration.",
5215 drops);
5216 if (Debug) {
5217 tim = time(NULL);
5218 DPRINT3(3, "reconfigure(%u): %.15s: "
5219 "discarded %d messages\n",
5220 mythreadno, ctime_r(&tim, cbuf)+4, drops);
5225 * If all threads still haven't exited
5226 * something is stuck or hosed. We just
5227 * have no option but to exit.
5229 if (conf_threads) {
5230 thread_stuck:
5231 if (Debug) {
5232 tim = time(NULL);
5233 DPRINT2(3, "reconfigure(%u): %.15s: really stuck\n",
5234 mythreadno, ctime_r(&tim, cbuf)+4);
5237 shutdown_input();
5238 delete_doorfiles();
5239 (void) uname(&up);
5241 (void) snprintf(buf, sizeof (buf),
5242 "syslogd(%s): some logger thread(s) "
5243 "are stuck%s; syslogd is shutting down.",
5244 up.nodename,
5245 console_stuck ? " (including the console)" : "");
5247 if (console_stuck) {
5248 FILE *m = popen(MAILCMD, "w");
5250 if (m != NULL) {
5251 (void) fprintf(m, "%s\n", buf);
5252 (void) pclose(m);
5256 disable_errorlog();
5257 logerror(buf);
5258 exit(1);
5261 /* Free up some resources */
5262 if (Files != (struct filed *)&fallback) {
5263 for (f = Files; f < &Files[nlogs]; f++) {
5264 (void) pthread_join(f->f_thread, NULL);
5265 filed_destroy(f);
5267 free(Files);
5270 dealloc_stacks(nlogs);
5272 if (Debug) {
5273 tim = time(NULL);
5274 DPRINT2(3, "reconfigure(%u): %.15s: cleanup complete\n",
5275 mythreadno, ctime_r(&tim, cbuf)+4);
5278 hnc_init(1); /* purge hostname cache */
5279 conf_init(); /* start reconfigure */
5281 out:;
5282 /* Now should be ready to dispatch error messages from syslogd. */
5283 enable_errorlog();
5285 /* Wake up the log thread */
5287 if (Debug) {
5288 tim = time(NULL);
5289 DPRINT2(3, "reconfigure(%u): %.15s: resuming logmsg()\n",
5290 mythreadno, ctime_r(&tim, cbuf)+4);
5293 (void) pthread_mutex_lock(&hup_lock);
5294 hup_state = HUP_COMPLETED;
5295 (void) pthread_cond_signal(&hup_done);
5296 (void) pthread_mutex_unlock(&hup_lock);
5300 * The following function implements simple hostname cache mechanism.
5301 * Host name cache is implemented through hash table bucket chaining method.
5302 * Collisions are handled by bucket chaining.
5304 * hnc_init():
5305 * allocate and initialize the cache. If reinit is set,
5306 * invalidate all cache entries.
5307 * hnc_look():
5308 * It hashes the ipaddress gets the index and walks thru the
5309 * single linked list. if cached entry was found, it will
5310 * put in the head of the list, and return.While going through
5311 * the entries, an entry which has already expired will be invalidated.
5312 * hnc_register():
5313 * Hashes the ipaddress finds the index and puts current entry to the list.
5314 * hnc_unreg():
5315 * invalidate the cachep.
5318 static void
5319 hnc_init(int reinit)
5321 struct hostname_cache **hpp;
5322 pthread_t mythreadno;
5323 int i;
5325 if (Debug) {
5326 mythreadno = pthread_self();
5329 if (reinit) {
5330 (void) pthread_mutex_lock(&hnc_mutex);
5332 for (i = 0; i < hnc_size; i++) {
5333 for (hpp = &hnc_cache[i]; *hpp != NULL; ) {
5334 hnc_unreg(hpp);
5338 (void) pthread_mutex_unlock(&hnc_mutex);
5339 DPRINT1(2, "hnc_init(%u): hostname cache re-configured\n",
5340 mythreadno);
5341 } else {
5343 hnc_cache = calloc(hnc_size, sizeof (struct hostname_cache *));
5345 if (hnc_cache == NULL) {
5346 MALLOC_FAIL("hostname cache");
5347 logerror("hostname cache disabled");
5348 return;
5351 DPRINT3(1, "hnc_init(%u): hostname cache configured %d entry"
5352 " ttl:%d\n", mythreadno, hnc_size, hnc_ttl);
5356 static host_list_t *
5357 hnc_lookup(struct netbuf *nbp, struct netconfig *ncp, int *hindex)
5359 struct hostname_cache **hpp, *hp;
5360 time_t now;
5361 pthread_t mythreadno;
5362 int index;
5364 if (Debug) {
5365 mythreadno = pthread_self();
5368 if (hnc_cache == NULL) {
5369 return (NULL);
5372 (void) pthread_mutex_lock(&hnc_mutex);
5373 now = time(0);
5375 *hindex = index = addr_hash(nbp);
5377 for (hpp = &hnc_cache[index]; (hp = *hpp) != NULL; ) {
5378 DPRINT4(10, "hnc_lookup(%u): check %p on %p for %s\n",
5379 mythreadno, (void *)hp->h, (void *)hp,
5380 hp->h->hl_hosts[0]);
5382 if (hp->expire < now) {
5383 DPRINT2(9, "hnc_lookup(%u): purge %p\n",
5384 mythreadno, (void *)hp);
5385 hnc_unreg(hpp);
5386 continue;
5389 if (ncp == hp->ncp && same_addr(&hp->addr, nbp)) {
5391 * found!
5392 * Put the entry at the top.
5395 if (hp != hnc_cache[index]) {
5396 /* unlink from active list */
5397 *hpp = (*hpp)->next;
5398 /* push it onto the top */
5399 hp->next = hnc_cache[index];
5400 hnc_cache[index] = hp;
5403 (void) pthread_mutex_lock(&hp->h->hl_mutex);
5404 hp->h->hl_refcnt++;
5405 (void) pthread_mutex_unlock(&hp->h->hl_mutex);
5407 DPRINT4(9, "hnc_lookup(%u): found %p on %p for %s\n",
5408 mythreadno, (void *)hp->h, (void *)hp,
5409 hp->h->hl_hosts[0]);
5411 (void) pthread_mutex_unlock(&hnc_mutex);
5412 return (hp->h);
5415 hpp = &hp->next;
5418 (void) pthread_mutex_unlock(&hnc_mutex);
5419 return (NULL);
5422 static void
5423 hnc_register(struct netbuf *nbp, struct netconfig *ncp,
5424 host_list_t *h, int hindex)
5426 struct hostname_cache **hpp, **tailp, *hp, *entry;
5427 void *addrbuf;
5428 time_t now;
5429 pthread_t mythreadno;
5430 int i;
5432 if (Debug) {
5433 mythreadno = pthread_self();
5436 if (hnc_cache == NULL) {
5437 return;
5440 if ((addrbuf = malloc(nbp->len)) == NULL) {
5441 MALLOC_FAIL("pushing hostname cache");
5442 return;
5445 if ((entry = malloc(sizeof (struct hostname_cache))) == NULL) {
5446 MALLOC_FAIL("pushing hostname entry");
5447 free(addrbuf);
5448 return;
5451 (void) pthread_mutex_lock(&hnc_mutex);
5453 i = 0;
5455 now = time(0);
5457 * first go through active list, and discard the
5458 * caches which has been invalid. Count number of
5459 * non-expired buckets.
5462 for (hpp = &hnc_cache[hindex]; (hp = *hpp) != NULL; ) {
5463 tailp = hpp;
5465 if (hp->expire < now) {
5466 DPRINT2(9, "hnc_register(%u): discard %p\n",
5467 mythreadno, (void *)hp);
5468 hnc_unreg(hpp);
5469 } else {
5470 i++;
5471 hpp = &hp->next;
5476 * If max limit of chained hash buckets has been used up
5477 * delete the least active element in the chain.
5479 if (i == MAX_BUCKETS) {
5480 hnc_unreg(tailp);
5483 (void) memcpy(addrbuf, nbp->buf, nbp->len);
5484 entry->addr.len = nbp->len;
5485 entry->addr.buf = addrbuf;
5486 entry->ncp = ncp;
5487 entry->h = h;
5488 entry->expire = time(NULL) + hnc_ttl;
5490 /* insert it at the top */
5491 entry->next = hnc_cache[hindex];
5492 hnc_cache[hindex] = entry;
5495 * As far as cache is valid, corresponding host_list must
5496 * also be valid. Increments the refcnt to avoid freeing
5497 * host_list.
5499 h->hl_refcnt++;
5500 DPRINT4(9, "hnc_register(%u): reg %p onto %p for %s\n",
5501 mythreadno, (void *)entry->h, (void *)entry, entry->h->hl_hosts[0]);
5502 (void) pthread_mutex_unlock(&hnc_mutex);
5505 static void
5506 hnc_unreg(struct hostname_cache **hpp)
5508 struct hostname_cache *hp = *hpp;
5509 pthread_t mythreadno;
5511 if (Debug) {
5512 mythreadno = pthread_self();
5515 DPRINT4(9, "hnc_unreg(%u): unreg %p on %p for %s\n",
5516 mythreadno, (void *)hp->h, (void *)hp, hp->h->hl_hosts[0]);
5517 free(hp->addr.buf);
5518 freehl(hp->h);
5520 /* unlink from active list */
5521 *hpp = (*hpp)->next;
5523 free(hp);
5527 * Once this is called, error messages through logerror() will go to
5528 * the console immediately. Also, messages are queued into the tmpq
5529 * to be able to later put them into inputq.
5531 static void
5532 disable_errorlog()
5534 (void) dataq_init(&tmpq);
5536 (void) pthread_mutex_lock(&logerror_lock);
5537 interrorlog = 0;
5538 (void) pthread_mutex_unlock(&logerror_lock);
5542 * Turn internal error messages to regular input stream.
5543 * All pending messages are pulled and pushed into the regular
5544 * input queue.
5546 static void
5547 enable_errorlog()
5549 log_message_t *mp;
5551 (void) pthread_mutex_lock(&logerror_lock);
5552 interrorlog = 1;
5553 (void) pthread_mutex_unlock(&logerror_lock);
5556 * push all the pending messages into inputq.
5558 while (dataq_dequeue(&tmpq, (void **)&mp, 1) == 0) {
5559 (void) dataq_enqueue(&inputq, mp);
5561 (void) dataq_destroy(&tmpq);
5565 * Generate a hash value of the given address and derive
5566 * an index into the hnc_cache hashtable.
5567 * The hashing method is similar to what Java does for strings.
5569 static int
5570 addr_hash(struct netbuf *nbp)
5572 char *uap;
5573 int i;
5574 unsigned long hcode = 0;
5576 uap = nbp->buf;
5578 if (uap == NULL) {
5579 return (0);
5583 * Compute a hashcode of the address string
5585 for (i = 0; i < nbp->len; i++)
5586 hcode = (31 * hcode) + uap[i];
5589 * Scramble the hashcode for better distribution
5591 hcode += ~(hcode << 9);
5592 hcode ^= (hcode >> 14);
5593 hcode += (hcode << 4);
5594 hcode ^= (hcode >> 10);
5596 return ((int)(hcode % hnc_size));