81d220452f5a0ec5aae5e57803789ba7b5070b15
[project/procd.git] / 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 <stdio.h>
21 #include <unistd.h>
22 #include <sys/types.h>
23 #include <sys/socket.h>
24
25 #define SYSLOG_NAMES
26 #include <syslog.h>
27
28 #include <libubox/blobmsg_json.h>
29 #include <libubox/usock.h>
30 #include <libubox/uloop.h>
31 #include "libubus.h"
32
33 enum {
34         LOG_STDOUT,
35         LOG_FILE,
36         LOG_NET,
37 };
38
39 enum {
40         LOG_MSG,
41         LOG_ID,
42         LOG_PRIO,
43         LOG_SOURCE,
44         LOG_TIME,
45         __LOG_MAX
46 };
47
48 static const struct blobmsg_policy log_policy[] = {
49         [LOG_MSG] = { .name = "msg", .type = BLOBMSG_TYPE_STRING },
50         [LOG_ID] = { .name = "id", .type = BLOBMSG_TYPE_INT32 },
51         [LOG_PRIO] = { .name = "priority", .type = BLOBMSG_TYPE_INT32 },
52         [LOG_SOURCE] = { .name = "source", .type = BLOBMSG_TYPE_INT32 },
53         [LOG_TIME] = { .name = "time", .type = BLOBMSG_TYPE_INT64 },
54 };
55
56 static struct ubus_subscriber log_event;
57 static struct uloop_timeout retry;
58 static struct uloop_fd sender;
59 static const char *log_file, *log_ip, *log_port, *log_prefix, *pid_file;
60 static int log_type = LOG_STDOUT;
61 static int log_size, log_udp;
62
63 static const char* getcodetext(int value, CODE *codetable) {
64         CODE *i;
65
66         if (value >= 0)
67                 for (i = codetable; i->c_val != -1; i++)
68                         if (i->c_val == value)
69                                 return (i->c_name);
70         return "<unknown>";
71 };
72
73 static void log_handle_reconnect(struct uloop_timeout *timeout)
74 {
75         sender.fd = usock((log_udp) ? (USOCK_UDP) : (USOCK_TCP), log_ip, log_port);
76         if (sender.fd < 0) {
77                 fprintf(stderr, "failed to connect: %s\n", strerror(errno));
78                 uloop_timeout_set(&retry, 1000);
79         } else {
80                 uloop_fd_add(&sender, ULOOP_READ);
81                 syslog(0, "Logread connected to %s:%s\n", log_ip, log_port);
82         }
83 }
84
85 static void log_handle_remove(struct ubus_context *ctx, struct ubus_subscriber *s,
86                         uint32_t id)
87 {
88         fprintf(stderr, "Object %08x went away\n", id);
89 }
90
91 static void log_handle_fd(struct uloop_fd *u, unsigned int events)
92 {
93         if (u->eof) {
94                 uloop_fd_delete(u);
95                 close(sender.fd);
96                 sender.fd = -1;
97                 uloop_timeout_set(&retry, 1000);
98         }
99 }
100
101 static int log_notify(struct ubus_context *ctx, struct ubus_object *obj,
102                         struct ubus_request_data *req, const char *method,
103                         struct blob_attr *msg)
104 {
105         struct blob_attr *tb[__LOG_MAX];
106         struct stat s;
107         char buf[512];
108         uint32_t p;
109         char *str;
110         time_t t;
111         char *c;
112
113         if (sender.fd < 0)
114                 return 0;
115
116         blobmsg_parse(log_policy, ARRAY_SIZE(log_policy), tb, blob_data(msg), blob_len(msg));
117         if (!tb[LOG_ID] || !tb[LOG_PRIO] || !tb[LOG_SOURCE] || !tb[LOG_TIME])
118                 return 1;
119
120         if ((log_type == LOG_FILE) && log_size && (!stat(log_file, &s)) && (s.st_size > log_size)) {
121                 char *old = malloc(strlen(log_file) + 5);
122
123                 close(sender.fd);
124                 if (old) {
125                         sprintf(old, "%s.old", log_file);
126                         rename(log_file, old);
127                         free(old);
128                 }
129                 sender.fd = open(log_file, O_CREAT | O_WRONLY | O_APPEND, 0600);
130                 if (sender.fd < 0) {
131 //                      fprintf(stderr, "failed to open %s: %s\n", log_file, strerror(errno));
132                         exit(-1);
133                 }
134         }
135
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                 int len;
144
145                 *buf = '\0';
146                 if (log_prefix)
147                         snprintf(buf, sizeof(buf), "%s: ", log_prefix);
148
149                 len = strlen(buf);
150
151                 snprintf(&buf[len], sizeof(buf) - len, "%s%s\n",
152                         (blobmsg_get_u32(tb[LOG_SOURCE])) ? ("") : ("kernel: "),
153                         method);
154                 if (log_udp)
155                         err = write(sender.fd, buf, strlen(buf));
156                 else
157                         err = send(sender.fd, buf, strlen(buf), 0);
158
159                 if (err < 0) {
160                         syslog(0, "failed to send log data to %s:%s via %s\n",
161                                 log_ip, log_port, (log_udp) ? ("udp") : ("tcp"));
162                         uloop_fd_delete(&sender);
163                         close(sender.fd);
164                         sender.fd = -1;
165                         uloop_timeout_set(&retry, 1000);
166                 }
167         } else {
168                 snprintf(buf, sizeof(buf), "%s %s.%s%s %s\n",
169                         c, getcodetext(LOG_FAC(p) << 3, facilitynames), getcodetext(LOG_PRI(p), prioritynames),
170                         (blobmsg_get_u32(tb[LOG_SOURCE])) ? ("") : (" kernel:"),
171                         method);
172                 write(sender.fd, buf, strlen(buf));
173         }
174
175         free(str);
176         if (log_type == LOG_FILE)
177                 fsync(sender.fd);
178
179         return 0;
180 }
181
182 static void follow_log(struct ubus_context *ctx, int id)
183 {
184         FILE *fp;
185         int ret;
186
187         signal(SIGPIPE, SIG_IGN);
188
189         if (pid_file) {
190                 fp = fopen(pid_file, "w+");
191                 if (fp) {
192                         fprintf(fp, "%d", getpid());
193                         fclose(fp);
194                 }
195         }
196
197         uloop_init();
198         ubus_add_uloop(ctx);
199
200         log_event.remove_cb = log_handle_remove;
201         log_event.cb = log_notify;
202         ret = ubus_register_subscriber(ctx, &log_event);
203         if (ret)
204                 fprintf(stderr, "Failed to add watch handler: %s\n", ubus_strerror(ret));
205
206         ret = ubus_subscribe(ctx, &log_event, id);
207         if (ret)
208                 fprintf(stderr, "Failed to add watch handler: %s\n", ubus_strerror(ret));
209
210         if (log_ip && log_port) {
211                 openlog("logread", LOG_PID, LOG_DAEMON);
212                 log_type = LOG_NET;
213                 sender.cb = log_handle_fd;
214                 retry.cb = log_handle_reconnect;
215                 uloop_timeout_set(&retry, 1000);
216         } else if (log_file) {
217                 log_type = LOG_FILE;
218                 sender.fd = open(log_file, O_CREAT | O_WRONLY| O_APPEND, 0600);
219                 if (sender.fd < 0) {
220                         fprintf(stderr, "failed to open %s: %s\n", log_file, strerror(errno));
221                         exit(-1);
222                 }
223         } else {
224                 sender.fd = STDOUT_FILENO;
225         }
226
227         uloop_run();
228         ubus_free(ctx);
229         uloop_done();
230 }
231
232 enum {
233         READ_LINE,
234         __READ_MAX
235 };
236
237
238
239 static const struct blobmsg_policy read_policy[] = {
240         [READ_LINE] = { .name = "lines", .type = BLOBMSG_TYPE_ARRAY },
241 };
242
243 static void read_cb(struct ubus_request *req, int type, struct blob_attr *msg)
244 {
245         struct blob_attr *cur;
246         struct blob_attr *_tb[__READ_MAX];
247         time_t t;
248         int rem;
249
250         if (!msg)
251                 return;
252
253         blobmsg_parse(read_policy, ARRAY_SIZE(read_policy), _tb, blob_data(msg), blob_len(msg));
254         if (!_tb[READ_LINE])
255                 return;
256         blobmsg_for_each_attr(cur, _tb[READ_LINE], rem) {
257                 struct blob_attr *tb[__LOG_MAX];
258                 uint32_t p;
259                 char *c;
260
261                 if (blobmsg_type(cur) != BLOBMSG_TYPE_TABLE)
262                         continue;
263
264                 blobmsg_parse(log_policy, ARRAY_SIZE(log_policy), tb, blobmsg_data(cur), blobmsg_data_len(cur));
265                 if (!tb[LOG_MSG] || !tb[LOG_ID] || !tb[LOG_PRIO] || !tb[LOG_SOURCE] || !tb[LOG_TIME])
266                         continue;
267
268                 t = blobmsg_get_u64(tb[LOG_TIME]);
269                 p = blobmsg_get_u32(tb[LOG_PRIO]);
270                 c = ctime(&t);
271                 c[strlen(c) - 1] = '\0';
272
273                 printf("%s %s.%s%s %s\n",
274                         c, getcodetext(LOG_FAC(p) << 3, facilitynames), getcodetext(LOG_PRI(p), prioritynames),
275                         (blobmsg_get_u32(tb[LOG_SOURCE])) ? ("") : (" kernel:"),
276                         blobmsg_get_string(tb[LOG_MSG]));
277         }
278 }
279
280 static int usage(const char *prog)
281 {
282         fprintf(stderr, "Usage: %s [options]\n"
283                 "Options:\n"
284                 "    -s <path>          Path to ubus socket\n"
285                 "    -l <count>         Got only the last 'count' messages\n"
286                 "    -r <server> <port> Stream message to a server\n"
287                 "    -F <file>          Log file\n"
288                 "    -S <bytes>         Log size\n"
289                 "    -p <file>          PID file\n"
290                 "    -P <prefix>        Prefix custom text to streamed messages\n"
291                 "    -f                 Follow log messages\n"
292                 "    -u                 Use UDP as the protocol\n"
293                 "\n", prog);
294         return 1;
295 }
296
297 int main(int argc, char **argv)
298 {
299         struct ubus_context *ctx;
300         uint32_t id;
301         const char *ubus_socket = NULL;
302         int ch, ret, subscribe = 0, lines = 0;
303         static struct blob_buf b;
304
305         while ((ch = getopt(argc, argv, "ufcs:l:r:F:p:S:P:")) != -1) {
306                 switch (ch) {
307                 case 'u':
308                         log_udp = 1;
309                         break;
310                 case 's':
311                         ubus_socket = optarg;
312                         break;
313                 case 'r':
314                         log_ip = optarg++;
315                         log_port = argv[optind++];
316                         break;
317                 case 'F':
318                         log_file = optarg;
319                         break;
320                 case 'p':
321                         pid_file = optarg;
322                         break;
323                 case 'P':
324                         log_prefix = optarg;
325                         break;
326                 case 'f':
327                         subscribe = 1;
328                         break;
329                 case 'l':
330                         lines = atoi(optarg);
331                         break;
332                 case 'S':
333                         log_size = atoi(optarg);
334                         if (log_size < 1)
335                                 log_size = 1;
336                         log_size *= 1024;
337                         break;
338                 default:
339                         return usage(*argv);
340                 }
341         }
342
343         ctx = ubus_connect(ubus_socket);
344         if (!ctx) {
345                 fprintf(stderr, "Failed to connect to ubus\n");
346                 return -1;
347         }
348
349         ret = ubus_lookup_id(ctx, "log", &id);
350         if (ret)
351                 fprintf(stderr, "Failed to find log object: %s\n", ubus_strerror(ret));
352
353         if (!subscribe || lines) {
354                 blob_buf_init(&b, 0);
355                 if (lines)
356                         blobmsg_add_u32(&b, "lines", lines);
357                 ubus_invoke(ctx, id, "read", b.head, read_cb, 0, 3000);
358         }
359
360         if (subscribe)
361                 follow_log(ctx, id);
362
363         return 0;
364 }