logger.c revision 160917
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 160917 2006-08-02 13:21:44Z bms $");
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 *, 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, *svcname, buf[1024];
93
94	tag = NULL;
95	host = NULL;
96	svcname = "syslog";
97	pri = LOG_USER | LOG_NOTICE;
98	logflags = 0;
99	unsetenv("TZ");
100	while ((ch = getopt(argc, argv, "46Af:h:iP:p:st:")) != -1)
101		switch((char)ch) {
102		case '4':
103			family = PF_INET;
104			break;
105#ifdef INET6
106		case '6':
107			family = PF_INET6;
108			break;
109#endif
110		case 'A':
111			send_to_all++;
112			break;
113		case 'f':		/* file to log */
114			if (freopen(optarg, "r", stdin) == NULL)
115				err(1, "%s", optarg);
116			break;
117		case 'h':		/* hostname to deliver to */
118			host = optarg;
119			break;
120		case 'i':		/* log process id also */
121			logflags |= LOG_PID;
122			break;
123		case 'P':		/* service name or port number */
124			svcname = optarg;
125			break;
126		case 'p':		/* priority */
127			pri = pencode(optarg);
128			break;
129		case 's':		/* log to standard error */
130			logflags |= LOG_PERROR;
131			break;
132		case 't':		/* tag */
133			tag = optarg;
134			break;
135		case '?':
136		default:
137			usage();
138		}
139	argc -= optind;
140	argv += optind;
141
142	/* setup for logging */
143	openlog(tag ? tag : getlogin(), logflags, 0);
144	(void) fclose(stdout);
145
146	/* log input line if appropriate */
147	if (argc > 0) {
148		char *p, *endp;
149		size_t len;
150
151		for (p = buf, endp = buf + sizeof(buf) - 2; *argv;) {
152			len = strlen(*argv);
153			if (p + len > endp && p > buf) {
154				logmessage(pri, host, svcname, buf);
155				p = buf;
156			}
157			if (len > sizeof(buf) - 1)
158				logmessage(pri, host, svcname, *argv++);
159			else {
160				if (p != buf)
161					*p++ = ' ';
162				bcopy(*argv++, p, len);
163				*(p += len) = '\0';
164			}
165		}
166		if (p != buf)
167			logmessage(pri, host, svcname, buf);
168	} else
169		while (fgets(buf, sizeof(buf), stdin) != NULL)
170			logmessage(pri, host, svcname, buf);
171	exit(0);
172}
173
174/*
175 *  Send the message to syslog, either on the local host, or on a remote host
176 */
177void
178logmessage(int pri, char *host, char *svcname, char *buf)
179{
180	static struct socks *socks;
181	static int nsock = 0;
182	struct addrinfo hints, *res, *r;
183	char *line;
184	int maxs, len, sock, error, i, lsent;
185
186	if (host == NULL) {
187		syslog(pri, "%s", buf);
188		return;
189	}
190
191	if (nsock <= 0) {	/* set up socket stuff */
192		/* resolve hostname */
193		memset(&hints, 0, sizeof(hints));
194		hints.ai_family = family;
195		hints.ai_socktype = SOCK_DGRAM;
196		error = getaddrinfo(host, svcname, &hints, &res);
197		if (error == EAI_SERVICE) {
198			warnx("%s/udp: unknown service", svcname);
199			error = getaddrinfo(host, "514", &hints, &res);
200		}
201		if (error)
202			errx(1, "%s: %s", gai_strerror(error), host);
203		/* count max number of sockets we may open */
204		for (maxs = 0, r = res; r; r = r->ai_next, maxs++);
205		socks = malloc(maxs * sizeof(struct socks));
206		if (!socks)
207			errx(1, "couldn't allocate memory for sockets");
208		for (r = res; r; r = r->ai_next) {
209			sock = socket(r->ai_family, r->ai_socktype,
210				      r->ai_protocol);
211			if (sock < 0)
212				continue;
213			memcpy(&socks[nsock].addr, r->ai_addr, r->ai_addrlen);
214			socks[nsock].addrlen = r->ai_addrlen;
215			socks[nsock++].sock = sock;
216		}
217		freeaddrinfo(res);
218		if (nsock <= 0)
219			errx(1, "socket");
220	}
221
222	if ((len = asprintf(&line, "<%d>%s", pri, buf)) == -1)
223		errx(1, "asprintf");
224
225	lsent = -1;
226	for (i = 0; i < nsock; ++i) {
227		lsent = sendto(socks[i].sock, line, len, 0,
228			       (struct sockaddr *)&socks[i].addr,
229			       socks[i].addrlen);
230		if (lsent == len && !send_to_all)
231			break;
232	}
233	if (lsent != len) {
234		if (lsent == -1)
235			warn ("sendto");
236		else
237			warnx ("sendto: short send - %d bytes", lsent);
238	}
239
240	free(line);
241}
242
243/*
244 *  Decode a symbolic name to a numeric value
245 */
246int
247pencode(char *s)
248{
249	char *save;
250	int fac, lev;
251
252	for (save = s; *s && *s != '.'; ++s);
253	if (*s) {
254		*s = '\0';
255		fac = decode(save, facilitynames);
256		if (fac < 0)
257			errx(1, "unknown facility name: %s", save);
258		*s++ = '.';
259	}
260	else {
261		fac = 0;
262		s = save;
263	}
264	lev = decode(s, prioritynames);
265	if (lev < 0)
266		errx(1, "unknown priority name: %s", save);
267	return ((lev & LOG_PRIMASK) | (fac & LOG_FACMASK));
268}
269
270int
271decode(char *name, CODE *codetab)
272{
273	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(void)
287{
288	(void)fprintf(stderr, "usage: %s\n",
289	    "logger [-46Ais] [-f file] [-h host] [-P port] [-p pri] [-t tag]\n"
290	    "              [message ...]"
291	    );
292	exit(1);
293}
294