]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/logs-show.c
tree-wide: drop 'This file is part of systemd' blurb
[thirdparty/systemd.git] / src / shared / logs-show.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2 /***
3 Copyright 2012 Lennart Poettering
4 ***/
5
6 #include <errno.h>
7 #include <fcntl.h>
8 #include <signal.h>
9 #include <stdint.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <sys/socket.h>
13 #include <syslog.h>
14 #include <time.h>
15 #include <unistd.h>
16
17 #include "sd-id128.h"
18 #include "sd-journal.h"
19
20 #include "alloc-util.h"
21 #include "fd-util.h"
22 #include "format-util.h"
23 #include "hashmap.h"
24 #include "hostname-util.h"
25 #include "io-util.h"
26 #include "journal-internal.h"
27 #include "log.h"
28 #include "logs-show.h"
29 #include "macro.h"
30 #include "output-mode.h"
31 #include "parse-util.h"
32 #include "process-util.h"
33 #include "sparse-endian.h"
34 #include "stdio-util.h"
35 #include "string-table.h"
36 #include "string-util.h"
37 #include "strv.h"
38 #include "terminal-util.h"
39 #include "time-util.h"
40 #include "utf8.h"
41 #include "util.h"
42
43 /* up to three lines (each up to 100 characters) or 300 characters, whichever is less */
44 #define PRINT_LINE_THRESHOLD 3
45 #define PRINT_CHAR_THRESHOLD 300
46
47 #define JSON_THRESHOLD 4096
48
49 static int print_catalog(FILE *f, sd_journal *j) {
50 int r;
51 _cleanup_free_ char *t = NULL, *z = NULL;
52
53 r = sd_journal_get_catalog(j, &t);
54 if (r < 0)
55 return r;
56
57 z = strreplace(strstrip(t), "\n", "\n-- ");
58 if (!z)
59 return log_oom();
60
61 fputs("-- ", f);
62 fputs(z, f);
63 fputc('\n', f);
64
65 return 0;
66 }
67
68 static int parse_field(const void *data, size_t length, const char *field, size_t field_len, char **target, size_t *target_len) {
69 size_t nl;
70 char *buf;
71
72 assert(data);
73 assert(field);
74 assert(target);
75
76 if (length < field_len)
77 return 0;
78
79 if (memcmp(data, field, field_len))
80 return 0;
81
82 nl = length - field_len;
83
84 buf = newdup_suffix0(char, (const char*) data + field_len, nl);
85 if (!buf)
86 return log_oom();
87
88 free(*target);
89 *target = buf;
90
91 if (target_len)
92 *target_len = nl;
93
94 return 1;
95 }
96
97 typedef struct ParseFieldVec {
98 const char *field;
99 size_t field_len;
100 char **target;
101 size_t *target_len;
102 } ParseFieldVec;
103
104 #define PARSE_FIELD_VEC_ENTRY(_field, _target, _target_len) \
105 { .field = _field, .field_len = strlen(_field), .target = _target, .target_len = _target_len }
106
107 static int parse_fieldv(const void *data, size_t length, const ParseFieldVec *fields, unsigned n_fields) {
108 unsigned i;
109
110 for (i = 0; i < n_fields; i++) {
111 const ParseFieldVec *f = &fields[i];
112 int r;
113
114 r = parse_field(data, length, f->field, f->field_len, f->target, f->target_len);
115 if (r < 0)
116 return r;
117 else if (r > 0)
118 break;
119 }
120
121 return 0;
122 }
123
124 static int field_set_test(Set *fields, const char *name, size_t n) {
125 char *s = NULL;
126
127 if (!fields)
128 return 1;
129
130 s = strndupa(name, n);
131 if (!s)
132 return log_oom();
133
134 return set_get(fields, s) ? 1 : 0;
135 }
136
137 static bool shall_print(const char *p, size_t l, OutputFlags flags) {
138 assert(p);
139
140 if (flags & OUTPUT_SHOW_ALL)
141 return true;
142
143 if (l >= PRINT_CHAR_THRESHOLD)
144 return false;
145
146 if (!utf8_is_printable(p, l))
147 return false;
148
149 return true;
150 }
151
152 static bool print_multiline(
153 FILE *f,
154 unsigned prefix,
155 unsigned n_columns,
156 OutputFlags flags,
157 int priority,
158 const char* message,
159 size_t message_len,
160 size_t highlight[2]) {
161
162 const char *color_on = "", *color_off = "", *highlight_on = "";
163 const char *pos, *end;
164 bool ellipsized = false;
165 int line = 0;
166
167 if (flags & OUTPUT_COLOR) {
168 if (priority <= LOG_ERR) {
169 color_on = ANSI_HIGHLIGHT_RED;
170 color_off = ANSI_NORMAL;
171 highlight_on = ANSI_HIGHLIGHT;
172 } else if (priority <= LOG_NOTICE) {
173 color_on = ANSI_HIGHLIGHT;
174 color_off = ANSI_NORMAL;
175 highlight_on = ANSI_HIGHLIGHT_RED;
176 }
177 }
178
179 /* A special case: make sure that we print a newline when
180 the message is empty. */
181 if (message_len == 0)
182 fputs("\n", f);
183
184 for (pos = message;
185 pos < message + message_len;
186 pos = end + 1, line++) {
187 bool continuation = line > 0;
188 bool tail_line;
189 int len;
190 for (end = pos; end < message + message_len && *end != '\n'; end++)
191 ;
192 len = end - pos;
193 assert(len >= 0);
194
195 /* We need to figure out when we are showing not-last line, *and*
196 * will skip subsequent lines. In that case, we will put the dots
197 * at the end of the line, instead of putting dots in the middle
198 * or not at all.
199 */
200 tail_line =
201 line + 1 == PRINT_LINE_THRESHOLD ||
202 end + 1 >= message + PRINT_CHAR_THRESHOLD;
203
204 if (flags & (OUTPUT_FULL_WIDTH | OUTPUT_SHOW_ALL) ||
205 (prefix + len + 1 < n_columns && !tail_line)) {
206 if (highlight &&
207 (size_t) (pos - message) <= highlight[0] &&
208 highlight[0] < (size_t) len) {
209
210 fprintf(f, "%*s%s%.*s",
211 continuation * prefix, "",
212 color_on, (int) highlight[0], pos);
213 fprintf(f, "%s%.*s",
214 highlight_on,
215 (int) (MIN((size_t) len, highlight[1]) - highlight[0]),
216 pos + highlight[0]);
217 if ((size_t) len > highlight[1])
218 fprintf(f, "%s%.*s",
219 color_on,
220 (int) (len - highlight[1]),
221 pos + highlight[1]);
222 fprintf(f, "%s\n", color_off);
223
224 } else
225 fprintf(f, "%*s%s%.*s%s\n",
226 continuation * prefix, "",
227 color_on, len, pos, color_off);
228 continue;
229 }
230
231 /* Beyond this point, ellipsization will happen. */
232 ellipsized = true;
233
234 if (prefix < n_columns && n_columns - prefix >= 3) {
235 if (n_columns - prefix > (unsigned) len + 3)
236 fprintf(f, "%*s%s%.*s...%s\n",
237 continuation * prefix, "",
238 color_on, len, pos, color_off);
239 else {
240 _cleanup_free_ char *e;
241
242 e = ellipsize_mem(pos, len, n_columns - prefix,
243 tail_line ? 100 : 90);
244 if (!e)
245 fprintf(f, "%*s%s%.*s%s\n",
246 continuation * prefix, "",
247 color_on, len, pos, color_off);
248 else
249 fprintf(f, "%*s%s%s%s\n",
250 continuation * prefix, "",
251 color_on, e, color_off);
252 }
253 } else
254 fputs("...\n", f);
255
256 if (tail_line)
257 break;
258 }
259
260 return ellipsized;
261 }
262
263 static int output_timestamp_monotonic(FILE *f, sd_journal *j, const char *monotonic) {
264 sd_id128_t boot_id;
265 uint64_t t;
266 int r;
267
268 assert(f);
269 assert(j);
270
271 r = -ENXIO;
272 if (monotonic)
273 r = safe_atou64(monotonic, &t);
274 if (r < 0)
275 r = sd_journal_get_monotonic_usec(j, &t, &boot_id);
276 if (r < 0)
277 return log_error_errno(r, "Failed to get monotonic timestamp: %m");
278
279 fprintf(f, "[%5"PRI_USEC".%06"PRI_USEC"]", t / USEC_PER_SEC, t % USEC_PER_SEC);
280 return 1 + 5 + 1 + 6 + 1;
281 }
282
283 static int output_timestamp_realtime(FILE *f, sd_journal *j, OutputMode mode, OutputFlags flags, const char *realtime) {
284 char buf[MAX(FORMAT_TIMESTAMP_MAX, 64)];
285 struct tm *(*gettime_r)(const time_t *, struct tm *);
286 struct tm tm;
287 uint64_t x;
288 time_t t;
289 int r;
290
291 assert(f);
292 assert(j);
293
294 if (realtime)
295 r = safe_atou64(realtime, &x);
296 if (!realtime || r < 0 || !VALID_REALTIME(x))
297 r = sd_journal_get_realtime_usec(j, &x);
298 if (r < 0)
299 return log_error_errno(r, "Failed to get realtime timestamp: %m");
300
301 if (IN_SET(mode, OUTPUT_SHORT_FULL, OUTPUT_WITH_UNIT)) {
302 const char *k;
303
304 if (flags & OUTPUT_UTC)
305 k = format_timestamp_utc(buf, sizeof(buf), x);
306 else
307 k = format_timestamp(buf, sizeof(buf), x);
308 if (!k) {
309 log_error("Failed to format timestamp: %"PRIu64, x);
310 return -EINVAL;
311 }
312
313 } else {
314 char usec[7];
315
316 gettime_r = (flags & OUTPUT_UTC) ? gmtime_r : localtime_r;
317 t = (time_t) (x / USEC_PER_SEC);
318
319 switch (mode) {
320
321 case OUTPUT_SHORT_UNIX:
322 xsprintf(buf, "%10"PRI_TIME".%06"PRIu64, t, x % USEC_PER_SEC);
323 break;
324
325 case OUTPUT_SHORT_ISO:
326 if (strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%S%z", gettime_r(&t, &tm)) <= 0) {
327 log_error("Failed to format ISO time");
328 return -EINVAL;
329 }
330 break;
331
332 case OUTPUT_SHORT_ISO_PRECISE:
333 /* No usec in strftime, so we leave space and copy over */
334 if (strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%S.xxxxxx%z", gettime_r(&t, &tm)) <= 0) {
335 log_error("Failed to format ISO-precise time");
336 return -EINVAL;
337 }
338 xsprintf(usec, "%06"PRI_USEC, x % USEC_PER_SEC);
339 memcpy(buf + 20, usec, 6);
340 break;
341
342 case OUTPUT_SHORT:
343 case OUTPUT_SHORT_PRECISE:
344
345 if (strftime(buf, sizeof(buf), "%b %d %H:%M:%S", gettime_r(&t, &tm)) <= 0) {
346 log_error("Failed to format syslog time");
347 return -EINVAL;
348 }
349
350 if (mode == OUTPUT_SHORT_PRECISE) {
351 size_t k;
352
353 assert(sizeof(buf) > strlen(buf));
354 k = sizeof(buf) - strlen(buf);
355
356 r = snprintf(buf + strlen(buf), k, ".%06"PRIu64, x % USEC_PER_SEC);
357 if (r <= 0 || (size_t) r >= k) { /* too long? */
358 log_error("Failed to format precise time");
359 return -EINVAL;
360 }
361 }
362 break;
363
364 default:
365 assert_not_reached("Unknown time format");
366 }
367 }
368
369 fputs(buf, f);
370 return (int) strlen(buf);
371 }
372
373 static int output_short(
374 FILE *f,
375 sd_journal *j,
376 OutputMode mode,
377 unsigned n_columns,
378 OutputFlags flags,
379 Set *output_fields,
380 size_t highlight[2]) {
381
382 int r;
383 const void *data;
384 size_t length;
385 size_t n = 0;
386 _cleanup_free_ char *hostname = NULL, *identifier = NULL, *comm = NULL, *pid = NULL, *fake_pid = NULL, *message = NULL, *realtime = NULL, *monotonic = NULL, *priority = NULL, *unit = NULL, *user_unit = NULL;
387 size_t hostname_len = 0, identifier_len = 0, comm_len = 0, pid_len = 0, fake_pid_len = 0, message_len = 0, realtime_len = 0, monotonic_len = 0, priority_len = 0, unit_len = 0, user_unit_len = 0;
388 int p = LOG_INFO;
389 bool ellipsized = false;
390 const ParseFieldVec fields[] = {
391 PARSE_FIELD_VEC_ENTRY("_PID=", &pid, &pid_len),
392 PARSE_FIELD_VEC_ENTRY("_COMM=", &comm, &comm_len),
393 PARSE_FIELD_VEC_ENTRY("MESSAGE=", &message, &message_len),
394 PARSE_FIELD_VEC_ENTRY("PRIORITY=", &priority, &priority_len),
395 PARSE_FIELD_VEC_ENTRY("_HOSTNAME=", &hostname, &hostname_len),
396 PARSE_FIELD_VEC_ENTRY("SYSLOG_PID=", &fake_pid, &fake_pid_len),
397 PARSE_FIELD_VEC_ENTRY("SYSLOG_IDENTIFIER=", &identifier, &identifier_len),
398 PARSE_FIELD_VEC_ENTRY("_SOURCE_REALTIME_TIMESTAMP=", &realtime, &realtime_len),
399 PARSE_FIELD_VEC_ENTRY("_SOURCE_MONOTONIC_TIMESTAMP=", &monotonic, &monotonic_len),
400 PARSE_FIELD_VEC_ENTRY("_SYSTEMD_UNIT=", &unit, &unit_len),
401 PARSE_FIELD_VEC_ENTRY("_SYSTEMD_USER_UNIT=", &user_unit, &user_unit_len),
402 };
403 size_t highlight_shifted[] = {highlight ? highlight[0] : 0, highlight ? highlight[1] : 0};
404
405 assert(f);
406 assert(j);
407
408 /* Set the threshold to one bigger than the actual print
409 * threshold, so that if the line is actually longer than what
410 * we're willing to print, ellipsization will occur. This way
411 * we won't output a misleading line without any indication of
412 * truncation.
413 */
414 sd_journal_set_data_threshold(j, flags & (OUTPUT_SHOW_ALL|OUTPUT_FULL_WIDTH) ? 0 : PRINT_CHAR_THRESHOLD + 1);
415
416 JOURNAL_FOREACH_DATA_RETVAL(j, data, length, r) {
417 r = parse_fieldv(data, length, fields, ELEMENTSOF(fields));
418 if (r < 0)
419 return r;
420 }
421 if (r == -EBADMSG) {
422 log_debug_errno(r, "Skipping message we can't read: %m");
423 return 0;
424 }
425 if (r < 0)
426 return log_error_errno(r, "Failed to get journal fields: %m");
427
428 if (!message) {
429 log_debug("Skipping message without MESSAGE= field.");
430 return 0;
431 }
432
433 if (!(flags & OUTPUT_SHOW_ALL))
434 strip_tab_ansi(&message, &message_len, highlight_shifted);
435
436 if (priority_len == 1 && *priority >= '0' && *priority <= '7')
437 p = *priority - '0';
438
439 if (mode == OUTPUT_SHORT_MONOTONIC)
440 r = output_timestamp_monotonic(f, j, monotonic);
441 else
442 r = output_timestamp_realtime(f, j, mode, flags, realtime);
443 if (r < 0)
444 return r;
445 n += r;
446
447 if (flags & OUTPUT_NO_HOSTNAME) {
448 /* Suppress display of the hostname if this is requested. */
449 hostname = mfree(hostname);
450 hostname_len = 0;
451 }
452
453 if (hostname && shall_print(hostname, hostname_len, flags)) {
454 fprintf(f, " %.*s", (int) hostname_len, hostname);
455 n += hostname_len + 1;
456 }
457
458 if (mode == OUTPUT_WITH_UNIT && ((unit && shall_print(unit, unit_len, flags)) || (user_unit && shall_print(user_unit, user_unit_len, flags)))) {
459 if (unit) {
460 fprintf(f, " %.*s", (int) unit_len, unit);
461 n += unit_len + 1;
462 }
463 if (user_unit) {
464 if (unit)
465 fprintf(f, "/%.*s", (int) user_unit_len, user_unit);
466 else
467 fprintf(f, " %.*s", (int) user_unit_len, user_unit);
468 n += unit_len + 1;
469 }
470 } else if (identifier && shall_print(identifier, identifier_len, flags)) {
471 fprintf(f, " %.*s", (int) identifier_len, identifier);
472 n += identifier_len + 1;
473 } else if (comm && shall_print(comm, comm_len, flags)) {
474 fprintf(f, " %.*s", (int) comm_len, comm);
475 n += comm_len + 1;
476 } else
477 fputs(" unknown", f);
478
479 if (pid && shall_print(pid, pid_len, flags)) {
480 fprintf(f, "[%.*s]", (int) pid_len, pid);
481 n += pid_len + 2;
482 } else if (fake_pid && shall_print(fake_pid, fake_pid_len, flags)) {
483 fprintf(f, "[%.*s]", (int) fake_pid_len, fake_pid);
484 n += fake_pid_len + 2;
485 }
486
487 if (!(flags & OUTPUT_SHOW_ALL) && !utf8_is_printable(message, message_len)) {
488 char bytes[FORMAT_BYTES_MAX];
489 fprintf(f, ": [%s blob data]\n", format_bytes(bytes, sizeof(bytes), message_len));
490 } else {
491 fputs(": ", f);
492 ellipsized |=
493 print_multiline(f, n + 2, n_columns, flags, p,
494 message, message_len,
495 highlight_shifted);
496 }
497
498 if (flags & OUTPUT_CATALOG)
499 print_catalog(f, j);
500
501 return ellipsized;
502 }
503
504 static int output_verbose(
505 FILE *f,
506 sd_journal *j,
507 OutputMode mode,
508 unsigned n_columns,
509 OutputFlags flags,
510 Set *output_fields,
511 size_t highlight[2]) {
512
513 const void *data;
514 size_t length;
515 _cleanup_free_ char *cursor = NULL;
516 uint64_t realtime = 0;
517 char ts[FORMAT_TIMESTAMP_MAX + 7];
518 const char *timestamp;
519 int r;
520
521 assert(f);
522 assert(j);
523
524 sd_journal_set_data_threshold(j, 0);
525
526 r = sd_journal_get_data(j, "_SOURCE_REALTIME_TIMESTAMP", &data, &length);
527 if (r == -ENOENT)
528 log_debug("Source realtime timestamp not found");
529 else if (r < 0)
530 return log_full_errno(r == -EADDRNOTAVAIL ? LOG_DEBUG : LOG_ERR, r, "Failed to get source realtime timestamp: %m");
531 else {
532 _cleanup_free_ char *value = NULL;
533
534 r = parse_field(data, length, "_SOURCE_REALTIME_TIMESTAMP=",
535 STRLEN("_SOURCE_REALTIME_TIMESTAMP="), &value,
536 NULL);
537 if (r < 0)
538 return r;
539 assert(r > 0);
540
541 r = safe_atou64(value, &realtime);
542 if (r < 0)
543 log_debug_errno(r, "Failed to parse realtime timestamp: %m");
544 }
545
546 if (r < 0) {
547 r = sd_journal_get_realtime_usec(j, &realtime);
548 if (r < 0)
549 return log_full_errno(r == -EADDRNOTAVAIL ? LOG_DEBUG : LOG_ERR, r, "Failed to get realtime timestamp: %m");
550 }
551
552 r = sd_journal_get_cursor(j, &cursor);
553 if (r < 0)
554 return log_error_errno(r, "Failed to get cursor: %m");
555
556 timestamp = flags & OUTPUT_UTC ? format_timestamp_us_utc(ts, sizeof ts, realtime)
557 : format_timestamp_us(ts, sizeof ts, realtime);
558 fprintf(f, "%s [%s]\n",
559 timestamp ?: "(no timestamp)",
560 cursor);
561
562 JOURNAL_FOREACH_DATA_RETVAL(j, data, length, r) {
563 const char *c;
564 int fieldlen;
565 const char *on = "", *off = "";
566
567 c = memchr(data, '=', length);
568 if (!c) {
569 log_error("Invalid field.");
570 return -EINVAL;
571 }
572 fieldlen = c - (const char*) data;
573
574 r = field_set_test(output_fields, data, fieldlen);
575 if (r < 0)
576 return r;
577 if (!r)
578 continue;
579
580 if (flags & OUTPUT_COLOR && startswith(data, "MESSAGE=")) {
581 on = ANSI_HIGHLIGHT;
582 off = ANSI_NORMAL;
583 }
584
585 if ((flags & OUTPUT_SHOW_ALL) ||
586 (((length < PRINT_CHAR_THRESHOLD) || flags & OUTPUT_FULL_WIDTH)
587 && utf8_is_printable(data, length))) {
588 fprintf(f, " %s%.*s=", on, fieldlen, (const char*)data);
589 print_multiline(f, 4 + fieldlen + 1, 0, OUTPUT_FULL_WIDTH, 0, c + 1, length - fieldlen - 1, NULL);
590 fputs(off, f);
591 } else {
592 char bytes[FORMAT_BYTES_MAX];
593
594 fprintf(f, " %s%.*s=[%s blob data]%s\n",
595 on,
596 (int) (c - (const char*) data),
597 (const char*) data,
598 format_bytes(bytes, sizeof(bytes), length - (c - (const char *) data) - 1),
599 off);
600 }
601 }
602
603 if (r < 0)
604 return r;
605
606 if (flags & OUTPUT_CATALOG)
607 print_catalog(f, j);
608
609 return 0;
610 }
611
612 static int output_export(
613 FILE *f,
614 sd_journal *j,
615 OutputMode mode,
616 unsigned n_columns,
617 OutputFlags flags,
618 Set *output_fields,
619 size_t highlight[2]) {
620
621 sd_id128_t boot_id;
622 char sid[33];
623 int r;
624 usec_t realtime, monotonic;
625 _cleanup_free_ char *cursor = NULL;
626 const void *data;
627 size_t length;
628
629 assert(j);
630
631 sd_journal_set_data_threshold(j, 0);
632
633 r = sd_journal_get_realtime_usec(j, &realtime);
634 if (r < 0)
635 return log_error_errno(r, "Failed to get realtime timestamp: %m");
636
637 r = sd_journal_get_monotonic_usec(j, &monotonic, &boot_id);
638 if (r < 0)
639 return log_error_errno(r, "Failed to get monotonic timestamp: %m");
640
641 r = sd_journal_get_cursor(j, &cursor);
642 if (r < 0)
643 return log_error_errno(r, "Failed to get cursor: %m");
644
645 fprintf(f,
646 "__CURSOR=%s\n"
647 "__REALTIME_TIMESTAMP="USEC_FMT"\n"
648 "__MONOTONIC_TIMESTAMP="USEC_FMT"\n"
649 "_BOOT_ID=%s\n",
650 cursor,
651 realtime,
652 monotonic,
653 sd_id128_to_string(boot_id, sid));
654
655 JOURNAL_FOREACH_DATA_RETVAL(j, data, length, r) {
656 const char *c;
657
658 /* We already printed the boot id from the data in the header, hence let's suppress it here */
659 if (memory_startswith(data, length, "_BOOT_ID="))
660 continue;
661
662 c = memchr(data, '=', length);
663 if (!c) {
664 log_error("Invalid field.");
665 return -EINVAL;
666 }
667
668 r = field_set_test(output_fields, data, c - (const char *) data);
669 if (r < 0)
670 return r;
671 if (!r)
672 continue;
673
674 if (utf8_is_printable_newline(data, length, false))
675 fwrite(data, length, 1, f);
676 else {
677 uint64_t le64;
678
679 fwrite(data, c - (const char*) data, 1, f);
680 fputc('\n', f);
681 le64 = htole64(length - (c - (const char*) data) - 1);
682 fwrite(&le64, sizeof(le64), 1, f);
683 fwrite(c + 1, length - (c - (const char*) data) - 1, 1, f);
684 }
685
686 fputc('\n', f);
687 }
688 if (r == -EBADMSG) {
689 log_debug_errno(r, "Skipping message we can't read: %m");
690 return 0;
691 }
692
693 if (r < 0)
694 return r;
695
696 fputc('\n', f);
697
698 return 0;
699 }
700
701 void json_escape(
702 FILE *f,
703 const char* p,
704 size_t l,
705 OutputFlags flags) {
706
707 assert(f);
708 assert(p);
709
710 if (!(flags & OUTPUT_SHOW_ALL) && l >= JSON_THRESHOLD)
711 fputs("null", f);
712
713 else if (!(flags & OUTPUT_SHOW_ALL) && !utf8_is_printable(p, l)) {
714 bool not_first = false;
715
716 fputs("[ ", f);
717
718 while (l > 0) {
719 if (not_first)
720 fprintf(f, ", %u", (uint8_t) *p);
721 else {
722 not_first = true;
723 fprintf(f, "%u", (uint8_t) *p);
724 }
725
726 p++;
727 l--;
728 }
729
730 fputs(" ]", f);
731 } else {
732 fputc('\"', f);
733
734 while (l > 0) {
735 if (IN_SET(*p, '"', '\\')) {
736 fputc('\\', f);
737 fputc(*p, f);
738 } else if (*p == '\n')
739 fputs("\\n", f);
740 else if ((uint8_t) *p < ' ')
741 fprintf(f, "\\u%04x", (uint8_t) *p);
742 else
743 fputc(*p, f);
744
745 p++;
746 l--;
747 }
748
749 fputc('\"', f);
750 }
751 }
752
753 static int output_json(
754 FILE *f,
755 sd_journal *j,
756 OutputMode mode,
757 unsigned n_columns,
758 OutputFlags flags,
759 Set *output_fields,
760 size_t highlight[2]) {
761
762 uint64_t realtime, monotonic;
763 _cleanup_free_ char *cursor = NULL;
764 const void *data;
765 size_t length;
766 sd_id128_t boot_id;
767 char sid[33], *k;
768 int r;
769 Hashmap *h = NULL;
770 bool done, separator;
771
772 assert(j);
773
774 sd_journal_set_data_threshold(j, flags & OUTPUT_SHOW_ALL ? 0 : JSON_THRESHOLD);
775
776 r = sd_journal_get_realtime_usec(j, &realtime);
777 if (r < 0)
778 return log_error_errno(r, "Failed to get realtime timestamp: %m");
779
780 r = sd_journal_get_monotonic_usec(j, &monotonic, &boot_id);
781 if (r < 0)
782 return log_error_errno(r, "Failed to get monotonic timestamp: %m");
783
784 r = sd_journal_get_cursor(j, &cursor);
785 if (r < 0)
786 return log_error_errno(r, "Failed to get cursor: %m");
787
788 if (mode == OUTPUT_JSON_PRETTY)
789 fprintf(f,
790 "{\n"
791 "\t\"__CURSOR\" : \"%s\",\n"
792 "\t\"__REALTIME_TIMESTAMP\" : \""USEC_FMT"\",\n"
793 "\t\"__MONOTONIC_TIMESTAMP\" : \""USEC_FMT"\",\n"
794 "\t\"_BOOT_ID\" : \"%s\"",
795 cursor,
796 realtime,
797 monotonic,
798 sd_id128_to_string(boot_id, sid));
799 else {
800 if (mode == OUTPUT_JSON_SSE)
801 fputs("data: ", f);
802
803 fprintf(f,
804 "{ \"__CURSOR\" : \"%s\", "
805 "\"__REALTIME_TIMESTAMP\" : \""USEC_FMT"\", "
806 "\"__MONOTONIC_TIMESTAMP\" : \""USEC_FMT"\", "
807 "\"_BOOT_ID\" : \"%s\"",
808 cursor,
809 realtime,
810 monotonic,
811 sd_id128_to_string(boot_id, sid));
812 }
813
814 h = hashmap_new(&string_hash_ops);
815 if (!h)
816 return log_oom();
817
818 /* First round, iterate through the entry and count how often each field appears */
819 JOURNAL_FOREACH_DATA_RETVAL(j, data, length, r) {
820 const char *eq;
821 char *n;
822 unsigned u;
823
824 if (memory_startswith(data, length, "_BOOT_ID="))
825 continue;
826
827 eq = memchr(data, '=', length);
828 if (!eq)
829 continue;
830
831 n = memdup_suffix0(data, eq - (const char*) data);
832 if (!n) {
833 r = log_oom();
834 goto finish;
835 }
836
837 u = PTR_TO_UINT(hashmap_get(h, n));
838 if (u == 0) {
839 r = hashmap_put(h, n, UINT_TO_PTR(1));
840 if (r < 0) {
841 free(n);
842 log_oom();
843 goto finish;
844 }
845 } else {
846 r = hashmap_update(h, n, UINT_TO_PTR(u + 1));
847 free(n);
848 if (r < 0) {
849 log_oom();
850 goto finish;
851 }
852 }
853 }
854 if (r == -EBADMSG) {
855 log_debug_errno(r, "Skipping message we can't read: %m");
856 return 0;
857 }
858 if (r < 0)
859 return r;
860
861 separator = true;
862 do {
863 done = true;
864
865 SD_JOURNAL_FOREACH_DATA(j, data, length) {
866 const char *eq;
867 char *kk;
868 _cleanup_free_ char *n = NULL;
869 size_t m;
870 unsigned u;
871
872 /* We already printed the boot id from the data in
873 * the header, hence let's suppress it here */
874 if (memory_startswith(data, length, "_BOOT_ID="))
875 continue;
876
877 eq = memchr(data, '=', length);
878 if (!eq)
879 continue;
880
881 m = eq - (const char*) data;
882 n = memdup_suffix0(data, m);
883 if (!n) {
884 r = log_oom();
885 goto finish;
886 }
887
888 if (output_fields && !set_get(output_fields, n))
889 continue;
890
891 if (separator)
892 fputs(mode == OUTPUT_JSON_PRETTY ? ",\n\t" : ", ", f);
893
894 u = PTR_TO_UINT(hashmap_get2(h, n, (void**) &kk));
895 if (u == 0)
896 /* We already printed this, let's jump to the next */
897 separator = false;
898
899 else if (u == 1) {
900 /* Field only appears once, output it directly */
901
902 json_escape(f, data, m, flags);
903 fputs(" : ", f);
904
905 json_escape(f, eq + 1, length - m - 1, flags);
906
907 hashmap_remove(h, n);
908 free(kk);
909
910 separator = true;
911
912 } else {
913 /* Field appears multiple times, output it as array */
914 json_escape(f, data, m, flags);
915 fputs(" : [ ", f);
916 json_escape(f, eq + 1, length - m - 1, flags);
917
918 /* Iterate through the end of the list */
919
920 while (sd_journal_enumerate_data(j, &data, &length) > 0) {
921 if (length < m + 1)
922 continue;
923
924 if (memcmp(data, n, m) != 0)
925 continue;
926
927 if (((const char*) data)[m] != '=')
928 continue;
929
930 fputs(", ", f);
931 json_escape(f, (const char*) data + m + 1, length - m - 1, flags);
932 }
933
934 fputs(" ]", f);
935
936 hashmap_remove(h, n);
937 free(kk);
938
939 /* Iterate data fields form the beginning */
940 done = false;
941 separator = true;
942
943 break;
944 }
945 }
946
947 } while (!done);
948
949 if (mode == OUTPUT_JSON_PRETTY)
950 fputs("\n}\n", f);
951 else if (mode == OUTPUT_JSON_SSE)
952 fputs("}\n\n", f);
953 else
954 fputs(" }\n", f);
955
956 r = 0;
957
958 finish:
959 while ((k = hashmap_steal_first_key(h)))
960 free(k);
961
962 hashmap_free(h);
963
964 return r;
965 }
966
967 static int output_cat(
968 FILE *f,
969 sd_journal *j,
970 OutputMode mode,
971 unsigned n_columns,
972 OutputFlags flags,
973 Set *output_fields,
974 size_t highlight[2]) {
975
976 const void *data;
977 size_t l;
978 int r;
979 const char *highlight_on = "", *highlight_off = "";
980
981 assert(j);
982 assert(f);
983
984 if (flags & OUTPUT_COLOR) {
985 highlight_on = ANSI_HIGHLIGHT_RED;
986 highlight_off = ANSI_NORMAL;
987 }
988
989 sd_journal_set_data_threshold(j, 0);
990
991 r = sd_journal_get_data(j, "MESSAGE", &data, &l);
992 if (r == -EBADMSG) {
993 log_debug_errno(r, "Skipping message we can't read: %m");
994 return 0;
995 }
996 if (r < 0) {
997 /* An entry without MESSAGE=? */
998 if (r == -ENOENT)
999 return 0;
1000
1001 return log_error_errno(r, "Failed to get data: %m");
1002 }
1003
1004 assert(l >= 8);
1005
1006 if (highlight && (flags & OUTPUT_COLOR)) {
1007 assert(highlight[0] <= highlight[1]);
1008 assert(highlight[1] <= l - 8);
1009
1010 fwrite((const char*) data + 8, 1, highlight[0], f);
1011 fwrite(highlight_on, 1, strlen(highlight_on), f);
1012 fwrite((const char*) data + 8 + highlight[0], 1, highlight[1] - highlight[0], f);
1013 fwrite(highlight_off, 1, strlen(highlight_off), f);
1014 fwrite((const char*) data + 8 + highlight[1], 1, l - 8 - highlight[1], f);
1015 } else
1016 fwrite((const char*) data + 8, 1, l - 8, f);
1017 fputc('\n', f);
1018
1019 return 0;
1020 }
1021
1022 static int (*output_funcs[_OUTPUT_MODE_MAX])(
1023 FILE *f,
1024 sd_journal*j,
1025 OutputMode mode,
1026 unsigned n_columns,
1027 OutputFlags flags,
1028 Set *output_fields,
1029 size_t highlight[2]) = {
1030
1031 [OUTPUT_SHORT] = output_short,
1032 [OUTPUT_SHORT_ISO] = output_short,
1033 [OUTPUT_SHORT_ISO_PRECISE] = output_short,
1034 [OUTPUT_SHORT_PRECISE] = output_short,
1035 [OUTPUT_SHORT_MONOTONIC] = output_short,
1036 [OUTPUT_SHORT_UNIX] = output_short,
1037 [OUTPUT_SHORT_FULL] = output_short,
1038 [OUTPUT_VERBOSE] = output_verbose,
1039 [OUTPUT_EXPORT] = output_export,
1040 [OUTPUT_JSON] = output_json,
1041 [OUTPUT_JSON_PRETTY] = output_json,
1042 [OUTPUT_JSON_SSE] = output_json,
1043 [OUTPUT_CAT] = output_cat,
1044 [OUTPUT_WITH_UNIT] = output_short,
1045 };
1046
1047 int show_journal_entry(
1048 FILE *f,
1049 sd_journal *j,
1050 OutputMode mode,
1051 unsigned n_columns,
1052 OutputFlags flags,
1053 char **output_fields,
1054 size_t highlight[2],
1055 bool *ellipsized) {
1056
1057 int ret;
1058 _cleanup_set_free_free_ Set *fields = NULL;
1059 assert(mode >= 0);
1060 assert(mode < _OUTPUT_MODE_MAX);
1061
1062 if (n_columns <= 0)
1063 n_columns = columns();
1064
1065 if (output_fields) {
1066 fields = set_new(&string_hash_ops);
1067 if (!fields)
1068 return log_oom();
1069
1070 ret = set_put_strdupv(fields, output_fields);
1071 if (ret < 0)
1072 return ret;
1073 }
1074
1075 ret = output_funcs[mode](f, j, mode, n_columns, flags, fields, highlight);
1076
1077 if (ellipsized && ret > 0)
1078 *ellipsized = true;
1079
1080 return ret;
1081 }
1082
1083 static int maybe_print_begin_newline(FILE *f, OutputFlags *flags) {
1084 assert(f);
1085 assert(flags);
1086
1087 if (!(*flags & OUTPUT_BEGIN_NEWLINE))
1088 return 0;
1089
1090 /* Print a beginning new line if that's request, but only once
1091 * on the first line we print. */
1092
1093 fputc('\n', f);
1094 *flags &= ~OUTPUT_BEGIN_NEWLINE;
1095 return 0;
1096 }
1097
1098 int show_journal(
1099 FILE *f,
1100 sd_journal *j,
1101 OutputMode mode,
1102 unsigned n_columns,
1103 usec_t not_before,
1104 unsigned how_many,
1105 OutputFlags flags,
1106 bool *ellipsized) {
1107
1108 int r;
1109 unsigned line = 0;
1110 bool need_seek = false;
1111 int warn_cutoff = flags & OUTPUT_WARN_CUTOFF;
1112
1113 assert(j);
1114 assert(mode >= 0);
1115 assert(mode < _OUTPUT_MODE_MAX);
1116
1117 if (how_many == (unsigned) -1)
1118 need_seek = true;
1119 else {
1120 /* Seek to end */
1121 r = sd_journal_seek_tail(j);
1122 if (r < 0)
1123 return log_error_errno(r, "Failed to seek to tail: %m");
1124
1125 r = sd_journal_previous_skip(j, how_many);
1126 if (r < 0)
1127 return log_error_errno(r, "Failed to skip previous: %m");
1128 }
1129
1130 for (;;) {
1131 for (;;) {
1132 usec_t usec;
1133
1134 if (need_seek) {
1135 r = sd_journal_next(j);
1136 if (r < 0)
1137 return log_error_errno(r, "Failed to iterate through journal: %m");
1138 }
1139
1140 if (r == 0)
1141 break;
1142
1143 need_seek = true;
1144
1145 if (not_before > 0) {
1146 r = sd_journal_get_monotonic_usec(j, &usec, NULL);
1147
1148 /* -ESTALE is returned if the
1149 timestamp is not from this boot */
1150 if (r == -ESTALE)
1151 continue;
1152 else if (r < 0)
1153 return log_error_errno(r, "Failed to get journal time: %m");
1154
1155 if (usec < not_before)
1156 continue;
1157 }
1158
1159 line++;
1160 maybe_print_begin_newline(f, &flags);
1161
1162 r = show_journal_entry(f, j, mode, n_columns, flags, NULL, NULL, ellipsized);
1163 if (r < 0)
1164 return r;
1165 }
1166
1167 if (warn_cutoff && line < how_many && not_before > 0) {
1168 sd_id128_t boot_id;
1169 usec_t cutoff = 0;
1170
1171 /* Check whether the cutoff line is too early */
1172
1173 r = sd_id128_get_boot(&boot_id);
1174 if (r < 0)
1175 return log_error_errno(r, "Failed to get boot id: %m");
1176
1177 r = sd_journal_get_cutoff_monotonic_usec(j, boot_id, &cutoff, NULL);
1178 if (r < 0)
1179 return log_error_errno(r, "Failed to get journal cutoff time: %m");
1180
1181 if (r > 0 && not_before < cutoff) {
1182 maybe_print_begin_newline(f, &flags);
1183 fprintf(f, "Warning: Journal has been rotated since unit was started. Log output is incomplete or unavailable.\n");
1184 }
1185
1186 warn_cutoff = false;
1187 }
1188
1189 if (!(flags & OUTPUT_FOLLOW))
1190 break;
1191
1192 r = sd_journal_wait(j, USEC_INFINITY);
1193 if (r < 0)
1194 return log_error_errno(r, "Failed to wait for journal: %m");
1195
1196 }
1197
1198 return 0;
1199 }
1200
1201 int add_matches_for_unit(sd_journal *j, const char *unit) {
1202 const char *m1, *m2, *m3, *m4;
1203 int r;
1204
1205 assert(j);
1206 assert(unit);
1207
1208 m1 = strjoina("_SYSTEMD_UNIT=", unit);
1209 m2 = strjoina("COREDUMP_UNIT=", unit);
1210 m3 = strjoina("UNIT=", unit);
1211 m4 = strjoina("OBJECT_SYSTEMD_UNIT=", unit);
1212
1213 (void)(
1214 /* Look for messages from the service itself */
1215 (r = sd_journal_add_match(j, m1, 0)) ||
1216
1217 /* Look for coredumps of the service */
1218 (r = sd_journal_add_disjunction(j)) ||
1219 (r = sd_journal_add_match(j, "MESSAGE_ID=fc2e22bc6ee647b6b90729ab34a250b1", 0)) ||
1220 (r = sd_journal_add_match(j, "_UID=0", 0)) ||
1221 (r = sd_journal_add_match(j, m2, 0)) ||
1222
1223 /* Look for messages from PID 1 about this service */
1224 (r = sd_journal_add_disjunction(j)) ||
1225 (r = sd_journal_add_match(j, "_PID=1", 0)) ||
1226 (r = sd_journal_add_match(j, m3, 0)) ||
1227
1228 /* Look for messages from authorized daemons about this service */
1229 (r = sd_journal_add_disjunction(j)) ||
1230 (r = sd_journal_add_match(j, "_UID=0", 0)) ||
1231 (r = sd_journal_add_match(j, m4, 0))
1232 );
1233
1234 if (r == 0 && endswith(unit, ".slice")) {
1235 const char *m5;
1236
1237 m5 = strjoina("_SYSTEMD_SLICE=", unit);
1238
1239 /* Show all messages belonging to a slice */
1240 (void)(
1241 (r = sd_journal_add_disjunction(j)) ||
1242 (r = sd_journal_add_match(j, m5, 0))
1243 );
1244 }
1245
1246 return r;
1247 }
1248
1249 int add_matches_for_user_unit(sd_journal *j, const char *unit, uid_t uid) {
1250 int r;
1251 char *m1, *m2, *m3, *m4;
1252 char muid[sizeof("_UID=") + DECIMAL_STR_MAX(uid_t)];
1253
1254 assert(j);
1255 assert(unit);
1256
1257 m1 = strjoina("_SYSTEMD_USER_UNIT=", unit);
1258 m2 = strjoina("USER_UNIT=", unit);
1259 m3 = strjoina("COREDUMP_USER_UNIT=", unit);
1260 m4 = strjoina("OBJECT_SYSTEMD_USER_UNIT=", unit);
1261 sprintf(muid, "_UID="UID_FMT, uid);
1262
1263 (void) (
1264 /* Look for messages from the user service itself */
1265 (r = sd_journal_add_match(j, m1, 0)) ||
1266 (r = sd_journal_add_match(j, muid, 0)) ||
1267
1268 /* Look for messages from systemd about this service */
1269 (r = sd_journal_add_disjunction(j)) ||
1270 (r = sd_journal_add_match(j, m2, 0)) ||
1271 (r = sd_journal_add_match(j, muid, 0)) ||
1272
1273 /* Look for coredumps of the service */
1274 (r = sd_journal_add_disjunction(j)) ||
1275 (r = sd_journal_add_match(j, m3, 0)) ||
1276 (r = sd_journal_add_match(j, muid, 0)) ||
1277 (r = sd_journal_add_match(j, "_UID=0", 0)) ||
1278
1279 /* Look for messages from authorized daemons about this service */
1280 (r = sd_journal_add_disjunction(j)) ||
1281 (r = sd_journal_add_match(j, m4, 0)) ||
1282 (r = sd_journal_add_match(j, muid, 0)) ||
1283 (r = sd_journal_add_match(j, "_UID=0", 0))
1284 );
1285
1286 if (r == 0 && endswith(unit, ".slice")) {
1287 const char *m5;
1288
1289 m5 = strjoina("_SYSTEMD_SLICE=", unit);
1290
1291 /* Show all messages belonging to a slice */
1292 (void)(
1293 (r = sd_journal_add_disjunction(j)) ||
1294 (r = sd_journal_add_match(j, m5, 0)) ||
1295 (r = sd_journal_add_match(j, muid, 0))
1296 );
1297 }
1298
1299 return r;
1300 }
1301
1302 static int get_boot_id_for_machine(const char *machine, sd_id128_t *boot_id) {
1303 _cleanup_close_pair_ int pair[2] = { -1, -1 };
1304 _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, rootfd = -1;
1305 pid_t pid, child;
1306 char buf[37];
1307 ssize_t k;
1308 int r;
1309
1310 assert(machine);
1311 assert(boot_id);
1312
1313 if (!machine_name_is_valid(machine))
1314 return -EINVAL;
1315
1316 r = container_get_leader(machine, &pid);
1317 if (r < 0)
1318 return r;
1319
1320 r = namespace_open(pid, &pidnsfd, &mntnsfd, NULL, NULL, &rootfd);
1321 if (r < 0)
1322 return r;
1323
1324 if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) < 0)
1325 return -errno;
1326
1327 r = safe_fork("(sd-bootid)", FORK_RESET_SIGNALS|FORK_DEATHSIG, &child);
1328 if (r < 0)
1329 return r;
1330 if (r == 0) {
1331 int fd;
1332
1333 pair[0] = safe_close(pair[0]);
1334
1335 r = namespace_enter(pidnsfd, mntnsfd, -1, -1, rootfd);
1336 if (r < 0)
1337 _exit(EXIT_FAILURE);
1338
1339 fd = open("/proc/sys/kernel/random/boot_id", O_RDONLY|O_CLOEXEC|O_NOCTTY);
1340 if (fd < 0)
1341 _exit(EXIT_FAILURE);
1342
1343 r = loop_read_exact(fd, buf, 36, false);
1344 safe_close(fd);
1345 if (r < 0)
1346 _exit(EXIT_FAILURE);
1347
1348 k = send(pair[1], buf, 36, MSG_NOSIGNAL);
1349 if (k != 36)
1350 _exit(EXIT_FAILURE);
1351
1352 _exit(EXIT_SUCCESS);
1353 }
1354
1355 pair[1] = safe_close(pair[1]);
1356
1357 r = wait_for_terminate_and_check("(sd-bootid)", child, 0);
1358 if (r < 0)
1359 return r;
1360 if (r != EXIT_SUCCESS)
1361 return -EIO;
1362
1363 k = recv(pair[0], buf, 36, 0);
1364 if (k != 36)
1365 return -EIO;
1366
1367 buf[36] = 0;
1368 r = sd_id128_from_string(buf, boot_id);
1369 if (r < 0)
1370 return r;
1371
1372 return 0;
1373 }
1374
1375 int add_match_this_boot(sd_journal *j, const char *machine) {
1376 char match[9+32+1] = "_BOOT_ID=";
1377 sd_id128_t boot_id;
1378 int r;
1379
1380 assert(j);
1381
1382 if (machine) {
1383 r = get_boot_id_for_machine(machine, &boot_id);
1384 if (r < 0)
1385 return log_error_errno(r, "Failed to get boot id of container %s: %m", machine);
1386 } else {
1387 r = sd_id128_get_boot(&boot_id);
1388 if (r < 0)
1389 return log_error_errno(r, "Failed to get boot id: %m");
1390 }
1391
1392 sd_id128_to_string(boot_id, match + 9);
1393 r = sd_journal_add_match(j, match, strlen(match));
1394 if (r < 0)
1395 return log_error_errno(r, "Failed to add match: %m");
1396
1397 r = sd_journal_add_conjunction(j);
1398 if (r < 0)
1399 return log_error_errno(r, "Failed to add conjunction: %m");
1400
1401 return 0;
1402 }
1403
1404 int show_journal_by_unit(
1405 FILE *f,
1406 const char *unit,
1407 OutputMode mode,
1408 unsigned n_columns,
1409 usec_t not_before,
1410 unsigned how_many,
1411 uid_t uid,
1412 OutputFlags flags,
1413 int journal_open_flags,
1414 bool system_unit,
1415 bool *ellipsized) {
1416
1417 _cleanup_(sd_journal_closep) sd_journal *j = NULL;
1418 int r;
1419
1420 assert(mode >= 0);
1421 assert(mode < _OUTPUT_MODE_MAX);
1422 assert(unit);
1423
1424 if (how_many <= 0)
1425 return 0;
1426
1427 r = sd_journal_open(&j, journal_open_flags);
1428 if (r < 0)
1429 return log_error_errno(r, "Failed to open journal: %m");
1430
1431 r = add_match_this_boot(j, NULL);
1432 if (r < 0)
1433 return r;
1434
1435 if (system_unit)
1436 r = add_matches_for_unit(j, unit);
1437 else
1438 r = add_matches_for_user_unit(j, unit, uid);
1439 if (r < 0)
1440 return log_error_errno(r, "Failed to add unit matches: %m");
1441
1442 if (DEBUG_LOGGING) {
1443 _cleanup_free_ char *filter;
1444
1445 filter = journal_make_match_string(j);
1446 if (!filter)
1447 return log_oom();
1448
1449 log_debug("Journal filter: %s", filter);
1450 }
1451
1452 return show_journal(f, j, mode, n_columns, not_before, how_many, flags, ellipsized);
1453 }