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