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

systemd / systemd / 23966986054

03 Apr 2026 09:22PM UTC coverage: 72.107% (-0.3%) from 72.362%
23966986054

push

github

daandemeyer
fd-util: Add missing assert()

1 of 1 new or added line in 1 file covered. (100.0%)

7891 existing lines in 120 files now uncovered.

318256 of 441368 relevant lines covered (72.11%)

1186882.96 hits per line

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

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

3
#include <fcntl.h>
4
#include <sys/signalfd.h>
5
#include <sys/stat.h>
6
#include <sys/uio.h>
7
#include <threads.h>
8
#include <unistd.h>
9

10
#include "sd-messages.h"
11

12
#include "alloc-util.h"
13
#include "ansi-color.h"
14
#include "argv-util.h"
15
#include "env-util.h"
16
#include "errno-util.h"
17
#include "extract-word.h"
18
#include "fd-util.h"
19
#include "format-util.h"
20
#include "iovec-util.h"
21
#include "list.h"
22
#include "log.h"
23
#include "log-context.h"
24
#include "parse-util.h"
25
#include "proc-cmdline.h"
26
#include "process-util.h"
27
#include "ratelimit.h"
28
#include "signal-util.h"
29
#include "socket-util.h"
30
#include "stdio-util.h"
31
#include "string-table.h"
32
#include "string-util.h"
33
#include "strv.h"
34
#include "syslog-util.h"
35
#include "terminal-util.h"
36
#include "time-util.h"
37
#include "utf8.h"
38

39
#define SNDBUF_SIZE (8*1024*1024)
40
#define IOVEC_MAX 256U
41

42
static log_syntax_callback_t log_syntax_callback = NULL;
43
static void *log_syntax_callback_userdata = NULL;
44

45
static LogTarget log_target = LOG_TARGET_CONSOLE;
46
static int log_max_level = LOG_INFO;
47
static int log_target_max_level[_LOG_TARGET_SINGLE_MAX] = {
48
        [LOG_TARGET_CONSOLE] = INT_MAX,
49
        [LOG_TARGET_KMSG]    = INT_MAX,
50
        [LOG_TARGET_SYSLOG]  = INT_MAX,
51
        [LOG_TARGET_JOURNAL] = INT_MAX,
52
};
53
static int log_facility = LOG_DAEMON;
54
static bool ratelimit_kmsg = true;
55

56
static int console_fd = STDERR_FILENO;
57
static int console_fd_is_tty = -1; /* tri-state: -1 means don't know */
58
static int syslog_fd = -EBADF;
59
static int kmsg_fd = -EBADF;
60
static int journal_fd = -EBADF;
61

62
static bool syslog_is_stream = false;
63

64
static int show_color = -1; /* tristate */
65
static bool show_location = false;
66
static bool show_time = false;
67
static bool show_tid = false;
68

69
static bool upgrade_syslog_to_journal = false;
70
static bool always_reopen_console = false;
71
static bool open_when_needed = false;
72
static bool prohibit_ipc = false;
73

74
static thread_local const char *log_prefix = NULL;
75

76
#if LOG_MESSAGE_VERIFICATION || defined(__COVERITY__)
77
bool _log_message_dummy = false; /* Always false */
78
#endif
79

80
/* An assert to use in logging functions that does not call recursively
81
 * into our logging functions (since that might lead to a loop). */
82
#define assert_raw(expr)                                                \
83
        do {                                                            \
84
                if (_unlikely_(!(expr))) {                              \
85
                        fputs(#expr "\n", stderr);                      \
86
                        abort();                                        \
87
                }                                                       \
88
        } while (false)
89

90
static void log_close_console(void) {
377,269✔
91
        /* See comment in log_close_journal() */
92
        (void) safe_close_above_stdio(TAKE_FD(console_fd));
377,269✔
93
        console_fd_is_tty = -1;
377,269✔
94
}
377,269✔
95

96
static int log_open_console(void) {
72,101✔
97

98
        if (!always_reopen_console) {
72,101✔
99
                console_fd = STDERR_FILENO;
53,489✔
100
                console_fd_is_tty = -1;
53,489✔
101
                return 0;
53,489✔
102
        }
103

104
        if (console_fd < 3) {
18,612✔
105
                int fd;
16,193✔
106

107
                fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
16,193✔
108
                if (fd < 0)
16,193✔
109
                        return fd;
110

111
                console_fd = fd_move_above_stdio(fd);
14,878✔
112
                console_fd_is_tty = true;
14,878✔
113
        }
114

115
        return 0;
116
}
117

118
static void log_close_kmsg(void) {
196,836✔
119
        /* See comment in log_close_journal() */
120
        (void) safe_close(TAKE_FD(kmsg_fd));
196,836✔
121
}
196,836✔
122

123
static int log_open_kmsg(void) {
17,369✔
124

125
        if (kmsg_fd >= 0)
17,369✔
126
                return 0;
127

128
        kmsg_fd = open("/dev/kmsg", O_WRONLY|O_NOCTTY|O_CLOEXEC);
14,678✔
129
        if (kmsg_fd < 0)
14,678✔
130
                return -errno;
6,914✔
131

132
        kmsg_fd = fd_move_above_stdio(kmsg_fd);
7,764✔
133
        return 0;
7,764✔
134
}
135

136
static void log_close_syslog(void) {
449,368✔
137
        /* See comment in log_close_journal() */
138
        (void) safe_close(TAKE_FD(syslog_fd));
449,368✔
139
}
449,368✔
140

141
static int create_log_socket(int type) {
169,384✔
142
        struct timeval tv;
169,384✔
143
        int fd;
169,384✔
144

145
        fd = socket(AF_UNIX, type|SOCK_CLOEXEC, 0);
169,384✔
146
        if (fd < 0)
169,384✔
147
                return -errno;
×
148

149
        fd = fd_move_above_stdio(fd);
169,384✔
150
        (void) fd_inc_sndbuf(fd, SNDBUF_SIZE);
169,384✔
151

152
        /* We need a blocking fd here since we'd otherwise lose messages way too early. However, let's not hang forever
153
         * in the unlikely case of a deadlock. */
154
        if (getpid_cached() == 1)
169,384✔
155
                timeval_store(&tv, 10 * USEC_PER_MSEC);
276✔
156
        else
157
                timeval_store(&tv, 10 * USEC_PER_SEC);
169,108✔
158
        (void) setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
169,384✔
159

160
        return fd;
169,384✔
161
}
162

163
static int log_open_syslog(void) {
2✔
164
        int r;
2✔
165

166
        if (syslog_fd >= 0)
2✔
167
                return 0;
168

169
        syslog_fd = create_log_socket(SOCK_DGRAM);
2✔
170
        if (syslog_fd < 0) {
2✔
171
                r = syslog_fd;
×
172
                goto fail;
×
173
        }
174

175
        r = connect_unix_path(syslog_fd, AT_FDCWD, "/dev/log");
2✔
176
        if (r < 0) {
2✔
177
                safe_close(syslog_fd);
×
178

179
                /* Some legacy syslog systems still use stream sockets. They really shouldn't. But what can
180
                 * we do... */
181
                syslog_fd = create_log_socket(SOCK_STREAM);
×
182
                if (syslog_fd < 0) {
×
183
                        r = syslog_fd;
×
184
                        goto fail;
×
185
                }
186

187
                r = connect_unix_path(syslog_fd, AT_FDCWD, "/dev/log");
×
188
                if (r < 0)
×
189
                        goto fail;
×
190

191
                syslog_is_stream = true;
×
192
        } else
193
                syslog_is_stream = false;
2✔
194

195
        return 0;
196

197
fail:
×
198
        log_close_syslog();
×
199
        return r;
×
200
}
201

202
static void log_close_journal(void) {
278,548✔
203
        /* If the journal FD is bad, safe_close will fail, and will try to log, which will fail, so we'll
204
         * try to close the journal FD, which is bad, so safe_close will fail... Whether we can close it
205
         * or not, invalidate it immediately so that we don't get in a recursive loop until we run out of
206
         * stack. */
207
        (void) safe_close(TAKE_FD(journal_fd));
278,548✔
208
}
278,548✔
209

210
static int log_open_journal(void) {
179,935✔
211
        int r;
179,935✔
212

213
        if (journal_fd >= 0)
179,935✔
214
                return 0;
215

216
        journal_fd = create_log_socket(SOCK_DGRAM);
169,382✔
217
        if (journal_fd < 0) {
169,382✔
218
                r = journal_fd;
×
219
                goto fail;
×
220
        }
221

222
        r = connect_unix_path(journal_fd, AT_FDCWD, "/run/systemd/journal/socket");
169,382✔
223
        if (r < 0)
169,382✔
224
                goto fail;
95✔
225

226
        return 0;
227

228
fail:
95✔
229
        log_close_journal();
95✔
230
        return r;
95✔
231
}
232

233
bool stderr_is_journal(void) {
246,709✔
234
        _cleanup_free_ char *w = NULL;
246,709✔
235
        const char *e;
246,709✔
236
        uint64_t dev, ino;
246,709✔
237
        struct stat st;
246,709✔
238

239
        e = getenv("JOURNAL_STREAM");
246,709✔
240
        if (!e)
246,709✔
241
                return false;
242

243
        if (extract_first_word(&e, &w, ":", EXTRACT_DONT_COALESCE_SEPARATORS) <= 0)
31,172✔
244
                return false;
245
        if (!e)
31,172✔
246
                return false;
247

248
        if (safe_atou64(w, &dev) < 0)
31,172✔
249
                return false;
250
        if (safe_atou64(e, &ino) < 0)
31,172✔
251
                return false;
252

253
        if (fstat(STDERR_FILENO, &st) < 0)
31,172✔
254
                return false;
255

256
        return st.st_dev == dev && st.st_ino == ino;
35,297✔
257
}
258

259
int log_open(void) {
252,534✔
260
        int r;
252,534✔
261

262
        /* Do not call from library code. */
263

264
        /* This function is often called in preparation for logging. Let's make sure we don't clobber errno,
265
         * so that a call to a logging function immediately following a log_open() call can still easily
266
         * reference an error that happened immediately before the log_open() call. */
267
        PROTECT_ERRNO;
252,534✔
268

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

274
        if (log_target == LOG_TARGET_NULL) {
252,534✔
275
                log_close_journal();
1✔
276
                log_close_syslog();
1✔
277
                log_close_console();
1✔
278
                return 0;
279
        }
280

281
        if (getpid_cached() == 1 ||
490,431✔
282
            stderr_is_journal() ||
237,898✔
283
            IN_SET(log_target,
219,364✔
284
                   LOG_TARGET_KMSG,
285
                   LOG_TARGET_JOURNAL,
286
                   LOG_TARGET_JOURNAL_OR_KMSG,
287
                   LOG_TARGET_SYSLOG,
288
                   LOG_TARGET_SYSLOG_OR_KMSG)) {
289

290
                if (!prohibit_ipc) {
189,401✔
291
                        if (IN_SET(log_target,
184,838✔
292
                                   LOG_TARGET_AUTO,
293
                                   LOG_TARGET_JOURNAL_OR_KMSG,
294
                                   LOG_TARGET_JOURNAL)) {
295

296
                                r = log_open_journal();
171,003✔
297
                                if (r >= 0) {
171,003✔
298
                                        log_close_syslog();
170,921✔
299
                                        log_close_console();
170,921✔
300
                                        return r;
301
                                }
302
                        }
303

304
                        if (IN_SET(log_target,
13,917✔
305
                                   LOG_TARGET_SYSLOG_OR_KMSG,
306
                                   LOG_TARGET_SYSLOG)) {
307

308
                                r = log_open_syslog();
2✔
309
                                if (r >= 0) {
2✔
310
                                        log_close_journal();
2✔
311
                                        log_close_console();
2✔
312
                                        return r;
313
                                }
314
                        }
315
                }
316

317
                if (IN_SET(log_target, LOG_TARGET_AUTO,
18,478✔
318
                                       LOG_TARGET_JOURNAL_OR_KMSG,
319
                                       LOG_TARGET_SYSLOG_OR_KMSG,
320
                                       LOG_TARGET_KMSG)) {
321
                        r = log_open_kmsg();
16,422✔
322
                        if (r >= 0) {
16,422✔
323
                                log_close_journal();
9,509✔
324
                                log_close_syslog();
9,509✔
325
                                log_close_console();
9,509✔
326
                                return r;
327
                        }
328
                }
329
        }
330

331
        log_close_journal();
72,101✔
332
        log_close_syslog();
72,101✔
333

334
        return log_open_console();
72,101✔
335
}
336

337
void log_set_target(LogTarget target) {
95,368✔
338
        assert(target >= 0);
95,368✔
339
        assert(target < _LOG_TARGET_MAX);
95,368✔
340

341
        if (upgrade_syslog_to_journal) {
95,368✔
342
                if (target == LOG_TARGET_SYSLOG)
314✔
343
                        target = LOG_TARGET_JOURNAL;
344
                else if (target == LOG_TARGET_SYSLOG_OR_KMSG)
314✔
345
                        target = LOG_TARGET_JOURNAL_OR_KMSG;
×
346
        }
347

348
        log_target = target;
95,368✔
349
}
95,368✔
350

351
void log_set_target_and_open(LogTarget target) {
299✔
352
        log_set_target(target);
299✔
353
        log_open();
299✔
354
}
299✔
355

356
void log_close(void) {
196,836✔
357
        /* Do not call from library code. */
358

359
        log_close_journal();
196,836✔
360
        log_close_syslog();
196,836✔
361
        log_close_kmsg();
196,836✔
362
        log_close_console();
196,836✔
363
}
196,836✔
364

365
void log_forget_fds(void) {
10,545✔
366
        /* Do not call from library code. */
367

368
        console_fd = kmsg_fd = syslog_fd = journal_fd = -EBADF;
10,545✔
369
        console_fd_is_tty = -1;
10,545✔
370
}
10,545✔
371

372
int log_set_max_level(int level) {
807,219✔
373
        assert(level == LOG_NULL || log_level_is_valid(level));
807,219✔
374

375
        int old = log_max_level;
807,219✔
376
        log_max_level = level;
807,219✔
377

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

386
        /* Ensure that our own LOG_NULL define maps sanely to the log mask */
387
        assert_cc(LOG_UPTO(LOG_NULL) == 0);
807,219✔
388

389
        return old;
807,219✔
390
}
391

392
void log_set_facility(int facility) {
170✔
393
        log_facility = facility;
170✔
394
}
170✔
395

396
static bool check_console_fd_is_tty(void) {
201,696✔
397
        if (console_fd < 0)
201,696✔
398
                return false;
399

400
        if (console_fd_is_tty < 0)
201,696✔
401
                console_fd_is_tty = isatty_safe(console_fd);
12,376✔
402

403
        return console_fd_is_tty;
201,696✔
404
}
405

406
static int write_to_console(
308,429✔
407
                int level,
408
                int error,
409
                const char *file,
410
                int line,
411
                const char *func,
412
                const char *buffer) {
413

414
        static int dumb = -1;
308,429✔
415

416
        char location[256],
308,429✔
417
             header_time[FORMAT_TIMESTAMP_MAX],
418
             prefix[1 + DECIMAL_STR_MAX(int) + 2],
419
             tid_string[3 + DECIMAL_STR_MAX(pid_t) + 1];
420
        struct iovec iovec[11];
308,429✔
421
        const char *on = NULL, *off = NULL;
308,429✔
422
        size_t n = 0;
308,429✔
423

424
        if (console_fd < 0)
308,429✔
425
                return 0;
308,429✔
426

427
        if (dumb < 0)
307,780✔
428
                dumb = getenv_terminal_is_dumb();
13,143✔
429

430
        if (LOG_PRI(level) > log_target_max_level[LOG_TARGET_CONSOLE])
307,780✔
431
                return 0;
432

433
        if (log_target == LOG_TARGET_CONSOLE_PREFIXED) {
201,696✔
434
                xsprintf(prefix, "<%i>", level);
385✔
435
                iovec[n++] = IOVEC_MAKE_STRING(prefix);
385✔
436
        }
437

438
        if (show_time &&
201,696✔
439
            format_timestamp(header_time, sizeof(header_time), now(CLOCK_REALTIME))) {
×
440
                iovec[n++] = IOVEC_MAKE_STRING(header_time);
×
441
                iovec[n++] = IOVEC_MAKE_STRING(" ");
×
442
        }
443

444
        if (show_tid) {
201,696✔
445
                xsprintf(tid_string, "(" PID_FMT ") ", gettid());
×
446
                iovec[n++] = IOVEC_MAKE_STRING(tid_string);
×
447
        }
448

449
        if (log_get_show_color())
201,696✔
450
                get_log_colors(LOG_PRI(level), &on, &off, NULL);
192,617✔
451

452
        if (show_location) {
201,696✔
453
                const char *lon = "", *loff = "";
×
454
                if (log_get_show_color()) {
×
455
                        lon = ansi_highlight_yellow4();
×
456
                        loff = ansi_normal();
×
457
                }
458

459
                (void) snprintf(location, sizeof location, "%s%s:%i%s: ", lon, file, line, loff);
×
460
                iovec[n++] = IOVEC_MAKE_STRING(location);
×
461
        }
462

463
        if (on)
201,696✔
464
                iovec[n++] = IOVEC_MAKE_STRING(on);
178,304✔
465
        if (log_prefix) {
201,696✔
466
                iovec[n++] = IOVEC_MAKE_STRING(log_prefix);
8,558✔
467
                iovec[n++] = IOVEC_MAKE_STRING(": ");
8,558✔
468
        }
469
        iovec[n++] = IOVEC_MAKE_STRING(buffer);
201,696✔
470
        if (off)
201,696✔
471
                iovec[n++] = IOVEC_MAKE_STRING(off);
178,304✔
472

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

480
        if (writev(console_fd, iovec, n) < 0) {
201,696✔
481

482
                if (errno == EIO && getpid_cached() == 1) {
×
483

484
                        /* If somebody tried to kick us from our console tty (via vhangup() or suchlike), try
485
                         * to reconnect. */
486

487
                        log_close_console();
×
488
                        (void) log_open_console();
×
489
                        if (console_fd < 0)
×
490
                                return 0;
491

492
                        if (writev(console_fd, iovec, n) < 0)
×
493
                                return -errno;
×
494
                } else
495
                        return -errno;
×
496
        }
497

498
        return 1;
499
}
500

501
static int write_to_syslog(
180✔
502
                int level,
503
                int error,
504
                const char *file,
505
                int line,
506
                const char *func,
507
                const char *buffer) {
508

509
        char header_priority[2 + DECIMAL_STR_MAX(int) + 1],
180✔
510
             header_time[64],
511
             header_pid[4 + DECIMAL_STR_MAX(pid_t) + 1];
512
        struct tm tm;
180✔
513
        int r;
180✔
514

515
        if (syslog_fd < 0)
180✔
516
                return 0;
180✔
517

518
        if (LOG_PRI(level) > log_target_max_level[LOG_TARGET_SYSLOG])
180✔
519
                return 0;
520

521
        xsprintf(header_priority, "<%i>", level);
180✔
522

523
        r = localtime_or_gmtime_usec(now(CLOCK_REALTIME), /* utc= */ false, &tm);
180✔
524
        if (r < 0)
180✔
525
                return r;
526

527
        if (strftime(header_time, sizeof(header_time), "%h %e %T ", &tm) <= 0)
180✔
528
                return -EINVAL;
529

530
        xsprintf(header_pid, "["PID_FMT"]: ", getpid_cached());
180✔
531

532
        struct iovec iovec[] = {
1,440✔
533
                IOVEC_MAKE_STRING(header_priority),
180✔
534
                IOVEC_MAKE_STRING(header_time),
180✔
535
                IOVEC_MAKE_STRING(program_invocation_short_name),
180✔
536
                IOVEC_MAKE_STRING(header_pid),
180✔
537
                IOVEC_MAKE_STRING(strempty(log_prefix)),
292✔
538
                IOVEC_MAKE_STRING(log_prefix ? ": " : ""),
292✔
539
                IOVEC_MAKE_STRING(buffer),
180✔
540
        };
541
        const struct msghdr msghdr = {
180✔
542
                .msg_iov = iovec,
543
                .msg_iovlen = ELEMENTSOF(iovec),
544
        };
545

546
        /* When using syslog via SOCK_STREAM separate the messages by NUL chars */
547
        if (syslog_is_stream)
180✔
548
                iovec[ELEMENTSOF(iovec) - 1].iov_len++;
×
549

550
        for (;;) {
180✔
551
                ssize_t n;
180✔
552

553
                n = sendmsg(syslog_fd, &msghdr, MSG_NOSIGNAL);
180✔
554
                if (n < 0)
180✔
555
                        return -errno;
×
556

557
                if (!syslog_is_stream)
180✔
558
                        break;
559

560
                if (iovec_increment(iovec, ELEMENTSOF(iovec), n))
×
561
                        break;
562
        }
563

564
        return 1;
565
}
566

567
static int write_to_kmsg(
263,481✔
568
                int level,
569
                int error,
570
                const char *file,
571
                int line,
572
                const char *func,
573
                const char *buffer) {
574

575
        /* Set a ratelimit on the amount of messages logged to /dev/kmsg. This is mostly supposed to be a
576
         * safety catch for the case where start indiscriminately logging in a loop. It will not catch cases
577
         * where we log excessively, but not in a tight loop.
578
         *
579
         * Note that this ratelimit is per-emitter, so we might still overwhelm /dev/kmsg with multiple
580
         * loggers.
581
         */
582
        static thread_local RateLimit ratelimit = { 5 * USEC_PER_SEC, 200 };
263,481✔
583

584
        char header_priority[2 + DECIMAL_STR_MAX(int) + 1],
263,481✔
585
             header_pid[4 + DECIMAL_STR_MAX(pid_t) + 1];
586

587
        if (kmsg_fd < 0)
263,481✔
588
                return 0;
263,481✔
589

590
        if (LOG_PRI(level) > log_target_max_level[LOG_TARGET_KMSG])
45,601✔
591
                return 0;
592

593
        if (ratelimit_kmsg && !ratelimit_below(&ratelimit)) {
45,601✔
594
                if (ratelimit_num_dropped(&ratelimit) > 1)
×
595
                        return 0;
596

597
                buffer = "Too many messages being logged to kmsg, ignoring";
598
        }
599

600
        xsprintf(header_priority, "<%i>", level);
45,601✔
601
        xsprintf(header_pid, "["PID_FMT"]: ", getpid_cached());
45,601✔
602

603
        const struct iovec iovec[] = {
364,808✔
604
                IOVEC_MAKE_STRING(header_priority),
45,601✔
605
                IOVEC_MAKE_STRING(program_invocation_short_name),
45,601✔
606
                IOVEC_MAKE_STRING(header_pid),
45,601✔
607
                IOVEC_MAKE_STRING(strempty(log_prefix)),
69,492✔
608
                IOVEC_MAKE_STRING(log_prefix ? ": " : ""),
69,492✔
609
                IOVEC_MAKE_STRING(buffer),
45,601✔
610
                IOVEC_MAKE_STRING("\n"),
45,601✔
611
        };
612

613
        if (writev(kmsg_fd, iovec, ELEMENTSOF(iovec)) < 0)
45,601✔
614
                return -errno;
×
615

616
        return 1;
617
}
618

619
static int log_do_header(
5,921,388✔
620
                char *header,
621
                size_t size,
622
                int level,
623
                int error,
624
                const char *file, int line, const char *func,
625
                const char *object_field, const char *object,
626
                const char *extra_field, const char *extra) {
627
        int r;
5,921,388✔
628

629
        error = IS_SYNTHETIC_ERRNO(error) ? 0 : ERRNO_VALUE(error);
5,921,388✔
630

631
        r = snprintf(header, size,
5,921,388✔
632
                     "PRIORITY=%i\n"
633
                     "SYSLOG_FACILITY=%i\n"
634
                     "TID=" PID_FMT "\n"
635
                     "%s%.256s%s"        /* CODE_FILE */
636
                     "%s%.*i%s"          /* CODE_LINE */
637
                     "%s%.256s%s"        /* CODE_FUNC */
638
                     "%s%.*i%s"          /* ERRNO */
639
                     "%s%.256s%s"        /* object */
640
                     "%s%.256s%s"        /* extra */
641
                     "SYSLOG_IDENTIFIER=%.256s\n",
642
                     LOG_PRI(level),
643
                     LOG_FAC(level),
5,921,388✔
644
                     gettid(),
645
                     isempty(file) ? "" : "CODE_FILE=",
5,921,388✔
646
                     isempty(file) ? "" : file,
5,921,388✔
647
                     isempty(file) ? "" : "\n",
5,921,388✔
648
                     line ? "CODE_LINE=" : "",
649
                     line ? 1 : 0, line, /* %.0d means no output too, special case for 0 */
650
                     line ? "\n" : "",
651
                     isempty(func) ? "" : "CODE_FUNC=",
5,921,388✔
652
                     isempty(func) ? "" : func,
5,921,388✔
653
                     isempty(func) ? "" : "\n",
5,921,388✔
654
                     error ? "ERRNO=" : "",
655
                     error ? 1 : 0, error,
656
                     error ? "\n" : "",
657
                     isempty(object) ? "" : ASSERT_PTR(object_field),
5,921,388✔
658
                     isempty(object) ? "" : object,
5,921,388✔
659
                     isempty(object) ? "" : "\n",
5,921,388✔
660
                     isempty(extra) ? "" : ASSERT_PTR(extra_field),
5,921,388✔
661
                     isempty(extra) ? "" : extra,
5,921,388✔
662
                     isempty(extra) ? "" : "\n",
5,921,388✔
663
                     program_invocation_short_name);
664
        assert_raw((size_t) r < size);
5,921,388✔
665

666
        return 0;
5,921,388✔
667
}
668

669
static void log_do_context(struct iovec *iovec, size_t iovec_len, size_t *n) {
5,921,388✔
670
        assert(iovec);
5,921,388✔
671
        assert(n);
5,921,388✔
672

673
        LIST_FOREACH(ll, c, log_context_head()) {
8,517,051✔
674
                STRV_FOREACH(s, c->fields) {
24,094,814✔
675
                        if (*n + 2 >= iovec_len)
21,364,849✔
676
                                return;
×
677

678
                        iovec[(*n)++] = IOVEC_MAKE_STRING(*s);
21,364,849✔
679
                        iovec[(*n)++] = IOVEC_MAKE_STRING("\n");
21,364,849✔
680
                }
681

682
                for (size_t i = 0; i < c->n_input_iovec; i++) {
2,748,617✔
683
                        if (*n + 2 >= iovec_len)
18,682✔
684
                                return;
30✔
685

686
                        iovec[(*n)++] = c->input_iovec[i];
18,652✔
687
                        iovec[(*n)++] = IOVEC_MAKE_STRING("\n");
18,652✔
688
                }
689

690
                if (c->key && c->value) {
2,729,935✔
691
                        if (*n + 3 >= iovec_len)
301,018✔
692
                                return;
134,272✔
693

694
                        iovec[(*n)++] = IOVEC_MAKE_STRING(c->key);
166,746✔
695
                        iovec[(*n)++] = IOVEC_MAKE_STRING(c->value);
166,746✔
696
                        iovec[(*n)++] = IOVEC_MAKE_STRING("\n");
166,746✔
697
                }
698
        }
699
}
700

701
static int write_to_journal(
6,160,454✔
702
                int level,
703
                int error,
704
                const char *file,
705
                int line,
706
                const char *func,
707
                const char *object_field,
708
                const char *object,
709
                const char *extra_field,
710
                const char *extra,
711
                const char *buffer) {
712

713
        char header[LINE_MAX];
6,160,454✔
714
        size_t n = 0, iovec_len;
6,160,454✔
715
        struct iovec *iovec;
6,160,454✔
716

717
        if (journal_fd < 0)
6,160,454✔
718
                return 0;
6,160,454✔
719

720
        if (LOG_PRI(level) > log_target_max_level[LOG_TARGET_JOURNAL])
5,860,080✔
721
                return 0;
722

723
        iovec_len = MIN(6 + log_context_num_fields() * 3, IOVEC_MAX);
5,860,080✔
724
        iovec = newa(struct iovec, iovec_len);
5,860,080✔
725

726
        log_do_header(header, sizeof(header), level, error, file, line, func, object_field, object, extra_field, extra);
5,860,080✔
727

728
        iovec[n++] = IOVEC_MAKE_STRING(header);
5,860,080✔
729
        iovec[n++] = IOVEC_MAKE_STRING("MESSAGE=");
5,860,080✔
730
        if (log_prefix) {
5,860,080✔
731
                iovec[n++] = IOVEC_MAKE_STRING(log_prefix);
1,943,890✔
732
                iovec[n++] = IOVEC_MAKE_STRING(": ");
1,943,890✔
733
        }
734
        iovec[n++] = IOVEC_MAKE_STRING(buffer);
5,860,080✔
735
        iovec[n++] = IOVEC_MAKE_STRING("\n");
5,860,080✔
736

737
        log_do_context(iovec, iovec_len, &n);
5,860,080✔
738

739
        const struct msghdr msghdr = {
5,860,080✔
740
                .msg_iov = iovec,
741
                .msg_iovlen = n,
742
        };
743

744
        if (sendmsg(journal_fd, &msghdr, MSG_NOSIGNAL) < 0)
5,860,080✔
745
                return -errno;
1,153✔
746

747
        return 1;
748
}
749

750
int log_dispatch_internal(
6,200,086✔
751
                int level,
752
                int error,
753
                const char *file,
754
                int line,
755
                const char *func,
756
                const char *object_field,
757
                const char *object,
758
                const char *extra_field,
759
                const char *extra,
760
                char *buffer) {
761

762
        assert_raw(buffer);
6,200,086✔
763

764
        if (log_target == LOG_TARGET_NULL)
6,200,086✔
765
                return -ERRNO_VALUE(error);
37✔
766

767
        /* Patch in LOG_DAEMON facility if necessary */
768
        if (LOG_FAC(level) == 0)
6,200,049✔
769
                level |= log_facility;
6,189,891✔
770

771
        if (open_when_needed)
6,200,049✔
772
                (void) log_open();
146,157✔
773

774
        do {
6,250,670✔
775
                char *e;
6,250,670✔
776
                int k = 0;
6,250,670✔
777

778
                buffer += strspn(buffer, NEWLINE);
6,250,670✔
779

780
                if (buffer[0] == 0)
6,250,670✔
781
                        break;
782

783
                if ((e = strpbrk(buffer, NEWLINE)))
6,213,137✔
784
                        *(e++) = 0;
50,621✔
785

786
                if (IN_SET(log_target, LOG_TARGET_AUTO,
6,213,137✔
787
                                       LOG_TARGET_JOURNAL_OR_KMSG,
788
                                       LOG_TARGET_JOURNAL)) {
789

790
                        k = write_to_journal(level, error, file, line, func, object_field, object, extra_field, extra, buffer);
6,160,454✔
791
                        if (k < 0 && k != -EAGAIN)
6,160,454✔
792
                                log_close_journal();
4✔
793
                }
794

795
                if (IN_SET(log_target, LOG_TARGET_SYSLOG_OR_KMSG,
6,213,137✔
796
                                       LOG_TARGET_SYSLOG)) {
797

798
                        k = write_to_syslog(level, error, file, line, func, buffer);
180✔
799
                        if (k < 0 && k != -EAGAIN)
180✔
800
                                log_close_syslog();
×
801
                }
802

803
                if (k <= 0 &&
6,213,137✔
804
                    IN_SET(log_target, LOG_TARGET_AUTO,
354,030✔
805
                                       LOG_TARGET_SYSLOG_OR_KMSG,
806
                                       LOG_TARGET_JOURNAL_OR_KMSG,
807
                                       LOG_TARGET_KMSG)) {
808

809
                        if (k < 0)
263,481✔
810
                                log_open_kmsg();
947✔
811

812
                        k = write_to_kmsg(level, error, file, line, func, buffer);
263,481✔
813
                        if (k < 0) {
263,481✔
814
                                log_close_kmsg();
×
815
                                (void) log_open_console();
×
816
                        }
817
                }
818

819
                if (k <= 0)
354,030✔
820
                        (void) write_to_console(level, error, file, line, func, buffer);
308,429✔
821

822
                buffer = e;
6,213,137✔
823
        } while (buffer);
6,213,137✔
824

825
        if (open_when_needed)
6,200,049✔
826
                log_close();
146,157✔
827

828
        return -ERRNO_VALUE(error);
6,200,049✔
829
}
830

831
int log_dump_internal(
9✔
832
                int level,
833
                int error,
834
                const char *file,
835
                int line,
836
                const char *func,
837
                char *buffer) {
838

839
        PROTECT_ERRNO;
9✔
840

841
        /* This modifies the buffer... */
842

843
        if (_likely_(LOG_PRI(level) > log_max_level))
9✔
844
                return -ERRNO_VALUE(error);
×
845

846
        return log_dispatch_internal(level, error, file, line, func, NULL, NULL, NULL, NULL, buffer);
9✔
847
}
848

849
int log_internalv(
4,335,444✔
850
                int level,
851
                int error,
852
                const char *file,
853
                int line,
854
                const char *func,
855
                const char *format,
856
                va_list ap) {
857

858
        if (_likely_(LOG_PRI(level) > log_max_level))
4,335,444✔
859
                return -ERRNO_VALUE(error);
4,335,444✔
860

861
        /* Make sure that %m maps to the specified error (or "Success"). */
862
        char buffer[LINE_MAX];
4,335,444✔
863
        LOCAL_ERRNO(ERRNO_VALUE(error));
4,335,444✔
864

865
        (void) vsnprintf(buffer, sizeof buffer, format, ap);
4,335,444✔
866

867
        return log_dispatch_internal(level, error, file, line, func, NULL, NULL, NULL, NULL, buffer);
4,335,444✔
868
}
869

870
int log_internal(
4,333,755✔
871
                int level,
872
                int error,
873
                const char *file,
874
                int line,
875
                const char *func,
876
                const char *format, ...) {
877

878
        va_list ap;
4,333,755✔
879
        int r;
4,333,755✔
880

881
        va_start(ap, format);
4,333,755✔
882
        r = log_internalv(level, error, file, line, func, format, ap);
4,333,755✔
883
        va_end(ap);
4,333,755✔
884

885
        return r;
4,333,755✔
886
}
887

888
int log_object_internalv(
1,905,230✔
889
                int level,
890
                int error,
891
                const char *file,
892
                int line,
893
                const char *func,
894
                const char *object_field,
895
                const char *object,
896
                const char *extra_field,
897
                const char *extra,
898
                const char *format,
899
                va_list ap) {
900

901
        char *buffer, *b;
1,905,230✔
902

903
        if (_likely_(LOG_PRI(level) > log_max_level))
1,905,230✔
904
                return -ERRNO_VALUE(error);
1,905,230✔
905

906
        /* Make sure that %m maps to the specified error (or "Success"). */
907
        LOCAL_ERRNO(ERRNO_VALUE(error));
×
908

909
        LOG_SET_PREFIX(object);
3,709,356✔
910

911
        b = buffer = newa(char, LINE_MAX);
1,854,678✔
912
        (void) vsnprintf(b, LINE_MAX, format, ap);
1,854,678✔
913

914
        return log_dispatch_internal(level, error, file, line, func,
1,854,678✔
915
                                     object_field, object, extra_field, extra, buffer);
916
}
917

918
int log_object_internal(
1,900,214✔
919
                int level,
920
                int error,
921
                const char *file,
922
                int line,
923
                const char *func,
924
                const char *object_field,
925
                const char *object,
926
                const char *extra_field,
927
                const char *extra,
928
                const char *format, ...) {
929

930
        va_list ap;
1,900,214✔
931
        int r;
1,900,214✔
932

933
        va_start(ap, format);
1,900,214✔
934
        r = log_object_internalv(level, error, file, line, func, object_field, object, extra_field, extra, format, ap);
1,900,214✔
935
        va_end(ap);
1,900,214✔
936

937
        return r;
1,900,214✔
938
}
939

940
int log_oom_internal(int level, const char *file, int line, const char *func) {
×
941
        return log_internal(level, ENOMEM, file, line, func, "Out of memory.");
×
942
}
943

944
int log_format_iovec(
59,209✔
945
                struct iovec *iovec,
946
                size_t iovec_len,
947
                size_t *n,
948
                bool newline_separator,
949
                int error,
950
                const char *format,
951
                va_list ap) {
952

953
        assert(iovec);
59,209✔
954
        assert(n);
59,209✔
955

956
        while (format && *n + 1 < iovec_len) {
344,540✔
957
                va_list aq;
285,331✔
958
                char *m;
285,331✔
959
                int r;
285,331✔
960

961
                /* We need to copy the va_list structure,
962
                 * since vasprintf() leaves it afterwards at
963
                 * an undefined location */
964

965
                errno = ERRNO_VALUE(error);
285,331✔
966

967
                va_copy(aq, ap);
285,331✔
968
                r = vasprintf(&m, format, aq);
285,331✔
969
                va_end(aq);
285,331✔
970
                if (r < 0)
285,331✔
UNCOV
971
                        return -EINVAL;
×
972

973
                /* Now, jump enough ahead, so that we point to
974
                 * the next format string */
975
                VA_FORMAT_ADVANCE(format, ap);
912,679✔
976

977
                iovec[(*n)++] = IOVEC_MAKE_STRING(m);
285,331✔
978
                if (newline_separator)
285,331✔
979
                        iovec[(*n)++] = IOVEC_MAKE_STRING("\n");
283,656✔
980

981
                format = va_arg(ap, char *);
285,331✔
982
        }
983
        return 0;
984
}
985

986
int log_struct_internal(
68,628✔
987
                int level,
988
                int error,
989
                const char *file,
990
                int line,
991
                const char *func,
992
                const char *format, ...) {
993

994
        char buf[LINE_MAX];
68,628✔
995
        bool found = false;
68,628✔
996
        PROTECT_ERRNO;
68,628✔
997
        va_list ap;
68,628✔
998

999
        if (_likely_(LOG_PRI(level) > log_max_level) ||
68,628✔
1000
            log_target == LOG_TARGET_NULL)
68,628✔
1001
                return -ERRNO_VALUE(error);
50✔
1002

1003
        if (LOG_FAC(level) == 0)
68,578✔
1004
                level |= log_facility;
68,578✔
1005

1006
        if (IN_SET(log_target,
68,578✔
1007
                   LOG_TARGET_AUTO,
1008
                   LOG_TARGET_JOURNAL_OR_KMSG,
1009
                   LOG_TARGET_JOURNAL)) {
1010

1011
                if (open_when_needed)
66,710✔
1012
                        log_open_journal();
8,932✔
1013

1014
                if (journal_fd >= 0) {
66,710✔
1015
                        char header[LINE_MAX];
59,029✔
1016
                        struct iovec *iovec;
59,029✔
1017
                        size_t n = 0, m, iovec_len;
59,029✔
1018
                        int r;
59,029✔
1019
                        bool fallback = false;
59,029✔
1020

1021
                        iovec_len = MIN(17 + log_context_num_fields() * 3, IOVEC_MAX);
59,029✔
1022
                        iovec = newa(struct iovec, iovec_len);
59,029✔
1023

1024
                        /* If the journal is available do structured logging.
1025
                         * Do not report the errno if it is synthetic. */
1026
                        log_do_header(header, sizeof(header), level, error, file, line, func, NULL, NULL, NULL, NULL);
59,029✔
1027
                        iovec[n++] = IOVEC_MAKE_STRING(header);
59,029✔
1028

1029
                        va_start(ap, format);
59,029✔
1030
                        DISABLE_WARNING_FORMAT_NONLITERAL;
59,029✔
1031
                        r = log_format_iovec(iovec, iovec_len, &n, true, error, format, ap);
59,029✔
1032
                        REENABLE_WARNING;
59,029✔
1033
                        m = n;
59,029✔
1034
                        if (r < 0)
59,029✔
1035
                                fallback = true;
1036
                        else {
1037
                                log_do_context(iovec, iovec_len, &n);
59,029✔
1038

1039
                                const struct msghdr msghdr = {
59,029✔
1040
                                        .msg_iov = iovec,
1041
                                        .msg_iovlen = n,
1042
                                };
1043

1044
                                (void) sendmsg(journal_fd, &msghdr, MSG_NOSIGNAL);
59,029✔
1045
                        }
1046

1047
                        va_end(ap);
59,029✔
1048
                        for (size_t i = 1; i < m; i += 2)
342,680✔
1049
                                free(iovec[i].iov_base);
283,651✔
1050

1051
                        if (!fallback) {
59,029✔
1052
                                if (open_when_needed)
59,029✔
1053
                                        log_close();
8,919✔
1054

1055
                                return -ERRNO_VALUE(error);
59,029✔
1056
                        }
1057
                }
1058
        }
1059

1060
        /* Fallback if journal logging is not available or didn't work. */
1061

1062
        va_start(ap, format);
9,549✔
1063
        while (format) {
29,033✔
1064
                va_list aq;
29,033✔
1065

1066
                errno = ERRNO_VALUE(error);
29,033✔
1067

1068
                va_copy(aq, ap);
29,033✔
1069
                DISABLE_WARNING_FORMAT_NONLITERAL;
29,033✔
1070
                (void) vsnprintf(buf, sizeof buf, format, aq);
29,033✔
1071
                REENABLE_WARNING;
29,033✔
1072
                va_end(aq);
29,033✔
1073

1074
                if (startswith(buf, "MESSAGE=")) {
29,033✔
1075
                        found = true;
9,549✔
1076
                        break;
9,549✔
1077
                }
1078

1079
                VA_FORMAT_ADVANCE(format, ap);
52,464✔
1080

1081
                format = va_arg(ap, char *);
19,484✔
1082
        }
1083
        va_end(ap);
9,549✔
1084

1085
        if (!found) {
9,549✔
1086
                if (open_when_needed)
×
UNCOV
1087
                        log_close();
×
1088

UNCOV
1089
                return -ERRNO_VALUE(error);
×
1090
        }
1091

1092
        return log_dispatch_internal(level, error, file, line, func, NULL, NULL, NULL, NULL, buf + 8);
9,549✔
1093
}
1094

1095
int log_struct_iovec_internal(
2,304✔
1096
                int level,
1097
                int error,
1098
                const char *file,
1099
                int line,
1100
                const char *func,
1101
                const struct iovec input_iovec[],
1102
                size_t n_input_iovec) {
1103

1104
        PROTECT_ERRNO;
2,304✔
1105

1106
        if (_likely_(LOG_PRI(level) > log_max_level) ||
2,304✔
1107
            log_target == LOG_TARGET_NULL)
2,304✔
UNCOV
1108
                return -ERRNO_VALUE(error);
×
1109

1110
        if (LOG_FAC(level) == 0)
2,304✔
1111
                level |= log_facility;
2,304✔
1112

1113
        if (IN_SET(log_target, LOG_TARGET_AUTO,
2,304✔
1114
                               LOG_TARGET_JOURNAL_OR_KMSG,
1115
                               LOG_TARGET_JOURNAL) &&
2,304✔
1116
            journal_fd >= 0) {
2,304✔
1117

1118
                char header[LINE_MAX];
2,279✔
1119
                struct iovec *iovec;
2,279✔
1120
                size_t n = 0, iovec_len;
2,279✔
1121

1122
                iovec_len = MIN(1 + n_input_iovec * 2 + log_context_num_fields() * 3, IOVEC_MAX);
2,279✔
1123
                iovec = newa(struct iovec, iovec_len);
2,279✔
1124

1125
                log_do_header(header, sizeof(header), level, error, file, line, func, NULL, NULL, NULL, NULL);
2,279✔
1126

1127
                iovec[n++] = IOVEC_MAKE_STRING(header);
2,279✔
1128
                for (size_t i = 0; i < n_input_iovec; i++) {
18,182✔
1129
                        iovec[n++] = input_iovec[i];
15,903✔
1130
                        iovec[n++] = IOVEC_MAKE_STRING("\n");
15,903✔
1131
                }
1132

1133
                log_do_context(iovec, iovec_len, &n);
2,279✔
1134

1135
                const struct msghdr msghdr = {
2,279✔
1136
                        .msg_iov = iovec,
1137
                        .msg_iovlen = n,
1138
                };
1139

1140
                if (sendmsg(journal_fd, &msghdr, MSG_NOSIGNAL) >= 0)
2,279✔
1141
                        return -ERRNO_VALUE(error);
2,276✔
1142
        }
1143

1144
        for (size_t i = 0; i < n_input_iovec; i++)
112✔
1145
                if (memory_startswith(input_iovec[i].iov_base, input_iovec[i].iov_len, "MESSAGE=")) {
112✔
1146
                        char *m;
28✔
1147

1148
                        m = strndupa_safe((char*) input_iovec[i].iov_base + STRLEN("MESSAGE="),
28✔
1149
                                          input_iovec[i].iov_len - STRLEN("MESSAGE="));
1150

1151
                        return log_dispatch_internal(level, error, file, line, func, NULL, NULL, NULL, NULL, m);
28✔
1152
                }
1153

1154
        /* Couldn't find MESSAGE=. */
UNCOV
1155
        return -ERRNO_VALUE(error);
×
1156
}
1157

1158
int log_set_target_from_string(const char *e) {
11,196✔
1159
        LogTarget t;
11,196✔
1160

1161
        t = log_target_from_string(e);
11,196✔
1162
        if (t < 0)
11,196✔
1163
                return t;
1164

1165
        log_set_target(t);
11,194✔
1166
        return 0;
11,194✔
1167
}
1168

1169
int log_set_max_level_from_string(const char *e) {
27,365✔
1170
        int r;
72,819✔
1171

1172
        for (;;) {
72,819✔
1173
                _cleanup_free_ char *word = NULL, *prefix = NULL;
72,819✔
1174
                LogTarget target;
72,819✔
1175
                const char *colon;
72,819✔
1176

1177
                r = extract_first_word(&e, &word, ",", 0);
72,819✔
1178
                if (r < 0)
72,819✔
1179
                        return r;
1180
                if (r == 0)
72,819✔
1181
                        break;
1182

1183
                colon = strchr(word, ':');
45,454✔
1184
                if (!colon) {
45,454✔
1185
                        r = log_level_from_string(word);
27,363✔
1186
                        if (r < 0)
27,363✔
1187
                                return r;
1188

1189
                        log_set_max_level(r);
27,363✔
1190
                        continue;
27,363✔
1191
                }
1192

1193
                prefix = strndup(word, colon - word);
18,091✔
1194
                if (!prefix)
18,091✔
1195
                        return -ENOMEM;
1196

1197
                target = log_target_from_string(prefix);
18,091✔
1198
                if (target < 0)
18,091✔
1199
                        return target;
1200

1201
                if (target >= _LOG_TARGET_SINGLE_MAX)
18,091✔
1202
                        return -EINVAL;
1203

1204
                r = log_level_from_string(colon + 1);
18,091✔
1205
                if (r < 0)
18,091✔
1206
                        return r;
1207

1208
                log_target_max_level[target] = r;
18,091✔
1209
        }
1210

1211
        return 0;
27,365✔
1212
}
1213

1214
int log_max_levels_to_string(int level, char **ret) {
2,700✔
1215
        _cleanup_free_ char *s = NULL;
2,700✔
1216
        int r;
2,700✔
1217

1218
        assert(ret);
2,700✔
1219

1220
        r = log_level_to_string_alloc(level, &s);
2,700✔
1221
        if (r < 0)
2,700✔
1222
                return r;
1223

1224
        for (LogTarget target = 0; target < _LOG_TARGET_SINGLE_MAX; target++) {
13,500✔
1225
                _cleanup_free_ char *l = NULL;
2,700✔
1226

1227
                if (log_target_max_level[target] == INT_MAX)
10,800✔
1228
                        continue;
8,100✔
1229

1230
                r = log_level_to_string_alloc(log_target_max_level[target], &l);
2,700✔
1231
                if (r < 0)
2,700✔
1232
                        return r;
1233

1234
                r = strextendf_with_separator(&s, ",", "%s:%s", log_target_to_string(target), l);
2,700✔
1235
                if (r < 0)
2,700✔
1236
                        return r;
1237
        }
1238

1239
        *ret = TAKE_PTR(s);
2,700✔
1240
        return 0;
2,700✔
1241
}
1242

1243
static int log_set_ratelimit_kmsg_from_string(const char *e) {
7,642✔
1244
        int r;
7,642✔
1245

1246
        r = parse_boolean(e);
7,642✔
1247
        if (r < 0)
7,642✔
1248
                return r;
1249

1250
        ratelimit_kmsg = r;
7,642✔
1251
        return 0;
7,642✔
1252
}
1253

1254
static int parse_proc_cmdline_item(const char *key, const char *value, void *data) {
276,868✔
1255

1256
        /*
1257
         * The systemd.log_xyz= settings are parsed by all tools, and
1258
         * so is "debug".
1259
         *
1260
         * However, "quiet" is only parsed by PID 1, and only turns of
1261
         * status output to /dev/console, but does not alter the log
1262
         * level.
1263
         */
1264

1265
        if (streq(key, "debug") && !value)
276,868✔
UNCOV
1266
                log_set_max_level(LOG_DEBUG);
×
1267

1268
        else if (proc_cmdline_key_streq(key, "systemd.log_target")) {
276,868✔
1269

1270
                if (proc_cmdline_value_missing(key, value))
×
1271
                        return 0;
1272

UNCOV
1273
                if (log_set_target_from_string(value) < 0)
×
UNCOV
1274
                        log_warning("Failed to parse log target '%s', ignoring.", value);
×
1275

1276
        } else if (proc_cmdline_key_streq(key, "systemd.log_level")) {
276,868✔
1277

1278
                if (proc_cmdline_value_missing(key, value))
7,642✔
1279
                        return 0;
1280

1281
                if (log_set_max_level_from_string(value) < 0)
7,642✔
UNCOV
1282
                        log_warning("Failed to parse log level setting '%s', ignoring.", value);
×
1283

1284
        } else if (proc_cmdline_key_streq(key, "systemd.log_color")) {
269,226✔
1285

UNCOV
1286
                if (log_show_color_from_string(value ?: "1") < 0)
×
UNCOV
1287
                        log_warning("Failed to parse log color setting '%s', ignoring.", value);
×
1288

1289
        } else if (proc_cmdline_key_streq(key, "systemd.log_location")) {
269,226✔
1290

UNCOV
1291
                if (log_show_location_from_string(value ?: "1") < 0)
×
UNCOV
1292
                        log_warning("Failed to parse log location setting '%s', ignoring.", value);
×
1293

1294
        } else if (proc_cmdline_key_streq(key, "systemd.log_tid")) {
269,226✔
1295

UNCOV
1296
                if (log_show_tid_from_string(value ?: "1") < 0)
×
UNCOV
1297
                        log_warning("Failed to parse log tid setting '%s', ignoring.", value);
×
1298

1299
        } else if (proc_cmdline_key_streq(key, "systemd.log_time")) {
269,226✔
1300

UNCOV
1301
                if (log_show_time_from_string(value ?: "1") < 0)
×
UNCOV
1302
                        log_warning("Failed to parse log time setting '%s', ignoring.", value);
×
1303

1304
        } else if (proc_cmdline_key_streq(key, "systemd.log_ratelimit_kmsg")) {
269,226✔
1305

1306
                if (log_set_ratelimit_kmsg_from_string(value ?: "1") < 0)
7,642✔
UNCOV
1307
                        log_warning("Failed to parse log ratelimit kmsg boolean '%s', ignoring.", value);
×
1308
        }
1309

1310
        return 0;
1311
}
1312

1313
static bool should_parse_proc_cmdline(void) {
73,160✔
1314
        /* PID1 always reads the kernel command line. */
1315
        if (getpid_cached() == 1)
73,160✔
1316
                return true;
1317

1318
        /* Otherwise, parse the command line if invoked directly by systemd. */
1319
        return invoked_by_systemd();
73,031✔
1320
}
1321

1322
void log_parse_environment_variables(void) {
75,805✔
1323
        const char *e;
75,805✔
1324
        int r;
75,805✔
1325

1326
        e = getenv("SYSTEMD_LOG_TARGET");
75,805✔
1327
        if (e && log_set_target_from_string(e) < 0)
75,805✔
1328
                log_warning("Failed to parse log target '%s', ignoring.", e);
2✔
1329

1330
        e = getenv("SYSTEMD_LOG_LEVEL");
75,805✔
1331
        if (e) {
75,805✔
1332
                r = log_set_max_level_from_string(e);
8,265✔
1333
                if (r < 0)
8,265✔
UNCOV
1334
                        log_warning_errno(r, "Failed to parse log level '%s', ignoring: %m", e);
×
1335
        } else {
1336
                /* If no explicit log level is specified then let's see if this is a debug invocation, and if
1337
                 * so raise the log level to debug too. Note that this is not symmetric: just because
1338
                 * DEBUG_INVOCATION is explicitly set to 0 we won't lower the log level below debug. This
1339
                 * follows the logic that debug logging is an opt-in thing anyway, and if there's any reason
1340
                 * to enable it we should not disable it here automatically. */
1341
                r = getenv_bool("DEBUG_INVOCATION");
67,540✔
1342
                if (r < 0 && r != -ENXIO)
67,540✔
UNCOV
1343
                        log_warning_errno(r, "Failed to parse $DEBUG_INVOCATION value, ignoring: %m");
×
1344
                else if (r > 0)
67,540✔
UNCOV
1345
                        log_set_max_level(LOG_DEBUG);
×
1346
        }
1347

1348
        e = getenv("SYSTEMD_LOG_COLOR");
75,805✔
1349
        if (e && log_show_color_from_string(e) < 0)
75,805✔
UNCOV
1350
                log_warning("Failed to parse log color '%s', ignoring.", e);
×
1351

1352
        e = getenv("SYSTEMD_LOG_LOCATION");
75,805✔
1353
        if (e && log_show_location_from_string(e) < 0)
75,805✔
UNCOV
1354
                log_warning("Failed to parse log location '%s', ignoring.", e);
×
1355

1356
        e = getenv("SYSTEMD_LOG_TIME");
75,805✔
1357
        if (e && log_show_time_from_string(e) < 0)
75,805✔
UNCOV
1358
                log_warning("Failed to parse log time '%s', ignoring.", e);
×
1359

1360
        e = getenv("SYSTEMD_LOG_TID");
75,805✔
1361
        if (e && log_show_tid_from_string(e) < 0)
75,805✔
UNCOV
1362
                log_warning("Failed to parse log tid '%s', ignoring.", e);
×
1363

1364
        e = getenv("SYSTEMD_LOG_RATELIMIT_KMSG");
75,805✔
1365
        if (e && log_set_ratelimit_kmsg_from_string(e) < 0)
75,805✔
UNCOV
1366
                log_warning("Failed to parse log ratelimit kmsg boolean '%s', ignoring.", e);
×
1367
}
75,805✔
1368

1369
void log_parse_environment(void) {
73,160✔
1370
        /* Do not call from library code. */
1371

1372
        if (should_parse_proc_cmdline())
73,160✔
1373
                (void) proc_cmdline_parse(parse_proc_cmdline_item, NULL, PROC_CMDLINE_STRIP_RD_PREFIX);
7,718✔
1374

1375
        log_parse_environment_variables();
73,160✔
1376
}
73,160✔
1377

1378
LogTarget log_get_target(void) {
21,250✔
1379
        return log_target;
21,250✔
1380
}
1381

1382
void log_settle_target(void) {
18,852✔
1383

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

1390
        LogTarget t = log_get_target();
18,852✔
1391

1392
        if (t != LOG_TARGET_AUTO)
18,852✔
1393
                return;
1394

1395
        t = getpid_cached() == 1 || stderr_is_journal() ? (prohibit_ipc ? LOG_TARGET_KMSG : LOG_TARGET_JOURNAL_OR_KMSG)
25,945✔
1396
                                                        : LOG_TARGET_CONSOLE;
17,224✔
1397
        log_set_target(t);
8,721✔
1398
}
1399

1400
int log_get_max_level(void) {
19,751,853✔
1401
        return log_max_level;
19,751,853✔
1402
}
1403

1404
int log_get_target_max_level(LogTarget target) {
8✔
1405
        assert(target >= 0);
8✔
1406
        assert(target < _LOG_TARGET_SINGLE_MAX);
8✔
1407
        return log_target_max_level[target];
8✔
1408
}
1409

1410
void log_show_color(bool b) {
63,462✔
1411
        show_color = b;
63,462✔
1412
}
63,462✔
1413

1414
bool log_get_show_color(void) {
236,521✔
1415
        return show_color > 0; /* Defaults to false. */
236,521✔
1416
}
1417

UNCOV
1418
void log_show_location(bool b) {
×
UNCOV
1419
        show_location = b;
×
UNCOV
1420
}
×
1421

1422
bool log_get_show_location(void) {
14✔
1423
        return show_location;
14✔
1424
}
1425

1426
void log_show_time(bool b) {
1✔
1427
        show_time = b;
1✔
1428
}
1✔
1429

1430
bool log_get_show_time(void) {
14✔
1431
        return show_time;
14✔
1432
}
1433

1434
void log_show_tid(bool b) {
1✔
1435
        show_tid = b;
1✔
1436
}
1✔
1437

UNCOV
1438
bool log_get_show_tid(void) {
×
1439
        return show_tid;
×
1440
}
1441

1442
int log_show_color_from_string(const char *e) {
×
1443
        int r;
×
1444

UNCOV
1445
        r = parse_boolean(e);
×
1446
        if (r < 0)
×
1447
                return r;
1448

UNCOV
1449
        log_show_color(r);
×
1450
        return 0;
×
1451
}
1452

1453
int log_show_location_from_string(const char *e) {
×
1454
        int r;
×
1455

UNCOV
1456
        r = parse_boolean(e);
×
1457
        if (r < 0)
×
1458
                return r;
1459

UNCOV
1460
        log_show_location(r);
×
1461
        return 0;
×
1462
}
1463

1464
int log_show_time_from_string(const char *e) {
×
1465
        int r;
×
1466

UNCOV
1467
        r = parse_boolean(e);
×
1468
        if (r < 0)
×
1469
                return r;
1470

UNCOV
1471
        log_show_time(r);
×
1472
        return 0;
×
1473
}
1474

1475
int log_show_tid_from_string(const char *e) {
×
1476
        int r;
×
1477

UNCOV
1478
        r = parse_boolean(e);
×
1479
        if (r < 0)
×
1480
                return r;
1481

UNCOV
1482
        log_show_tid(r);
×
UNCOV
1483
        return 0;
×
1484
}
1485

1486
bool log_on_console(void) {
92,624✔
1487
        if (IN_SET(log_target, LOG_TARGET_CONSOLE,
92,624✔
1488
                               LOG_TARGET_CONSOLE_PREFIXED))
1489
                return true;
1490

1491
        return syslog_fd < 0 && kmsg_fd < 0 && journal_fd < 0;
120,245✔
1492
}
1493

1494
static const char *const log_target_table[_LOG_TARGET_MAX] = {
1495
        [LOG_TARGET_CONSOLE]          = "console",
1496
        [LOG_TARGET_CONSOLE_PREFIXED] = "console-prefixed",
1497
        [LOG_TARGET_KMSG]             = "kmsg",
1498
        [LOG_TARGET_JOURNAL]          = "journal",
1499
        [LOG_TARGET_JOURNAL_OR_KMSG]  = "journal-or-kmsg",
1500
        [LOG_TARGET_SYSLOG]           = "syslog",
1501
        [LOG_TARGET_SYSLOG_OR_KMSG]   = "syslog-or-kmsg",
1502
        [LOG_TARGET_AUTO]             = "auto",
1503
        [LOG_TARGET_NULL]             = "null",
1504
};
1505

1506
DEFINE_STRING_TABLE_LOOKUP(log_target, LogTarget);
34,782✔
1507

1508
void log_received_signal(int level, const struct signalfd_siginfo *si) {
4,794✔
1509
        assert(si);
4,794✔
1510

1511
        if (si_code_from_process(si->ssi_code) && pid_is_valid(si->ssi_pid)) {
5,013✔
1512
                _cleanup_free_ char *p = NULL;
219✔
1513

1514
                (void) pid_get_comm(si->ssi_pid, &p);
219✔
1515

1516
                log_full(level,
219✔
1517
                         "Received SIG%s from PID %"PRIu32" (%s).",
1518
                         signal_to_string(si->ssi_signo),
1519
                         si->ssi_pid, strna(p));
1520
        } else
1521
                log_full(level,
4,575✔
1522
                         "Received SIG%s.",
1523
                         signal_to_string(si->ssi_signo));
1524
}
4,794✔
1525

1526
void set_log_syntax_callback(log_syntax_callback_t cb, void *userdata) {
956✔
1527
        assert(!log_syntax_callback || !cb);
956✔
1528
        assert(!log_syntax_callback_userdata || !userdata);
956✔
1529

1530
        log_syntax_callback = cb;
956✔
1531
        log_syntax_callback_userdata = userdata;
956✔
1532
}
956✔
1533

1534
int log_syntax_internal(
20,490✔
1535
                const char *unit,
1536
                int level,
1537
                const char *config_file,
1538
                unsigned config_line,
1539
                int error,
1540
                const char *file,
1541
                int line,
1542
                const char *func,
1543
                const char *format, ...) {
1544

1545
        PROTECT_ERRNO;
20,490✔
1546

1547
        if (log_syntax_callback)
20,490✔
1548
                log_syntax_callback(unit, level, log_syntax_callback_userdata);
1,518✔
1549

1550
        if (_likely_(LOG_PRI(level) > log_max_level) ||
20,490✔
1551
            log_target == LOG_TARGET_NULL)
20,490✔
1552
                return -ERRNO_VALUE(error);
30✔
1553

1554
        char buffer[LINE_MAX];
20,460✔
1555
        va_list ap;
20,460✔
1556
        const char *unit_fmt = NULL;
20,460✔
1557

1558
        errno = ERRNO_VALUE(error);
20,460✔
1559

1560
        va_start(ap, format);
20,460✔
1561
        (void) vsnprintf(buffer, sizeof buffer, format, ap);
20,460✔
1562
        va_end(ap);
20,460✔
1563

1564
        if (unit)
20,460✔
1565
                unit_fmt = getpid_cached() == 1 ? "UNIT=%s" : "USER_UNIT=%s";
12,598✔
1566

1567
        if (config_file) {
20,460✔
1568
                if (config_line > 0)
20,450✔
1569
                        return log_struct_internal(
13,778✔
1570
                                        level,
1571
                                        error,
1572
                                        file, line, func,
1573
                                        LOG_MESSAGE_ID(SD_MESSAGE_INVALID_CONFIGURATION_STR),
13,778✔
1574
                                        LOG_ITEM("CONFIG_FILE=%s", config_file),
13,778✔
1575
                                        LOG_ITEM("CONFIG_LINE=%u", config_line),
13,778✔
1576
                                        LOG_MESSAGE("%s:%u: %s", config_file, config_line, buffer),
13,778✔
1577
                                        unit_fmt, unit,
1578
                                        NULL);
1579
                else
1580
                        return log_struct_internal(
6,672✔
1581
                                        level,
1582
                                        error,
1583
                                        file, line, func,
1584
                                        LOG_MESSAGE_ID(SD_MESSAGE_INVALID_CONFIGURATION_STR),
6,672✔
1585
                                        LOG_ITEM("CONFIG_FILE=%s", config_file),
6,672✔
1586
                                        LOG_MESSAGE("%s: %s", config_file, buffer),
6,672✔
1587
                                        unit_fmt, unit,
1588
                                        NULL);
1589
        } else if (unit)
10✔
UNCOV
1590
                return log_struct_internal(
×
1591
                                level,
1592
                                error,
1593
                                file, line, func,
UNCOV
1594
                                LOG_MESSAGE_ID(SD_MESSAGE_INVALID_CONFIGURATION_STR),
×
UNCOV
1595
                                LOG_MESSAGE("%s: %s", unit, buffer),
×
1596
                                unit_fmt, unit,
1597
                                NULL);
1598
        else
1599
                return log_struct_internal(
10✔
1600
                                level,
1601
                                error,
1602
                                file, line, func,
1603
                                LOG_MESSAGE_ID(SD_MESSAGE_INVALID_CONFIGURATION_STR),
10✔
1604
                                LOG_MESSAGE("%s", buffer),
10✔
1605
                                NULL);
1606
}
1607

1608
int log_syntax_invalid_utf8_internal(
1✔
1609
                const char *unit,
1610
                int level,
1611
                const char *config_file,
1612
                unsigned config_line,
1613
                const char *file,
1614
                int line,
1615
                const char *func,
1616
                const char *rvalue) {
1617

UNCOV
1618
        PROTECT_ERRNO;
×
1619
        _cleanup_free_ char *p = NULL;
1✔
1620

1621
        if (rvalue)
1✔
1622
                p = utf8_escape_invalid(rvalue);
1✔
1623

1624
        return log_syntax_internal(unit, level, config_file, config_line,
1✔
1625
                                   SYNTHETIC_ERRNO(EINVAL), file, line, func,
1626
                                   "String is not UTF-8 clean, ignoring assignment: %s", strna(p));
1627
}
1628

1629
int log_syntax_parse_error_internal(
128✔
1630
                const char *unit,
1631
                const char *config_file,
1632
                unsigned config_line,
1633
                int error,
1634
                bool critical,
1635
                const char *file,
1636
                int line,
1637
                const char *func,
1638
                const char *lvalue,
1639
                const char *rvalue) {
1640

UNCOV
1641
        PROTECT_ERRNO;
×
1642
        _cleanup_free_ char *escaped = NULL;
128✔
1643

1644
        /* OOM is always handled as critical. */
1645
        if (ERRNO_VALUE(error) == ENOMEM)
128✔
1646
                return log_oom_internal(LOG_ERR, file, line, func);
×
1647

1648
        if (rvalue && !utf8_is_valid(rvalue)) {
256✔
UNCOV
1649
                escaped = utf8_escape_invalid(rvalue);
×
1650
                if (!escaped)
×
1651
                        rvalue = "(oom)";
1652
                else
UNCOV
1653
                        rvalue = " (escaped)";
×
1654
        }
1655

1656
        log_syntax_internal(unit, critical ? LOG_ERR : LOG_WARNING, config_file, config_line, error,
640✔
1657
                            file, line, func,
1658
                            "Failed to parse %s=%s%s%s%s%s",
1659
                            strna(lvalue), strempty(escaped), strempty(rvalue),
1660
                            critical ? "" : ", ignoring",
1661
                            error == 0 ? "." : ": ",
1662
                            error == 0 ? "" : STRERROR(error));
128✔
1663

1664
        return critical ? -ERRNO_VALUE(error) : 0;
128✔
1665
}
1666

1667
void log_set_upgrade_syslog_to_journal(bool b) {
251✔
1668
        upgrade_syslog_to_journal = b;
251✔
1669

1670
        /* Make the change effective immediately */
1671
        if (b) {
251✔
1672
                if (log_target == LOG_TARGET_SYSLOG)
251✔
UNCOV
1673
                        log_target = LOG_TARGET_JOURNAL;
×
1674
                else if (log_target == LOG_TARGET_SYSLOG_OR_KMSG)
251✔
UNCOV
1675
                        log_target = LOG_TARGET_JOURNAL_OR_KMSG;
×
1676
        }
1677
}
251✔
1678

1679
void log_set_always_reopen_console(bool b) {
10,700✔
1680
        always_reopen_console = b;
10,700✔
1681
}
10,700✔
1682

1683
void log_set_open_when_needed(bool b) {
29,556✔
1684
        open_when_needed = b;
29,556✔
1685
}
29,556✔
1686

1687
void log_set_prohibit_ipc(bool b) {
35,268✔
1688
        prohibit_ipc = b;
35,268✔
1689
}
35,268✔
1690

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

UNCOV
1695
        return getpid_cached() == 1 ? LOG_EMERG : LOG_ERR;
×
1696
}
1697

1698
int log_dup_console(void) {
111✔
1699
        int copy;
111✔
1700

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

1704
        if (console_fd < 0 || console_fd >= 3)
111✔
1705
                return 0;
1706

1707
        copy = fcntl(console_fd, F_DUPFD_CLOEXEC, 3);
1✔
1708
        if (copy < 0)
1✔
UNCOV
1709
                return -errno;
×
1710

1711
        console_fd = copy;
1✔
1712
        return 0;
1✔
1713
}
1714

1715
void log_setup(void) {
72,451✔
1716
        log_set_target(LOG_TARGET_AUTO);
72,451✔
1717
        log_parse_environment();
72,451✔
1718
        (void) log_open();
72,451✔
1719
        if (log_on_console() && show_color < 0)
72,451✔
1720
                log_show_color(true);
63,362✔
1721
}
72,451✔
1722

1723
const char* _log_set_prefix(const char *prefix, bool force) {
3,730,954✔
1724
        const char *old = log_prefix;
3,730,954✔
1725

1726
        if (prefix || force)
3,730,954✔
1727
                log_prefix = prefix;
3,728,708✔
1728

1729
        return old;
3,730,954✔
1730
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc