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