blob: 1e6f55fa4cd74e50eebfa9b0a6e323f6c5d8ec4b [file] [log] [blame]
Mark Salyzynae4d9282014-10-15 08:49:39 -07001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <ctype.h>
18#include <errno.h>
19#include <inttypes.h>
20#include <limits.h>
21#include <stdarg.h>
22#include <stdlib.h>
23#include <sys/prctl.h>
24#include <sys/uio.h>
25#include <syslog.h>
26
27#include <log/logger.h>
28
29#include "LogKlog.h"
30
31#define KMSG_PRIORITY(PRI) \
32 '<', \
33 '0' + (LOG_SYSLOG | (PRI)) / 10, \
34 '0' + (LOG_SYSLOG | (PRI)) % 10, \
35 '>'
36
37static const char priority_message[] = { KMSG_PRIORITY(LOG_INFO), '\0' };
38
Mark Salyzyn2c3b3002015-05-22 15:23:44 -070039// Parsing is hard
40
41// called if we see a '<', s is the next character, returns pointer after '>'
42static char *is_prio(char *s) {
43 if (!isdigit(*s++)) {
44 return NULL;
45 }
Mark Salyzyn618d0de2015-07-13 10:19:34 -070046 static const size_t max_prio_len = 4;
47 size_t len = 0;
Mark Salyzyn2c3b3002015-05-22 15:23:44 -070048 char c;
Mark Salyzyn618d0de2015-07-13 10:19:34 -070049 while (((c = *s++)) && (++len <= max_prio_len)) {
Mark Salyzynee49c6a2015-06-12 14:59:42 -070050 if (!isdigit(c)) {
51 return (c == '>') ? s : NULL;
Mark Salyzyn2c3b3002015-05-22 15:23:44 -070052 }
53 }
54 return NULL;
55}
56
57// called if we see a '[', s is the next character, returns pointer after ']'
58static char *is_timestamp(char *s) {
59 while (*s == ' ') {
60 ++s;
61 }
62 if (!isdigit(*s++)) {
63 return NULL;
64 }
65 bool first_period = true;
66 char c;
67 while ((c = *s++)) {
68 if ((c == '.') && first_period) {
69 first_period = false;
Mark Salyzynee49c6a2015-06-12 14:59:42 -070070 } else if (!isdigit(c)) {
71 return ((c == ']') && !first_period && (*s == ' ')) ? s : NULL;
Mark Salyzyn2c3b3002015-05-22 15:23:44 -070072 }
73 }
74 return NULL;
75}
76
77// Like strtok_r with "\r\n" except that we look for log signatures (regex)
Mark Salyzyn618d0de2015-07-13 10:19:34 -070078// \(\(<[0-9]\{1,4\}>\)\([[] *[0-9]+[.][0-9]+[]] \)\{0,1\}\|[[] *[0-9]+[.][0-9]+[]] \)
Mark Salyzyn2c3b3002015-05-22 15:23:44 -070079// and split if we see a second one without a newline.
80
81#define SIGNATURE_MASK 0xF0
82// <digit> following ('0' to '9' masked with ~SIGNATURE_MASK) added to signature
83#define LESS_THAN_SIG SIGNATURE_MASK
84#define OPEN_BRACKET_SIG ((SIGNATURE_MASK << 1) & SIGNATURE_MASK)
85// space is one more than <digit> of 9
Mark Salyzyn3e21de22015-06-08 14:51:30 -070086#define OPEN_BRACKET_SPACE ((char)(OPEN_BRACKET_SIG | 10))
Mark Salyzyn2c3b3002015-05-22 15:23:44 -070087
88char *log_strtok_r(char *s, char **last) {
89 if (!s) {
90 if (!(s = *last)) {
91 return NULL;
92 }
93 // fixup for log signature split <,
94 // LESS_THAN_SIG + <digit>
95 if ((*s & SIGNATURE_MASK) == LESS_THAN_SIG) {
96 *s = (*s & ~SIGNATURE_MASK) + '0';
97 *--s = '<';
98 }
99 // fixup for log signature split [,
100 // OPEN_BRACKET_SPACE is space, OPEN_BRACKET_SIG + <digit>
101 if ((*s & SIGNATURE_MASK) == OPEN_BRACKET_SIG) {
102 if (*s == OPEN_BRACKET_SPACE) {
103 *s = ' ';
104 } else {
105 *s = (*s & ~SIGNATURE_MASK) + '0';
106 }
107 *--s = '[';
108 }
109 }
110
111 s += strspn(s, "\r\n");
112
113 if (!*s) { // no non-delimiter characters
114 *last = NULL;
115 return NULL;
116 }
117 char *peek, *tok = s;
118
119 for (;;) {
120 char c = *s++;
121 switch (c) {
122 case '\0':
123 *last = NULL;
124 return tok;
125
126 case '\r':
127 case '\n':
128 s[-1] = '\0';
129 *last = s;
130 return tok;
131
132 case '<':
133 peek = is_prio(s);
134 if (!peek) {
135 break;
136 }
137 if (s != (tok + 1)) { // not first?
138 s[-1] = '\0';
139 *s &= ~SIGNATURE_MASK;
140 *s |= LESS_THAN_SIG; // signature for '<'
141 *last = s;
142 return tok;
143 }
144 s = peek;
145 if ((*s == '[') && ((peek = is_timestamp(s + 1)))) {
146 s = peek;
147 }
148 break;
149
150 case '[':
151 peek = is_timestamp(s);
152 if (!peek) {
153 break;
154 }
155 if (s != (tok + 1)) { // not first?
156 s[-1] = '\0';
157 if (*s == ' ') {
158 *s = OPEN_BRACKET_SPACE;
159 } else {
160 *s &= ~SIGNATURE_MASK;
161 *s |= OPEN_BRACKET_SIG; // signature for '['
162 }
163 *last = s;
164 return tok;
165 }
166 s = peek;
167 break;
168 }
169 }
Mark Salyzyn618d0de2015-07-13 10:19:34 -0700170 // NOTREACHED
Mark Salyzyn2c3b3002015-05-22 15:23:44 -0700171}
172
Mark Salyzynae4d9282014-10-15 08:49:39 -0700173log_time LogKlog::correction = log_time(CLOCK_REALTIME) - log_time(CLOCK_MONOTONIC);
174
Mark Salyzyn77187782015-05-12 15:21:31 -0700175LogKlog::LogKlog(LogBuffer *buf, LogReader *reader, int fdWrite, int fdRead, bool auditd) :
176 SocketListener(fdRead, false),
177 logbuf(buf),
178 reader(reader),
179 signature(CLOCK_MONOTONIC),
Mark Salyzyn77187782015-05-12 15:21:31 -0700180 initialized(false),
181 enableLogging(true),
182 auditd(auditd) {
Mark Salyzynae4d9282014-10-15 08:49:39 -0700183 static const char klogd_message[] = "%slogd.klogd: %" PRIu64 "\n";
184 char buffer[sizeof(priority_message) + sizeof(klogd_message) + 20 - 4];
185 snprintf(buffer, sizeof(buffer), klogd_message, priority_message,
186 signature.nsec());
187 write(fdWrite, buffer, strlen(buffer));
188}
189
190bool LogKlog::onDataAvailable(SocketClient *cli) {
191 if (!initialized) {
192 prctl(PR_SET_NAME, "logd.klogd");
193 initialized = true;
194 enableLogging = false;
195 }
196
197 char buffer[LOGGER_ENTRY_MAX_PAYLOAD];
198 size_t len = 0;
199
200 for(;;) {
201 ssize_t retval = 0;
202 if ((sizeof(buffer) - 1 - len) > 0) {
203 retval = read(cli->getSocket(), buffer + len, sizeof(buffer) - 1 - len);
204 }
205 if ((retval == 0) && (len == 0)) {
206 break;
207 }
208 if (retval < 0) {
209 return false;
210 }
211 len += retval;
212 bool full = len == (sizeof(buffer) - 1);
213 char *ep = buffer + len;
214 *ep = '\0';
215 len = 0;
Mark Salyzyn2c3b3002015-05-22 15:23:44 -0700216 for(char *ptr = NULL, *tok = buffer;
217 ((tok = log_strtok_r(tok, &ptr)));
Mark Salyzynae4d9282014-10-15 08:49:39 -0700218 tok = NULL) {
219 if (((tok + strlen(tok)) == ep) && (retval != 0) && full) {
220 len = strlen(tok);
221 memmove(buffer, tok, len);
222 break;
223 }
224 if (*tok) {
225 log(tok);
226 }
227 }
228 }
229
230 return true;
231}
232
233
234void LogKlog::calculateCorrection(const log_time &monotonic,
235 const char *real_string) {
236 log_time real;
237 if (!real.strptime(real_string, "%Y-%m-%d %H:%M:%S.%09q UTC")) {
238 return;
239 }
240 // kernel report UTC, log_time::strptime is localtime from calendar.
241 // Bionic and liblog strptime does not support %z or %Z to pick up
242 // timezone so we are calculating our own correction.
243 time_t now = real.tv_sec;
244 struct tm tm;
245 memset(&tm, 0, sizeof(tm));
246 tm.tm_isdst = -1;
247 localtime_r(&now, &tm);
248 real.tv_sec += tm.tm_gmtoff;
249 correction = real - monotonic;
250}
251
252void LogKlog::sniffTime(log_time &now, const char **buf, bool reverse) {
253 const char *cp;
254 if ((cp = now.strptime(*buf, "[ %s.%q]"))) {
255 static const char suspend[] = "PM: suspend entry ";
256 static const char resume[] = "PM: suspend exit ";
Mark Salyzynacb1ddf2015-07-23 09:22:50 -0700257 static const char healthd[] = "healthd: battery ";
Mark Salyzynae4d9282014-10-15 08:49:39 -0700258 static const char suspended[] = "Suspended for ";
259
260 if (isspace(*cp)) {
261 ++cp;
262 }
263 if (!strncmp(cp, suspend, sizeof(suspend) - 1)) {
264 calculateCorrection(now, cp + sizeof(suspend) - 1);
265 } else if (!strncmp(cp, resume, sizeof(resume) - 1)) {
266 calculateCorrection(now, cp + sizeof(resume) - 1);
Mark Salyzynacb1ddf2015-07-23 09:22:50 -0700267 } else if (!strncmp(cp, healthd, sizeof(healthd) - 1)) {
268 // look for " 2???-??-?? ??:??:??.????????? ???"
269 const char *tp;
270 for (tp = cp + sizeof(healthd) - 1; *tp && (*tp != '\n'); ++tp) {
271 if ((tp[0] == ' ') && (tp[1] == '2') && (tp[5] == '-')) {
272 calculateCorrection(now, tp + 1);
273 break;
274 }
275 }
Mark Salyzynae4d9282014-10-15 08:49:39 -0700276 } else if (!strncmp(cp, suspended, sizeof(suspended) - 1)) {
277 log_time real;
278 char *endp;
279 real.tv_sec = strtol(cp + sizeof(suspended) - 1, &endp, 10);
280 if (*endp == '.') {
281 real.tv_nsec = strtol(endp + 1, &endp, 10) * 1000000L;
282 if (reverse) {
283 correction -= real;
284 } else {
285 correction += real;
286 }
287 }
288 }
289
290 convertMonotonicToReal(now);
291 *buf = cp;
292 } else {
293 now = log_time(CLOCK_REALTIME);
294 }
295}
296
297// Passed the entire SYSLOG_ACTION_READ_ALL buffer and interpret a
298// compensated start time.
299void LogKlog::synchronize(const char *buf) {
300 const char *cp = strstr(buf, "] PM: suspend e");
301 if (!cp) {
302 return;
303 }
304
305 do {
306 --cp;
307 } while ((cp > buf) && (isdigit(*cp) || isspace(*cp) || (*cp == '.')));
308
309 log_time now;
310 sniffTime(now, &cp, true);
311
312 char *suspended = strstr(buf, "] Suspended for ");
313 if (!suspended || (suspended > cp)) {
314 return;
315 }
316 cp = suspended;
317
318 do {
319 --cp;
320 } while ((cp > buf) && (isdigit(*cp) || isspace(*cp) || (*cp == '.')));
321
322 sniffTime(now, &cp, true);
323}
324
325// kernel log prefix, convert to a kernel log priority number
326static int parseKernelPrio(const char **buf) {
327 int pri = LOG_USER | LOG_INFO;
328 const char *cp = *buf;
329 if (*cp == '<') {
330 pri = 0;
331 while(isdigit(*++cp)) {
332 pri = (pri * 10) + *cp - '0';
333 }
334 if (*cp == '>') {
335 ++cp;
336 } else {
337 cp = *buf;
338 pri = LOG_USER | LOG_INFO;
339 }
340 *buf = cp;
341 }
342 return pri;
343}
344
345// Convert kernel log priority number into an Android Logger priority number
346static int convertKernelPrioToAndroidPrio(int pri) {
347 switch(pri & LOG_PRIMASK) {
348 case LOG_EMERG:
349 // FALLTHRU
350 case LOG_ALERT:
351 // FALLTHRU
352 case LOG_CRIT:
353 return ANDROID_LOG_FATAL;
354
355 case LOG_ERR:
356 return ANDROID_LOG_ERROR;
357
358 case LOG_WARNING:
359 return ANDROID_LOG_WARN;
360
361 default:
362 // FALLTHRU
363 case LOG_NOTICE:
364 // FALLTHRU
365 case LOG_INFO:
366 break;
367
368 case LOG_DEBUG:
369 return ANDROID_LOG_DEBUG;
370 }
371
372 return ANDROID_LOG_INFO;
373}
374
375//
376// log a message into the kernel log buffer
377//
378// Filter rules to parse <PRI> <TIME> <tag> and <message> in order for
379// them to appear correct in the logcat output:
380//
381// LOG_KERN (0):
382// <PRI>[<TIME>] <tag> ":" <message>
383// <PRI>[<TIME>] <tag> <tag> ":" <message>
384// <PRI>[<TIME>] <tag> <tag>_work ":" <message>
385// <PRI>[<TIME>] <tag> '<tag>.<num>' ":" <message>
386// <PRI>[<TIME>] <tag> '<tag><num>' ":" <message>
387// <PRI>[<TIME>] <tag>_host '<tag>.<num>' ":" <message>
388// (unimplemented) <PRI>[<TIME>] <tag> '<num>.<tag>' ":" <message>
389// <PRI>[<TIME>] "[INFO]"<tag> : <message>
390// <PRI>[<TIME>] "------------[ cut here ]------------" (?)
391// <PRI>[<TIME>] "---[ end trace 3225a3070ca3e4ac ]---" (?)
392// LOG_USER, LOG_MAIL, LOG_DAEMON, LOG_AUTH, LOG_SYSLOG, LOG_LPR, LOG_NEWS
393// LOG_UUCP, LOG_CRON, LOG_AUTHPRIV, LOG_FTP:
394// <PRI+TAG>[<TIME>] (see sys/syslog.h)
395// Observe:
396// Minimum tag length = 3 NB: drops things like r5:c00bbadf, but allow PM:
397// Maximum tag words = 2
398// Maximum tag length = 16 NB: we are thinking of how ugly logcat can get.
399// Not a Tag if there is no message content.
400// leading additional spaces means no tag, inherit last tag.
401// Not a Tag if <tag>: is "ERROR:", "WARNING:", "INFO:" or "CPU:"
402// Drop:
403// empty messages
404// messages with ' audit(' in them if auditd is running
405// logd.klogd:
406// return -1 if message logd.klogd: <signature>
407//
408int LogKlog::log(const char *buf) {
409 if (auditd && strstr(buf, " audit(")) {
410 return 0;
411 }
412
413 int pri = parseKernelPrio(&buf);
414
415 log_time now;
416 sniffTime(now, &buf, false);
417
418 // sniff for start marker
419 const char klogd_message[] = "logd.klogd: ";
420 if (!strncmp(buf, klogd_message, sizeof(klogd_message) - 1)) {
421 char *endp;
422 uint64_t sig = strtoll(buf + sizeof(klogd_message) - 1, &endp, 10);
423 if (sig == signature.nsec()) {
424 if (initialized) {
425 enableLogging = true;
426 } else {
427 enableLogging = false;
428 }
429 return -1;
430 }
431 return 0;
432 }
433
434 if (!enableLogging) {
435 return 0;
436 }
437
438 // Parse pid, tid and uid (not possible)
439 const pid_t pid = 0;
440 const pid_t tid = 0;
441 const uid_t uid = 0;
442
443 // Parse (rules at top) to pull out a tag from the incoming kernel message.
444 // Some may view the following as an ugly heuristic, the desire is to
445 // beautify the kernel logs into an Android Logging format; the goal is
446 // admirable but costly.
447 while (isspace(*buf)) {
448 ++buf;
449 }
450 if (!*buf) {
451 return 0;
452 }
453 const char *start = buf;
454 const char *tag = "";
455 const char *etag = tag;
456 if (!isspace(*buf)) {
457 const char *bt, *et, *cp;
458
459 bt = buf;
460 if (!strncmp(buf, "[INFO]", 6)) {
461 // <PRI>[<TIME>] "[INFO]"<tag> ":" message
462 bt = buf + 6;
463 }
464 for(et = bt; *et && (*et != ':') && !isspace(*et); ++et);
465 for(cp = et; isspace(*cp); ++cp);
466 size_t size;
467
468 if (*cp == ':') {
469 // One Word
470 tag = bt;
471 etag = et;
472 buf = cp + 1;
473 } else {
474 size = et - bt;
475 if (strncmp(bt, cp, size)) {
476 // <PRI>[<TIME>] <tag>_host '<tag>.<num>' : message
477 if (!strncmp(bt + size - 5, "_host", 5)
Mark Salyzyn618d0de2015-07-13 10:19:34 -0700478 && !strncmp(bt, cp, size - 5)) {
Mark Salyzynae4d9282014-10-15 08:49:39 -0700479 const char *b = cp;
480 cp += size - 5;
481 if (*cp == '.') {
482 while (!isspace(*++cp) && (*cp != ':'));
483 const char *e;
484 for(e = cp; isspace(*cp); ++cp);
485 if (*cp == ':') {
486 tag = b;
487 etag = e;
488 buf = cp + 1;
489 }
490 }
491 } else {
492 while (!isspace(*++cp) && (*cp != ':'));
493 const char *e;
494 for(e = cp; isspace(*cp); ++cp);
495 // Two words
496 if (*cp == ':') {
497 tag = bt;
498 etag = e;
499 buf = cp + 1;
500 }
501 }
502 } else if (isspace(cp[size])) {
Mark Salyzynae4d9282014-10-15 08:49:39 -0700503 cp += size;
504 while (isspace(*++cp));
505 // <PRI>[<TIME>] <tag> <tag> : message
506 if (*cp == ':') {
507 tag = bt;
508 etag = et;
509 buf = cp + 1;
510 }
511 } else if (cp[size] == ':') {
512 // <PRI>[<TIME>] <tag> <tag> : message
513 tag = bt;
514 etag = et;
515 buf = cp + size + 1;
516 } else if ((cp[size] == '.') || isdigit(cp[size])) {
517 // <PRI>[<TIME>] <tag> '<tag>.<num>' : message
518 // <PRI>[<TIME>] <tag> '<tag><num>' : message
519 const char *b = cp;
520 cp += size;
521 while (!isspace(*++cp) && (*cp != ':'));
522 const char *e = cp;
523 while (isspace(*cp)) {
524 ++cp;
525 }
526 if (*cp == ':') {
527 tag = b;
528 etag = e;
529 buf = cp + 1;
530 }
531 } else {
532 while (!isspace(*++cp) && (*cp != ':'));
533 const char *e = cp;
534 while (isspace(*cp)) {
535 ++cp;
536 }
537 // Two words
538 if (*cp == ':') {
539 tag = bt;
540 etag = e;
541 buf = cp + 1;
542 }
543 }
544 }
545 size = etag - tag;
546 if ((size <= 1)
Mark Salyzyn618d0de2015-07-13 10:19:34 -0700547 // register names like x9
548 || ((size == 2) && (isdigit(tag[0]) || isdigit(tag[1])))
549 // register names like x18 but not driver names like en0
550 || ((size == 3) && (isdigit(tag[1]) && isdigit(tag[2])))
551 // blacklist
552 || ((size == 3) && !strncmp(tag, "CPU", 3))
553 || ((size == 7) && !strncmp(tag, "WARNING", 7))
554 || ((size == 5) && !strncmp(tag, "ERROR", 5))
555 || ((size == 4) && !strncmp(tag, "INFO", 4))) {
Mark Salyzynae4d9282014-10-15 08:49:39 -0700556 buf = start;
557 etag = tag = "";
558 }
559 }
560 size_t l = etag - tag;
Mark Salyzynee49c6a2015-06-12 14:59:42 -0700561 // skip leading space
Mark Salyzynae4d9282014-10-15 08:49:39 -0700562 while (isspace(*buf)) {
563 ++buf;
564 }
Mark Salyzynee49c6a2015-06-12 14:59:42 -0700565 // truncate trailing space
566 size_t b = strlen(buf);
567 while (b && isspace(buf[b-1])) {
568 --b;
569 }
570 // trick ... allow tag with empty content to be logged. log() drops empty
571 if (!b && l) {
572 buf = " ";
573 b = 1;
574 }
575 size_t n = 1 + l + 1 + b + 1;
Mark Salyzynae4d9282014-10-15 08:49:39 -0700576
577 // Allocate a buffer to hold the interpreted log message
578 int rc = n;
579 char *newstr = reinterpret_cast<char *>(malloc(n));
580 if (!newstr) {
581 rc = -ENOMEM;
582 return rc;
583 }
584 char *np = newstr;
585
586 // Convert priority into single-byte Android logger priority
587 *np = convertKernelPrioToAndroidPrio(pri);
588 ++np;
589
590 // Copy parsed tag following priority
591 strncpy(np, tag, l);
592 np += l;
593 *np = '\0';
594 ++np;
595
596 // Copy main message to the remainder
Mark Salyzynee49c6a2015-06-12 14:59:42 -0700597 strncpy(np, buf, b);
598 np[b] = '\0';
Mark Salyzynae4d9282014-10-15 08:49:39 -0700599
600 // Log message
601 rc = logbuf->log(LOG_ID_KERNEL, now, uid, pid, tid, newstr,
602 (n <= USHRT_MAX) ? (unsigned short) n : USHRT_MAX);
603 free(newstr);
604
605 // notify readers
606 if (!rc) {
607 reader->notifyNewLog();
608 }
609
610 return rc;
611}