logger.c revision 93525
1/*
2 * Copyright (c) 1983, 1993
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 *    must display the following acknowledgement:
15 *	This product includes software developed by the University of
16 *	California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 *    may be used to endorse or promote products derived from this software
19 *    without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 */
33
34#ifndef lint
35static const char copyright[] =
36"@(#) Copyright (c) 1983, 1993\n\
37	The Regents of the University of California.  All rights reserved.\n";
38#endif /* not lint */
39
40#ifndef lint
41#if 0
42static char sccsid[] = "@(#)logger.c	8.1 (Berkeley) 6/6/93";
43#endif
44#endif /* not lint */
45
46#include <sys/cdefs.h>
47__FBSDID("$FreeBSD: head/usr.bin/logger/logger.c 93525 2002-04-01 11:06:00Z dwmalone $");
48
49#include <sys/types.h>
50#include <sys/socket.h>
51#include <netinet/in.h>
52
53#include <ctype.h>
54#include <err.h>
55#include <netdb.h>
56#include <stdio.h>
57#include <stdlib.h>
58#include <string.h>
59#include <unistd.h>
60
61#define	SYSLOG_NAMES
62#include <syslog.h>
63
64int	decode(char *, CODE *);
65int	pencode(char *);
66static void	logmessage(int, char *, char *);
67static void	usage(void);
68
69struct socks {
70    int sock;
71    int addrlen;
72    struct sockaddr_storage addr;
73};
74
75#ifdef INET6
76int	family = PF_UNSPEC;	/* protocol family (IPv4, IPv6 or both) */
77#else
78int	family = PF_INET;	/* protocol family (IPv4 only) */
79#endif
80int	send_to_all = 0;	/* send message to all IPv4/IPv6 addresses */
81
82/*
83 * logger -- read and log utility
84 *
85 *	Reads from an input and arranges to write the result on the system
86 *	log.
87 */
88int
89main(argc, argv)
90	int argc;
91	char *argv[];
92{
93	int ch, logflags, pri;
94	char *tag, *host, buf[1024];
95
96	tag = NULL;
97	host = NULL;
98	pri = LOG_USER | LOG_NOTICE;
99	logflags = 0;
100	unsetenv("TZ");
101	while ((ch = getopt(argc, argv, "46Af:h:ip:st:")) != -1)
102		switch((char)ch) {
103		case '4':
104			family = PF_INET;
105			break;
106#ifdef INET6
107		case '6':
108			family = PF_INET6;
109			break;
110#endif
111		case 'A':
112			send_to_all++;
113			break;
114		case 'f':		/* file to log */
115			if (freopen(optarg, "r", stdin) == NULL)
116				err(1, "%s", optarg);
117			break;
118		case 'h':		/* hostname to deliver to */
119			host = optarg;
120			break;
121		case 'i':		/* log process id also */
122			logflags |= LOG_PID;
123			break;
124		case 'p':		/* priority */
125			pri = pencode(optarg);
126			break;
127		case 's':		/* log to standard error */
128			logflags |= LOG_PERROR;
129			break;
130		case 't':		/* tag */
131			tag = optarg;
132			break;
133		case '?':
134		default:
135			usage();
136		}
137	argc -= optind;
138	argv += optind;
139
140	/* setup for logging */
141	openlog(tag ? tag : getlogin(), logflags, 0);
142	(void) fclose(stdout);
143
144	/* log input line if appropriate */
145	if (argc > 0) {
146		register char *p, *endp;
147		size_t len;
148
149		for (p = buf, endp = buf + sizeof(buf) - 2; *argv;) {
150			len = strlen(*argv);
151			if (p + len > endp && p > buf) {
152				logmessage(pri, host, buf);
153				p = buf;
154			}
155			if (len > sizeof(buf) - 1)
156				logmessage(pri, host, *argv++);
157			else {
158				if (p != buf)
159					*p++ = ' ';
160				bcopy(*argv++, p, len);
161				*(p += len) = '\0';
162			}
163		}
164		if (p != buf)
165			logmessage(pri, host, buf);
166	} else
167		while (fgets(buf, sizeof(buf), stdin) != NULL)
168			logmessage(pri, host, buf);
169	exit(0);
170}
171
172/*
173 *  Send the message to syslog, either on the local host, or on a remote host
174 */
175void
176logmessage(int pri, char *host, char *buf)
177{
178	static struct socks *socks;
179	static int nsock = 0;
180	struct addrinfo hints, *res, *r;
181	char *line;
182	int maxs, len, sock, error, i, lsent;
183
184	if (host == NULL) {
185		syslog(pri, "%s", buf);
186		return;
187	}
188
189	if (nsock <= 0) {	/* set up socket stuff */
190		/* resolve hostname */
191		memset(&hints, 0, sizeof(hints));
192		hints.ai_family = family;
193		hints.ai_socktype = SOCK_DGRAM;
194		error = getaddrinfo(host, "syslog", &hints, &res);
195		if (error == EAI_SERVICE) {
196			warnx ("syslog/udp: unknown service");	/* not fatal */
197			error = getaddrinfo(host, "514", &hints, &res);
198		}
199		if (error)
200			errx(1, "%s: %s", gai_strerror(error), host);
201		/* count max number of sockets we may open */
202		for (maxs = 0, r = res; r; r = r->ai_next, maxs++);
203		socks = malloc(maxs * sizeof(struct socks));
204		if (!socks)
205			errx(1, "couldn't allocate memory for sockets");
206		for (r = res; r; r = r->ai_next) {
207			sock = socket(r->ai_family, r->ai_socktype,
208				      r->ai_protocol);
209			if (sock < 0)
210				continue;
211			memcpy(&socks[nsock].addr, r->ai_addr, r->ai_addrlen);
212			socks[nsock].addrlen = r->ai_addrlen;
213			socks[nsock++].sock = sock;
214		}
215		freeaddrinfo(res);
216		if (nsock <= 0)
217			errx(1, "socket");
218	}
219
220	if ((len = asprintf(&line, "<%d>%s", pri, buf)) == -1)
221		errx(1, "asprintf");
222
223	for (i = 0; i < nsock; ++i) {
224		lsent = sendto(socks[i].sock, line, len, 0,
225			       (struct sockaddr *)&socks[i].addr,
226			       socks[i].addrlen);
227		if (lsent == len && !send_to_all)
228			break;
229	}
230	if (lsent != len) {
231		if (lsent == -1)
232			warn ("sendto");
233		else
234			warnx ("sendto: short send - %d bytes", lsent);
235	}
236
237	free(line);
238}
239
240/*
241 *  Decode a symbolic name to a numeric value
242 */
243int
244pencode(s)
245	register char *s;
246{
247	char *save;
248	int fac, lev;
249
250	for (save = s; *s && *s != '.'; ++s);
251	if (*s) {
252		*s = '\0';
253		fac = decode(save, facilitynames);
254		if (fac < 0)
255			errx(1, "unknown facility name: %s", save);
256		*s++ = '.';
257	}
258	else {
259		fac = 0;
260		s = save;
261	}
262	lev = decode(s, prioritynames);
263	if (lev < 0)
264		errx(1, "unknown priority name: %s", save);
265	return ((lev & LOG_PRIMASK) | (fac & LOG_FACMASK));
266}
267
268int
269decode(name, codetab)
270	char *name;
271	CODE *codetab;
272{
273	register CODE *c;
274
275	if (isdigit(*name))
276		return (atoi(name));
277
278	for (c = codetab; c->c_name; c++)
279		if (!strcasecmp(name, c->c_name))
280			return (c->c_val);
281
282	return (-1);
283}
284
285static void
286usage()
287{
288	(void)fprintf(stderr, "usage: %s\n",
289	    "logger [-46Ais] [-f file] [-h host] [-p pri] [-t tag] [message ...]"
290	    );
291	exit(1);
292}
293