blob: 3cae9e936adbebbfa6c9e20961349b244a210e58 [file] [log] [blame]
liubin281ac462023-07-19 14:22:54 +08001/*
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/ustream.h>
29#include <libubox/blobmsg_json.h>
30#include <libubox/usock.h>
31#include <libubox/uloop.h>
32#include "libubus.h"
33#include "syslog.h"
34#include "log_config.h"
35
36enum {
37 LOG_STDOUT,
38 LOG_FILE,
39 LOG_NET,
40};
41
42enum {
43 LOG_MSG,
44 LOG_ID,
45 LOG_PRIO,
46 LOG_SOURCE,
47 LOG_TIME,
48 __LOG_MAX
49};
50
51static 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
59static struct uloop_timeout retry;
60static struct uloop_fd sender;
61static const char *log_file, *log_ip, *log_port, *log_prefix, *pid_file, *hostname;
62static int log_type = LOG_STDOUT;
63static int log_size = 1 * 1024 * 1024, log_udp, log_follow = 0;
64static struct file_list_t file_list;
65static struct filter_list_t *filter_log = NULL;
66static char tmp_log[48] = {0};
67
68static const char* getcodetext(int value, CODE *codetable) {
69 CODE *i;
70
71 if (value >= 0)
72 for (i = codetable; i->c_val != -1; i++)
73 if (i->c_val == value)
74 return (i->c_name);
75 return "<unknown>";
76};
77
78static void log_handle_reconnect(struct uloop_timeout *timeout)
79{
80 sender.fd = usock((log_udp) ? (USOCK_UDP) : (USOCK_TCP), log_ip, log_port);
81 if (sender.fd < 0) {
82 fprintf(stderr, "failed to connect: %s\n", strerror(errno));
83 uloop_timeout_set(&retry, 1000);
84 } else {
85 uloop_fd_add(&sender, ULOOP_READ);
86 syslog(0, "Logread connected to %s:%s\n", log_ip, log_port);
87 }
88}
89
90static void log_handle_fd(struct uloop_fd *u, unsigned int events)
91{
92 if (u->eof) {
93 uloop_fd_delete(u);
94 close(sender.fd);
95 sender.fd = -1;
96 uloop_timeout_set(&retry, 1000);
97 }
98}
99
100static int filter_char_to_pri(char c)
101{
102 switch (c) {
103 case 'v':
104 return 8;
105 case 'd':
106 return LOG_DEBUG;
107 case 'i':
108 return LOG_INFO;
109 case 'w':
110 return LOG_WARNING;
111 case 'e':
112 return LOG_ERR;
113 case 'f':
114 return LOG_ALERT;
115 case '*':
116 default:
117 return 8;
118 }
119}
120
121static int syslog_fileter_log(int pri, char *tag, struct filter_list_t *filter)
122{
123 struct filter_list_t *_filter = filter;
124
125 while(_filter)
126 {
127 int p = filter_char_to_pri(_filter->priority);
128 if(_filter->tag)
129 {
130 int len = strlen(_filter->tag);
131 // tag and priority
132 if(0 == memcmp(_filter->tag, tag, len) && ((pri < p) || (pri == p)))
133 return 0;
134 }else{ // have no tag
135 if(pri > p)
136 return -1;
137 else
138 return 0;
139 }
140 _filter = _filter->next;
141 }
142
143 return -1;
144}
145static int log_notify(struct blob_attr *msg)
146{
147 struct blob_attr *tb[__LOG_MAX];
148 struct stat s;
149 char buf[512];
150 uint32_t p;
151 char *str;
152 time_t t;
153 char *c, *m;
154
155 if (sender.fd < 0)
156 return 0;
157
158 blobmsg_parse(log_policy, ARRAY_SIZE(log_policy), tb, blob_data(msg), blob_len(msg));
159 if (!tb[LOG_ID] || !tb[LOG_PRIO] || !tb[LOG_SOURCE] || !tb[LOG_TIME] || !tb[LOG_MSG])
160 return 1;
161
162 if ((log_type == LOG_FILE) && log_size && (!stat(tmp_log, &s)) && (s.st_size > log_size)) {
163 sender.fd = get_rotate_file(sender.fd, log_file, &file_list);
164 if (sender.fd < 0) {
165 fprintf(stderr, "failed to open %s: %s\n", tmp_log, strerror(errno));
166 exit(-1);
167 }
168 }
169
170 m = blobmsg_get_string(tb[LOG_MSG]);
171 t = blobmsg_get_u64(tb[LOG_TIME]) / 1000;
172 c = ctime(&t);
173 p = blobmsg_get_u32(tb[LOG_PRIO]);
174 c[strlen(c) - 1] = '\0';
175 str = blobmsg_format_json(msg, true);
176
177 if(filter_log && syslog_fileter_log(LOG_PRI(p), m, filter_log))
178 {
179 // printf("%s %d: fileter pri:%d tag:%s!\n", __FUNCTION__, __LINE__, p, m);
180 exit(-1);
181 }
182 if (log_type == LOG_NET) {
183 int err;
184
185 snprintf(buf, sizeof(buf), "<%u>", p);
186 strncat(buf, c + 4, 16);
187 if (hostname) {
188 strncat(buf, hostname, sizeof(buf));
189 strncat(buf, " ", sizeof(buf));
190 }
191 if (log_prefix) {
192 strncat(buf, log_prefix, sizeof(buf));
193 strncat(buf, ": ", sizeof(buf));
194 }
195 if (blobmsg_get_u32(tb[LOG_SOURCE]) == SOURCE_KLOG)
196 strncat(buf, "kernel: ", sizeof(buf));
197 strncat(buf, m, sizeof(buf));
198 if (log_udp)
199 err = write(sender.fd, buf, strlen(buf));
200 else
201 err = send(sender.fd, buf, strlen(buf), 0);
202
203 if (err < 0) {
204 syslog(0, "failed to send log data to %s:%s via %s\n",
205 log_ip, log_port, (log_udp) ? ("udp") : ("tcp"));
206 uloop_fd_delete(&sender);
207 close(sender.fd);
208 sender.fd = -1;
209 uloop_timeout_set(&retry, 1000);
210 }
211 } else {
212 snprintf(buf, sizeof(buf), "%s %s.%s%s %s\n",
213 c, getcodetext(LOG_FAC(p) << 3, facilitynames), getcodetext(LOG_PRI(p), prioritynames),
214 (blobmsg_get_u32(tb[LOG_SOURCE])) ? ("") : (" kernel:"), m);
215 write(sender.fd, buf, strlen(buf));
216 }
217
218 free(str);
219 if (log_type == LOG_FILE)
220 fsync(sender.fd);
221
222 return 0;
223}
224
225static void logread_fd_data_cb(struct ustream *s, int bytes)
226{
227 while (true) {
228 int len;
229 struct blob_attr *a;
230
231 a = (void*) ustream_get_read_buf(s, &len);
232 if (len < sizeof(*a) || len < blob_len(a) + sizeof(*a))
233 break;
234 log_notify(a);
235 ustream_consume(s, blob_len(a) + sizeof(*a));
236 }
237 if (!log_follow)
238 uloop_end();
239}
240
241static void logread_fd_cb(struct ubus_request *req, int fd)
242{
243 static struct ustream_fd test_fd;
244
245 test_fd.stream.notify_read = logread_fd_data_cb;
246 ustream_fd_init(&test_fd, fd);
247}
248
249static void logread_complete_cb(struct ubus_request *req, int ret)
250{
251}
252
253void* syslog_main(void* 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 log_config_entry *config = (log_config_entry *)argv;
263
264 pthread_detach(pthread_self());
265
266 if (NULL == argv)
267 return NULL;
268
269 signal(SIGPIPE, SIG_IGN);
270 uloop_init();
271
272 log_file = config->out_path;
273 memset(&file_list, 0, sizeof(struct file_list_t));
274 file_list.total = config->rotate_file_count;
275 if(config->rotate_file_size)
276 log_size = config->rotate_file_size;
277 if(config->ip)
278 {
279 printf("%s %d : %s:%s\n", __FUNCTION__, __LINE__, config->ip, config->port);
280 log_ip = config->ip;
281 log_port = config->port;
282 }
283 filter_log = config->filter_list;
284 // Follow log messages
285 log_follow = 1;
286 ctx = ubus_connect(ubus_socket);
287 if (!ctx) {
288 fprintf(stderr, "Failed to connect to ubus\n");
289 return -1;
290 }
291 ubus_add_uloop(ctx);
292
293 printf("syslog log start...\n");
294 /* ugly ugly ugly ... we need a real reconnect logic */
295 do {
296 ret = ubus_lookup_id(ctx, "log", &id);
297 if (ret) {
298 fprintf(stderr, "Failed to find log object: %s\n", ubus_strerror(ret));
299 sleep(1);
300 continue;
301 }
302
303 blob_buf_init(&b, 0);
304 if (lines)
305 blobmsg_add_u32(&b, "lines", lines);
306 else if (log_follow)
307 blobmsg_add_u32(&b, "lines", 0);
308 if (log_follow) {
309 if (pid_file) {
310 FILE *fp = fopen(pid_file, "w+");
311 if (fp) {
312 fprintf(fp, "%d", getpid());
313 fclose(fp);
314 }
315 }
316 }
317
318 if (log_ip && log_port) {
319 openlog("logread", LOG_PID, LOG_DAEMON);
320 log_type = LOG_NET;
321 sender.cb = log_handle_fd;
322 retry.cb = log_handle_reconnect;
323 uloop_timeout_set(&retry, 1000);
324 } else if (log_file) {
325 log_type = LOG_FILE;
326 // 先将文件保存到 /tmp/log/ 目录下,后面到达 rotate_file_size 后,转移到out_path
327 sprintf(tmp_log, "/tmp/log%s", strstr_tail(log_file, "/"));
328 sender.fd = open(tmp_log, O_CREAT | O_WRONLY| O_APPEND, 0600);
329 if (sender.fd < 0) {
330 fprintf(stderr, "failed to open %s: %s\n", tmp_log, strerror(errno));
331 exit(-1);
332 }
333 } else {
334 sender.fd = STDOUT_FILENO;
335 }
336
337 ubus_invoke_async(ctx, id, "read", b.head, &req);
338 req.fd_cb = logread_fd_cb;
339 req.complete_cb = logread_complete_cb;
340 ubus_complete_request_async(ctx, &req);
341
342 uloop_run();
343 ubus_free(ctx);
344 uloop_done();
345
346 } while (ret && tries--);
347
348 pthread_exit(NULL);
349 return NULL;
350}