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