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: src/usr.bin/logger/logger.c,v 1.17 2008/02/05 17:34:44 obrien Exp $");
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 *);
66#ifndef __APPLE__
67static void	logmessage(int, const char *, const char *, const char *);
68#endif
69static void	usage(void);
70
71struct socks {
72    int sock;
73    int addrlen;
74    struct sockaddr_storage addr;
75};
76
77#ifdef INET6
78int	family = PF_UNSPEC;	/* protocol family (IPv4, IPv6 or both) */
79#else
80int	family = PF_INET;	/* protocol family (IPv4 only) */
81#endif
82int	send_to_all = 0;	/* send message to all IPv4/IPv6 addresses */
83
84/*
85 * logger -- read and log utility
86 *
87 *	Reads from an input and arranges to write the result on the system
88 *	log.
89 */
90int
91main(int argc, char *argv[])
92{
93	int ch, logflags, pri;
94	char *tag, *host, buf[1024];
95	const char *svcname;
96
97	tag = NULL;
98	host = NULL;
99	svcname = "syslog";
100	pri = LOG_USER | LOG_NOTICE;
101	logflags = 0;
102	unsetenv("TZ");
103#ifdef __APPLE__
104	while ((ch = getopt(argc, argv, "f:ip:st:")) != -1)
105#else
106	while ((ch = getopt(argc, argv, "46Af:h:iP:p:st:")) != -1)
107#endif
108		switch((char)ch) {
109#ifndef __APPLE__
110		case '4':
111			family = PF_INET;
112			break;
113#ifdef INET6
114		case '6':
115			family = PF_INET6;
116			break;
117#endif
118		case 'A':
119			send_to_all++;
120			break;
121#endif /* __APPLE__ */
122		case 'f':		/* file to log */
123			if (freopen(optarg, "r", stdin) == NULL)
124				err(1, "%s", optarg);
125			break;
126#ifndef __APPLE__
127		case 'h':		/* hostname to deliver to */
128			host = optarg;
129			break;
130#endif /* __APPLE__ */
131		case 'i':		/* log process id also */
132			logflags |= LOG_PID;
133			break;
134#ifndef __APPLE__
135		case 'P':		/* service name or port number */
136			svcname = optarg;
137			break;
138#endif /* __APPLE__ */
139		case 'p':		/* priority */
140			pri = pencode(optarg);
141			break;
142		case 's':		/* log to standard error */
143			logflags |= LOG_PERROR;
144			break;
145		case 't':		/* tag */
146			tag = optarg;
147			break;
148		case '?':
149		default:
150			usage();
151		}
152	argc -= optind;
153	argv += optind;
154
155	/* setup for logging */
156	openlog(tag ? tag : getlogin(), logflags, 0);
157	(void) fclose(stdout);
158
159	/* log input line if appropriate */
160	if (argc > 0) {
161		char *p, *endp;
162		size_t len;
163
164		for (p = buf, endp = buf + sizeof(buf) - 2; *argv;) {
165			len = strlen(*argv);
166			if (p + len > endp && p > buf) {
167#ifdef __APPLE__
168				syslog(pri, "%s", buf);
169#else
170				logmessage(pri, host, svcname, buf);
171#endif
172				p = buf;
173			}
174			if (len > sizeof(buf) - 1)
175#ifdef __APPLE__
176				syslog(pri, "%s", *argv++);
177#else
178				logmessage(pri, host, svcname, *argv++);
179#endif
180			else {
181				if (p != buf)
182					*p++ = ' ';
183				bcopy(*argv++, p, len);
184				*(p += len) = '\0';
185			}
186		}
187		if (p != buf)
188#ifdef __APPLE__
189			syslog(pri, "%s", buf);
190#else
191			logmessage(pri, host, svcname, buf);
192#endif
193	} else
194		while (fgets(buf, sizeof(buf), stdin) != NULL)
195#ifdef __APPLE__
196			syslog(pri, "%s", buf);
197#else
198			logmessage(pri, host, svcname, buf);
199#endif
200	exit(0);
201}
202
203#ifndef __APPLE__
204/*
205 *  Send the message to syslog, either on the local host, or on a remote host
206 */
207void
208logmessage(int pri, const char *host, const char *svcname, const char *buf)
209{
210	static struct socks *socks;
211	static int nsock = 0;
212	struct addrinfo hints, *res, *r;
213	char *line;
214	int maxs, len, sock, error, i, lsent;
215
216	if (host == NULL) {
217		syslog(pri, "%s", buf);
218		return;
219	}
220
221	if (nsock <= 0) {	/* set up socket stuff */
222		/* resolve hostname */
223		memset(&hints, 0, sizeof(hints));
224		hints.ai_family = family;
225		hints.ai_socktype = SOCK_DGRAM;
226		error = getaddrinfo(host, svcname, &hints, &res);
227		if (error == EAI_SERVICE) {
228			warnx("%s/udp: unknown service", svcname);
229			error = getaddrinfo(host, "514", &hints, &res);
230		}
231		if (error)
232			errx(1, "%s: %s", gai_strerror(error), host);
233		/* count max number of sockets we may open */
234		for (maxs = 0, r = res; r; r = r->ai_next, maxs++);
235		socks = malloc(maxs * sizeof(struct socks));
236		if (!socks)
237			errx(1, "couldn't allocate memory for sockets");
238		for (r = res; r; r = r->ai_next) {
239			sock = socket(r->ai_family, r->ai_socktype,
240				      r->ai_protocol);
241			if (sock < 0)
242				continue;
243			memcpy(&socks[nsock].addr, r->ai_addr, r->ai_addrlen);
244			socks[nsock].addrlen = r->ai_addrlen;
245			socks[nsock++].sock = sock;
246		}
247		freeaddrinfo(res);
248		if (nsock <= 0)
249			errx(1, "socket");
250	}
251
252	if ((len = asprintf(&line, "<%d>%s", pri, buf)) == -1)
253		errx(1, "asprintf");
254
255	lsent = -1;
256	for (i = 0; i < nsock; ++i) {
257		lsent = sendto(socks[i].sock, line, len, 0,
258			       (struct sockaddr *)&socks[i].addr,
259			       socks[i].addrlen);
260		if (lsent == len && !send_to_all)
261			break;
262	}
263	if (lsent != len) {
264		if (lsent == -1)
265			warn ("sendto");
266		else
267			warnx ("sendto: short send - %d bytes", lsent);
268	}
269
270	free(line);
271}
272#endif /* __APPLE__ */
273
274/*
275 *  Decode a symbolic name to a numeric value
276 */
277int
278pencode(char *s)
279{
280	char *save;
281	int fac, lev;
282
283	for (save = s; *s && *s != '.'; ++s);
284	if (*s) {
285		*s = '\0';
286		fac = decode(save, facilitynames);
287		if (fac < 0)
288			errx(1, "unknown facility name: %s", save);
289		*s++ = '.';
290	}
291	else {
292		fac = 0;
293		s = save;
294	}
295	lev = decode(s, prioritynames);
296	if (lev < 0)
297		errx(1, "unknown priority name: %s", save);
298	return ((lev & LOG_PRIMASK) | (fac & LOG_FACMASK));
299}
300
301int
302decode(char *name, CODE *codetab)
303{
304	CODE *c;
305
306	if (isdigit(*name))
307		return (atoi(name));
308
309	for (c = codetab; c->c_name; c++)
310		if (!strcasecmp(name, c->c_name))
311			return (c->c_val);
312
313	return (-1);
314}
315
316static void
317usage(void)
318{
319	(void)fprintf(stderr, "usage: %s\n",
320#ifdef __APPLE__
321	    "logger [-is] [-f file] [-p pri] [-t tag]\n"
322#else
323	    "logger [-46Ais] [-f file] [-h host] [-P port] [-p pri] [-t tag]\n"
324#endif
325	    "              [message ...]"
326	    );
327	exit(1);
328}
329