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