xref: /freebsd/usr.bin/logger/logger.c (revision 2e3f49888ec8851bafb22011533217487764fdb0)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1983, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #include <sys/capsicum.h>
33 #include <sys/param.h>
34 #include <sys/socket.h>
35 #include <netinet/in.h>
36 
37 #include <capsicum_helpers.h>
38 #include <ctype.h>
39 #include <err.h>
40 #include <netdb.h>
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <time.h>
45 #include <unistd.h>
46 
47 #include <libcasper.h>
48 #include <casper/cap_syslog.h>
49 
50 #define	SYSLOG_NAMES
51 #include <syslog.h>
52 
53 #define	sstosa(ss)	((struct sockaddr *)(void *)ss)
54 
55 struct socks {
56 	int sk_sock;
57 	int sk_addrlen;
58 	struct sockaddr_storage sk_addr;
59 };
60 
61 static int	decode(char *, const CODE *);
62 static int	pencode(char *);
63 static ssize_t	socksetup(const char *, const char *, const char *,
64 		    struct socks **);
65 static void	logmessage(int, const char *, const char *, const char *,
66 		    struct socks *, ssize_t, const char *);
67 static void	usage(void);
68 
69 static cap_channel_t *capsyslog;
70 #ifdef INET6
71 static int family = PF_UNSPEC;	/* protocol family (IPv4, IPv6 or both) */
72 #else
73 static int family = PF_INET;	/* protocol family (IPv4 only) */
74 #endif
75 static int send_to_all = 0;	/* send message to all IPv4/IPv6 addresses */
76 
77 /*
78  * logger -- read and log utility
79  *
80  *	Reads from an input and arranges to write the result on the system
81  *	log.
82  */
83 int
84 main(int argc, char *argv[])
85 {
86 	cap_channel_t *capcas;
87 	struct socks *socks;
88 	ssize_t nsock;
89 	time_t now;
90 	int ch, logflags, pri;
91 	char *tag, *host, buf[1024], *timestamp, tbuf[26],
92 	    *hostname, hbuf[MAXHOSTNAMELEN], *pristr;
93 	const char *svcname, *src;
94 
95 	tag = NULL;
96 	host = NULL;
97 	hostname = NULL;
98 	svcname = "syslog";
99 	src = NULL;
100 	socks = NULL;
101 	pri = LOG_USER | LOG_NOTICE;
102 	pristr = NULL;
103 	logflags = 0;
104 	unsetenv("TZ");
105 	while ((ch = getopt(argc, argv, "46Af:H:h:iP:p:S:st:")) != -1)
106 		switch((char)ch) {
107 		case '4':
108 			family = PF_INET;
109 			break;
110 #ifdef INET6
111 		case '6':
112 			family = PF_INET6;
113 			break;
114 #endif
115 		case 'A':
116 			send_to_all++;
117 			break;
118 		case 'f':		/* file to log */
119 			if (freopen(optarg, "r", stdin) == NULL)
120 				err(1, "%s", optarg);
121 			setvbuf(stdin, 0, _IONBF, 0);
122 			break;
123 		case 'H':		/* hostname to set in message header */
124 			hostname = optarg;
125 			break;
126 		case 'h':		/* hostname to deliver to */
127 			host = optarg;
128 			break;
129 		case 'i':		/* log process id also */
130 			logflags |= LOG_PID;
131 			break;
132 		case 'P':		/* service name or port number */
133 			svcname = optarg;
134 			break;
135 		case 'p':		/* priority */
136 			pristr = optarg;
137 			break;
138 		case 's':		/* log to standard error */
139 			logflags |= LOG_PERROR;
140 			break;
141 		case 'S':		/* source address */
142 			src = optarg;
143 			break;
144 		case 't':		/* tag */
145 			tag = optarg;
146 			break;
147 		case '?':
148 		default:
149 			usage();
150 		}
151 	argc -= optind;
152 	argv += optind;
153 
154 	if (host) {
155 		nsock = socksetup(src, host, svcname, &socks);
156 		if (nsock <= 0)
157 			errx(1, "socket");
158 	} else {
159 		if (src)
160 			errx(1, "-h option is missing.");
161 		nsock = 0;
162 	}
163 
164 	capcas = cap_init();
165 	if (capcas == NULL)
166 		err(1, "Unable to contact Casper");
167 	caph_cache_catpages();
168 	caph_cache_tzdata();
169 	if (nsock == 0) {
170 		if (caph_enter_casper() < 0)
171 			err(1, "Unable to enter capability mode");
172 	}
173 	capsyslog = cap_service_open(capcas, "system.syslog");
174 	if (capsyslog == NULL)
175 		err(1, "Unable to open system.syslog service");
176 	cap_close(capcas);
177 
178 	if (pristr != NULL)
179 		pri = pencode(pristr);
180 	if (tag == NULL)
181 		tag = getlogin();
182 	/* setup for logging */
183 	if (host == NULL)
184 		cap_openlog(capsyslog, tag, logflags, 0);
185 
186 	if (hostname == NULL) {
187 		hostname = hbuf;
188 		(void )gethostname(hbuf, MAXHOSTNAMELEN);
189 		*strchrnul(hostname, '.') = '\0';
190 	}
191 
192 	timestamp = tbuf + 4;
193 
194 	/* log input line if appropriate */
195 	if (argc > 0) {
196 		char *p, *endp;
197 		size_t len;
198 
199 		(void )time(&now);
200 		(void )ctime_r(&now, tbuf);
201 		tbuf[19] = '\0';
202 
203 		for (p = buf, endp = buf + sizeof(buf) - 2; *argv;) {
204 			len = strlen(*argv);
205 			if (p + len > endp && p > buf) {
206 				logmessage(pri, timestamp, hostname, tag,
207 				    socks, nsock, buf);
208 				p = buf;
209 			}
210 			if (len > sizeof(buf) - 1)
211 				logmessage(pri, timestamp, hostname, tag,
212 				    socks, nsock, *argv++);
213 			else {
214 				if (p != buf)
215 					*p++ = ' ';
216 				bcopy(*argv++, p, len);
217 				*(p += len) = '\0';
218 			}
219 		}
220 		if (p != buf)
221 			logmessage(pri, timestamp, hostname, tag, socks, nsock,
222 			    buf);
223 	} else
224 		while (fgets(buf, sizeof(buf), stdin) != NULL) {
225 			(void )time(&now);
226 			(void )ctime_r(&now, tbuf);
227 			tbuf[19] = '\0';
228 
229 			logmessage(pri, timestamp, hostname, tag, socks, nsock,
230 			    buf);
231 		}
232 	exit(0);
233 }
234 
235 static ssize_t
236 socksetup(const char *src, const char *dst, const char *svcname,
237 	struct socks **socks)
238 {
239 	struct addrinfo hints, *res, *res0;
240 	struct sockaddr_storage *ss_src[AF_MAX];
241 	struct socks *sk;
242 	ssize_t nsock = 0;
243 	int error, maxs;
244 
245 	memset(&ss_src[0], 0, sizeof(ss_src));
246 	if (src) {
247 		char *p, *p0, *hs, *hbuf, *sbuf;
248 
249 		hbuf = sbuf = NULL;
250 		p0 = p = strdup(src);
251 		if (p0 == NULL)
252 			err(1, "strdup failed");
253 		hs = p0;	/* point to search ":" */
254 #ifdef INET6
255 		/* -S option supports IPv6 addr in "[2001:db8::1]:service". */
256 		if (*p0 == '[') {
257 			p = strchr(p0, ']');
258 			if (p == NULL)
259 				errx(1, "\"]\" not found in src addr");
260 			*p = '\0';
261 			/* hs points just after ']' (':' or '\0'). */
262 			hs = p + 1;
263 			/*
264 			 * p points just after '[' while it points hs
265 			 * in the case of [].
266 			 */
267 			p = ((p0 + 1) == (hs - 1)) ? hs : p0 + 1;
268 		}
269 #endif
270 		if (*p != '\0') {
271 			/* (p == hs) means ":514" or "[]:514". */
272 			hbuf = (p == hs && *p == ':') ? NULL : p;
273 			p = strchr(hs, ':');
274 			if (p != NULL) {
275 				*p = '\0';
276 				sbuf = (*(p + 1) != '\0') ? p + 1 : NULL;
277 			}
278 		}
279 		hints = (struct addrinfo){
280 			.ai_family = family,
281 			.ai_socktype = SOCK_DGRAM,
282 			.ai_flags = AI_PASSIVE
283 		};
284 		error = getaddrinfo(hbuf, sbuf, &hints, &res0);
285 		if (error)
286 			errx(1, "%s: %s", gai_strerror(error), src);
287 		for (res = res0; res; res = res->ai_next) {
288 			switch (res->ai_family) {
289 			case AF_INET:
290 #ifdef INET6
291 			case AF_INET6:
292 #endif
293 				if (ss_src[res->ai_family] != NULL)
294 					continue;
295 				ss_src[res->ai_family] =
296 				    malloc(sizeof(struct sockaddr_storage));
297 				if (ss_src[res->ai_family] == NULL)
298 					err(1, "malloc failed");
299 				memcpy(ss_src[res->ai_family], res->ai_addr,
300 				    res->ai_addrlen);
301 			}
302 		}
303 		freeaddrinfo(res0);
304 		free(p0);
305 	}
306 
307 	/* resolve hostname */
308 	hints = (struct addrinfo){
309 		.ai_family = family,
310 		.ai_socktype = SOCK_DGRAM
311 	};
312 	error = getaddrinfo(dst, svcname, &hints, &res0);
313 	if (error == EAI_SERVICE) {
314 		warnx("%s/udp: unknown service", svcname);
315 		error = getaddrinfo(dst, "514", &hints, &res0);
316 	}
317 	if (error)
318 		errx(1, "%s: %s", gai_strerror(error), dst);
319 	/* count max number of sockets we may open */
320 	maxs = 0;
321 	for (res = res0; res; res = res->ai_next)
322 		maxs++;
323 	sk = calloc(maxs, sizeof(*sk));
324 	if (sk == NULL)
325 		errx(1, "couldn't allocate memory for sockets");
326 	for (res = res0; res; res = res->ai_next) {
327 		int s;
328 
329 		s = socket(res->ai_family, res->ai_socktype,
330 		    res->ai_protocol);
331 		if (s < 0)
332 			continue;
333 		if (src && ss_src[res->ai_family] == NULL)
334 			errx(1, "address family mismatch");
335 
336 		if (ss_src[res->ai_family]) {
337 			error = bind(s, sstosa(ss_src[res->ai_family]),
338 				    ss_src[res->ai_family]->ss_len);
339 			if (error < 0)
340 				err(1, "bind");
341 		}
342 		sk[nsock] = (struct socks){
343 			.sk_addrlen = res->ai_addrlen,
344 			.sk_sock = s
345 		};
346 		memcpy(&sk[nsock].sk_addr, res->ai_addr, res->ai_addrlen);
347 		nsock++;
348 	}
349 	freeaddrinfo(res0);
350 
351 	*socks = sk;
352 	return (nsock);
353 }
354 
355 /*
356  *  Send the message to syslog, either on the local host, or on a remote host
357  */
358 static void
359 logmessage(int pri, const char *timestamp, const char *hostname,
360     const char *tag, struct socks *sk, ssize_t nsock, const char *buf)
361 {
362 	char *line;
363 	int len, i, lsent;
364 
365 	if (nsock == 0) {
366 		cap_syslog(capsyslog, pri, "%s", buf);
367 		return;
368 	}
369 	if ((len = asprintf(&line, "<%d>%s %s %s: %s", pri, timestamp,
370 	    hostname, tag, buf)) == -1)
371 		errx(1, "asprintf");
372 
373 	lsent = -1;
374 	for (i = 0; i < nsock; i++) {
375 		lsent = sendto(sk[i].sk_sock, line, len, 0,
376 			       sstosa(&sk[i].sk_addr), sk[i].sk_addrlen);
377 		if (lsent == len && !send_to_all)
378 			break;
379 	}
380 	if (lsent != len) {
381 		if (lsent == -1)
382 			warn("sendto");
383 		else
384 			warnx("sendto: short send - %d bytes", lsent);
385 	}
386 
387 	free(line);
388 }
389 
390 /*
391  *  Decode a symbolic name to a numeric value
392  */
393 static int
394 pencode(char *s)
395 {
396 	char *save;
397 	int fac, lev;
398 
399 	for (save = s; *s && *s != '.'; ++s);
400 	if (*s) {
401 		*s = '\0';
402 		fac = decode(save, facilitynames);
403 		if (fac < 0)
404 			errx(1, "unknown facility name: %s", save);
405 		*s++ = '.';
406 	}
407 	else {
408 		fac = 0;
409 		s = save;
410 	}
411 	lev = decode(s, prioritynames);
412 	if (lev < 0)
413 		errx(1, "unknown priority name: %s", save);
414 	return ((lev & LOG_PRIMASK) | (fac & LOG_FACMASK));
415 }
416 
417 static int
418 decode(char *name, const CODE *codetab)
419 {
420 	const CODE *c;
421 
422 	if (isdigit(*name))
423 		return (atoi(name));
424 
425 	for (c = codetab; c->c_name; c++)
426 		if (!strcasecmp(name, c->c_name))
427 			return (c->c_val);
428 
429 	return (-1);
430 }
431 
432 static void
433 usage(void)
434 {
435 	(void)fprintf(stderr, "usage: %s\n",
436 	    "logger [-46Ais] [-f file] [-h host] [-P port] [-p pri] [-t tag]\n"
437 	    "              [-S addr:port] [message ...]"
438 	    );
439 	exit(1);
440 }
441