xref: /freebsd/usr.bin/logger/logger.c (revision 9fd69f37d28cfd7438cac3eeb45fe9dd46b4d7dd)
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
35 static 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
42 static 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$");
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 
64 int	decode(char *, CODE *);
65 int	pencode(char *);
66 static void	logmessage(int, const char *, const char *, const char *);
67 static void	usage(void);
68 
69 struct socks {
70     int sock;
71     int addrlen;
72     struct sockaddr_storage addr;
73 };
74 
75 #ifdef INET6
76 int	family = PF_UNSPEC;	/* protocol family (IPv4, IPv6 or both) */
77 #else
78 int	family = PF_INET;	/* protocol family (IPv4 only) */
79 #endif
80 int	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  */
88 int
89 main(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 			setvbuf(stdin, 0, _IONBF, 0);
118 			break;
119 		case 'h':		/* hostname to deliver to */
120 			host = optarg;
121 			break;
122 		case 'i':		/* log process id also */
123 			logflags |= LOG_PID;
124 			break;
125 		case 'P':		/* service name or port number */
126 			svcname = optarg;
127 			break;
128 		case 'p':		/* priority */
129 			pri = pencode(optarg);
130 			break;
131 		case 's':		/* log to standard error */
132 			logflags |= LOG_PERROR;
133 			break;
134 		case 't':		/* tag */
135 			tag = optarg;
136 			break;
137 		case '?':
138 		default:
139 			usage();
140 		}
141 	argc -= optind;
142 	argv += optind;
143 
144 	/* setup for logging */
145 	openlog(tag ? tag : getlogin(), logflags, 0);
146 	(void) fclose(stdout);
147 
148 	/* log input line if appropriate */
149 	if (argc > 0) {
150 		char *p, *endp;
151 		size_t len;
152 
153 		for (p = buf, endp = buf + sizeof(buf) - 2; *argv;) {
154 			len = strlen(*argv);
155 			if (p + len > endp && p > buf) {
156 				logmessage(pri, host, svcname, buf);
157 				p = buf;
158 			}
159 			if (len > sizeof(buf) - 1)
160 				logmessage(pri, host, svcname, *argv++);
161 			else {
162 				if (p != buf)
163 					*p++ = ' ';
164 				bcopy(*argv++, p, len);
165 				*(p += len) = '\0';
166 			}
167 		}
168 		if (p != buf)
169 			logmessage(pri, host, svcname, buf);
170 	} else
171 		while (fgets(buf, sizeof(buf), stdin) != NULL)
172 			logmessage(pri, host, svcname, buf);
173 	exit(0);
174 }
175 
176 /*
177  *  Send the message to syslog, either on the local host, or on a remote host
178  */
179 void
180 logmessage(int pri, const char *host, const char *svcname, const char *buf)
181 {
182 	static struct socks *socks;
183 	static int nsock = 0;
184 	struct addrinfo hints, *res, *r;
185 	char *line;
186 	int maxs, len, sock, error, i, lsent;
187 
188 	if (host == NULL) {
189 		syslog(pri, "%s", buf);
190 		return;
191 	}
192 
193 	if (nsock <= 0) {	/* set up socket stuff */
194 		/* resolve hostname */
195 		memset(&hints, 0, sizeof(hints));
196 		hints.ai_family = family;
197 		hints.ai_socktype = SOCK_DGRAM;
198 		error = getaddrinfo(host, svcname, &hints, &res);
199 		if (error == EAI_SERVICE) {
200 			warnx("%s/udp: unknown service", svcname);
201 			error = getaddrinfo(host, "514", &hints, &res);
202 		}
203 		if (error)
204 			errx(1, "%s: %s", gai_strerror(error), host);
205 		/* count max number of sockets we may open */
206 		for (maxs = 0, r = res; r; r = r->ai_next, maxs++);
207 		socks = malloc(maxs * sizeof(struct socks));
208 		if (!socks)
209 			errx(1, "couldn't allocate memory for sockets");
210 		for (r = res; r; r = r->ai_next) {
211 			sock = socket(r->ai_family, r->ai_socktype,
212 				      r->ai_protocol);
213 			if (sock < 0)
214 				continue;
215 			memcpy(&socks[nsock].addr, r->ai_addr, r->ai_addrlen);
216 			socks[nsock].addrlen = r->ai_addrlen;
217 			socks[nsock++].sock = sock;
218 		}
219 		freeaddrinfo(res);
220 		if (nsock <= 0)
221 			errx(1, "socket");
222 	}
223 
224 	if ((len = asprintf(&line, "<%d>%s", pri, buf)) == -1)
225 		errx(1, "asprintf");
226 
227 	lsent = -1;
228 	for (i = 0; i < nsock; ++i) {
229 		lsent = sendto(socks[i].sock, line, len, 0,
230 			       (struct sockaddr *)&socks[i].addr,
231 			       socks[i].addrlen);
232 		if (lsent == len && !send_to_all)
233 			break;
234 	}
235 	if (lsent != len) {
236 		if (lsent == -1)
237 			warn ("sendto");
238 		else
239 			warnx ("sendto: short send - %d bytes", lsent);
240 	}
241 
242 	free(line);
243 }
244 
245 /*
246  *  Decode a symbolic name to a numeric value
247  */
248 int
249 pencode(char *s)
250 {
251 	char *save;
252 	int fac, lev;
253 
254 	for (save = s; *s && *s != '.'; ++s);
255 	if (*s) {
256 		*s = '\0';
257 		fac = decode(save, facilitynames);
258 		if (fac < 0)
259 			errx(1, "unknown facility name: %s", save);
260 		*s++ = '.';
261 	}
262 	else {
263 		fac = 0;
264 		s = save;
265 	}
266 	lev = decode(s, prioritynames);
267 	if (lev < 0)
268 		errx(1, "unknown priority name: %s", save);
269 	return ((lev & LOG_PRIMASK) | (fac & LOG_FACMASK));
270 }
271 
272 int
273 decode(char *name, CODE *codetab)
274 {
275 	CODE *c;
276 
277 	if (isdigit(*name))
278 		return (atoi(name));
279 
280 	for (c = codetab; c->c_name; c++)
281 		if (!strcasecmp(name, c->c_name))
282 			return (c->c_val);
283 
284 	return (-1);
285 }
286 
287 static void
288 usage(void)
289 {
290 	(void)fprintf(stderr, "usage: %s\n",
291 	    "logger [-46Ais] [-f file] [-h host] [-P port] [-p pri] [-t tag]\n"
292 	    "              [message ...]"
293 	    );
294 	exit(1);
295 }
296