• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

systemd / systemd / 13867348974

14 Mar 2025 10:27PM UTC coverage: 71.757% (-0.1%) from 71.9%
13867348974

push

github

yuwata
journal-remote: added custom headers support

54 of 67 new or added lines in 3 files covered. (80.6%)

1306 existing lines in 39 files now uncovered.

295405 of 411675 relevant lines covered (71.76%)

715677.93 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

85.6
/src/basic/log.c
1
/* SPDX-License-Identifier: LGPL-2.1-or-later */
2

3
#include <errno.h>
4
#include <fcntl.h>
5
#include <inttypes.h>
6
#include <limits.h>
7
#include <stdarg.h>
8
#include <stddef.h>
9
#include <sys/signalfd.h>
10
#include <sys/stat.h>
11
#include <sys/time.h>
12
#include <sys/uio.h>
13
#include <sys/un.h>
14
#include <threads.h>
15
#include <unistd.h>
16

17
#include "sd-messages.h"
18

19
#include "alloc-util.h"
20
#include "ansi-color.h"
21
#include "argv-util.h"
22
#include "env-util.h"
23
#include "errno-util.h"
24
#include "fd-util.h"
25
#include "format-util.h"
26
#include "iovec-util.h"
27
#include "log.h"
28
#include "macro.h"
29
#include "missing_syscall.h"
30
#include "parse-util.h"
31
#include "proc-cmdline.h"
32
#include "process-util.h"
33
#include "ratelimit.h"
34
#include "signal-util.h"
35
#include "socket-util.h"
36
#include "stdio-util.h"
37
#include "string-table.h"
38
#include "string-util.h"
39
#include "strv.h"
40
#include "syslog-util.h"
41
#include "terminal-util.h"
42
#include "time-util.h"
43
#include "utf8.h"
44

45
#define SNDBUF_SIZE (8*1024*1024)
46
#define IOVEC_MAX 256U
47

48
static log_syntax_callback_t log_syntax_callback = NULL;
49
static void *log_syntax_callback_userdata = NULL;
50

51
static LogTarget log_target = LOG_TARGET_CONSOLE;
52
static int log_max_level = LOG_INFO;
53
static int log_target_max_level[_LOG_TARGET_SINGLE_MAX] = {
54
        [LOG_TARGET_CONSOLE] = INT_MAX,
55
        [LOG_TARGET_KMSG]    = INT_MAX,
56
        [LOG_TARGET_SYSLOG]  = INT_MAX,
57
        [LOG_TARGET_JOURNAL] = INT_MAX,
58
};
59
static int log_facility = LOG_DAEMON;
60
static bool ratelimit_kmsg = true;
61

62
static int console_fd = STDERR_FILENO;
63
static int console_fd_is_tty = -1; /* tri-state: -1 means don't know */
64
static int syslog_fd = -EBADF;
65
static int kmsg_fd = -EBADF;
66
static int journal_fd = -EBADF;
67

68
static bool syslog_is_stream = false;
69

70
static int show_color = -1; /* tristate */
71
static bool show_location = false;
72
static bool show_time = false;
73
static bool show_tid = false;
74

75
static bool upgrade_syslog_to_journal = false;
76
static bool always_reopen_console = false;
77
static bool open_when_needed = false;
78
static bool prohibit_ipc = false;
79
static bool assert_return_is_critical = BUILD_MODE_DEVELOPER;
80

81
/* Akin to glibc's __abort_msg; which is private and we hence cannot
82
 * use here. */
83
static char *log_abort_msg = NULL;
84

85
typedef struct LogContext {
86
        unsigned n_ref;
87
        /* Depending on which destructor is used (log_context_free() or log_context_detach()) the memory
88
         * referenced by this is freed or not */
89
        char **fields;
90
        struct iovec *input_iovec;
91
        size_t n_input_iovec;
92
        char *key;
93
        char *value;
94
        bool owned;
95
        LIST_FIELDS(struct LogContext, ll);
96
} LogContext;
97

98
static thread_local LIST_HEAD(LogContext, _log_context) = NULL;
99
static thread_local size_t _log_context_num_fields = 0;
100

101
static thread_local const char *log_prefix = NULL;
102

103
#if LOG_MESSAGE_VERIFICATION || defined(__COVERITY__)
104
bool _log_message_dummy = false; /* Always false */
105
#endif
106

107
/* An assert to use in logging functions that does not call recursively
108
 * into our logging functions (since that might lead to a loop). */
109
#define assert_raw(expr)                                                \
110
        do {                                                            \
111
                if (_unlikely_(!(expr))) {                              \
112
                        fputs(#expr "\n", stderr);                      \
113
                        abort();                                        \
114
                }                                                       \
115
        } while (false)
116

117
static void log_close_console(void) {
529,251✔
118
        /* See comment in log_close_journal() */
119
        (void) safe_close_above_stdio(TAKE_FD(console_fd));
529,251✔
120
        console_fd_is_tty = -1;
529,251✔
121
}
529,251✔
122

123
static int log_open_console(void) {
53,197✔
124

125
        if (!always_reopen_console) {
53,197✔
126
                console_fd = STDERR_FILENO;
19,079✔
127
                console_fd_is_tty = -1;
19,079✔
128
                return 0;
19,079✔
129
        }
130

131
        if (console_fd < 3) {
34,118✔
132
                int fd;
31,934✔
133

134
                fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
31,934✔
135
                if (fd < 0)
31,934✔
136
                        return fd;
137

138
                console_fd = fd_move_above_stdio(fd);
17,936✔
139
                console_fd_is_tty = true;
17,936✔
140
        }
141

142
        return 0;
143
}
144

145
static void log_close_kmsg(void) {
244,324✔
146
        /* See comment in log_close_journal() */
147
        (void) safe_close(TAKE_FD(kmsg_fd));
244,324✔
148
}
244,324✔
149

150
static int log_open_kmsg(void) {
46,312✔
151

152
        if (kmsg_fd >= 0)
46,312✔
153
                return 0;
154

155
        kmsg_fd = open("/dev/kmsg", O_WRONLY|O_NOCTTY|O_CLOEXEC);
38,700✔
156
        if (kmsg_fd < 0)
38,700✔
157
                return -errno;
19,938✔
158

159
        kmsg_fd = fd_move_above_stdio(kmsg_fd);
18,762✔
160
        return 0;
18,762✔
161
}
162

163
static void log_close_syslog(void) {
582,444✔
164
        /* See comment in log_close_journal() */
165
        (void) safe_close(TAKE_FD(syslog_fd));
582,444✔
166
}
582,444✔
167

168
static int create_log_socket(int type) {
247,887✔
169
        struct timeval tv;
247,887✔
170
        int fd;
247,887✔
171

172
        fd = socket(AF_UNIX, type|SOCK_CLOEXEC, 0);
247,887✔
173
        if (fd < 0)
247,887✔
174
                return -errno;
×
175

176
        fd = fd_move_above_stdio(fd);
247,887✔
177
        (void) fd_inc_sndbuf(fd, SNDBUF_SIZE);
247,887✔
178

179
        /* We need a blocking fd here since we'd otherwise lose messages way too early. However, let's not hang forever
180
         * in the unlikely case of a deadlock. */
181
        if (getpid_cached() == 1)
247,887✔
182
                timeval_store(&tv, 10 * USEC_PER_MSEC);
396✔
183
        else
184
                timeval_store(&tv, 10 * USEC_PER_SEC);
247,491✔
185
        (void) setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
247,887✔
186

187
        return fd;
247,887✔
188
}
189

190
static int log_open_syslog(void) {
2✔
191
        int r;
2✔
192

193
        if (syslog_fd >= 0)
2✔
194
                return 0;
195

196
        syslog_fd = create_log_socket(SOCK_DGRAM);
2✔
197
        if (syslog_fd < 0) {
2✔
198
                r = syslog_fd;
×
199
                goto fail;
×
200
        }
201

202
        r = connect_unix_path(syslog_fd, AT_FDCWD, "/dev/log");
2✔
203
        if (r < 0) {
2✔
204
                safe_close(syslog_fd);
×
205

206
                /* Some legacy syslog systems still use stream sockets. They really shouldn't. But what can
207
                 * we do... */
208
                syslog_fd = create_log_socket(SOCK_STREAM);
×
209
                if (syslog_fd < 0) {
×
210
                        r = syslog_fd;
×
211
                        goto fail;
×
212
                }
213

214
                r = connect_unix_path(syslog_fd, AT_FDCWD, "/dev/log");
×
215
                if (r < 0)
×
216
                        goto fail;
×
217

218
                syslog_is_stream = true;
×
219
        } else
220
                syslog_is_stream = false;
2✔
221

222
        return 0;
223

224
fail:
×
225
        log_close_syslog();
×
226
        return r;
×
227
}
228

229
static void log_close_journal(void) {
323,142✔
230
        /* If the journal FD is bad, safe_close will fail, and will try to log, which will fail, so we'll
231
         * try to close the journal FD, which is bad, so safe_close will fail... Whether we can close it
232
         * or not, invalidate it immediately so that we don't get in a recursive loop until we run out of
233
         * stack. */
234
        (void) safe_close(TAKE_FD(journal_fd));
323,142✔
235
}
323,142✔
236

237
static int log_open_journal(void) {
267,583✔
238
        int r;
267,583✔
239

240
        if (journal_fd >= 0)
267,583✔
241
                return 0;
242

243
        journal_fd = create_log_socket(SOCK_DGRAM);
247,885✔
244
        if (journal_fd < 0) {
247,885✔
245
                r = journal_fd;
×
246
                goto fail;
×
247
        }
248

249
        r = connect_unix_path(journal_fd, AT_FDCWD, "/run/systemd/journal/socket");
247,885✔
250
        if (r < 0)
247,885✔
251
                goto fail;
80✔
252

253
        return 0;
254

255
fail:
80✔
256
        log_close_journal();
80✔
257
        return r;
80✔
258
}
259

260
bool stderr_is_journal(void) {
313,487✔
261
        _cleanup_free_ char *w = NULL;
313,487✔
262
        const char *e;
313,487✔
263
        uint64_t dev, ino;
313,487✔
264
        struct stat st;
313,487✔
265

266
        e = getenv("JOURNAL_STREAM");
313,487✔
267
        if (!e)
313,487✔
268
                return false;
269

270
        if (extract_first_word(&e, &w, ":", EXTRACT_DONT_COALESCE_SEPARATORS) <= 0)
81,478✔
271
                return false;
272
        if (!e)
81,478✔
273
                return false;
274

275
        if (safe_atou64(w, &dev) < 0)
81,478✔
276
                return false;
277
        if (safe_atou64(e, &ino) < 0)
81,478✔
278
                return false;
279

280
        if (fstat(STDERR_FILENO, &st) < 0)
81,478✔
281
                return false;
282

283
        return st.st_dev == dev && st.st_ino == ino;
95,667✔
284
}
285

286
int log_open(void) {
338,122✔
287
        int r;
338,122✔
288

289
        /* Do not call from library code. */
290

291
        /* This function is often called in preparation for logging. Let's make sure we don't clobber errno,
292
         * so that a call to a logging function immediately following a log_open() call can still easily
293
         * reference an error that happened immediately before the log_open() call. */
294
        PROTECT_ERRNO;
338,122✔
295

296
        /* If we don't use the console, we close it here to not get killed by SAK. If we don't use syslog, we
297
         * close it here too, so that we are not confused by somebody deleting the socket in the fs, and to
298
         * make sure we don't use it if prohibit_ipc is set. If we don't use /dev/kmsg we still keep it open,
299
         * because there is no reason to close it. */
300

301
        if (log_target == LOG_TARGET_NULL) {
338,122✔
302
                log_close_journal();
1✔
303
                log_close_syslog();
1✔
304
                log_close_console();
1✔
305
                return 0;
306
        }
307

308
        if (getpid_cached() == 1 ||
647,685✔
309
            stderr_is_journal() ||
309,564✔
310
            IN_SET(log_target,
246,187✔
311
                   LOG_TARGET_KMSG,
312
                   LOG_TARGET_JOURNAL,
313
                   LOG_TARGET_JOURNAL_OR_KMSG,
314
                   LOG_TARGET_SYSLOG,
315
                   LOG_TARGET_SYSLOG_OR_KMSG)) {
316

317
                if (!prohibit_ipc) {
306,470✔
318
                        if (IN_SET(log_target,
297,286✔
319
                                   LOG_TARGET_AUTO,
320
                                   LOG_TARGET_JOURNAL_OR_KMSG,
321
                                   LOG_TARGET_JOURNAL)) {
322

323
                                r = log_open_journal();
259,454✔
324
                                if (r >= 0) {
259,454✔
325
                                        log_close_syslog();
259,387✔
326
                                        log_close_console();
259,387✔
327
                                        return r;
328
                                }
329
                        }
330

331
                        if (IN_SET(log_target,
37,899✔
332
                                   LOG_TARGET_SYSLOG_OR_KMSG,
333
                                   LOG_TARGET_SYSLOG)) {
334

335
                                r = log_open_syslog();
2✔
336
                                if (r >= 0) {
2✔
337
                                        log_close_journal();
2✔
338
                                        log_close_console();
2✔
339
                                        return r;
340
                                }
341
                        }
342
                }
343

344
                if (IN_SET(log_target, LOG_TARGET_AUTO,
47,081✔
345
                                       LOG_TARGET_JOURNAL_OR_KMSG,
346
                                       LOG_TARGET_SYSLOG_OR_KMSG,
347
                                       LOG_TARGET_KMSG)) {
348
                        r = log_open_kmsg();
45,474✔
349
                        if (r >= 0) {
45,474✔
350
                                log_close_journal();
25,536✔
351
                                log_close_syslog();
25,536✔
352
                                log_close_console();
25,536✔
353
                                return r;
354
                        }
355
                }
356
        }
357

358
        log_close_journal();
53,196✔
359
        log_close_syslog();
53,196✔
360

361
        return log_open_console();
53,196✔
362
}
363

364
void log_set_target(LogTarget target) {
109,668✔
365
        assert(target >= 0);
109,668✔
366
        assert(target < _LOG_TARGET_MAX);
109,668✔
367

368
        if (upgrade_syslog_to_journal) {
109,668✔
369
                if (target == LOG_TARGET_SYSLOG)
377✔
370
                        target = LOG_TARGET_JOURNAL;
371
                else if (target == LOG_TARGET_SYSLOG_OR_KMSG)
377✔
372
                        target = LOG_TARGET_JOURNAL_OR_KMSG;
×
373
        }
374

375
        log_target = target;
109,668✔
376
}
109,668✔
377

378
void log_set_target_and_open(LogTarget target) {
302✔
379
        log_set_target(target);
302✔
380
        log_open();
302✔
381
}
302✔
382

383
void log_close(void) {
244,324✔
384
        /* Do not call from library code. */
385

386
        log_close_journal();
244,324✔
387
        log_close_syslog();
244,324✔
388
        log_close_kmsg();
244,324✔
389
        log_close_console();
244,324✔
390
}
244,324✔
391

392
void log_forget_fds(void) {
13,261✔
393
        /* Do not call from library code. */
394

395
        console_fd = kmsg_fd = syslog_fd = journal_fd = -EBADF;
13,261✔
396
        console_fd_is_tty = -1;
13,261✔
397
}
13,261✔
398

399
int log_set_max_level(int level) {
183,167✔
400
        assert(level == LOG_NULL || log_level_is_valid(level));
183,167✔
401

402
        int old = log_max_level;
183,167✔
403
        log_max_level = level;
183,167✔
404

405
        /* Also propagate max log level to libc's syslog(), just in case some other component loaded into our
406
         * process logs directly via syslog(). You might wonder why we maintain our own log level variable if
407
         * libc has the same functionality. This has multiple reasons, first and foremost that we want to
408
         * apply this to all our log targets, not just syslog and console. Moreover, we cannot query the
409
         * current log mask from glibc without changing it, but that's useful for testing the current log
410
         * level before even entering the log functions like we do in our macros. */
411
        setlogmask(LOG_UPTO(level));
183,167✔
412

413
        /* Ensure that our own LOG_NULL define maps sanely to the log mask */
414
        assert_cc(LOG_UPTO(LOG_NULL) == 0);
183,167✔
415

416
        return old;
183,167✔
417
}
418

419
void log_set_facility(int facility) {
298✔
420
        log_facility = facility;
298✔
421
}
298✔
422

423
static bool check_console_fd_is_tty(void) {
25,536✔
424
        if (console_fd < 0)
25,536✔
425
                return false;
426

427
        if (console_fd_is_tty < 0)
25,536✔
428
                console_fd_is_tty = isatty_safe(console_fd);
1,379✔
429

430
        return console_fd_is_tty;
25,536✔
431
}
432

433
static int write_to_console(
121,719✔
434
                int level,
435
                int error,
436
                const char *file,
437
                int line,
438
                const char *func,
439
                const char *buffer) {
440

441
        static int dumb = -1;
121,719✔
442

443
        char location[256],
121,719✔
444
             header_time[FORMAT_TIMESTAMP_MAX],
445
             prefix[1 + DECIMAL_STR_MAX(int) + 2],
446
             tid_string[3 + DECIMAL_STR_MAX(pid_t) + 1];
447
        struct iovec iovec[11];
121,719✔
448
        const char *on = NULL, *off = NULL;
121,719✔
449
        size_t n = 0;
121,719✔
450

451
        if (console_fd < 0)
121,719✔
452
                return 0;
121,719✔
453

454
        if (dumb < 0)
99,294✔
455
                dumb = getenv_terminal_is_dumb();
2,304✔
456

457
        if (LOG_PRI(level) > log_target_max_level[LOG_TARGET_CONSOLE])
99,294✔
458
                return 0;
459

460
        if (log_target == LOG_TARGET_CONSOLE_PREFIXED) {
25,536✔
461
                xsprintf(prefix, "<%i>", level);
443✔
462
                iovec[n++] = IOVEC_MAKE_STRING(prefix);
443✔
463
        }
464

465
        if (show_time &&
25,536✔
466
            format_timestamp(header_time, sizeof(header_time), now(CLOCK_REALTIME))) {
×
467
                iovec[n++] = IOVEC_MAKE_STRING(header_time);
×
468
                iovec[n++] = IOVEC_MAKE_STRING(" ");
×
469
        }
470

471
        if (show_tid) {
25,536✔
472
                xsprintf(tid_string, "(" PID_FMT ") ", gettid());
×
473
                iovec[n++] = IOVEC_MAKE_STRING(tid_string);
×
474
        }
475

476
        if (log_get_show_color())
25,536✔
477
                get_log_colors(LOG_PRI(level), &on, &off, NULL);
10,954✔
478

479
        if (show_location) {
25,536✔
480
                const char *lon = "", *loff = "";
×
481
                if (log_get_show_color()) {
×
482
                        lon = ansi_highlight_yellow4();
×
483
                        loff = ansi_normal();
×
484
                }
485

486
                (void) snprintf(location, sizeof location, "%s%s:%i%s: ", lon, file, line, loff);
×
487
                iovec[n++] = IOVEC_MAKE_STRING(location);
×
488
        }
489

490
        if (on)
25,536✔
491
                iovec[n++] = IOVEC_MAKE_STRING(on);
10,530✔
492
        if (log_prefix) {
25,536✔
493
                iovec[n++] = IOVEC_MAKE_STRING(log_prefix);
2,430✔
494
                iovec[n++] = IOVEC_MAKE_STRING(": ");
2,430✔
495
        }
496
        iovec[n++] = IOVEC_MAKE_STRING(buffer);
25,536✔
497
        if (off)
25,536✔
498
                iovec[n++] = IOVEC_MAKE_STRING(off);
10,530✔
499

500
        /* When writing to a TTY we output an extra '\r' (i.e. CR) first, to generate CRNL rather than just
501
         * NL. This is a robustness thing in case the TTY is currently in raw mode (specifically: has the
502
         * ONLCR flag off). We want that subsequent output definitely starts at the beginning of the line
503
         * again, after all. If the TTY is not in raw mode the extra CR should not hurt. If we're writing to
504
         * a dumb terminal, only write NL as CRNL might be interpreted as a double newline. */
505
        iovec[n++] = IOVEC_MAKE_STRING(check_console_fd_is_tty() && !dumb ? "\r\n" : "\n");
51,072✔
506

507
        if (writev(console_fd, iovec, n) < 0) {
25,536✔
508

509
                if (errno == EIO && getpid_cached() == 1) {
86✔
510

511
                        /* If somebody tried to kick us from our console tty (via vhangup() or suchlike), try
512
                         * to reconnect. */
513

514
                        log_close_console();
1✔
515
                        (void) log_open_console();
1✔
516
                        if (console_fd < 0)
1✔
517
                                return 0;
518

519
                        if (writev(console_fd, iovec, n) < 0)
1✔
520
                                return -errno;
×
521
                } else
522
                        return -errno;
85✔
523
        }
524

525
        return 1;
526
}
527

528
static int write_to_syslog(
180✔
529
                int level,
530
                int error,
531
                const char *file,
532
                int line,
533
                const char *func,
534
                const char *buffer) {
535

536
        char header_priority[2 + DECIMAL_STR_MAX(int) + 1],
180✔
537
             header_time[64],
538
             header_pid[4 + DECIMAL_STR_MAX(pid_t) + 1];
539
        struct tm tm;
180✔
540
        int r;
180✔
541

542
        if (syslog_fd < 0)
180✔
543
                return 0;
180✔
544

545
        if (LOG_PRI(level) > log_target_max_level[LOG_TARGET_SYSLOG])
180✔
546
                return 0;
547

548
        xsprintf(header_priority, "<%i>", level);
180✔
549

550
        r = localtime_or_gmtime_usec(now(CLOCK_REALTIME), /* utc= */ false, &tm);
180✔
551
        if (r < 0)
180✔
552
                return r;
553

554
        if (strftime(header_time, sizeof(header_time), "%h %e %T ", &tm) <= 0)
180✔
555
                return -EINVAL;
556

557
        xsprintf(header_pid, "["PID_FMT"]: ", getpid_cached());
180✔
558

559
        struct iovec iovec[] = {
900✔
560
                IOVEC_MAKE_STRING(header_priority),
180✔
561
                IOVEC_MAKE_STRING(header_time),
180✔
562
                IOVEC_MAKE_STRING(program_invocation_short_name),
180✔
563
                IOVEC_MAKE_STRING(header_pid),
180✔
564
                IOVEC_MAKE_STRING(strempty(log_prefix)),
180✔
565
                IOVEC_MAKE_STRING(log_prefix ? ": " : ""),
180✔
566
                IOVEC_MAKE_STRING(buffer),
180✔
567
        };
568
        const struct msghdr msghdr = {
180✔
569
                .msg_iov = iovec,
570
                .msg_iovlen = ELEMENTSOF(iovec),
571
        };
572

573
        /* When using syslog via SOCK_STREAM separate the messages by NUL chars */
574
        if (syslog_is_stream)
180✔
575
                iovec[ELEMENTSOF(iovec) - 1].iov_len++;
×
576

577
        for (;;) {
180✔
578
                ssize_t n;
180✔
579

580
                n = sendmsg(syslog_fd, &msghdr, MSG_NOSIGNAL);
180✔
581
                if (n < 0)
180✔
582
                        return -errno;
×
583

584
                if (!syslog_is_stream)
180✔
585
                        break;
586

587
                if (iovec_increment(iovec, ELEMENTSOF(iovec), n))
×
588
                        break;
589
        }
590

591
        return 1;
592
}
593

594
static int write_to_kmsg(
181,299✔
595
                int level,
596
                int error,
597
                const char *file,
598
                int line,
599
                const char *func,
600
                const char *buffer) {
601

602
        /* Set a ratelimit on the amount of messages logged to /dev/kmsg. This is mostly supposed to be a
603
         * safety catch for the case where start indiscriminately logging in a loop. It will not catch cases
604
         * where we log excessively, but not in a tight loop.
605
         *
606
         * Note that this ratelimit is per-emitter, so we might still overwhelm /dev/kmsg with multiple
607
         * loggers.
608
         */
609
        static thread_local RateLimit ratelimit = { 5 * USEC_PER_SEC, 200 };
181,299✔
610

611
        char header_priority[2 + DECIMAL_STR_MAX(int) + 1],
181,299✔
612
             header_pid[4 + DECIMAL_STR_MAX(pid_t) + 1];
613

614
        if (kmsg_fd < 0)
181,299✔
615
                return 0;
181,299✔
616

617
        if (LOG_PRI(level) > log_target_max_level[LOG_TARGET_KMSG])
131,440✔
618
                return 0;
619

620
        if (ratelimit_kmsg && !ratelimit_below(&ratelimit)) {
131,440✔
621
                if (ratelimit_num_dropped(&ratelimit) > 1)
×
622
                        return 0;
623

624
                buffer = "Too many messages being logged to kmsg, ignoring";
625
        }
626

627
        xsprintf(header_priority, "<%i>", level);
131,440✔
628
        xsprintf(header_pid, "["PID_FMT"]: ", getpid_cached());
131,440✔
629

630
        const struct iovec iovec[] = {
657,200✔
631
                IOVEC_MAKE_STRING(header_priority),
131,440✔
632
                IOVEC_MAKE_STRING(program_invocation_short_name),
131,440✔
633
                IOVEC_MAKE_STRING(header_pid),
131,440✔
634
                IOVEC_MAKE_STRING(strempty(log_prefix)),
131,440✔
635
                IOVEC_MAKE_STRING(log_prefix ? ": " : ""),
131,440✔
636
                IOVEC_MAKE_STRING(buffer),
131,440✔
637
                IOVEC_MAKE_STRING("\n"),
131,440✔
638
        };
639

640
        if (writev(kmsg_fd, iovec, ELEMENTSOF(iovec)) < 0)
131,440✔
641
                return -errno;
×
642

643
        return 1;
644
}
645

646
static int log_do_header(
4,875,484✔
647
                char *header,
648
                size_t size,
649
                int level,
650
                int error,
651
                const char *file, int line, const char *func,
652
                const char *object_field, const char *object,
653
                const char *extra_field, const char *extra) {
654
        int r;
4,875,484✔
655

656
        error = IS_SYNTHETIC_ERRNO(error) ? 0 : ERRNO_VALUE(error);
4,875,484✔
657

658
        r = snprintf(header, size,
4,875,484✔
659
                     "PRIORITY=%i\n"
660
                     "SYSLOG_FACILITY=%i\n"
661
                     "TID=" PID_FMT "\n"
662
                     "%s%.256s%s"        /* CODE_FILE */
663
                     "%s%.*i%s"          /* CODE_LINE */
664
                     "%s%.256s%s"        /* CODE_FUNC */
665
                     "%s%.*i%s"          /* ERRNO */
666
                     "%s%.256s%s"        /* object */
667
                     "%s%.256s%s"        /* extra */
668
                     "SYSLOG_IDENTIFIER=%.256s\n",
669
                     LOG_PRI(level),
670
                     LOG_FAC(level),
4,875,484✔
671
                     gettid(),
672
                     isempty(file) ? "" : "CODE_FILE=",
4,875,484✔
673
                     isempty(file) ? "" : file,
4,875,484✔
674
                     isempty(file) ? "" : "\n",
4,875,484✔
675
                     line ? "CODE_LINE=" : "",
676
                     line ? 1 : 0, line, /* %.0d means no output too, special case for 0 */
677
                     line ? "\n" : "",
678
                     isempty(func) ? "" : "CODE_FUNC=",
4,875,484✔
679
                     isempty(func) ? "" : func,
4,875,484✔
680
                     isempty(func) ? "" : "\n",
4,875,484✔
681
                     error ? "ERRNO=" : "",
682
                     error ? 1 : 0, error,
683
                     error ? "\n" : "",
684
                     isempty(object) ? "" : ASSERT_PTR(object_field),
4,875,484✔
685
                     isempty(object) ? "" : object,
4,875,484✔
686
                     isempty(object) ? "" : "\n",
4,875,484✔
687
                     isempty(extra) ? "" : ASSERT_PTR(extra_field),
4,875,484✔
688
                     isempty(extra) ? "" : extra,
4,875,484✔
689
                     isempty(extra) ? "" : "\n",
4,875,484✔
690
                     program_invocation_short_name);
691
        assert_raw((size_t) r < size);
4,875,484✔
692

693
        return 0;
4,875,484✔
694
}
695

696
static void log_do_context(struct iovec *iovec, size_t iovec_len, size_t *n) {
4,875,484✔
697
        assert(iovec);
4,875,484✔
698
        assert(n);
4,875,484✔
699

700
        LIST_FOREACH(ll, c, _log_context) {
7,228,279✔
701
                STRV_FOREACH(s, c->fields) {
19,862,628✔
702
                        if (*n + 2 >= iovec_len)
17,495,817✔
703
                                return;
×
704

705
                        iovec[(*n)++] = IOVEC_MAKE_STRING(*s);
17,495,817✔
706
                        iovec[(*n)++] = IOVEC_MAKE_STRING("\n");
17,495,817✔
707
                }
708

709
                for (size_t i = 0; i < c->n_input_iovec; i++) {
2,370,908✔
710
                        if (*n + 2 >= iovec_len)
4,097✔
711
                                return;
×
712

713
                        iovec[(*n)++] = c->input_iovec[i];
4,097✔
714
                        iovec[(*n)++] = IOVEC_MAKE_STRING("\n");
4,097✔
715
                }
716

717
                if (c->key && c->value) {
2,366,811✔
718
                        if (*n + 3 >= iovec_len)
372,737✔
719
                                return;
14,016✔
720

721
                        iovec[(*n)++] = IOVEC_MAKE_STRING(c->key);
358,721✔
722
                        iovec[(*n)++] = IOVEC_MAKE_STRING(c->value);
358,721✔
723
                        iovec[(*n)++] = IOVEC_MAKE_STRING("\n");
358,721✔
724
                }
725
        }
726
}
727

728
static int write_to_journal(
5,025,640✔
729
                int level,
730
                int error,
731
                const char *file,
732
                int line,
733
                const char *func,
734
                const char *object_field,
735
                const char *object,
736
                const char *extra_field,
737
                const char *extra,
738
                const char *buffer) {
739

740
        char header[LINE_MAX];
5,025,640✔
741
        size_t n = 0, iovec_len;
5,025,640✔
742
        struct iovec *iovec;
5,025,640✔
743

744
        if (journal_fd < 0)
5,025,640✔
745
                return 0;
5,025,640✔
746

747
        if (LOG_PRI(level) > log_target_max_level[LOG_TARGET_JOURNAL])
4,821,657✔
748
                return 0;
749

750
        iovec_len = MIN(6 + _log_context_num_fields * 3, IOVEC_MAX);
4,821,657✔
751
        iovec = newa(struct iovec, iovec_len);
4,821,657✔
752

753
        log_do_header(header, sizeof(header), level, error, file, line, func, object_field, object, extra_field, extra);
4,821,657✔
754

755
        iovec[n++] = IOVEC_MAKE_STRING(header);
4,821,657✔
756
        iovec[n++] = IOVEC_MAKE_STRING("MESSAGE=");
4,821,657✔
757
        if (log_prefix) {
4,821,657✔
758
                iovec[n++] = IOVEC_MAKE_STRING(log_prefix);
1,960,565✔
759
                iovec[n++] = IOVEC_MAKE_STRING(": ");
1,960,565✔
760
        }
761
        iovec[n++] = IOVEC_MAKE_STRING(buffer);
4,821,657✔
762
        iovec[n++] = IOVEC_MAKE_STRING("\n");
4,821,657✔
763

764
        log_do_context(iovec, iovec_len, &n);
4,821,657✔
765

766
        const struct msghdr msghdr = {
4,821,657✔
767
                .msg_iov = iovec,
768
                .msg_iovlen = n,
769
        };
770

771
        if (sendmsg(journal_fd, &msghdr, MSG_NOSIGNAL) < 0)
4,821,657✔
772
                return -errno;
857✔
773

774
        return 1;
775
}
776

777
int log_dispatch_internal(
5,064,519✔
778
                int level,
779
                int error,
780
                const char *file,
781
                int line,
782
                const char *func,
783
                const char *object_field,
784
                const char *object,
785
                const char *extra_field,
786
                const char *extra,
787
                char *buffer) {
788

789
        assert_raw(buffer);
5,064,519✔
790

791
        if (log_target == LOG_TARGET_NULL)
5,064,519✔
792
                return -ERRNO_VALUE(error);
10✔
793

794
        /* Patch in LOG_DAEMON facility if necessary */
795
        if (LOG_FAC(level) == 0)
5,064,509✔
796
                level |= log_facility;
5,047,871✔
797

798
        if (open_when_needed)
5,064,509✔
799
                (void) log_open();
202,726✔
800

801
        do {
5,118,047✔
802
                char *e;
5,118,047✔
803
                int k = 0;
5,118,047✔
804

805
                buffer += strspn(buffer, NEWLINE);
5,118,047✔
806

807
                if (buffer[0] == 0)
5,118,047✔
808
                        break;
809

810
                if ((e = strpbrk(buffer, NEWLINE)))
5,074,139✔
811
                        *(e++) = 0;
53,538✔
812

813
                if (IN_SET(log_target, LOG_TARGET_AUTO,
5,074,139✔
814
                                       LOG_TARGET_JOURNAL_OR_KMSG,
815
                                       LOG_TARGET_JOURNAL)) {
816

817
                        k = write_to_journal(level, error, file, line, func, object_field, object, extra_field, extra, buffer);
5,025,640✔
818
                        if (k < 0 && k != -EAGAIN)
5,025,640✔
819
                                log_close_journal();
3✔
820
                }
821

822
                if (IN_SET(log_target, LOG_TARGET_SYSLOG_OR_KMSG,
5,074,139✔
823
                                       LOG_TARGET_SYSLOG)) {
824

825
                        k = write_to_syslog(level, error, file, line, func, buffer);
180✔
826
                        if (k < 0 && k != -EAGAIN)
180✔
827
                                log_close_syslog();
×
828
                }
829

830
                if (k <= 0 &&
5,074,139✔
831
                    IN_SET(log_target, LOG_TARGET_AUTO,
253,159✔
832
                                       LOG_TARGET_SYSLOG_OR_KMSG,
833
                                       LOG_TARGET_JOURNAL_OR_KMSG,
834
                                       LOG_TARGET_KMSG)) {
835

836
                        if (k < 0)
181,299✔
837
                                log_open_kmsg();
838✔
838

839
                        k = write_to_kmsg(level, error, file, line, func, buffer);
181,299✔
840
                        if (k < 0) {
181,299✔
841
                                log_close_kmsg();
×
842
                                (void) log_open_console();
×
843
                        }
844
                }
845

846
                if (k <= 0)
253,159✔
847
                        (void) write_to_console(level, error, file, line, func, buffer);
121,719✔
848

849
                buffer = e;
5,074,139✔
850
        } while (buffer);
5,074,139✔
851

852
        if (open_when_needed)
5,064,509✔
853
                log_close();
202,726✔
854

855
        return -ERRNO_VALUE(error);
5,064,509✔
856
}
857

858
int log_dump_internal(
6✔
859
                int level,
860
                int error,
861
                const char *file,
862
                int line,
863
                const char *func,
864
                char *buffer) {
865

866
        PROTECT_ERRNO;
6✔
867

868
        /* This modifies the buffer... */
869

870
        if (_likely_(LOG_PRI(level) > log_max_level))
6✔
871
                return -ERRNO_VALUE(error);
×
872

873
        return log_dispatch_internal(level, error, file, line, func, NULL, NULL, NULL, NULL, buffer);
6✔
874
}
875

876
int log_internalv(
3,000,820✔
877
                int level,
878
                int error,
879
                const char *file,
880
                int line,
881
                const char *func,
882
                const char *format,
883
                va_list ap) {
884

885
        if (_likely_(LOG_PRI(level) > log_max_level))
3,000,820✔
886
                return -ERRNO_VALUE(error);
3,000,820✔
887

888
        /* Make sure that %m maps to the specified error (or "Success"). */
889
        char buffer[LINE_MAX];
3,000,596✔
890
        LOCAL_ERRNO(ERRNO_VALUE(error));
3,000,596✔
891

892
        (void) vsnprintf(buffer, sizeof buffer, format, ap);
3,000,596✔
893

894
        return log_dispatch_internal(level, error, file, line, func, NULL, NULL, NULL, NULL, buffer);
3,000,596✔
895
}
896

897
int log_internal(
3,000,212✔
898
                int level,
899
                int error,
900
                const char *file,
901
                int line,
902
                const char *func,
903
                const char *format, ...) {
904

905
        va_list ap;
3,000,212✔
906
        int r;
3,000,212✔
907

908
        va_start(ap, format);
3,000,212✔
909
        r = log_internalv(level, error, file, line, func, format, ap);
3,000,212✔
910
        va_end(ap);
3,000,212✔
911

912
        return r;
3,000,212✔
913
}
914

915
int log_object_internalv(
2,082,688✔
916
                int level,
917
                int error,
918
                const char *file,
919
                int line,
920
                const char *func,
921
                const char *object_field,
922
                const char *object,
923
                const char *extra_field,
924
                const char *extra,
925
                const char *format,
926
                va_list ap) {
927

928
        char *buffer, *b;
2,082,688✔
929

930
        if (_likely_(LOG_PRI(level) > log_max_level))
2,082,688✔
931
                return -ERRNO_VALUE(error);
2,082,688✔
932

933
        /* Make sure that %m maps to the specified error (or "Success"). */
934
        LOCAL_ERRNO(ERRNO_VALUE(error));
×
935

936
        LOG_SET_PREFIX(object);
4,095,018✔
937

938
        b = buffer = newa(char, LINE_MAX);
2,047,509✔
939
        (void) vsnprintf(b, LINE_MAX, format, ap);
2,047,509✔
940

941
        return log_dispatch_internal(level, error, file, line, func,
2,047,509✔
942
                                     object_field, object, extra_field, extra, buffer);
943
}
944

945
int log_object_internal(
2,071,684✔
946
                int level,
947
                int error,
948
                const char *file,
949
                int line,
950
                const char *func,
951
                const char *object_field,
952
                const char *object,
953
                const char *extra_field,
954
                const char *extra,
955
                const char *format, ...) {
956

957
        va_list ap;
2,071,684✔
958
        int r;
2,071,684✔
959

960
        va_start(ap, format);
2,071,684✔
961
        r = log_object_internalv(level, error, file, line, func, object_field, object, extra_field, extra, format, ap);
2,071,684✔
962
        va_end(ap);
2,071,684✔
963

964
        return r;
2,071,684✔
965
}
966

967
static void log_assert(
378✔
968
                int level,
969
                const char *text,
970
                const char *file,
971
                int line,
972
                const char *func,
973
                const char *format) {
974

975
        static char buffer[LINE_MAX];
378✔
976

977
        if (_likely_(LOG_PRI(level) > log_max_level))
378✔
978
                return;
979

980
        DISABLE_WARNING_FORMAT_NONLITERAL;
378✔
981
        (void) snprintf(buffer, sizeof buffer, format, text, file, line, func);
378✔
982
        REENABLE_WARNING;
378✔
983

984
        log_abort_msg = buffer;
378✔
985

986
        log_dispatch_internal(level, 0, file, line, func, NULL, NULL, NULL, NULL, buffer);
378✔
987
}
988

989
_noreturn_ void log_assert_failed(
×
990
                const char *text,
991
                const char *file,
992
                int line,
993
                const char *func) {
994
        log_assert(LOG_CRIT, text, file, line, func,
×
995
                   "Assertion '%s' failed at %s:%u, function %s(). Aborting.");
996
        abort();
×
997
}
998

999
_noreturn_ void log_assert_failed_unreachable(
×
1000
                const char *file,
1001
                int line,
1002
                const char *func) {
1003
        log_assert(LOG_CRIT, "Code should not be reached", file, line, func,
×
1004
                   "%s at %s:%u, function %s(). Aborting. 💥");
1005
        abort();
×
1006
}
1007

1008
void log_assert_failed_return(
378✔
1009
                const char *text,
1010
                const char *file,
1011
                int line,
1012
                const char *func) {
1013

1014
        if (assert_return_is_critical)
378✔
1015
                log_assert_failed(text, file, line, func);
×
1016

1017
        PROTECT_ERRNO;
378✔
1018
        log_assert(LOG_DEBUG, text, file, line, func,
378✔
1019
                   "Assertion '%s' failed at %s:%u, function %s(), ignoring.");
1020
}
378✔
1021

1022
int log_oom_internal(int level, const char *file, int line, const char *func) {
×
1023
        return log_internal(level, ENOMEM, file, line, func, "Out of memory.");
×
1024
}
1025

1026
int log_format_iovec(
52,130✔
1027
                struct iovec *iovec,
1028
                size_t iovec_len,
1029
                size_t *n,
1030
                bool newline_separator,
1031
                int error,
1032
                const char *format,
1033
                va_list ap) {
1034

1035
        static const char nl = '\n';
52,130✔
1036

1037
        while (format && *n + 1 < iovec_len) {
327,728✔
1038
                va_list aq;
275,598✔
1039
                char *m;
275,598✔
1040
                int r;
275,598✔
1041

1042
                /* We need to copy the va_list structure,
1043
                 * since vasprintf() leaves it afterwards at
1044
                 * an undefined location */
1045

1046
                errno = ERRNO_VALUE(error);
275,598✔
1047

1048
                va_copy(aq, ap);
275,598✔
1049
                r = vasprintf(&m, format, aq);
275,598✔
1050
                va_end(aq);
275,598✔
1051
                if (r < 0)
275,598✔
1052
                        return -EINVAL;
×
1053

1054
                /* Now, jump enough ahead, so that we point to
1055
                 * the next format string */
1056
                VA_FORMAT_ADVANCE(format, ap);
611,912✔
1057

1058
                iovec[(*n)++] = IOVEC_MAKE_STRING(m);
275,598✔
1059
                if (newline_separator)
275,598✔
1060
                        iovec[(*n)++] = IOVEC_MAKE((char *)&nl, 1);
274,271✔
1061

1062
                format = va_arg(ap, char *);
275,598✔
1063
        }
1064
        return 0;
1065
}
1066

1067
int log_struct_internal(
67,930✔
1068
                int level,
1069
                int error,
1070
                const char *file,
1071
                int line,
1072
                const char *func,
1073
                const char *format, ...) {
1074

1075
        char buf[LINE_MAX];
67,930✔
1076
        bool found = false;
67,930✔
1077
        PROTECT_ERRNO;
67,930✔
1078
        va_list ap;
67,930✔
1079

1080
        if (_likely_(LOG_PRI(level) > log_max_level) ||
67,930✔
1081
            log_target == LOG_TARGET_NULL)
67,930✔
1082
                return -ERRNO_VALUE(error);
50✔
1083

1084
        if (LOG_FAC(level) == 0)
67,880✔
1085
                level |= log_facility;
67,880✔
1086

1087
        if (IN_SET(log_target,
67,880✔
1088
                   LOG_TARGET_AUTO,
1089
                   LOG_TARGET_JOURNAL_OR_KMSG,
1090
                   LOG_TARGET_JOURNAL)) {
1091

1092
                if (open_when_needed)
65,036✔
1093
                        log_open_journal();
8,129✔
1094

1095
                if (journal_fd >= 0) {
65,036✔
1096
                        char header[LINE_MAX];
51,979✔
1097
                        struct iovec *iovec;
51,979✔
1098
                        size_t n = 0, m, iovec_len;
51,979✔
1099
                        int r;
51,979✔
1100
                        bool fallback = false;
51,979✔
1101

1102
                        iovec_len = MIN(17 + _log_context_num_fields * 3, IOVEC_MAX);
51,979✔
1103
                        iovec = newa(struct iovec, iovec_len);
51,979✔
1104

1105
                        /* If the journal is available do structured logging.
1106
                         * Do not report the errno if it is synthetic. */
1107
                        log_do_header(header, sizeof(header), level, error, file, line, func, NULL, NULL, NULL, NULL);
51,979✔
1108
                        iovec[n++] = IOVEC_MAKE_STRING(header);
51,979✔
1109

1110
                        va_start(ap, format);
51,979✔
1111
                        r = log_format_iovec(iovec, iovec_len, &n, true, error, format, ap);
51,979✔
1112
                        m = n;
51,979✔
1113
                        if (r < 0)
51,979✔
1114
                                fallback = true;
1115
                        else {
1116
                                log_do_context(iovec, iovec_len, &n);
51,979✔
1117

1118
                                const struct msghdr msghdr = {
51,979✔
1119
                                        .msg_iov = iovec,
1120
                                        .msg_iovlen = n,
1121
                                };
1122

1123
                                (void) sendmsg(journal_fd, &msghdr, MSG_NOSIGNAL);
51,979✔
1124
                        }
1125

1126
                        va_end(ap);
51,979✔
1127
                        for (size_t i = 1; i < m; i += 2)
326,250✔
1128
                                free(iovec[i].iov_base);
274,271✔
1129

1130
                        if (!fallback) {
51,979✔
1131
                                if (open_when_needed)
51,979✔
1132
                                        log_close();
8,116✔
1133

1134
                                return -ERRNO_VALUE(error);
51,979✔
1135
                        }
1136
                }
1137
        }
1138

1139
        /* Fallback if journal logging is not available or didn't work. */
1140

1141
        va_start(ap, format);
15,901✔
1142
        while (format) {
40,677✔
1143
                va_list aq;
40,677✔
1144

1145
                errno = ERRNO_VALUE(error);
40,677✔
1146

1147
                va_copy(aq, ap);
40,677✔
1148
                (void) vsnprintf(buf, sizeof buf, format, aq);
40,677✔
1149
                va_end(aq);
40,677✔
1150

1151
                if (startswith(buf, "MESSAGE=")) {
40,677✔
1152
                        found = true;
15,901✔
1153
                        break;
15,901✔
1154
                }
1155

1156
                VA_FORMAT_ADVANCE(format, ap);
43,510✔
1157

1158
                format = va_arg(ap, char *);
24,776✔
1159
        }
1160
        va_end(ap);
15,901✔
1161

1162
        if (!found) {
15,901✔
1163
                if (open_when_needed)
×
1164
                        log_close();
×
1165

1166
                return -ERRNO_VALUE(error);
×
1167
        }
1168

1169
        return log_dispatch_internal(level, error, file, line, func, NULL, NULL, NULL, NULL, buf + 8);
15,901✔
1170
}
1171

1172
int log_struct_iovec_internal(
1,977✔
1173
                int level,
1174
                int error,
1175
                const char *file,
1176
                int line,
1177
                const char *func,
1178
                const struct iovec input_iovec[],
1179
                size_t n_input_iovec) {
1180

1181
        PROTECT_ERRNO;
1,977✔
1182

1183
        if (_likely_(LOG_PRI(level) > log_max_level) ||
1,977✔
1184
            log_target == LOG_TARGET_NULL)
1,977✔
1185
                return -ERRNO_VALUE(error);
×
1186

1187
        if (LOG_FAC(level) == 0)
1,977✔
1188
                level |= log_facility;
1,977✔
1189

1190
        if (IN_SET(log_target, LOG_TARGET_AUTO,
1,977✔
1191
                               LOG_TARGET_JOURNAL_OR_KMSG,
1192
                               LOG_TARGET_JOURNAL) &&
1,977✔
1193
            journal_fd >= 0) {
1,977✔
1194

1195
                char header[LINE_MAX];
1,848✔
1196
                struct iovec *iovec;
1,848✔
1197
                size_t n = 0, iovec_len;
1,848✔
1198

1199
                iovec_len = MIN(1 + n_input_iovec * 2 + _log_context_num_fields * 3, IOVEC_MAX);
1,848✔
1200
                iovec = newa(struct iovec, iovec_len);
1,848✔
1201

1202
                log_do_header(header, sizeof(header), level, error, file, line, func, NULL, NULL, NULL, NULL);
1,848✔
1203

1204
                iovec[n++] = IOVEC_MAKE_STRING(header);
1,848✔
1205
                for (size_t i = 0; i < n_input_iovec; i++) {
14,734✔
1206
                        iovec[n++] = input_iovec[i];
12,886✔
1207
                        iovec[n++] = IOVEC_MAKE_STRING("\n");
12,886✔
1208
                }
1209

1210
                log_do_context(iovec, iovec_len, &n);
1,848✔
1211

1212
                const struct msghdr msghdr = {
1,848✔
1213
                        .msg_iov = iovec,
1214
                        .msg_iovlen = n,
1215
                };
1216

1217
                if (sendmsg(journal_fd, &msghdr, MSG_NOSIGNAL) >= 0)
1,848✔
1218
                        return -ERRNO_VALUE(error);
1,848✔
1219
        }
1220

1221
        for (size_t i = 0; i < n_input_iovec; i++)
516✔
1222
                if (memory_startswith(input_iovec[i].iov_base, input_iovec[i].iov_len, "MESSAGE=")) {
516✔
1223
                        char *m;
129✔
1224

1225
                        m = strndupa_safe((char*) input_iovec[i].iov_base + STRLEN("MESSAGE="),
129✔
1226
                                          input_iovec[i].iov_len - STRLEN("MESSAGE="));
1227

1228
                        return log_dispatch_internal(level, error, file, line, func, NULL, NULL, NULL, NULL, m);
129✔
1229
                }
1230

1231
        /* Couldn't find MESSAGE=. */
1232
        return -ERRNO_VALUE(error);
×
1233
}
1234

1235
int log_set_target_from_string(const char *e) {
14,013✔
1236
        LogTarget t;
14,013✔
1237

1238
        t = log_target_from_string(e);
14,013✔
1239
        if (t < 0)
14,013✔
1240
                return t;
1241

1242
        log_set_target(t);
14,013✔
1243
        return 0;
14,013✔
1244
}
1245

1246
int log_set_max_level_from_string(const char *e) {
27,082✔
1247
        int r;
75,340✔
1248

1249
        for (;;) {
75,340✔
1250
                _cleanup_free_ char *word = NULL, *prefix = NULL;
75,340✔
1251
                LogTarget target;
75,340✔
1252
                const char *colon;
75,340✔
1253

1254
                r = extract_first_word(&e, &word, ",", 0);
75,340✔
1255
                if (r < 0)
75,340✔
1256
                        return r;
1257
                if (r == 0)
75,340✔
1258
                        break;
1259

1260
                colon = strchr(word, ':');
48,258✔
1261
                if (!colon) {
48,258✔
1262
                        r = log_level_from_string(word);
27,082✔
1263
                        if (r < 0)
27,082✔
1264
                                return r;
1265

1266
                        log_set_max_level(r);
27,082✔
1267
                        continue;
27,082✔
1268
                }
1269

1270
                prefix = strndup(word, colon - word);
21,176✔
1271
                if (!prefix)
21,176✔
1272
                        return -ENOMEM;
1273

1274
                target = log_target_from_string(prefix);
21,176✔
1275
                if (target < 0)
21,176✔
1276
                        return target;
1277

1278
                if (target >= _LOG_TARGET_SINGLE_MAX)
21,176✔
1279
                        return -EINVAL;
1280

1281
                r = log_level_from_string(colon + 1);
21,176✔
1282
                if (r < 0)
21,176✔
1283
                        return r;
1284

1285
                log_target_max_level[target] = r;
21,176✔
1286
        }
1287

1288
        return 0;
27,082✔
1289
}
1290

1291
int log_max_levels_to_string(int level, char **ret) {
3,834✔
1292
        _cleanup_free_ char *s = NULL;
3,834✔
1293
        int r;
3,834✔
1294

1295
        assert(ret);
3,834✔
1296

1297
        r = log_level_to_string_alloc(level, &s);
3,834✔
1298
        if (r < 0)
3,834✔
1299
                return r;
1300

1301
        for (LogTarget target = 0; target < _LOG_TARGET_SINGLE_MAX; target++) {
19,170✔
1302
                _cleanup_free_ char *l = NULL;
3,834✔
1303

1304
                if (log_target_max_level[target] == INT_MAX)
15,336✔
1305
                        continue;
11,502✔
1306

1307
                r = log_level_to_string_alloc(log_target_max_level[target], &l);
3,834✔
1308
                if (r < 0)
3,834✔
1309
                        return r;
1310

1311
                r = strextendf_with_separator(&s, ",", "%s:%s", log_target_to_string(target), l);
3,834✔
1312
                if (r < 0)
3,834✔
1313
                        return r;
1314
        }
1315

1316
        *ret = TAKE_PTR(s);
3,834✔
1317
        return 0;
3,834✔
1318
}
1319

1320
static int log_set_ratelimit_kmsg_from_string(const char *e) {
7,915✔
1321
        int r;
7,915✔
1322

1323
        r = parse_boolean(e);
7,915✔
1324
        if (r < 0)
7,915✔
1325
                return r;
1326

1327
        ratelimit_kmsg = r;
7,915✔
1328
        return 0;
7,915✔
1329
}
1330

1331
void log_set_assert_return_is_critical(bool b) {
1,159✔
1332
        assert_return_is_critical = b;
1,159✔
1333
}
1,159✔
1334

1335
bool log_get_assert_return_is_critical(void) {
386✔
1336
        return assert_return_is_critical;
386✔
1337
}
1338

1339
static int parse_proc_cmdline_item(const char *key, const char *value, void *data) {
288,702✔
1340

1341
        /*
1342
         * The systemd.log_xyz= settings are parsed by all tools, and
1343
         * so is "debug".
1344
         *
1345
         * However, "quiet" is only parsed by PID 1, and only turns of
1346
         * status output to /dev/console, but does not alter the log
1347
         * level.
1348
         */
1349

1350
        if (streq(key, "debug") && !value)
288,702✔
1351
                log_set_max_level(LOG_DEBUG);
×
1352

1353
        else if (proc_cmdline_key_streq(key, "systemd.log_target")) {
288,702✔
1354

1355
                if (proc_cmdline_value_missing(key, value))
×
1356
                        return 0;
1357

1358
                if (log_set_target_from_string(value) < 0)
×
1359
                        log_warning("Failed to parse log target '%s', ignoring.", value);
×
1360

1361
        } else if (proc_cmdline_key_streq(key, "systemd.log_level")) {
288,702✔
1362

1363
                if (proc_cmdline_value_missing(key, value))
7,915✔
1364
                        return 0;
1365

1366
                if (log_set_max_level_from_string(value) < 0)
7,915✔
1367
                        log_warning("Failed to parse log level setting '%s', ignoring.", value);
×
1368

1369
        } else if (proc_cmdline_key_streq(key, "systemd.log_color")) {
280,787✔
1370

1371
                if (log_show_color_from_string(value ?: "1") < 0)
×
1372
                        log_warning("Failed to parse log color setting '%s', ignoring.", value);
×
1373

1374
        } else if (proc_cmdline_key_streq(key, "systemd.log_location")) {
280,787✔
1375

1376
                if (log_show_location_from_string(value ?: "1") < 0)
×
1377
                        log_warning("Failed to parse log location setting '%s', ignoring.", value);
×
1378

1379
        } else if (proc_cmdline_key_streq(key, "systemd.log_tid")) {
280,787✔
1380

1381
                if (log_show_tid_from_string(value ?: "1") < 0)
×
1382
                        log_warning("Failed to parse log tid setting '%s', ignoring.", value);
×
1383

1384
        } else if (proc_cmdline_key_streq(key, "systemd.log_time")) {
280,787✔
1385

1386
                if (log_show_time_from_string(value ?: "1") < 0)
×
1387
                        log_warning("Failed to parse log time setting '%s', ignoring.", value);
×
1388

1389
        } else if (proc_cmdline_key_streq(key, "systemd.log_ratelimit_kmsg")) {
280,787✔
1390

1391
                if (log_set_ratelimit_kmsg_from_string(value ?: "1") < 0)
7,915✔
1392
                        log_warning("Failed to parse log ratelimit kmsg boolean '%s', ignoring.", value);
×
1393
        }
1394

1395
        return 0;
1396
}
1397

1398
static bool should_parse_proc_cmdline(void) {
90,864✔
1399
        /* PID1 always reads the kernel command line. */
1400
        if (getpid_cached() == 1)
90,864✔
1401
                return true;
1402

1403
        /* Otherwise, parse the command line if invoked directly by systemd. */
1404
        return invoked_by_systemd();
90,523✔
1405
}
1406

1407
void log_parse_environment_variables(void) {
92,420✔
1408
        const char *e;
92,420✔
1409
        int r;
92,420✔
1410

1411
        e = getenv("SYSTEMD_LOG_TARGET");
92,420✔
1412
        if (e && log_set_target_from_string(e) < 0)
92,420✔
1413
                log_warning("Failed to parse log target '%s', ignoring.", e);
×
1414

1415
        e = getenv("SYSTEMD_LOG_LEVEL");
92,420✔
1416
        if (e) {
92,420✔
1417
                r = log_set_max_level_from_string(e);
5,906✔
1418
                if (r < 0)
5,906✔
1419
                        log_warning_errno(r, "Failed to parse log level '%s', ignoring: %m", e);
×
1420
        } else {
1421
                /* If no explicit log level is specified then let's see if this is a debug invocation, and if
1422
                 * so raise the log level to debug too. Note that this is not symmetric: just because
1423
                 * DEBUG_INVOCATION is explicitly set to 0 we won't lower the log level below debug. This
1424
                 * follows the logic that debug logging is an opt-in thing anyway, and if there's any reason
1425
                 * to enable it we should not disable it here automatically. */
1426
                r = getenv_bool("DEBUG_INVOCATION");
86,514✔
1427
                if (r < 0 && r != -ENXIO)
86,514✔
1428
                        log_warning_errno(r, "Failed to parse $DEBUG_INVOCATION value, ignoring: %m");
×
1429
                else if (r > 0)
86,514✔
1430
                        log_set_max_level(LOG_DEBUG);
×
1431
        }
1432

1433
        e = getenv("SYSTEMD_LOG_COLOR");
92,420✔
1434
        if (e && log_show_color_from_string(e) < 0)
92,420✔
1435
                log_warning("Failed to parse log color '%s', ignoring.", e);
×
1436

1437
        e = getenv("SYSTEMD_LOG_LOCATION");
92,420✔
1438
        if (e && log_show_location_from_string(e) < 0)
92,420✔
1439
                log_warning("Failed to parse log location '%s', ignoring.", e);
×
1440

1441
        e = getenv("SYSTEMD_LOG_TIME");
92,420✔
1442
        if (e && log_show_time_from_string(e) < 0)
92,420✔
1443
                log_warning("Failed to parse log time '%s', ignoring.", e);
×
1444

1445
        e = getenv("SYSTEMD_LOG_TID");
92,420✔
1446
        if (e && log_show_tid_from_string(e) < 0)
92,420✔
1447
                log_warning("Failed to parse log tid '%s', ignoring.", e);
×
1448

1449
        e = getenv("SYSTEMD_LOG_RATELIMIT_KMSG");
92,420✔
1450
        if (e && log_set_ratelimit_kmsg_from_string(e) < 0)
92,420✔
1451
                log_warning("Failed to parse log ratelimit kmsg boolean '%s', ignoring.", e);
×
1452
}
92,420✔
1453

1454
void log_parse_environment(void) {
90,864✔
1455
        /* Do not call from library code. */
1456

1457
        if (should_parse_proc_cmdline())
90,864✔
1458
                (void) proc_cmdline_parse(parse_proc_cmdline_item, NULL, PROC_CMDLINE_STRIP_RD_PREFIX);
7,988✔
1459

1460
        log_parse_environment_variables();
90,864✔
1461
}
90,864✔
1462

1463
LogTarget log_get_target(void) {
19,232✔
1464
        return log_target;
19,232✔
1465
}
1466

1467
void log_settle_target(void) {
16,659✔
1468

1469
        /* If we're using LOG_TARGET_AUTO and opening the log again on every single log call, we'll check if
1470
         * stderr is attached to the journal every single log call. However, if we then close all file
1471
         * descriptors later, that will stop working because stderr will be closed as well. To avoid that
1472
         * problem, this function is used to permanently change the log target depending on whether stderr is
1473
         * connected to the journal or not. */
1474

1475
        LogTarget t = log_get_target();
16,659✔
1476

1477
        if (t != LOG_TARGET_AUTO)
16,659✔
1478
                return;
1479

1480
        t = getpid_cached() == 1 || stderr_is_journal() ? (prohibit_ipc ? LOG_TARGET_KMSG : LOG_TARGET_JOURNAL_OR_KMSG)
7,646✔
1481
                                                        : LOG_TARGET_CONSOLE;
7,635✔
1482
        log_set_target(t);
3,834✔
1483
}
1484

1485
int log_get_max_level(void) {
13,953,068✔
1486
        return log_max_level;
13,953,068✔
1487
}
1488

1489
void log_show_color(bool b) {
32,428✔
1490
        show_color = b;
32,428✔
1491
}
32,428✔
1492

1493
bool log_get_show_color(void) {
67,304✔
1494
        return show_color > 0; /* Defaults to false. */
67,304✔
1495
}
1496

1497
void log_show_location(bool b) {
×
1498
        show_location = b;
×
1499
}
×
1500

1501
bool log_get_show_location(void) {
14✔
1502
        return show_location;
14✔
1503
}
1504

1505
void log_show_time(bool b) {
1✔
1506
        show_time = b;
1✔
1507
}
1✔
1508

1509
bool log_get_show_time(void) {
14✔
1510
        return show_time;
14✔
1511
}
1512

1513
void log_show_tid(bool b) {
1✔
1514
        show_tid = b;
1✔
1515
}
1✔
1516

1517
bool log_get_show_tid(void) {
×
1518
        return show_tid;
×
1519
}
1520

1521
int log_show_color_from_string(const char *e) {
×
1522
        int r;
×
1523

1524
        r = parse_boolean(e);
×
1525
        if (r < 0)
×
1526
                return r;
1527

1528
        log_show_color(r);
×
1529
        return 0;
×
1530
}
1531

1532
int log_show_location_from_string(const char *e) {
×
1533
        int r;
×
1534

1535
        r = parse_boolean(e);
×
1536
        if (r < 0)
×
1537
                return r;
1538

1539
        log_show_location(r);
×
1540
        return 0;
×
1541
}
1542

1543
int log_show_time_from_string(const char *e) {
×
1544
        int r;
×
1545

1546
        r = parse_boolean(e);
×
1547
        if (r < 0)
×
1548
                return r;
1549

1550
        log_show_time(r);
×
1551
        return 0;
×
1552
}
1553

1554
int log_show_tid_from_string(const char *e) {
×
1555
        int r;
×
1556

1557
        r = parse_boolean(e);
×
1558
        if (r < 0)
×
1559
                return r;
1560

1561
        log_show_tid(r);
×
1562
        return 0;
×
1563
}
1564

1565
bool log_on_console(void) {
116,423✔
1566
        if (IN_SET(log_target, LOG_TARGET_CONSOLE,
116,423✔
1567
                               LOG_TARGET_CONSOLE_PREFIXED))
1568
                return true;
1569

1570
        return syslog_fd < 0 && kmsg_fd < 0 && journal_fd < 0;
199,172✔
1571
}
1572

1573
static const char *const log_target_table[_LOG_TARGET_MAX] = {
1574
        [LOG_TARGET_CONSOLE]          = "console",
1575
        [LOG_TARGET_CONSOLE_PREFIXED] = "console-prefixed",
1576
        [LOG_TARGET_KMSG]             = "kmsg",
1577
        [LOG_TARGET_JOURNAL]          = "journal",
1578
        [LOG_TARGET_JOURNAL_OR_KMSG]  = "journal-or-kmsg",
1579
        [LOG_TARGET_SYSLOG]           = "syslog",
1580
        [LOG_TARGET_SYSLOG_OR_KMSG]   = "syslog-or-kmsg",
1581
        [LOG_TARGET_AUTO]             = "auto",
1582
        [LOG_TARGET_NULL]             = "null",
1583
};
1584

1585
DEFINE_STRING_TABLE_LOOKUP(log_target, LogTarget);
42,971✔
1586

1587
void log_received_signal(int level, const struct signalfd_siginfo *si) {
5,937✔
1588
        assert(si);
5,937✔
1589

1590
        if (pid_is_valid(si->ssi_pid)) {
5,937✔
1591
                _cleanup_free_ char *p = NULL;
5,937✔
1592

1593
                (void) pid_get_comm(si->ssi_pid, &p);
5,937✔
1594

1595
                log_full(level,
7,124✔
1596
                         "Received SIG%s from PID %"PRIu32" (%s).",
1597
                         signal_to_string(si->ssi_signo),
1598
                         si->ssi_pid, strna(p));
1599
        } else
1600
                log_full(level,
×
1601
                         "Received SIG%s.",
1602
                         signal_to_string(si->ssi_signo));
1603
}
5,937✔
1604

1605
void set_log_syntax_callback(log_syntax_callback_t cb, void *userdata) {
844✔
1606
        assert(!log_syntax_callback || !cb);
844✔
1607
        assert(!log_syntax_callback_userdata || !userdata);
844✔
1608

1609
        log_syntax_callback = cb;
844✔
1610
        log_syntax_callback_userdata = userdata;
844✔
1611
}
844✔
1612

1613
int log_syntax_internal(
13,655✔
1614
                const char *unit,
1615
                int level,
1616
                const char *config_file,
1617
                unsigned config_line,
1618
                int error,
1619
                const char *file,
1620
                int line,
1621
                const char *func,
1622
                const char *format, ...) {
1623

1624
        PROTECT_ERRNO;
13,655✔
1625

1626
        if (log_syntax_callback)
13,655✔
1627
                log_syntax_callback(unit, level, log_syntax_callback_userdata);
786✔
1628

1629
        if (_likely_(LOG_PRI(level) > log_max_level) ||
13,655✔
1630
            log_target == LOG_TARGET_NULL)
13,655✔
1631
                return -ERRNO_VALUE(error);
30✔
1632

1633
        char buffer[LINE_MAX];
13,625✔
1634
        va_list ap;
13,625✔
1635
        const char *unit_fmt = NULL;
13,625✔
1636

1637
        errno = ERRNO_VALUE(error);
13,625✔
1638

1639
        va_start(ap, format);
13,625✔
1640
        (void) vsnprintf(buffer, sizeof buffer, format, ap);
13,625✔
1641
        va_end(ap);
13,625✔
1642

1643
        if (unit)
13,625✔
1644
                unit_fmt = getpid_cached() == 1 ? "UNIT=%s" : "USER_UNIT=%s";
6,691✔
1645

1646
        if (config_file) {
13,625✔
1647
                if (config_line > 0)
13,615✔
1648
                        return log_struct_internal(
8,163✔
1649
                                        level,
1650
                                        error,
1651
                                        file, line, func,
1652
                                        "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR,
1653
                                        "CONFIG_FILE=%s", config_file,
1654
                                        "CONFIG_LINE=%u", config_line,
1655
                                        LOG_MESSAGE("%s:%u: %s", config_file, config_line, buffer),
8,163✔
1656
                                        unit_fmt, unit,
1657
                                        NULL);
1658
                else
1659
                        return log_struct_internal(
5,452✔
1660
                                        level,
1661
                                        error,
1662
                                        file, line, func,
1663
                                        "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR,
1664
                                        "CONFIG_FILE=%s", config_file,
1665
                                        LOG_MESSAGE("%s: %s", config_file, buffer),
5,452✔
1666
                                        unit_fmt, unit,
1667
                                        NULL);
1668
        } else if (unit)
10✔
UNCOV
1669
                return log_struct_internal(
×
1670
                                level,
1671
                                error,
1672
                                file, line, func,
1673
                                "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR,
UNCOV
1674
                                LOG_MESSAGE("%s: %s", unit, buffer),
×
1675
                                unit_fmt, unit,
1676
                                NULL);
1677
        else
1678
                return log_struct_internal(
10✔
1679
                                level,
1680
                                error,
1681
                                file, line, func,
1682
                                "MESSAGE_ID=" SD_MESSAGE_INVALID_CONFIGURATION_STR,
1683
                                LOG_MESSAGE("%s", buffer),
10✔
1684
                                NULL);
1685
}
1686

1687
int log_syntax_invalid_utf8_internal(
1✔
1688
                const char *unit,
1689
                int level,
1690
                const char *config_file,
1691
                unsigned config_line,
1692
                const char *file,
1693
                int line,
1694
                const char *func,
1695
                const char *rvalue) {
1696

1697
        PROTECT_ERRNO;
×
1698
        _cleanup_free_ char *p = NULL;
1✔
1699

1700
        if (rvalue)
1✔
1701
                p = utf8_escape_invalid(rvalue);
1✔
1702

1703
        return log_syntax_internal(unit, level, config_file, config_line,
1✔
1704
                                   SYNTHETIC_ERRNO(EINVAL), file, line, func,
1705
                                   "String is not UTF-8 clean, ignoring assignment: %s", strna(p));
1706
}
1707

1708
int log_syntax_parse_error_internal(
110✔
1709
                const char *unit,
1710
                const char *config_file,
1711
                unsigned config_line,
1712
                int error,
1713
                bool critical,
1714
                const char *file,
1715
                int line,
1716
                const char *func,
1717
                const char *lvalue,
1718
                const char *rvalue) {
1719

1720
        PROTECT_ERRNO;
×
1721
        _cleanup_free_ char *escaped = NULL;
110✔
1722

1723
        /* OOM is always handled as critical. */
1724
        if (ERRNO_VALUE(error) == ENOMEM)
110✔
1725
                return log_oom_internal(LOG_ERR, file, line, func);
×
1726

1727
        if (rvalue && !utf8_is_valid(rvalue)) {
220✔
1728
                escaped = utf8_escape_invalid(rvalue);
×
1729
                if (!escaped)
×
1730
                        rvalue = "(oom)";
1731
                else
1732
                        rvalue = " (escaped)";
×
1733
        }
1734

1735
        log_syntax_internal(unit, critical ? LOG_ERR : LOG_WARNING, config_file, config_line, error,
550✔
1736
                            file, line, func,
1737
                            "Failed to parse %s=%s%s%s%s%s",
1738
                            strna(lvalue), strempty(escaped), strempty(rvalue),
1739
                            critical ? "" : ", ignoring",
1740
                            error == 0 ? "." : ": ",
1741
                            error == 0 ? "" : STRERROR(error));
110✔
1742

1743
        return critical ? -ERRNO_VALUE(error) : 0;
110✔
1744
}
1745

1746
void log_set_upgrade_syslog_to_journal(bool b) {
249✔
1747
        upgrade_syslog_to_journal = b;
249✔
1748

1749
        /* Make the change effective immediately */
1750
        if (b) {
249✔
1751
                if (log_target == LOG_TARGET_SYSLOG)
249✔
1752
                        log_target = LOG_TARGET_JOURNAL;
×
1753
                else if (log_target == LOG_TARGET_SYSLOG_OR_KMSG)
249✔
1754
                        log_target = LOG_TARGET_JOURNAL_OR_KMSG;
×
1755
        }
1756
}
249✔
1757

1758
void log_set_always_reopen_console(bool b) {
13,510✔
1759
        always_reopen_console = b;
13,510✔
1760
}
13,510✔
1761

1762
void log_set_open_when_needed(bool b) {
21,061✔
1763
        open_when_needed = b;
21,061✔
1764
}
21,061✔
1765

1766
void log_set_prohibit_ipc(bool b) {
54,648✔
1767
        prohibit_ipc = b;
54,648✔
1768
}
54,648✔
1769

1770
int log_emergency_level(void) {
×
1771
        /* Returns the log level to use for log_emergency() logging. We use LOG_EMERG only when we are PID 1, as only
1772
         * then the system of the whole system is obviously affected. */
1773

1774
        return getpid_cached() == 1 ? LOG_EMERG : LOG_ERR;
×
1775
}
1776

1777
int log_dup_console(void) {
127✔
1778
        int copy;
127✔
1779

1780
        /* Duplicate the fd we use for fd logging if it's < 3 and use the copy from now on. This call is useful
1781
         * whenever we want to continue logging through the original fd, but want to rearrange stderr. */
1782

1783
        if (console_fd < 0 || console_fd >= 3)
127✔
1784
                return 0;
1785

1786
        copy = fcntl(console_fd, F_DUPFD_CLOEXEC, 3);
1✔
1787
        if (copy < 0)
1✔
1788
                return -errno;
×
1789

1790
        console_fd = copy;
1✔
1791
        return 0;
1✔
1792
}
1793

1794
void log_setup(void) {
90,017✔
1795
        log_set_target(LOG_TARGET_AUTO);
90,017✔
1796
        log_parse_environment();
90,017✔
1797
        (void) log_open();
90,017✔
1798
        if (log_on_console() && show_color < 0)
90,017✔
1799
                log_show_color(true);
32,273✔
1800
}
90,017✔
1801

1802
const char* _log_set_prefix(const char *prefix, bool force) {
4,095,406✔
1803
        const char *old = log_prefix;
4,095,406✔
1804

1805
        if (prefix || force)
4,095,406✔
1806
                log_prefix = prefix;
4,092,772✔
1807

1808
        return old;
4,095,406✔
1809
}
1810

1811
static int saved_log_context_enabled = -1;
1812

1813
bool log_context_enabled(void) {
776,140✔
1814
        int r;
776,140✔
1815

1816
        if (log_get_max_level() == LOG_DEBUG)
776,140✔
1817
                return true;
1818

1819
        if (saved_log_context_enabled >= 0)
102,658✔
1820
                return saved_log_context_enabled;
95,417✔
1821

1822
        r = secure_getenv_bool("SYSTEMD_ENABLE_LOG_CONTEXT");
7,241✔
1823
        if (r < 0 && r != -ENXIO)
7,241✔
1824
                log_debug_errno(r, "Failed to parse $SYSTEMD_ENABLE_LOG_CONTEXT, ignoring: %m");
×
1825

1826
        saved_log_context_enabled = r > 0;
7,241✔
1827

1828
        return saved_log_context_enabled;
7,241✔
1829
}
1830

1831
static LogContext* log_context_attach(LogContext *c) {
708,883✔
1832
        assert(c);
708,883✔
1833

1834
        _log_context_num_fields += strv_length(c->fields);
708,883✔
1835
        _log_context_num_fields += c->n_input_iovec;
708,883✔
1836
        _log_context_num_fields += !!c->key;
708,883✔
1837

1838
        return LIST_PREPEND(ll, _log_context, c);
708,883✔
1839
}
1840

1841
static LogContext* log_context_detach(LogContext *c) {
682,199✔
1842
        if (!c)
682,199✔
1843
                return NULL;
1844

1845
        assert(_log_context_num_fields >= strv_length(c->fields) + c->n_input_iovec +!!c->key);
682,199✔
1846
        _log_context_num_fields -= strv_length(c->fields);
682,199✔
1847
        _log_context_num_fields -= c->n_input_iovec;
682,199✔
1848
        _log_context_num_fields -= !!c->key;
682,199✔
1849

1850
        LIST_REMOVE(ll, _log_context, c);
682,199✔
1851
        return NULL;
682,199✔
1852
}
1853

1854
LogContext* log_context_new(const char *key, const char *value) {
34,180✔
1855
        assert(key);
34,180✔
1856
        assert(endswith(key, "="));
34,180✔
1857
        assert(value);
34,180✔
1858

1859
        LIST_FOREACH(ll, i, _log_context)
51,261✔
1860
                if (i->key == key && i->value == value)
17,090✔
1861
                        return log_context_ref(i);
9✔
1862

1863
        LogContext *c = new(LogContext, 1);
34,171✔
1864
        if (!c)
34,171✔
1865
                return NULL;
1866

1867
        *c = (LogContext) {
34,171✔
1868
                .n_ref = 1,
1869
                .key = (char *) key,
1870
                .value = (char *) value,
1871
        };
1872

1873
        return log_context_attach(c);
34,171✔
1874
}
1875

1876
LogContext* log_context_new_strv(char **fields, bool owned) {
675,627✔
1877
        if (!fields)
675,627✔
1878
                return NULL;
1879

1880
        LIST_FOREACH(ll, i, _log_context)
675,616✔
1881
                if (i->fields == fields) {
1,085✔
1882
                        assert(!owned);
18✔
1883
                        return log_context_ref(i);
18✔
1884
                }
1885

1886
        LogContext *c = new(LogContext, 1);
674,531✔
1887
        if (!c)
674,531✔
1888
                return NULL;
1889

1890
        *c = (LogContext) {
674,531✔
1891
                .n_ref = 1,
1892
                .fields = fields,
1893
                .owned = owned,
1894
        };
1895

1896
        return log_context_attach(c);
674,531✔
1897
}
1898

1899
LogContext* log_context_new_iov(struct iovec *input_iovec, size_t n_input_iovec, bool owned) {
351,058✔
1900
        if (!input_iovec || n_input_iovec == 0)
351,058✔
1901
                return NULL;
1902

1903
        LIST_FOREACH(ll, i, _log_context)
777✔
1904
                if (i->input_iovec == input_iovec && i->n_input_iovec == n_input_iovec) {
596✔
1905
                        assert(!owned);
261✔
1906
                        return log_context_ref(i);
261✔
1907
                }
1908

1909
        LogContext *c = new(LogContext, 1);
181✔
1910
        if (!c)
181✔
1911
                return NULL;
1912

1913
        *c = (LogContext) {
181✔
1914
                .n_ref = 1,
1915
                .input_iovec = input_iovec,
1916
                .n_input_iovec = n_input_iovec,
1917
                .owned = owned,
1918
        };
1919

1920
        return log_context_attach(c);
181✔
1921
}
1922

1923
static LogContext* log_context_free(LogContext *c) {
682,199✔
1924
        if (!c)
682,199✔
1925
                return NULL;
1926

1927
        log_context_detach(c);
682,199✔
1928

1929
        if (c->owned) {
682,199✔
1930
                strv_free(c->fields);
673,445✔
1931
                iovec_array_free(c->input_iovec, c->n_input_iovec);
673,445✔
1932
                free(c->key);
673,445✔
1933
                free(c->value);
673,445✔
1934
        }
1935

1936
        return mfree(c);
682,199✔
1937
}
1938

1939
DEFINE_TRIVIAL_REF_UNREF_FUNC(LogContext, log_context, log_context_free);
682,775✔
1940

1941
LogContext* log_context_new_strv_consume(char **fields) {
673,491✔
1942
        LogContext *c = log_context_new_strv(fields, /*owned=*/ true);
673,491✔
1943
        if (!c)
673,491✔
1944
                strv_free(fields);
×
1945

1946
        return c;
673,491✔
1947
}
1948

1949
LogContext* log_context_new_iov_consume(struct iovec *input_iovec, size_t n_input_iovec) {
9✔
1950
        LogContext *c = log_context_new_iov(input_iovec, n_input_iovec, /*owned=*/ true);
9✔
1951
        if (!c)
9✔
1952
                iovec_array_free(input_iovec, n_input_iovec);
×
1953

1954
        return c;
9✔
1955
}
1956

1957
size_t log_context_num_contexts(void) {
81✔
1958
        size_t n = 0;
81✔
1959

1960
        LIST_FOREACH(ll, c, _log_context)
225✔
1961
                n++;
144✔
1962

1963
        return n;
81✔
1964
}
1965

1966
size_t log_context_num_fields(void) {
81✔
1967
        return _log_context_num_fields;
81✔
1968
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc