a7647421e95d2774332ce5d9de91756b5657faf9
[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 #define LOGD_CONNECT_RETRY 10
37
38 enum {
39 LOG_STDOUT,
40 LOG_FILE,
41 LOG_NET,
42 };
43
44 enum {
45 LOG_MSG,
46 LOG_ID,
47 LOG_PRIO,
48 LOG_SOURCE,
49 LOG_TIME,
50 __LOG_MAX
51 };
52
53 static const struct blobmsg_policy log_policy[] = {
54 [LOG_MSG] = { .name = "msg", .type = BLOBMSG_TYPE_STRING },
55 [LOG_ID] = { .name = "id", .type = BLOBMSG_TYPE_INT32 },
56 [LOG_PRIO] = { .name = "priority", .type = BLOBMSG_TYPE_INT32 },
57 [LOG_SOURCE] = { .name = "source", .type = BLOBMSG_TYPE_INT32 },
58 [LOG_TIME] = { .name = "time", .type = BLOBMSG_TYPE_INT64 },
59 };
60
61 static struct uloop_timeout retry;
62 static struct uloop_fd sender;
63 static regex_t regexp_preg;
64 static const char *log_file, *log_ip, *log_port, *log_prefix, *pid_file, *hostname, *regexp_pattern;
65 static int log_type = LOG_STDOUT;
66 static int log_size, log_udp, log_follow, log_trailer_null = 0;
67 static int log_timestamp;
68 static int logd_conn_tries = LOGD_CONNECT_RETRY;
69 static int facility_include;
70 static int facility_exclude;
71
72 /* check for facility filter; return 0 if message shall be dropped */
73 static int check_facility_filter(int f)
74 {
75 if (facility_include)
76 return !!(facility_include & (1 << f));
77 if (facility_exclude)
78 return !(facility_exclude & (1 << f));
79 return 1;
80 }
81
82 static const char* getcodetext(int value, CODE *codetable) {
83 CODE *i;
84
85 if (value >= 0)
86 for (i = codetable; i->c_val != -1; i++)
87 if (i->c_val == value)
88 return (i->c_name);
89 return "<unknown>";
90 };
91
92 static void log_handle_reconnect(struct uloop_timeout *timeout)
93 {
94 sender.fd = usock((log_udp) ? (USOCK_UDP) : (USOCK_TCP), log_ip, log_port);
95 if (sender.fd < 0) {
96 fprintf(stderr, "failed to connect: %m\n");
97 uloop_timeout_set(&retry, 1000);
98 } else {
99 uloop_fd_add(&sender, ULOOP_READ);
100 syslog(LOG_INFO, "Logread connected to %s:%s\n", log_ip, log_port);
101 }
102 }
103
104 static void log_handle_fd(struct uloop_fd *u, unsigned int events)
105 {
106 if (u->eof) {
107 uloop_fd_delete(u);
108 close(sender.fd);
109 sender.fd = -1;
110 uloop_timeout_set(&retry, 1000);
111 }
112 }
113
114 static int log_notify(struct blob_attr *msg)
115 {
116 struct blob_attr *tb[__LOG_MAX];
117 struct stat s;
118 char buf[LOG_LINE_SIZE + 128];
119 char buf_ts[32];
120 uint32_t p;
121 time_t t;
122 uint32_t t_ms = 0;
123 char *c, *m;
124 int ret = 0;
125
126 if (sender.fd < 0)
127 return 0;
128
129 blobmsg_parse(log_policy, ARRAY_SIZE(log_policy), tb, blob_data(msg), blob_len(msg));
130 if (!tb[LOG_ID] || !tb[LOG_PRIO] || !tb[LOG_SOURCE] || !tb[LOG_TIME] || !tb[LOG_MSG])
131 return 1;
132
133 if ((log_type == LOG_FILE) && log_size && (!stat(log_file, &s)) && (s.st_size > log_size)) {
134 char *old = malloc(strlen(log_file) + 5);
135
136 close(sender.fd);
137 if (old) {
138 sprintf(old, "%s.old", log_file);
139 rename(log_file, old);
140 free(old);
141 }
142 sender.fd = open(log_file, O_CREAT | O_WRONLY | O_APPEND, 0600);
143 if (sender.fd < 0) {
144 fprintf(stderr, "failed to open %s: %m\n", log_file);
145 exit(-1);
146 }
147 }
148 p = blobmsg_get_u32(tb[LOG_PRIO]);
149
150 if (!check_facility_filter(LOG_FAC(p)))
151 return 0;
152
153 m = blobmsg_get_string(tb[LOG_MSG]);
154 if (regexp_pattern &&
155 regexec(&regexp_preg, m, 0, NULL, 0) == REG_NOMATCH)
156 return 0;
157 t = blobmsg_get_u64(tb[LOG_TIME]) / 1000;
158 if (log_timestamp) {
159 t_ms = blobmsg_get_u64(tb[LOG_TIME]) % 1000;
160 snprintf(buf_ts, sizeof(buf_ts), "[%lu.%03u] ",
161 (unsigned long)t, t_ms);
162 }
163 c = ctime(&t);
164 c[strlen(c) - 1] = '\0';
165
166 if (log_type == LOG_NET) {
167 int err;
168
169 snprintf(buf, sizeof(buf), "<%u>", p);
170 strncat(buf, c + 4, 16);
171 if (log_timestamp) {
172 strncat(buf, buf_ts, sizeof(buf) - strlen(buf) - 1);
173 }
174 if (hostname) {
175 strncat(buf, hostname, sizeof(buf) - strlen(buf) - 1);
176 strncat(buf, " ", sizeof(buf) - strlen(buf) - 1);
177 }
178 if (log_prefix) {
179 strncat(buf, log_prefix, sizeof(buf) - strlen(buf) - 1);
180 strncat(buf, ": ", sizeof(buf) - strlen(buf) - 1);
181 }
182 if (blobmsg_get_u32(tb[LOG_SOURCE]) == SOURCE_KLOG)
183 strncat(buf, "kernel: ", sizeof(buf) - strlen(buf) - 1);
184 strncat(buf, m, sizeof(buf) - strlen(buf) - 1);
185 if (log_udp)
186 err = write(sender.fd, buf, strlen(buf));
187 else {
188 size_t buflen = strlen(buf);
189 if (!log_trailer_null)
190 buf[buflen] = '\n';
191 err = send(sender.fd, buf, buflen + 1, 0);
192 }
193
194 if (err < 0) {
195 syslog(LOG_INFO, "failed to send log data to %s:%s via %s\n",
196 log_ip, log_port, (log_udp) ? ("udp") : ("tcp"));
197 uloop_fd_delete(&sender);
198 close(sender.fd);
199 sender.fd = -1;
200 uloop_timeout_set(&retry, 1000);
201 }
202 } else {
203 snprintf(buf, sizeof(buf), "%s %s%s.%s%s %s\n",
204 c, log_timestamp ? buf_ts : "",
205 getcodetext(LOG_FAC(p) << 3, facilitynames),
206 getcodetext(LOG_PRI(p), prioritynames),
207 (blobmsg_get_u32(tb[LOG_SOURCE])) ? ("") : (" kernel:"), m);
208 ret = write(sender.fd, buf, strlen(buf));
209 }
210
211 if (log_type == LOG_FILE)
212 fsync(sender.fd);
213
214 return ret;
215 }
216
217 static int usage(const char *prog)
218 {
219 fprintf(stderr, "Usage: %s [options]\n"
220 "Options:\n"
221 " -s <path> Path to ubus socket\n"
222 " -l <count> Got only the last 'count' messages\n"
223 " -e <pattern> Filter messages with a regexp\n"
224 " -r <server> <port> Stream message to a server\n"
225 " -F <file> Log file\n"
226 " -S <bytes> Log size\n"
227 " -p <file> PID file\n"
228 " -h <hostname> Add hostname to the message\n"
229 " -P <prefix> Prefix custom text to streamed messages\n"
230 " -z <facility> handle only messages with given facility (0-23), repeatable\n"
231 " -Z <facility> ignore messages with given facility (0-23), repeatable\n"
232 " -f Follow log messages\n"
233 " -u Use UDP as the protocol\n"
234 " -t Add an extra timestamp\n"
235 " -0 Use \\0 instead of \\n as trailer when using TCP\n"
236 "\n", prog);
237 return 1;
238 }
239
240 static void logread_fd_data_cb(struct ustream *s, int bytes)
241 {
242 while (true) {
243 struct blob_attr *a;
244 int len, cur_len;
245
246 a = (void*) ustream_get_read_buf(s, &len);
247 if (len < sizeof(*a))
248 break;
249
250 cur_len = blob_len(a) + sizeof(*a);
251 if (len < cur_len)
252 break;
253
254 log_notify(a);
255 ustream_consume(s, cur_len);
256 }
257 }
258
259 static void logread_fd_state_cb(struct ustream *s)
260 {
261 if (log_follow)
262 logd_conn_tries = LOGD_CONNECT_RETRY;
263 uloop_end();
264 }
265
266 static void logread_fd_cb(struct ubus_request *req, int fd)
267 {
268 static struct ustream_fd test_fd;
269
270 memset(&test_fd, 0, sizeof(test_fd));
271
272 test_fd.stream.notify_read = logread_fd_data_cb;
273 test_fd.stream.notify_state = logread_fd_state_cb;
274 ustream_fd_init(&test_fd, fd);
275 }
276
277 static void logread_setup_output(void)
278 {
279 if (sender.fd || sender.cb)
280 return;
281
282 if (log_ip && log_port) {
283 openlog("logread", LOG_PID, LOG_DAEMON);
284 log_type = LOG_NET;
285 sender.cb = log_handle_fd;
286 retry.cb = log_handle_reconnect;
287 uloop_timeout_set(&retry, 1000);
288 } else if (log_file) {
289 log_type = LOG_FILE;
290 sender.fd = open(log_file, O_CREAT | O_WRONLY| O_APPEND, 0600);
291 if (sender.fd < 0) {
292 fprintf(stderr, "failed to open %s: %m\n", log_file);
293 exit(-1);
294 }
295 } else {
296 sender.fd = STDOUT_FILENO;
297 }
298 }
299
300 int main(int argc, char **argv)
301 {
302 struct ubus_context *ctx;
303 uint32_t id;
304 const char *ubus_socket = NULL;
305 int ch, ret, lines = 0;
306 static struct blob_buf b;
307
308 signal(SIGPIPE, SIG_IGN);
309
310 while ((ch = getopt(argc, argv, "u0fcs:l:z:Z:r:F:p:S:P:h:e:t")) != -1) {
311 switch (ch) {
312 case 'u':
313 log_udp = 1;
314 break;
315 case '0':
316 log_trailer_null = 1;
317 break;
318 case 's':
319 ubus_socket = optarg;
320 break;
321 case 'r':
322 log_ip = optarg++;
323 log_port = argv[optind++];
324 break;
325 case 'F':
326 log_file = optarg;
327 break;
328 case 'p':
329 pid_file = optarg;
330 break;
331 case 'P':
332 log_prefix = optarg;
333 break;
334 case 'f':
335 log_follow = 1;
336 break;
337 case 'l':
338 lines = atoi(optarg);
339 break;
340 case 'z':
341 id = strtoul(optarg, NULL, 0) & 0x1f;
342 facility_include |= (1 << id);
343 break;
344 case 'Z':
345 id = strtoul(optarg, NULL, 0) & 0x1f;
346 facility_exclude |= (1 << id);
347 break;
348 case 'S':
349 log_size = atoi(optarg);
350 if (log_size < 1)
351 log_size = 1;
352 log_size *= 1024;
353 break;
354 case 'h':
355 hostname = optarg;
356 break;
357 case 'e':
358 if (!regcomp(&regexp_preg, optarg, REG_NOSUB)) {
359 regexp_pattern = optarg;
360 }
361 break;
362 case 't':
363 log_timestamp = 1;
364 break;
365 default:
366 return usage(*argv);
367 }
368 }
369 uloop_init();
370
371 ctx = ubus_connect(ubus_socket);
372 if (!ctx) {
373 fprintf(stderr, "Failed to connect to ubus\n");
374 return -1;
375 }
376 ubus_add_uloop(ctx);
377
378 if (log_follow && pid_file) {
379 FILE *fp = fopen(pid_file, "w+");
380 if (fp) {
381 fprintf(fp, "%d", getpid());
382 fclose(fp);
383 }
384 }
385
386 blob_buf_init(&b, 0);
387 blobmsg_add_u8(&b, "stream", 1);
388 blobmsg_add_u8(&b, "oneshot", !log_follow);
389 if (lines)
390 blobmsg_add_u32(&b, "lines", lines);
391 else if (log_follow)
392 blobmsg_add_u32(&b, "lines", 0);
393
394 /* ugly ugly ugly ... we need a real reconnect logic */
395 do {
396 struct ubus_request req = { 0 };
397
398 ret = ubus_lookup_id(ctx, "log", &id);
399 if (ret) {
400 fprintf(stderr, "Failed to find log object: %s\n", ubus_strerror(ret));
401 sleep(1);
402 continue;
403 }
404 logd_conn_tries = 0;
405 logread_setup_output();
406
407 ubus_invoke_async(ctx, id, "read", b.head, &req);
408 req.fd_cb = logread_fd_cb;
409 ubus_complete_request_async(ctx, &req);
410
411 uloop_run();
412
413 } while (logd_conn_tries--);
414
415 ubus_free(ctx);
416 uloop_done();
417
418 if (log_follow && pid_file)
419 unlink(pid_file);
420
421 return ret;
422 }