logger.c revision 169344
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#if 0
41#ifndef lint
42static char sccsid[] = "@(#)logger.c	8.1 (Berkeley) 6/6/93";
43#endif /* not lint */
44#endif
45
46#include <sys/cdefs.h>
47__FBSDID("$FreeBSD: head/usr.bin/logger/logger.c 169344 2007-05-07 11:28:01Z 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, const char *, const char *, const 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(int argc, char *argv[])
90{
91	int ch, logflags, pri;
92	char *tag, *host, buf[1024];
93	const char *svcname;
94
95	tag = NULL;
96	host = NULL;
97	svcname = "syslog";
98	pri = LOG_USER | LOG_NOTICE;
99	logflags = 0;
100	unsetenv("TZ");
101	while ((ch = getopt(argc, argv, "46Af:h:iP:p: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':		/* service name or port number */
125			svcname = optarg;
126			break;
127		case 'p':		/* priority */
128			pri = pencode(optarg);
129			break;
130		case 's':		/* log to standard error */
131			logflags |= LOG_PERROR;
132			break;
133		case 't':		/* tag */
134			tag = optarg;
135			break;
136		case '?':
137		default:
138			usage();
139		}
140	argc -= optind;
141	argv += optind;
142
143	/* setup for logging */
144	openlog(tag ? tag : getlogin(), logflags, 0);
145	(void) fclose(stdout);
146
147	/* log input line if appropriate */
148	if (argc > 0) {
149		char *p, *endp;
150		size_t len;
151
152		for (p = buf, endp = buf + sizeof(buf) - 2; *argv;) {
153			len = strlen(*argv);
154			if (p + len > endp && p > buf) {
155				logmessage(pri, host, svcname, buf);
156				p = buf;
157			}
158			if (len > sizeof(buf) - 1)
159				logmessage(pri, host, svcname, *argv++);
160			else {
161				if (p != buf)
162					*p++ = ' ';
163				bcopy(*argv++, p, len);
164				*(p += len) = '\0';
165			}
166		}
167		if (p != buf)
168			logmessage(pri, host, svcname, buf);
169	} else
170		while (fgets(buf, sizeof(buf), stdin) != NULL)
171			logmessage(pri, host, svcname, buf);
172	exit(0);
173}
174
175/*
176 *  Send the message to syslog, either on the local host, or on a remote host
177 */
178void
179logmessage(int pri, const char *host, const char *svcname, const char *buf)
180{
181	static struct socks *socks;
182	static int nsock = 0;
183	struct addrinfo hints, *res, *r;
184	char *line;
185	int maxs, len, sock, error, i, lsent;
186
187	if (host == NULL) {
188		syslog(pri, "%s", buf);
189		return;
190	}
191
192	if (nsock <= 0) {	/* set up socket stuff */
193		/* resolve hostname */
194		memset(&hints, 0, sizeof(hints));
195		hints.ai_family = family;
196		hints.ai_socktype = SOCK_DGRAM;
197		error = getaddrinfo(host, svcname, &hints, &res);
198		if (error == EAI_SERVICE) {
199			warnx("%s/udp: unknown service", svcname);
200			error = getaddrinfo(host, "514", &hints, &res);
201		}
202		if (error)
203			errx(1, "%s: %s", gai_strerror(error), host);
204		/* count max number of sockets we may open */
205		for (maxs = 0, r = res; r; r = r->ai_next, maxs++);
206		socks = malloc(maxs * sizeof(struct socks));
207		if (!socks)
208			errx(1, "couldn't allocate memory for sockets");
209		for (r = res; r; r = r->ai_next) {
210			sock = socket(r->ai_family, r->ai_socktype,
211				      r->ai_protocol);
212			if (sock < 0)
213				continue;
214			memcpy(&socks[nsock].addr, r->ai_addr, r->ai_addrlen);
215			socks[nsock].addrlen = r->ai_addrlen;
216			socks[nsock++].sock = sock;
217		}
218		freeaddrinfo(res);
219		if (nsock <= 0)
220			errx(1, "socket");
221	}
222
223	if ((len = asprintf(&line, "<%d>%s", pri, buf)) == -1)
224		errx(1, "asprintf");
225
226	lsent = -1;
227	for (i = 0; i < nsock; ++i) {
228		lsent = sendto(socks[i].sock, line, len, 0,
229			       (struct sockaddr *)&socks[i].addr,
230			       socks[i].addrlen);
231		if (lsent == len && !send_to_all)
232			break;
233	}
234	if (lsent != len) {
235		if (lsent == -1)
236			warn ("sendto");
237		else
238			warnx ("sendto: short send - %d bytes", lsent);
239	}
240
241	free(line);
242}
243
244/*
245 *  Decode a symbolic name to a numeric value
246 */
247int
248pencode(char *s)
249{
250	char *save;
251	int fac, lev;
252
253	for (save = s; *s && *s != '.'; ++s);
254	if (*s) {
255		*s = '\0';
256		fac = decode(save, facilitynames);
257		if (fac < 0)
258			errx(1, "unknown facility name: %s", save);
259		*s++ = '.';
260	}
261	else {
262		fac = 0;
263		s = save;
264	}
265	lev = decode(s, prioritynames);
266	if (lev < 0)
267		errx(1, "unknown priority name: %s", save);
268	return ((lev & LOG_PRIMASK) | (fac & LOG_FACMASK));
269}
270
271int
272decode(char *name, CODE *codetab)
273{
274	CODE *c;
275
276	if (isdigit(*name))
277		return (atoi(name));
278
279	for (c = codetab; c->c_name; c++)
280		if (!strcasecmp(name, c->c_name))
281			return (c->c_val);
282
283	return (-1);
284}
285
286static void
287usage(void)
288{
289	(void)fprintf(stderr, "usage: %s\n",
290	    "logger [-46Ais] [-f file] [-h host] [-P port] [-p pri] [-t tag]\n"
291	    "              [message ...]"
292	    );
293	exit(1);
294}
295