logread: ensure that the len < sizeof(struct blob_attr) check runs before trying...
[project/ubox.git] / log / logread.c
1 /*
2  * Copyright (C) 2013 Felix Fietkau <nbd@openwrt.org>
3  * Copyright (C) 2013 John Crispin <blogic@openwrt.org>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU Lesser General Public License version 2.1
7  * as published by the Free Software Foundation
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  */
14
15 #include <sys/types.h>
16 #include <sys/stat.h>
17
18 #include <fcntl.h>
19 #include <time.h>
20 #include <regex.h>
21 #include <stdio.h>
22 #include <unistd.h>
23 #include <sys/types.h>
24 #include <sys/socket.h>
25
26 #define SYSLOG_NAMES
27 #include <syslog.h>
28
29 #include <libubox/ustream.h>
30 #include <libubox/blobmsg_json.h>
31 #include <libubox/usock.h>
32 #include <libubox/uloop.h>
33 #include "libubus.h"
34 #include "syslog.h"
35
36 enum {
37         LOG_STDOUT,
38         LOG_FILE,
39         LOG_NET,
40 };
41
42 enum {
43         LOG_MSG,
44         LOG_ID,
45         LOG_PRIO,
46         LOG_SOURCE,
47         LOG_TIME,
48         __LOG_MAX
49 };
50
51 static const struct blobmsg_policy log_policy[] = {
52         [LOG_MSG] = { .name = "msg", .type = BLOBMSG_TYPE_STRING },
53         [LOG_ID] = { .name = "id", .type = BLOBMSG_TYPE_INT32 },
54         [LOG_PRIO] = { .name = "priority", .type = BLOBMSG_TYPE_INT32 },
55         [LOG_SOURCE] = { .name = "source", .type = BLOBMSG_TYPE_INT32 },
56         [LOG_TIME] = { .name = "time", .type = BLOBMSG_TYPE_INT64 },
57 };
58
59 static struct uloop_timeout retry;
60 static struct uloop_fd sender;
61 static regex_t regexp_preg;
62 static const char *log_file, *log_ip, *log_port, *log_prefix, *pid_file, *hostname, *regexp_pattern;
63 static int log_type = LOG_STDOUT;
64 static int log_size, log_udp, log_follow, log_trailer_null = 0;
65
66 static const char* getcodetext(int value, CODE *codetable) {
67         CODE *i;
68
69         if (value >= 0)
70                 for (i = codetable; i->c_val != -1; i++)
71                         if (i->c_val == value)
72                                 return (i->c_name);
73         return "<unknown>";
74 };
75
76 static void log_handle_reconnect(struct uloop_timeout *timeout)
77 {
78         sender.fd = usock((log_udp) ? (USOCK_UDP) : (USOCK_TCP), log_ip, log_port);
79         if (sender.fd < 0) {
80                 fprintf(stderr, "failed to connect: %s\n", strerror(errno));
81                 uloop_timeout_set(&retry, 1000);
82         } else {
83                 uloop_fd_add(&sender, ULOOP_READ);
84                 syslog(LOG_INFO, "Logread connected to %s:%s\n", log_ip, log_port);
85         }
86 }
87
88 static void log_handle_fd(struct uloop_fd *u, unsigned int events)
89 {
90         if (u->eof) {
91                 uloop_fd_delete(u);
92                 close(sender.fd);
93                 sender.fd = -1;
94                 uloop_timeout_set(&retry, 1000);
95         }
96 }
97
98 static int log_notify(struct blob_attr *msg)
99 {
100         struct blob_attr *tb[__LOG_MAX];
101         struct stat s;
102         char buf[512];
103         uint32_t p;
104         char *str;
105         time_t t;
106         char *c, *m;
107         int ret = 0;
108
109         if (sender.fd < 0)
110                 return 0;
111
112         blobmsg_parse(log_policy, ARRAY_SIZE(log_policy), tb, blob_data(msg), blob_len(msg));
113         if (!tb[LOG_ID] || !tb[LOG_PRIO] || !tb[LOG_SOURCE] || !tb[LOG_TIME] || !tb[LOG_MSG])
114                 return 1;
115
116         if ((log_type == LOG_FILE) && log_size && (!stat(log_file, &s)) && (s.st_size > log_size)) {
117                 char *old = malloc(strlen(log_file) + 5);
118
119                 close(sender.fd);
120                 if (old) {
121                         sprintf(old, "%s.old", log_file);
122                         rename(log_file, old);
123                         free(old);
124                 }
125                 sender.fd = open(log_file, O_CREAT | O_WRONLY | O_APPEND, 0600);
126                 if (sender.fd < 0) {
127                         fprintf(stderr, "failed to open %s: %s\n", log_file, strerror(errno));
128                         exit(-1);
129                 }
130         }
131
132         m = blobmsg_get_string(tb[LOG_MSG]);
133         if (regexp_pattern &&
134             regexec(&regexp_preg, m, 0, NULL, 0) == REG_NOMATCH)
135                 return 0;
136         t = blobmsg_get_u64(tb[LOG_TIME]) / 1000;
137         c = ctime(&t);
138         p = blobmsg_get_u32(tb[LOG_PRIO]);
139         c[strlen(c) - 1] = '\0';
140         str = blobmsg_format_json(msg, true);
141         if (log_type == LOG_NET) {
142                 int err;
143
144                 snprintf(buf, sizeof(buf), "<%u>", p);
145                 strncat(buf, c + 4, 16);
146                 if (hostname) {
147                         strncat(buf, hostname, sizeof(buf) - strlen(buf) - 1);
148                         strncat(buf, " ", sizeof(buf) - strlen(buf) - 1);
149                 }
150                 if (log_prefix) {
151                         strncat(buf, log_prefix, sizeof(buf) - strlen(buf) - 1);
152                         strncat(buf, ": ", sizeof(buf) - strlen(buf) - 1);
153                 }
154                 if (blobmsg_get_u32(tb[LOG_SOURCE]) == SOURCE_KLOG)
155                         strncat(buf, "kernel: ", sizeof(buf) - strlen(buf) - 1);
156                 strncat(buf, m, sizeof(buf) - strlen(buf) - 1);
157                 if (log_udp)
158                         err = write(sender.fd, buf, strlen(buf));
159                 else {
160                         size_t buflen = strlen(buf);
161                         if (!log_trailer_null)
162                                 buf[buflen] = '\n';
163                         err = send(sender.fd, buf, buflen + 1, 0);
164                 }
165
166                 if (err < 0) {
167                         syslog(LOG_INFO, "failed to send log data to %s:%s via %s\n",
168                                 log_ip, log_port, (log_udp) ? ("udp") : ("tcp"));
169                         uloop_fd_delete(&sender);
170                         close(sender.fd);
171                         sender.fd = -1;
172                         uloop_timeout_set(&retry, 1000);
173                 }
174         } else {
175                 snprintf(buf, sizeof(buf), "%s %s.%s%s %s\n",
176                         c, getcodetext(LOG_FAC(p) << 3, facilitynames), getcodetext(LOG_PRI(p), prioritynames),
177                         (blobmsg_get_u32(tb[LOG_SOURCE])) ? ("") : (" kernel:"), m);
178                 ret = write(sender.fd, buf, strlen(buf));
179         }
180
181         free(str);
182         if (log_type == LOG_FILE)
183                 fsync(sender.fd);
184
185         return ret;
186 }
187
188 static int usage(const char *prog)
189 {
190         fprintf(stderr, "Usage: %s [options]\n"
191                 "Options:\n"
192                 "    -s <path>          Path to ubus socket\n"
193                 "    -l <count>         Got only the last 'count' messages\n"
194                 "    -e <pattern>       Filter messages with a regexp\n"
195                 "    -r <server> <port> Stream message to a server\n"
196                 "    -F <file>          Log file\n"
197                 "    -S <bytes>         Log size\n"
198                 "    -p <file>          PID file\n"
199                 "    -h <hostname>      Add hostname to the message\n"
200                 "    -P <prefix>        Prefix custom text to streamed messages\n"
201                 "    -f                 Follow log messages\n"
202                 "    -u                 Use UDP as the protocol\n"
203                 "    -0                 Use \\0 instead of \\n as trailer when using TCP\n"
204                 "\n", prog);
205         return 1;
206 }
207
208 static void logread_fd_data_cb(struct ustream *s, int bytes)
209 {
210         while (true) {
211                 struct blob_attr *a;
212                 int len, cur_len;
213
214                 a = (void*) ustream_get_read_buf(s, &len);
215                 if (len < sizeof(*a))
216                         break;
217
218                 cur_len = blob_len(a) + sizeof(*a);
219                 if (len < cur_len)
220                         break;
221
222                 log_notify(a);
223                 ustream_consume(s, cur_len);
224         }
225         if (!log_follow)
226                 uloop_end();
227 }
228
229 static void logread_fd_cb(struct ubus_request *req, int fd)
230 {
231         static struct ustream_fd test_fd;
232
233         test_fd.stream.notify_read = logread_fd_data_cb;
234         ustream_fd_init(&test_fd, fd);
235 }
236
237 int main(int argc, char **argv)
238 {
239         static struct ubus_request req;
240         struct ubus_context *ctx;
241         uint32_t id;
242         const char *ubus_socket = NULL;
243         int ch, ret, lines = 0;
244         static struct blob_buf b;
245         int tries = 5;
246
247         signal(SIGPIPE, SIG_IGN);
248
249         while ((ch = getopt(argc, argv, "u0fcs:l:r:F:p:S:P:h:e:")) != -1) {
250                 switch (ch) {
251                 case 'u':
252                         log_udp = 1;
253                         break;
254                 case '0':
255                         log_trailer_null = 1;
256                         break;
257                 case 's':
258                         ubus_socket = optarg;
259                         break;
260                 case 'r':
261                         log_ip = optarg++;
262                         log_port = argv[optind++];
263                         break;
264                 case 'F':
265                         log_file = optarg;
266                         break;
267                 case 'p':
268                         pid_file = optarg;
269                         break;
270                 case 'P':
271                         log_prefix = optarg;
272                         break;
273                 case 'f':
274                         log_follow = 1;
275                         break;
276                 case 'l':
277                         lines = atoi(optarg);
278                         break;
279                 case 'S':
280                         log_size = atoi(optarg);
281                         if (log_size < 1)
282                                 log_size = 1;
283                         log_size *= 1024;
284                         break;
285                 case 'h':
286                         hostname = optarg;
287                         break;
288                 case 'e':
289                         if (!regcomp(&regexp_preg, optarg, REG_NOSUB)) {
290                                 regexp_pattern = optarg;
291                         }
292                         break;
293                 default:
294                         return usage(*argv);
295                 }
296         }
297         uloop_init();
298
299         ctx = ubus_connect(ubus_socket);
300         if (!ctx) {
301                 fprintf(stderr, "Failed to connect to ubus\n");
302                 return -1;
303         }
304         ubus_add_uloop(ctx);
305
306         /* ugly ugly ugly ... we need a real reconnect logic */
307         do {
308                 ret = ubus_lookup_id(ctx, "log", &id);
309                 if (ret) {
310                         fprintf(stderr, "Failed to find log object: %s\n", ubus_strerror(ret));
311                         sleep(1);
312                         continue;
313                 }
314
315                 blob_buf_init(&b, 0);
316                 if (lines)
317                         blobmsg_add_u32(&b, "lines", lines);
318                 else if (log_follow)
319                         blobmsg_add_u32(&b, "lines", 0);
320                 if (log_follow) {
321                         if (pid_file) {
322                                 FILE *fp = fopen(pid_file, "w+");
323                                 if (fp) {
324                                         fprintf(fp, "%d", getpid());
325                                         fclose(fp);
326                                 }
327                         }
328                 }
329
330                 if (log_ip && log_port) {
331                         openlog("logread", LOG_PID, LOG_DAEMON);
332                         log_type = LOG_NET;
333                         sender.cb = log_handle_fd;
334                         retry.cb = log_handle_reconnect;
335                         uloop_timeout_set(&retry, 1000);
336                 } else if (log_file) {
337                         log_type = LOG_FILE;
338                         sender.fd = open(log_file, O_CREAT | O_WRONLY| O_APPEND, 0600);
339                         if (sender.fd < 0) {
340                                 fprintf(stderr, "failed to open %s: %s\n", log_file, strerror(errno));
341                                 exit(-1);
342                         }
343                 } else {
344                         sender.fd = STDOUT_FILENO;
345                 }
346
347                 ubus_invoke_async(ctx, id, "read", b.head, &req);
348                 req.fd_cb = logread_fd_cb;
349                 ubus_complete_request_async(ctx, &req);
350
351                 uloop_run();
352                 ubus_free(ctx);
353                 uloop_done();
354
355         } while (ret && tries--);
356
357         return ret;
358 }