chiark / gitweb /
util: move all to shared/ and split external dependencies in separate internal libraries
[elogind.git] / src / logs-show.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4   This file is part of systemd.
5
6   Copyright 2012 Lennart Poettering
7
8   systemd is free software; you can redistribute it and/or modify it
9   under the terms of the GNU General Public License as published by
10   the Free Software Foundation; either version 2 of the License, or
11   (at your option) any later version.
12
13   systemd is distributed in the hope that it will be useful, but
14   WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16   General Public License for more details.
17
18   You should have received a copy of the GNU General Public License
19   along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 ***/
21
22 #include <time.h>
23 #include <assert.h>
24 #include <errno.h>
25 #include <sys/poll.h>
26 #include <string.h>
27
28 #include "logs-show.h"
29 #include "log.h"
30 #include "util.h"
31
32 #define PRINT_THRESHOLD 128
33
34 static bool contains_unprintable(const void *p, size_t l) {
35         const char *j;
36
37         for (j = p; j < (const char *) p + l; j++)
38                 if (*j < ' ' || *j >= 127)
39                         return true;
40
41         return false;
42 }
43
44 static int parse_field(const void *data, size_t length, const char *field, char **target, size_t *target_size) {
45         size_t fl, nl;
46         void *buf;
47
48         assert(data);
49         assert(field);
50         assert(target);
51         assert(target_size);
52
53         fl = strlen(field);
54         if (length < fl)
55                 return 0;
56
57         if (memcmp(data, field, fl))
58                 return 0;
59
60         nl = length - fl;
61         buf = malloc(nl+1);
62         memcpy(buf, (const char*) data + fl, nl);
63         ((char*)buf)[nl] = 0;
64         if (!buf) {
65                 log_error("Out of memory");
66                 return -ENOMEM;
67         }
68
69         free(*target);
70         *target = buf;
71         *target_size = nl;
72
73         return 1;
74 }
75
76 static bool shall_print(bool show_all, char *p, size_t l) {
77         if (show_all)
78                 return true;
79
80         if (l > PRINT_THRESHOLD)
81                 return false;
82
83         if (contains_unprintable(p, l))
84                 return false;
85
86         return true;
87 }
88
89 static int output_short(sd_journal *j, unsigned line, unsigned n_columns, bool show_all, bool monotonic_mode) {
90         int r;
91         const void *data;
92         size_t length;
93         size_t n = 0;
94         char *hostname = NULL, *identifier = NULL, *comm = NULL, *pid = NULL, *fake_pid = NULL, *message = NULL, *realtime = NULL, *monotonic = NULL;
95         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;
96
97         assert(j);
98
99         SD_JOURNAL_FOREACH_DATA(j, data, length) {
100
101                 r = parse_field(data, length, "_HOSTNAME=", &hostname, &hostname_len);
102                 if (r < 0)
103                         goto finish;
104                 else if (r > 0)
105                         continue;
106
107                 r = parse_field(data, length, "SYSLOG_IDENTIFIER=", &identifier, &identifier_len);
108                 if (r < 0)
109                         goto finish;
110                 else if (r > 0)
111                         continue;
112
113                 r = parse_field(data, length, "_COMM=", &comm, &comm_len);
114                 if (r < 0)
115                         goto finish;
116                 else if (r > 0)
117                         continue;
118
119                 r = parse_field(data, length, "_PID=", &pid, &pid_len);
120                 if (r < 0)
121                         goto finish;
122                 else if (r > 0)
123                         continue;
124
125                 r = parse_field(data, length, "SYSLOG_PID=", &fake_pid, &fake_pid_len);
126                 if (r < 0)
127                         goto finish;
128                 else if (r > 0)
129                         continue;
130
131                 r = parse_field(data, length, "_SOURCE_REALTIME_TIMESTAMP=", &realtime, &realtime_len);
132                 if (r < 0)
133                         goto finish;
134                 else if (r > 0)
135                         continue;
136
137                 r = parse_field(data, length, "_SOURCE_MONOTONIC_TIMESTAMP=", &monotonic, &monotonic_len);
138                 if (r < 0)
139                         goto finish;
140                 else if (r > 0)
141                         continue;
142
143                 r = parse_field(data, length, "MESSAGE=", &message, &message_len);
144                 if (r < 0)
145                         goto finish;
146         }
147
148         if (!message) {
149                 r = 0;
150                 goto finish;
151         }
152
153         if (monotonic_mode) {
154                 uint64_t t;
155                 sd_id128_t boot_id;
156
157                 r = -ENOENT;
158
159                 if (monotonic)
160                         r = safe_atou64(monotonic, &t);
161
162                 if (r < 0)
163                         r = sd_journal_get_monotonic_usec(j, &t, &boot_id);
164
165                 if (r < 0) {
166                         log_error("Failed to get monotonic: %s", strerror(-r));
167                         goto finish;
168                 }
169
170                 printf("[%5llu.%06llu]",
171                        (unsigned long long) (t / USEC_PER_SEC),
172                        (unsigned long long) (t % USEC_PER_SEC));
173
174                 n += 1 + 5 + 1 + 6 + 1;
175
176         } else {
177                 char buf[64];
178                 uint64_t x;
179                 time_t t;
180                 struct tm tm;
181
182                 r = -ENOENT;
183
184                 if (realtime)
185                         r = safe_atou64(realtime, &x);
186
187                 if (r < 0)
188                         r = sd_journal_get_realtime_usec(j, &x);
189
190                 if (r < 0) {
191                         log_error("Failed to get realtime: %s", strerror(-r));
192                         goto finish;
193                 }
194
195                 t = (time_t) (x / USEC_PER_SEC);
196                 if (strftime(buf, sizeof(buf), "%b %d %H:%M:%S", localtime_r(&t, &tm)) <= 0) {
197                         log_error("Failed to format time.");
198                         goto finish;
199                 }
200
201                 fputs(buf, stdout);
202                 n += strlen(buf);
203         }
204
205         if (hostname && shall_print(show_all, hostname, hostname_len)) {
206                 printf(" %.*s", (int) hostname_len, hostname);
207                 n += hostname_len + 1;
208         }
209
210         if (identifier && shall_print(show_all, identifier, identifier_len)) {
211                 printf(" %.*s", (int) identifier_len, identifier);
212                 n += identifier_len + 1;
213         } else if (comm && shall_print(show_all, comm, comm_len)) {
214                 printf(" %.*s", (int) comm_len, comm);
215                 n += comm_len + 1;
216         }
217
218         if (pid && shall_print(show_all, pid, pid_len)) {
219                 printf("[%.*s]", (int) pid_len, pid);
220                 n += pid_len + 2;
221         } else if (fake_pid && shall_print(show_all, fake_pid, fake_pid_len)) {
222                 printf("[%.*s]", (int) fake_pid_len, fake_pid);
223                 n += fake_pid_len + 2;
224         }
225
226         if (show_all)
227                 printf(": %.*s\n", (int) message_len, message);
228         else if (contains_unprintable(message, message_len)) {
229                 char bytes[FORMAT_BYTES_MAX];
230                 printf(": [%s blob data]\n", format_bytes(bytes, sizeof(bytes), message_len));
231         } else if (message_len + n < n_columns)
232                 printf(": %.*s\n", (int) message_len, message);
233         else if (n < n_columns) {
234                 char *e;
235
236                 e = ellipsize_mem(message, message_len, n_columns - n - 2, 90);
237
238                 if (!e)
239                         printf(": %.*s\n", (int) message_len, message);
240                 else
241                         printf(": %s\n", e);
242
243                 free(e);
244         } else
245                 fputs("\n", stdout);
246
247         r = 0;
248
249 finish:
250         free(hostname);
251         free(identifier);
252         free(comm);
253         free(pid);
254         free(fake_pid);
255         free(message);
256         free(monotonic);
257         free(realtime);
258
259         return r;
260 }
261
262 static int output_short_realtime(sd_journal *j, unsigned line, unsigned n_columns, bool show_all) {
263         return output_short(j, line, n_columns, show_all, false);
264 }
265
266 static int output_short_monotonic(sd_journal *j, unsigned line, unsigned n_columns, bool show_all) {
267         return output_short(j, line, n_columns, show_all, true);
268 }
269
270 static int output_verbose(sd_journal *j, unsigned line, unsigned n_columns, bool show_all) {
271         const void *data;
272         size_t length;
273         char *cursor;
274         uint64_t realtime;
275         char ts[FORMAT_TIMESTAMP_MAX];
276         int r;
277
278         assert(j);
279
280         r = sd_journal_get_realtime_usec(j, &realtime);
281         if (r < 0) {
282                 log_error("Failed to get realtime timestamp: %s", strerror(-r));
283                 return r;
284         }
285
286         r = sd_journal_get_cursor(j, &cursor);
287         if (r < 0) {
288                 log_error("Failed to get cursor: %s", strerror(-r));
289                 return r;
290         }
291
292         printf("%s [%s]\n",
293                format_timestamp(ts, sizeof(ts), realtime),
294                cursor);
295
296         free(cursor);
297
298         SD_JOURNAL_FOREACH_DATA(j, data, length) {
299                 if (!show_all && (length > PRINT_THRESHOLD ||
300                                   contains_unprintable(data, length))) {
301                         const char *c;
302                         char bytes[FORMAT_BYTES_MAX];
303
304                         c = memchr(data, '=', length);
305                         if (!c) {
306                                 log_error("Invalid field.");
307                                 return -EINVAL;
308                         }
309
310                         printf("\t%.*s=[%s blob data]\n",
311                                (int) (c - (const char*) data),
312                                (const char*) data,
313                                format_bytes(bytes, sizeof(bytes), length - (c - (const char *) data) - 1));
314                 } else
315                         printf("\t%.*s\n", (int) length, (const char*) data);
316         }
317
318         return 0;
319 }
320
321 static int output_export(sd_journal *j, unsigned line, unsigned n_columns, bool show_all) {
322         sd_id128_t boot_id;
323         char sid[33];
324         int r;
325         usec_t realtime, monotonic;
326         char *cursor;
327         const void *data;
328         size_t length;
329
330         assert(j);
331
332         r = sd_journal_get_realtime_usec(j, &realtime);
333         if (r < 0) {
334                 log_error("Failed to get realtime timestamp: %s", strerror(-r));
335                 return r;
336         }
337
338         r = sd_journal_get_monotonic_usec(j, &monotonic, &boot_id);
339         if (r < 0) {
340                 log_error("Failed to get monotonic timestamp: %s", strerror(-r));
341                 return r;
342         }
343
344         r = sd_journal_get_cursor(j, &cursor);
345         if (r < 0) {
346                 log_error("Failed to get cursor: %s", strerror(-r));
347                 return r;
348         }
349
350         printf("__CURSOR=%s\n"
351                "__REALTIME_TIMESTAMP=%llu\n"
352                "__MONOTONIC_TIMESTAMP=%llu\n"
353                "_BOOT_ID=%s\n",
354                cursor,
355                (unsigned long long) realtime,
356                (unsigned long long) monotonic,
357                sd_id128_to_string(boot_id, sid));
358
359         free(cursor);
360
361         SD_JOURNAL_FOREACH_DATA(j, data, length) {
362
363                 /* We already printed the boot id, from the data in
364                  * the header, hence let's suppress it here */
365                 if (length >= 9 &&
366                     memcmp(data, "_BOOT_ID=", 9) == 0)
367                         continue;
368
369                 if (contains_unprintable(data, length)) {
370                         const char *c;
371                         uint64_t le64;
372
373                         c = memchr(data, '=', length);
374                         if (!c) {
375                                 log_error("Invalid field.");
376                                 return -EINVAL;
377                         }
378
379                         fwrite(data, c - (const char*) data, 1, stdout);
380                         fputc('\n', stdout);
381                         le64 = htole64(length - (c - (const char*) data) - 1);
382                         fwrite(&le64, sizeof(le64), 1, stdout);
383                         fwrite(c + 1, length - (c - (const char*) data) - 1, 1, stdout);
384                 } else
385                         fwrite(data, length, 1, stdout);
386
387                 fputc('\n', stdout);
388         }
389
390         fputc('\n', stdout);
391
392         return 0;
393 }
394
395 static void json_escape(const char* p, size_t l) {
396
397         if (contains_unprintable(p, l)) {
398                 bool not_first = false;
399
400                 fputs("[ ", stdout);
401
402                 while (l > 0) {
403                         if (not_first)
404                                 printf(", %u", (uint8_t) *p);
405                         else {
406                                 not_first = true;
407                                 printf("%u", (uint8_t) *p);
408                         }
409
410                         p++;
411                         l--;
412                 }
413
414                 fputs(" ]", stdout);
415         } else {
416                 fputc('\"', stdout);
417
418                 while (l > 0) {
419                         if (*p == '"' || *p == '\\') {
420                                 fputc('\\', stdout);
421                                 fputc(*p, stdout);
422                         } else
423                                 fputc(*p, stdout);
424
425                         p++;
426                         l--;
427                 }
428
429                 fputc('\"', stdout);
430         }
431 }
432
433 static int output_json(sd_journal *j, unsigned line, unsigned n_columns, bool show_all) {
434         uint64_t realtime, monotonic;
435         char *cursor;
436         const void *data;
437         size_t length;
438         sd_id128_t boot_id;
439         char sid[33];
440         int r;
441
442         assert(j);
443
444         r = sd_journal_get_realtime_usec(j, &realtime);
445         if (r < 0) {
446                 log_error("Failed to get realtime timestamp: %s", strerror(-r));
447                 return r;
448         }
449
450         r = sd_journal_get_monotonic_usec(j, &monotonic, &boot_id);
451         if (r < 0) {
452                 log_error("Failed to get monotonic timestamp: %s", strerror(-r));
453                 return r;
454         }
455
456         r = sd_journal_get_cursor(j, &cursor);
457         if (r < 0) {
458                 log_error("Failed to get cursor: %s", strerror(-r));
459                 return r;
460         }
461
462         if (line == 1)
463                 fputc('\n', stdout);
464         else
465                 fputs(",\n", stdout);
466
467         printf("{\n"
468                "\t\"__CURSOR\" : \"%s\",\n"
469                "\t\"__REALTIME_TIMESTAMP\" : \"%llu\",\n"
470                "\t\"__MONOTONIC_TIMESTAMP\" : \"%llu\",\n"
471                "\t\"_BOOT_ID\" : \"%s\"",
472                cursor,
473                (unsigned long long) realtime,
474                (unsigned long long) monotonic,
475                sd_id128_to_string(boot_id, sid));
476
477         free(cursor);
478
479         SD_JOURNAL_FOREACH_DATA(j, data, length) {
480                 const char *c;
481
482                 /* We already printed the boot id, from the data in
483                  * the header, hence let's suppress it here */
484                 if (length >= 9 &&
485                     memcmp(data, "_BOOT_ID=", 9) == 0)
486                         continue;
487
488                 c = memchr(data, '=', length);
489                 if (!c) {
490                         log_error("Invalid field.");
491                         return -EINVAL;
492                 }
493
494                 fputs(",\n\t", stdout);
495                 json_escape(data, c - (const char*) data);
496                 fputs(" : ", stdout);
497                 json_escape(c + 1, length - (c - (const char*) data) - 1);
498         }
499
500         fputs("\n}", stdout);
501         fflush(stdout);
502
503         return 0;
504 }
505
506 static int output_cat(sd_journal *j, unsigned line, unsigned n_columns, bool show_all) {
507         const void *data;
508         size_t l;
509         int r;
510
511         assert(j);
512
513         r = sd_journal_get_data(j, "MESSAGE", &data, &l);
514         if (r < 0) {
515                 log_error("Failed to get data: %s", strerror(-r));
516                 return r;
517         }
518
519         assert(l >= 8);
520
521         fwrite((const char*) data + 8, 1, l - 8, stdout);
522         putchar('\n');
523
524         return 0;
525 }
526
527 static int (*output_funcs[_OUTPUT_MODE_MAX])(sd_journal*j, unsigned line, unsigned n_columns, bool show_all) = {
528         [OUTPUT_SHORT] = output_short_realtime,
529         [OUTPUT_SHORT_MONOTONIC] = output_short_monotonic,
530         [OUTPUT_VERBOSE] = output_verbose,
531         [OUTPUT_EXPORT] = output_export,
532         [OUTPUT_JSON] = output_json,
533         [OUTPUT_CAT] = output_cat
534 };
535
536 int output_journal(sd_journal *j, OutputMode mode, unsigned line, unsigned n_columns, bool show_all) {
537         assert(mode >= 0);
538         assert(mode < _OUTPUT_MODE_MAX);
539
540         if (n_columns <= 0)
541                 n_columns = columns();
542
543         return output_funcs[mode](j, line, n_columns, show_all);
544 }
545
546 int show_journal_by_unit(
547                 const char *unit,
548                 OutputMode mode,
549                 unsigned n_columns,
550                 usec_t not_before,
551                 unsigned how_many,
552                 bool show_all,
553                 bool follow) {
554
555         char *m = NULL;
556         sd_journal *j;
557         int r;
558         int fd;
559         unsigned line = 0;
560         bool need_seek = false;
561
562         assert(mode >= 0);
563         assert(mode < _OUTPUT_MODE_MAX);
564         assert(unit);
565
566         if (!endswith(unit, ".service") &&
567             !endswith(unit, ".socket") &&
568             !endswith(unit, ".mount") &&
569             !endswith(unit, ".swap"))
570                 return 0;
571
572         if (how_many <= 0)
573                 return 0;
574
575         if (asprintf(&m, "_SYSTEMD_UNIT=%s", unit) < 0) {
576                 r = -ENOMEM;
577                 goto finish;
578         }
579
580         r = sd_journal_open(&j, SD_JOURNAL_LOCAL_ONLY|SD_JOURNAL_SYSTEM_ONLY);
581         if (r < 0)
582                 goto finish;
583
584         fd = sd_journal_get_fd(j);
585         if (fd < 0)
586                 goto finish;
587
588         r = sd_journal_add_match(j, m, strlen(m));
589         if (r < 0)
590                 goto finish;
591
592         r = sd_journal_seek_tail(j);
593         if (r < 0)
594                 goto finish;
595
596         r = sd_journal_previous_skip(j, how_many);
597         if (r < 0)
598                 goto finish;
599
600         if (mode == OUTPUT_JSON) {
601                 fputc('[', stdout);
602                 fflush(stdout);
603         }
604
605         for (;;) {
606                 for (;;) {
607                         usec_t usec;
608
609                         if (need_seek) {
610                                 r = sd_journal_next(j);
611                                 if (r < 0)
612                                         goto finish;
613                         }
614
615                         if (r == 0)
616                                 break;
617
618                         need_seek = true;
619
620                         if (not_before > 0) {
621                                 r = sd_journal_get_monotonic_usec(j, &usec, NULL);
622
623                                 /* -ESTALE is returned if the
624                                    timestamp is not from this boot */
625                                 if (r == -ESTALE)
626                                         continue;
627                                 else if (r < 0)
628                                         goto finish;
629
630                                 if (usec < not_before)
631                                         continue;
632                         }
633
634                         line ++;
635
636                         r = output_journal(j, mode, line, n_columns, show_all);
637                         if (r < 0)
638                                 goto finish;
639                 }
640
641                 if (!follow)
642                         break;
643
644                 r = fd_wait_for_event(fd, POLLIN, (usec_t) -1);
645                 if (r < 0)
646                         goto finish;
647
648                 r = sd_journal_process(j);
649                 if (r < 0)
650                         goto finish;
651
652         }
653
654         if (mode == OUTPUT_JSON)
655                 fputs("\n]\n", stdout);
656
657 finish:
658         if (m)
659                 free(m);
660
661         if (j)
662                 sd_journal_close(j);
663
664         return r;
665 }
666
667 static const char *const output_mode_table[_OUTPUT_MODE_MAX] = {
668         [OUTPUT_SHORT] = "short",
669         [OUTPUT_SHORT_MONOTONIC] = "short-monotonic",
670         [OUTPUT_VERBOSE] = "verbose",
671         [OUTPUT_EXPORT] = "export",
672         [OUTPUT_JSON] = "json",
673         [OUTPUT_CAT] = "cat"
674 };
675
676 DEFINE_STRING_TABLE_LOOKUP(output_mode, OutputMode);