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

systemd / systemd / 29378720657

14 Jul 2026 11:44PM UTC coverage: 72.936% (-0.004%) from 72.94%
29378720657

push

github

yuwata
sd-dhcp-relay: fix off-by-one when discarding BOOTREQUEST messages by hops count

According to RFC specifications
```
RFC 1542 section 4.1.1 states:
The relay agent MUST silently discard BOOTREQUEST messages whose 'hops'
   field exceeds the value 16."
```

"Exceeds the value 16" means hops > 16, i.e. a message that arrives with
hops == 16 is still valid and must be relayed (after which its hops field
becomes 17). The code used ">= 16", which silently dropped a valid message
that had legitimately traversed exactly 16 relay agents, one hop too early.

This matches the wording of the adjacent comment, which already says
"exceeds the value 16".

2 of 2 new or added lines in 2 files covered. (100.0%)

4253 existing lines in 80 files now uncovered.

345834 of 474164 relevant lines covered (72.94%)

1318659.74 hits per line

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

84.8
/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
void log_prefix_swap(const char **prefix) {
1,134✔
91
        assert(prefix);
1,134✔
92

93
        SWAP_TWO(log_prefix, *prefix);
1,134✔
94
}
1,134✔
95

96
static void log_close_console(void) {
491,435✔
97
        /* See comment in log_close_journal() */
98
        (void) safe_close_above_stdio(TAKE_FD(console_fd));
491,435✔
99
        console_fd_is_tty = -1;
491,435✔
100
}
491,435✔
101

102
static int log_open_console(void) {
82,175✔
103

104
        if (!always_reopen_console) {
82,175✔
105
                console_fd = STDERR_FILENO;
73,692✔
106
                console_fd_is_tty = -1;
73,692✔
107
                return 0;
73,692✔
108
        }
109

110
        if (console_fd < 3) {
8,483✔
111
                int fd;
6,151✔
112

113
                fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
6,151✔
114
                if (fd < 0)
6,151✔
115
                        return fd;
116

117
                console_fd = fd_move_above_stdio(fd);
5,931✔
118
                console_fd_is_tty = true;
5,931✔
119
        }
120

121
        return 0;
122
}
123

124
static void log_close_kmsg(void) {
245,382✔
125
        /* See comment in log_close_journal() */
126
        (void) safe_close(TAKE_FD(kmsg_fd));
245,382✔
127
}
245,382✔
128

129
static int log_open_kmsg(void) {
22,033✔
130

131
        if (kmsg_fd >= 0)
22,033✔
132
                return 0;
133

134
        kmsg_fd = open("/dev/kmsg", O_WRONLY|O_NOCTTY|O_CLOEXEC);
18,156✔
135
        if (kmsg_fd < 0)
18,156✔
136
                return -errno;
6,760✔
137

138
        kmsg_fd = fd_move_above_stdio(kmsg_fd);
11,396✔
139
        return 0;
11,396✔
140
}
141

142
static void log_close_syslog(void) {
573,608✔
143
        /* See comment in log_close_journal() */
144
        (void) safe_close(TAKE_FD(syslog_fd));
573,608✔
145
}
573,608✔
146

147
static int create_log_socket(int type) {
222,360✔
148
        struct timeval tv;
222,360✔
149
        int fd;
222,360✔
150

151
        fd = socket(AF_UNIX, type|SOCK_CLOEXEC, 0);
222,360✔
152
        if (fd < 0)
222,360✔
153
                return -errno;
×
154

155
        fd = fd_move_above_stdio(fd);
222,360✔
156
        (void) fd_inc_sndbuf(fd, SNDBUF_SIZE);
222,360✔
157

158
        /* We need a blocking fd here since we'd otherwise lose messages way too early. However, let's not hang forever
159
         * in the unlikely case of a deadlock. */
160
        if (getpid_cached() == 1)
222,360✔
161
                timeval_store(&tv, 10 * USEC_PER_MSEC);
306✔
162
        else
163
                timeval_store(&tv, 10 * USEC_PER_SEC);
222,054✔
164
        (void) setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
222,360✔
165

166
        return fd;
222,360✔
167
}
168

169
static int log_open_syslog(void) {
2✔
170
        int r;
2✔
171

172
        if (syslog_fd >= 0)
2✔
173
                return 0;
174

175
        syslog_fd = create_log_socket(SOCK_DGRAM);
2✔
176
        if (syslog_fd < 0) {
2✔
177
                r = syslog_fd;
×
178
                goto fail;
×
179
        }
180

181
        r = connect_unix_path(syslog_fd, AT_FDCWD, "/dev/log");
2✔
182
        if (r < 0) {
2✔
183
                safe_close(syslog_fd);
×
184

185
                /* Some legacy syslog systems still use stream sockets. They really shouldn't. But what can
186
                 * we do... */
187
                syslog_fd = create_log_socket(SOCK_STREAM);
×
188
                if (syslog_fd < 0) {
×
189
                        r = syslog_fd;
×
190
                        goto fail;
×
191
                }
192

193
                r = connect_unix_path(syslog_fd, AT_FDCWD, "/dev/log");
×
194
                if (r < 0)
×
195
                        goto fail;
×
196

197
                syslog_is_stream = true;
×
198
        } else
199
                syslog_is_stream = false;
2✔
200

201
        return 0;
202

203
fail:
×
204
        log_close_syslog();
×
205
        return r;
×
206
}
207

208
static void log_close_journal(void) {
342,657✔
209
        /* If the journal FD is bad, safe_close will fail, and will try to log, which will fail, so we'll
210
         * try to close the journal FD, which is bad, so safe_close will fail... Whether we can close it
211
         * or not, invalidate it immediately so that we don't get in a recursive loop until we run out of
212
         * stack. */
213
        (void) safe_close(TAKE_FD(journal_fd));
342,657✔
214
}
342,657✔
215

216
static int log_open_journal(void) {
242,359✔
217
        int r;
242,359✔
218

219
        if (journal_fd >= 0)
242,359✔
220
                return 0;
221

222
        journal_fd = create_log_socket(SOCK_DGRAM);
222,358✔
223
        if (journal_fd < 0) {
222,358✔
224
                r = journal_fd;
×
225
                goto fail;
×
226
        }
227

228
        r = connect_unix_path(journal_fd, AT_FDCWD, "/run/systemd/journal/socket");
222,358✔
229
        if (r < 0)
222,358✔
230
                goto fail;
95✔
231

232
        return 0;
233

234
fail:
95✔
235
        log_close_journal();
95✔
236
        return r;
95✔
237
}
238

239
bool stderr_is_journal(void) {
312,239✔
240
        _cleanup_free_ char *w = NULL;
312,239✔
241
        const char *e;
312,239✔
242
        uint64_t dev, ino;
312,239✔
243
        struct stat st;
312,239✔
244

245
        e = getenv("JOURNAL_STREAM");
312,239✔
246
        if (!e)
312,239✔
247
                return false;
248

249
        if (extract_first_word(&e, &w, ":", EXTRACT_DONT_COALESCE_SEPARATORS) <= 0)
38,240✔
250
                return false;
251
        if (!e)
38,240✔
252
                return false;
253

254
        if (safe_atou64(w, &dev) < 0)
38,240✔
255
                return false;
256
        if (safe_atou64(e, &ino) < 0)
38,240✔
257
                return false;
258

259
        if (fstat(STDERR_FILENO, &st) < 0)
38,240✔
260
                return false;
261

262
        return st.st_dev == dev && st.st_ino == ino;
44,111✔
263
}
264

265
int log_open(void) {
328,228✔
266
        int r;
328,228✔
267

268
        /* Do not call from library code. */
269

270
        /* This function is often called in preparation for logging. Let's make sure we don't clobber errno,
271
         * so that a call to a logging function immediately following a log_open() call can still easily
272
         * reference an error that happened immediately before the log_open() call. */
273
        PROTECT_ERRNO;
328,228✔
274

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

280
        if (log_target == LOG_TARGET_NULL) {
328,228✔
281
                log_close_journal();
2✔
282
                log_close_syslog();
2✔
283
                log_close_console();
2✔
284
                return 0;
285
        }
286

287
        if (getpid_cached() == 1 ||
630,037✔
288
            stderr_is_journal() ||
301,811✔
289
            IN_SET(log_target,
279,505✔
290
                   LOG_TARGET_KMSG,
291
                   LOG_TARGET_JOURNAL,
292
                   LOG_TARGET_JOURNAL_OR_KMSG,
293
                   LOG_TARGET_SYSLOG,
294
                   LOG_TARGET_SYSLOG_OR_KMSG)) {
295

296
                if (!prohibit_ipc) {
255,267✔
297
                        if (IN_SET(log_target,
248,316✔
298
                                   LOG_TARGET_AUTO,
299
                                   LOG_TARGET_JOURNAL_OR_KMSG,
300
                                   LOG_TARGET_JOURNAL)) {
301

302
                                r = log_open_journal();
231,141✔
303
                                if (r >= 0) {
231,141✔
304
                                        log_close_syslog();
231,059✔
305
                                        log_close_console();
231,059✔
306
                                        return r;
307
                                }
308
                        }
309

310
                        if (IN_SET(log_target,
17,257✔
311
                                   LOG_TARGET_SYSLOG_OR_KMSG,
312
                                   LOG_TARGET_SYSLOG)) {
313

314
                                r = log_open_syslog();
2✔
315
                                if (r >= 0) {
2✔
316
                                        log_close_journal();
2✔
317
                                        log_close_console();
2✔
318
                                        return r;
319
                                }
320
                        }
321
                }
322

323
                if (IN_SET(log_target, LOG_TARGET_AUTO,
24,206✔
324
                                       LOG_TARGET_JOURNAL_OR_KMSG,
325
                                       LOG_TARGET_SYSLOG_OR_KMSG,
326
                                       LOG_TARGET_KMSG)) {
327
                        r = log_open_kmsg();
21,746✔
328
                        if (r >= 0) {
21,746✔
329
                                log_close_journal();
14,990✔
330
                                log_close_syslog();
14,990✔
331
                                log_close_console();
14,990✔
332
                                return r;
333
                        }
334
                }
335
        }
336

337
        log_close_journal();
82,175✔
338
        log_close_syslog();
82,175✔
339

340
        return log_open_console();
82,175✔
341
}
342

343
void log_set_target(LogTarget target) {
111,442✔
344
        assert(target >= 0);
111,442✔
345
        assert(target < _LOG_TARGET_MAX);
111,442✔
346

347
        if (upgrade_syslog_to_journal) {
111,442✔
348
                if (target == LOG_TARGET_SYSLOG)
376✔
349
                        target = LOG_TARGET_JOURNAL;
350
                else if (target == LOG_TARGET_SYSLOG_OR_KMSG)
376✔
351
                        target = LOG_TARGET_JOURNAL_OR_KMSG;
×
352
        }
353

354
        log_target = target;
111,442✔
355
}
111,442✔
356

357
void log_set_target_and_open(LogTarget target) {
342✔
358
        log_set_target(target);
342✔
359
        log_open();
342✔
360
}
342✔
361

362
void log_close(void) {
245,382✔
363
        /* Do not call from library code. */
364

365
        log_close_journal();
245,382✔
366
        log_close_syslog();
245,382✔
367
        log_close_kmsg();
245,382✔
368
        log_close_console();
245,382✔
369
}
245,382✔
370

371
void log_forget_fds(void) {
12,968✔
372
        /* Do not call from library code. */
373

374
        console_fd = kmsg_fd = syslog_fd = journal_fd = -EBADF;
12,968✔
375
        console_fd_is_tty = -1;
12,968✔
376
}
12,968✔
377

378
int log_set_max_level(int level) {
1,156,451✔
379
        assert(level == LOG_NULL || log_level_is_valid(level));
1,156,451✔
380

381
        int old = log_max_level;
1,156,451✔
382
        log_max_level = level;
1,156,451✔
383

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

392
        /* Ensure that our own LOG_NULL define maps sanely to the log mask */
393
        assert_cc(LOG_UPTO(LOG_NULL) == 0);
1,156,451✔
394

395
        return old;
1,156,451✔
396
}
397

398
void log_set_facility(int facility) {
212✔
399
        log_facility = facility;
212✔
400
}
212✔
401

402
static bool check_console_fd_is_tty(void) {
241,769✔
403
        if (console_fd < 0)
241,769✔
404
                return false;
405

406
        if (console_fd_is_tty < 0)
241,769✔
407
                console_fd_is_tty = isatty_safe(console_fd);
14,784✔
408

409
        return console_fd_is_tty;
241,769✔
410
}
411

412
static int write_to_console(
369,461✔
413
                int level,
414
                int error,
415
                const char *file,
416
                int line,
417
                const char *func,
418
                const char *buffer) {
419

420
        static int dumb = -1;
369,461✔
421

422
        char location[256],
369,461✔
423
             header_time[FORMAT_TIMESTAMP_MAX],
424
             prefix[1 + DECIMAL_STR_MAX(int) + 2],
425
             tid_string[3 + DECIMAL_STR_MAX(pid_t) + 1];
426
        struct iovec iovec[11];
369,461✔
427
        const char *on = NULL, *off = NULL;
369,461✔
428
        size_t n = 0;
369,461✔
429

430
        if (console_fd < 0)
369,461✔
431
                return 0;
369,461✔
432

433
        if (dumb < 0)
368,695✔
434
                dumb = getenv_terminal_is_dumb();
15,559✔
435

436
        if (LOG_PRI(level) > log_target_max_level[LOG_TARGET_CONSOLE])
368,695✔
437
                return 0;
438

439
        if (log_target == LOG_TARGET_CONSOLE_PREFIXED) {
241,769✔
440
                xsprintf(prefix, "<%i>", level);
364✔
441
                iovec[n++] = IOVEC_MAKE_STRING(prefix);
364✔
442
        }
443

444
        if (show_time &&
241,769✔
445
            format_timestamp(header_time, sizeof(header_time), now(CLOCK_REALTIME))) {
×
446
                iovec[n++] = IOVEC_MAKE_STRING(header_time);
×
447
                iovec[n++] = IOVEC_MAKE_STRING(" ");
×
448
        }
449

450
        if (show_tid) {
241,769✔
451
                xsprintf(tid_string, "(" PID_FMT ") ", gettid());
×
452
                iovec[n++] = IOVEC_MAKE_STRING(tid_string);
×
453
        }
454

455
        if (log_get_show_color())
241,769✔
456
                get_log_colors(LOG_PRI(level), &on, &off, NULL);
234,982✔
457

458
        if (show_location) {
241,769✔
459
                const char *lon = "", *loff = "";
×
460
                if (log_get_show_color()) {
×
461
                        lon = ansi_highlight_yellow4();
×
462
                        loff = ansi_normal();
×
463
                }
464

465
                (void) snprintf(location, sizeof location, "%s%s:%i%s: ", lon, file, line, loff);
×
466
                iovec[n++] = IOVEC_MAKE_STRING(location);
×
467
        }
468

469
        if (on)
241,769✔
470
                iovec[n++] = IOVEC_MAKE_STRING(on);
214,548✔
471
        if (log_prefix) {
241,769✔
472
                iovec[n++] = IOVEC_MAKE_STRING(log_prefix);
9,869✔
473
                iovec[n++] = IOVEC_MAKE_STRING(": ");
9,869✔
474
        }
475
        iovec[n++] = IOVEC_MAKE_STRING(buffer);
241,769✔
476
        if (off)
241,769✔
477
                iovec[n++] = IOVEC_MAKE_STRING(off);
214,548✔
478

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

486
        if (writev(console_fd, iovec, n) < 0) {
241,769✔
487

488
                if (errno == EIO && getpid_cached() == 1) {
×
489

490
                        /* If somebody tried to kick us from our console tty (via vhangup() or suchlike), try
491
                         * to reconnect. */
492

493
                        log_close_console();
×
494
                        (void) log_open_console();
×
495
                        if (console_fd < 0)
×
496
                                return 0;
497

498
                        if (writev(console_fd, iovec, n) < 0)
×
499
                                return -errno;
×
500
                } else
501
                        return -errno;
×
502
        }
503

504
        return 1;
505
}
506

507
static int write_to_syslog(
180✔
508
                int level,
509
                int error,
510
                const char *file,
511
                int line,
512
                const char *func,
513
                const char *buffer) {
514

515
        char header_priority[2 + DECIMAL_STR_MAX(int) + 1],
180✔
516
             header_time[64],
517
             header_pid[4 + DECIMAL_STR_MAX(pid_t) + 1];
518
        struct tm tm;
180✔
519
        int r;
180✔
520

521
        if (syslog_fd < 0)
180✔
522
                return 0;
180✔
523

524
        if (LOG_PRI(level) > log_target_max_level[LOG_TARGET_SYSLOG])
180✔
525
                return 0;
526

527
        xsprintf(header_priority, "<%i>", level);
180✔
528

529
        r = localtime_or_gmtime_usec(now(CLOCK_REALTIME), /* utc= */ false, &tm);
180✔
530
        if (r < 0)
180✔
531
                return r;
532

533
        if (strftime(header_time, sizeof(header_time), "%h %e %T ", &tm) <= 0)
180✔
534
                return -EINVAL;
535

536
        xsprintf(header_pid, "["PID_FMT"]: ", getpid_cached());
180✔
537

538
        struct iovec iovec[] = {
1,440✔
539
                IOVEC_MAKE_STRING(header_priority),
180✔
540
                IOVEC_MAKE_STRING(header_time),
180✔
541
                IOVEC_MAKE_STRING(program_invocation_short_name),
180✔
542
                IOVEC_MAKE_STRING(header_pid),
180✔
543
                IOVEC_MAKE_STRING(strempty(log_prefix)),
292✔
544
                IOVEC_MAKE_STRING(log_prefix ? ": " : ""),
292✔
545
                IOVEC_MAKE_STRING(buffer),
180✔
546
        };
547
        const struct msghdr msghdr = {
180✔
548
                .msg_iov = iovec,
549
                .msg_iovlen = ELEMENTSOF(iovec),
550
        };
551

552
        /* When using syslog via SOCK_STREAM separate the messages by NUL chars */
553
        if (syslog_is_stream)
180✔
554
                iovec[ELEMENTSOF(iovec) - 1].iov_len++;
×
555

556
        for (;;) {
180✔
557
                ssize_t n;
180✔
558

559
                n = sendmsg(syslog_fd, &msghdr, MSG_NOSIGNAL);
180✔
560
                if (n < 0)
180✔
561
                        return -errno;
×
562

563
                if (!syslog_is_stream)
180✔
564
                        break;
565

566
                if (iovec_inc_many(iovec, ELEMENTSOF(iovec), n))
×
567
                        break;
568
        }
569

570
        return 1;
571
}
572

573
static int write_to_kmsg(
345,263✔
574
                int level,
575
                int error,
576
                const char *file,
577
                int line,
578
                const char *func,
579
                const char *buffer) {
580

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

590
        char header_priority[2 + DECIMAL_STR_MAX(int) + 1],
345,263✔
591
             header_pid[4 + DECIMAL_STR_MAX(pid_t) + 1];
592

593
        if (kmsg_fd < 0)
345,263✔
594
                return 0;
345,263✔
595

596
        if (LOG_PRI(level) > log_target_max_level[LOG_TARGET_KMSG])
83,737✔
597
                return 0;
598

599
        if (ratelimit_kmsg && !ratelimit_below(&ratelimit)) {
83,737✔
600
                if (ratelimit_num_dropped(&ratelimit) > 1)
×
601
                        return 0;
602

603
                buffer = "Too many messages being logged to kmsg, ignoring";
604
        }
605

606
        xsprintf(header_priority, "<%i>", level);
83,737✔
607
        xsprintf(header_pid, "["PID_FMT"]: ", getpid_cached());
83,737✔
608

609
        const struct iovec iovec[] = {
669,896✔
610
                IOVEC_MAKE_STRING(header_priority),
83,737✔
611
                IOVEC_MAKE_STRING(program_invocation_short_name),
83,737✔
612
                IOVEC_MAKE_STRING(header_pid),
83,737✔
613
                IOVEC_MAKE_STRING(strempty(log_prefix)),
129,298✔
614
                IOVEC_MAKE_STRING(log_prefix ? ": " : ""),
129,298✔
615
                IOVEC_MAKE_STRING(buffer),
83,737✔
616
                IOVEC_MAKE_STRING("\n"),
83,737✔
617
        };
618

619
        if (writev(kmsg_fd, iovec, ELEMENTSOF(iovec)) < 0)
83,737✔
620
                return -errno;
×
621

622
        return 1;
623
}
624

625
static int log_do_header(
6,285,452✔
626
                char *header,
627
                size_t size,
628
                int level,
629
                int error,
630
                const char *file, int line, const char *func,
631
                const char *object_field, const char *object,
632
                const char *extra_field, const char *extra) {
633
        int r;
6,285,452✔
634

635
        error = IS_SYNTHETIC_ERRNO(error) ? 0 : ERRNO_VALUE(error);
6,285,452✔
636

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

672
        return 0;
6,285,452✔
673
}
674

675
static void log_do_context(struct iovec *iovec, size_t iovec_len, size_t *n) {
6,285,452✔
676
        assert(iovec);
6,285,452✔
677
        assert(n);
6,285,452✔
678

679
        LIST_FOREACH(ll, c, log_context_head()) {
9,028,103✔
680
                STRV_FOREACH(s, c->fields) {
24,200,448✔
681
                        if (*n + 2 >= iovec_len)
21,273,913✔
682
                                return;
×
683

684
                        iovec[(*n)++] = IOVEC_MAKE_STRING(*s);
21,273,913✔
685
                        iovec[(*n)++] = IOVEC_MAKE_STRING("\n");
21,273,913✔
686
                }
687

688
                for (size_t i = 0; i < c->n_input_iovec; i++) {
2,953,826✔
689
                        if (*n + 2 >= iovec_len)
27,368✔
690
                                return;
77✔
691

692
                        iovec[(*n)++] = c->input_iovec[i];
27,291✔
693
                        iovec[(*n)++] = IOVEC_MAKE_STRING("\n");
27,291✔
694
                }
695

696
                if (c->key && c->value) {
2,926,458✔
697
                        if (*n + 3 >= iovec_len)
410,880✔
698
                                return;
183,807✔
699

700
                        iovec[(*n)++] = IOVEC_MAKE_STRING(c->key);
227,073✔
701
                        iovec[(*n)++] = IOVEC_MAKE_STRING(c->value);
227,073✔
702
                        iovec[(*n)++] = IOVEC_MAKE_STRING("\n");
227,073✔
703
                }
704
        }
705
}
706

707
static int write_to_journal(
6,593,991✔
708
                int level,
709
                int error,
710
                const char *file,
711
                int line,
712
                const char *func,
713
                const char *object_field,
714
                const char *object,
715
                const char *extra_field,
716
                const char *extra,
717
                const char *buffer) {
718

719
        char header[LINE_MAX];
6,593,991✔
720
        size_t n = 0, iovec_len;
6,593,991✔
721
        struct iovec *iovec;
6,593,991✔
722

723
        if (journal_fd < 0)
6,593,991✔
724
                return 0;
6,593,991✔
725

726
        if (LOG_PRI(level) > log_target_max_level[LOG_TARGET_JOURNAL])
6,197,479✔
727
                return 0;
728

729
        if (!MUL_SAFE(&iovec_len, log_context_num_fields(), 3) ||
6,197,479✔
730
            !ADD_SAFE(&iovec_len, iovec_len, 6))
6,197,479✔
731
                iovec_len = IOVEC_MAX;
732
        else
733
                iovec_len = MIN(iovec_len, IOVEC_MAX);
6,197,479✔
734
        iovec = newa(struct iovec, iovec_len);
6,197,479✔
735

736
        log_do_header(header, sizeof(header), level, error, file, line, func, object_field, object, extra_field, extra);
6,197,479✔
737

738
        iovec[n++] = IOVEC_MAKE_STRING(header);
6,197,479✔
739
        iovec[n++] = IOVEC_MAKE_STRING("MESSAGE=");
6,197,479✔
740
        if (log_prefix) {
6,197,479✔
741
                iovec[n++] = IOVEC_MAKE_STRING(log_prefix);
1,968,356✔
742
                iovec[n++] = IOVEC_MAKE_STRING(": ");
1,968,356✔
743
        }
744
        iovec[n++] = IOVEC_MAKE_STRING(buffer);
6,197,479✔
745
        iovec[n++] = IOVEC_MAKE_STRING("\n");
6,197,479✔
746

747
        log_do_context(iovec, iovec_len, &n);
6,197,479✔
748

749
        const struct msghdr msghdr = {
6,197,479✔
750
                .msg_iov = iovec,
751
                .msg_iovlen = n,
752
        };
753

754
        if (sendmsg(journal_fd, &msghdr, MSG_NOSIGNAL) < 0)
6,197,479✔
755
                return -errno;
686✔
756

757
        return 1;
758
}
759

760
int log_dispatch_internal(
6,635,870✔
761
                int level,
762
                int error,
763
                const char *file,
764
                int line,
765
                const char *func,
766
                const char *object_field,
767
                const char *object,
768
                const char *extra_field,
769
                const char *extra,
770
                char *buffer) {
771

772
        assert_raw(buffer);
6,635,870✔
773

774
        if (log_target == LOG_TARGET_NULL)
6,635,870✔
775
                return -ERRNO_VALUE(error);
38✔
776

777
        /* Patch in LOG_DAEMON facility if necessary */
778
        if (LOG_FAC(level) == 0)
6,635,832✔
779
                level |= log_facility;
6,621,611✔
780

781
        if (open_when_needed)
6,635,832✔
782
                (void) log_open();
194,170✔
783

784
        do {
6,691,240✔
785
                char *e;
6,691,240✔
786
                int k = 0;
6,691,240✔
787

788
                buffer += strspn(buffer, NEWLINE);
6,691,240✔
789

790
                if (buffer[0] == 0)
6,691,240✔
791
                        break;
792

793
                if ((e = strpbrk(buffer, NEWLINE)))
6,650,171✔
794
                        *(e++) = 0;
55,408✔
795

796
                if (IN_SET(log_target, LOG_TARGET_AUTO,
6,650,171✔
797
                                       LOG_TARGET_JOURNAL_OR_KMSG,
798
                                       LOG_TARGET_JOURNAL)) {
799

800
                        k = write_to_journal(level, error, file, line, func, object_field, object, extra_field, extra, buffer);
6,593,991✔
801
                        if (k < 0 && k != -EAGAIN)
6,593,991✔
802
                                log_close_journal();
11✔
803
                }
804

805
                if (IN_SET(log_target, LOG_TARGET_SYSLOG_OR_KMSG,
6,650,171✔
806
                                       LOG_TARGET_SYSLOG)) {
807

808
                        k = write_to_syslog(level, error, file, line, func, buffer);
180✔
809
                        if (k < 0 && k != -EAGAIN)
180✔
UNCOV
810
                                log_close_syslog();
×
811
                }
812

813
                if (k <= 0 &&
6,650,171✔
814
                    IN_SET(log_target, LOG_TARGET_AUTO,
453,198✔
815
                                       LOG_TARGET_SYSLOG_OR_KMSG,
816
                                       LOG_TARGET_JOURNAL_OR_KMSG,
817
                                       LOG_TARGET_KMSG)) {
818

819
                        if (k < 0)
345,263✔
820
                                log_open_kmsg();
287✔
821

822
                        k = write_to_kmsg(level, error, file, line, func, buffer);
345,263✔
823
                        if (k < 0) {
345,263✔
UNCOV
824
                                log_close_kmsg();
×
UNCOV
825
                                (void) log_open_console();
×
826
                        }
827
                }
828

829
                if (k <= 0)
453,198✔
830
                        (void) write_to_console(level, error, file, line, func, buffer);
369,461✔
831

832
                buffer = e;
6,650,171✔
833
        } while (buffer);
6,650,171✔
834

835
        if (open_when_needed)
6,635,832✔
836
                log_close();
194,170✔
837

838
        return -ERRNO_VALUE(error);
6,635,832✔
839
}
840

841
int log_dump_internal(
9✔
842
                int level,
843
                int error,
844
                const char *file,
845
                int line,
846
                const char *func,
847
                char *buffer) {
848

849
        PROTECT_ERRNO;
9✔
850

851
        /* This modifies the buffer... */
852

853
        if (_likely_(LOG_PRI(level) > log_max_level))
9✔
UNCOV
854
                return -ERRNO_VALUE(error);
×
855

856
        return log_dispatch_internal(level, error, file, line, func, NULL, NULL, NULL, NULL, buffer);
9✔
857
}
858

859
int log_internalv(
4,767,939✔
860
                int level,
861
                int error,
862
                const char *file,
863
                int line,
864
                const char *func,
865
                const char *format,
866
                va_list ap) {
867

868
        if (_likely_(LOG_PRI(level) > log_max_level))
4,767,939✔
869
                return -ERRNO_VALUE(error);
4,767,939✔
870

871
        /* Make sure that %m maps to the specified error (or "Success"). */
872
        char buffer[LINE_MAX];
4,767,939✔
873
        LOCAL_ERRNO(ERRNO_VALUE(error));
4,767,939✔
874

875
        (void) vsnprintf(buffer, sizeof buffer, format, ap);
4,767,939✔
876

877
        return log_dispatch_internal(level, error, file, line, func, NULL, NULL, NULL, NULL, buffer);
4,767,939✔
878
}
879

880
int log_internal(
4,766,033✔
881
                int level,
882
                int error,
883
                const char *file,
884
                int line,
885
                const char *func,
886
                const char *format, ...) {
887

888
        va_list ap;
4,766,033✔
889
        int r;
4,766,033✔
890

891
        va_start(ap, format);
4,766,033✔
892
        r = log_internalv(level, error, file, line, func, format, ap);
4,766,033✔
893
        va_end(ap);
4,766,033✔
894

895
        return r;
4,766,033✔
896
}
897

898
int log_object_internalv(
1,900,707✔
899
                int level,
900
                int error,
901
                const char *file,
902
                int line,
903
                const char *func,
904
                const char *object_field,
905
                const char *object,
906
                const char *extra_field,
907
                const char *extra,
908
                const char *format,
909
                va_list ap) {
910

911
        char *buffer, *b;
1,900,707✔
912

913
        if (_likely_(LOG_PRI(level) > log_max_level))
1,900,707✔
914
                return -ERRNO_VALUE(error);
1,900,707✔
915

916
        /* Make sure that %m maps to the specified error (or "Success"). */
UNCOV
917
        LOCAL_ERRNO(ERRNO_VALUE(error));
×
918

919
        LOG_SET_PREFIX(object);
3,707,746✔
920

921
        b = buffer = newa(char, LINE_MAX);
1,853,873✔
922
        (void) vsnprintf(b, LINE_MAX, format, ap);
1,853,873✔
923

924
        return log_dispatch_internal(level, error, file, line, func,
1,853,873✔
925
                                     object_field, object, extra_field, extra, buffer);
926
}
927

928
int log_object_internal(
1,892,892✔
929
                int level,
930
                int error,
931
                const char *file,
932
                int line,
933
                const char *func,
934
                const char *object_field,
935
                const char *object,
936
                const char *extra_field,
937
                const char *extra,
938
                const char *format, ...) {
939

940
        va_list ap;
1,892,892✔
941
        int r;
1,892,892✔
942

943
        va_start(ap, format);
1,892,892✔
944
        r = log_object_internalv(level, error, file, line, func, object_field, object, extra_field, extra, format, ap);
1,892,892✔
945
        va_end(ap);
1,892,892✔
946

947
        return r;
1,892,892✔
948
}
949

UNCOV
950
int log_oom_internal(int level, const char *file, int line, const char *func) {
×
UNCOV
951
        return log_internal(level, ENOMEM, file, line, func, "Out of memory.");
×
952
}
953

954
int log_format_iovec(
84,479✔
955
                struct iovec *iovec,
956
                size_t iovec_len,
957
                size_t *n,
958
                bool newline_separator,
959
                int error,
960
                const char *format,
961
                va_list ap) {
962

963
        assert(iovec);
84,479✔
964
        assert(n);
84,479✔
965

966
        while (format && *n + 1 < iovec_len) {
506,715✔
967
                va_list aq;
422,236✔
968
                char *m;
422,236✔
969
                int r;
422,236✔
970

971
                /* We need to copy the va_list structure,
972
                 * since vasprintf() leaves it afterwards at
973
                 * an undefined location */
974

975
                errno = ERRNO_VALUE(error);
422,236✔
976

977
                va_copy(aq, ap);
422,236✔
978
                r = vasprintf(&m, format, aq);
422,236✔
979
                va_end(aq);
422,236✔
980
                if (r < 0)
422,236✔
UNCOV
981
                        return -EINVAL;
×
982

983
                /* Now, jump enough ahead, so that we point to
984
                 * the next format string */
985
                VA_FORMAT_ADVANCE(format, ap);
1,348,797✔
986

987
                iovec[(*n)++] = IOVEC_MAKE_STRING(m);
422,236✔
988
                if (newline_separator)
422,236✔
989
                        iovec[(*n)++] = IOVEC_MAKE_STRING("\n");
419,861✔
990

991
                format = va_arg(ap, char *);
422,236✔
992
        }
993
        return 0;
994
}
995

996
int log_struct_internal(
97,830✔
997
                int level,
998
                int error,
999
                const char *file,
1000
                int line,
1001
                const char *func,
1002
                const char *format, ...) {
1003

1004
        char buf[LINE_MAX];
97,830✔
1005
        bool found = false;
97,830✔
1006
        PROTECT_ERRNO;
97,830✔
1007
        va_list ap;
97,830✔
1008

1009
        if (_likely_(LOG_PRI(level) > log_max_level) ||
97,830✔
1010
            log_target == LOG_TARGET_NULL)
97,830✔
1011
                return -ERRNO_VALUE(error);
50✔
1012

1013
        if (LOG_FAC(level) == 0)
97,780✔
1014
                level |= log_facility;
97,780✔
1015

1016
        if (IN_SET(log_target,
97,780✔
1017
                   LOG_TARGET_AUTO,
1018
                   LOG_TARGET_JOURNAL_OR_KMSG,
1019
                   LOG_TARGET_JOURNAL)) {
1020

1021
                if (open_when_needed)
95,784✔
1022
                        log_open_journal();
11,218✔
1023

1024
                if (journal_fd >= 0) {
95,784✔
1025
                        char header[LINE_MAX];
84,157✔
1026
                        struct iovec *iovec;
84,157✔
1027
                        size_t n = 0, m, iovec_len;
84,157✔
1028
                        int r;
84,157✔
1029
                        bool fallback = false;
84,157✔
1030

1031
                        if (!MUL_SAFE(&iovec_len, log_context_num_fields(), 3) ||
84,157✔
1032
                            !ADD_SAFE(&iovec_len, iovec_len, 17))
84,157✔
1033
                                iovec_len = IOVEC_MAX;
1034
                        else
1035
                                iovec_len = MIN(iovec_len, IOVEC_MAX);
84,157✔
1036
                        iovec = newa(struct iovec, iovec_len);
84,157✔
1037

1038
                        /* If the journal is available do structured logging.
1039
                         * Do not report the errno if it is synthetic. */
1040
                        log_do_header(header, sizeof(header), level, error, file, line, func, NULL, NULL, NULL, NULL);
84,157✔
1041
                        iovec[n++] = IOVEC_MAKE_STRING(header);
84,157✔
1042

1043
                        va_start(ap, format);
84,157✔
1044
                        DISABLE_WARNING_FORMAT_NONLITERAL;
84,157✔
1045
                        r = log_format_iovec(iovec, iovec_len, &n, true, error, format, ap);
84,157✔
1046
                        REENABLE_WARNING;
84,157✔
1047
                        m = n;
84,157✔
1048
                        if (r < 0)
84,157✔
1049
                                fallback = true;
1050
                        else {
1051
                                log_do_context(iovec, iovec_len, &n);
84,157✔
1052

1053
                                const struct msghdr msghdr = {
84,157✔
1054
                                        .msg_iov = iovec,
1055
                                        .msg_iovlen = n,
1056
                                };
1057

1058
                                (void) sendmsg(journal_fd, &msghdr, MSG_NOSIGNAL);
84,157✔
1059
                        }
1060

1061
                        va_end(ap);
84,157✔
1062
                        for (size_t i = 1; i < m; i += 2)
504,013✔
1063
                                free(iovec[i].iov_base);
419,856✔
1064

1065
                        if (!fallback) {
84,157✔
1066
                                if (open_when_needed)
84,157✔
1067
                                        log_close();
11,205✔
1068

1069
                                return -ERRNO_VALUE(error);
84,157✔
1070
                        }
1071
                }
1072
        }
1073

1074
        /* Fallback if journal logging is not available or didn't work. */
1075

1076
        va_start(ap, format);
13,623✔
1077
        while (format) {
40,340✔
1078
                va_list aq;
40,340✔
1079

1080
                errno = ERRNO_VALUE(error);
40,340✔
1081

1082
                va_copy(aq, ap);
40,340✔
1083
                DISABLE_WARNING_FORMAT_NONLITERAL;
40,340✔
1084
                (void) vsnprintf(buf, sizeof buf, format, aq);
40,340✔
1085
                REENABLE_WARNING;
40,340✔
1086
                va_end(aq);
40,340✔
1087

1088
                if (startswith(buf, "MESSAGE=")) {
40,340✔
1089
                        found = true;
13,623✔
1090
                        break;
13,623✔
1091
                }
1092

1093
                VA_FORMAT_ADVANCE(format, ap);
71,886✔
1094

1095
                format = va_arg(ap, char *);
26,717✔
1096
        }
1097
        va_end(ap);
13,623✔
1098

1099
        if (!found) {
13,623✔
UNCOV
1100
                if (open_when_needed)
×
UNCOV
1101
                        log_close();
×
1102

UNCOV
1103
                return -ERRNO_VALUE(error);
×
1104
        }
1105

1106
        return log_dispatch_internal(level, error, file, line, func, NULL, NULL, NULL, NULL, buf + 8);
13,623✔
1107
}
1108

1109
int log_struct_iovec_internal(
3,872✔
1110
                int level,
1111
                int error,
1112
                const char *file,
1113
                int line,
1114
                const char *func,
1115
                const struct iovec input_iovec[],
1116
                size_t n_input_iovec) {
1117

1118
        PROTECT_ERRNO;
3,872✔
1119

1120
        if (_likely_(LOG_PRI(level) > log_max_level) ||
3,872✔
1121
            log_target == LOG_TARGET_NULL)
3,872✔
UNCOV
1122
                return -ERRNO_VALUE(error);
×
1123

1124
        if (LOG_FAC(level) == 0)
3,872✔
1125
                level |= log_facility;
3,872✔
1126

1127
        if (IN_SET(log_target, LOG_TARGET_AUTO,
3,872✔
1128
                               LOG_TARGET_JOURNAL_OR_KMSG,
1129
                               LOG_TARGET_JOURNAL) &&
3,872✔
1130
            journal_fd >= 0) {
3,872✔
1131

1132
                char header[LINE_MAX];
3,816✔
1133
                struct iovec *iovec;
3,816✔
1134
                size_t n = 0, iovec_len, n_context_iovec, n_input_iovec_expanded;
3,816✔
1135

1136
                if (!MUL_SAFE(&n_input_iovec_expanded, n_input_iovec, 2) ||
3,816✔
1137
                    !MUL_SAFE(&n_context_iovec, log_context_num_fields(), 3) ||
3,816✔
1138
                    !ADD_SAFE(&iovec_len, 1, n_input_iovec_expanded) ||
3,816✔
1139
                    !ADD_SAFE(&iovec_len, iovec_len, n_context_iovec))
3,816✔
1140
                        iovec_len = IOVEC_MAX;
1141
                else
1142
                        iovec_len = MIN(iovec_len, IOVEC_MAX);
3,816✔
1143
                iovec = newa(struct iovec, iovec_len);
3,816✔
1144

1145
                log_do_header(header, sizeof(header), level, error, file, line, func, NULL, NULL, NULL, NULL);
3,816✔
1146

1147
                iovec[n++] = IOVEC_MAKE_STRING(header);
3,816✔
1148
                for (size_t i = 0; i < n_input_iovec && n + 2 <= iovec_len; i++) {
30,590✔
1149
                        iovec[n++] = input_iovec[i];
26,774✔
1150
                        iovec[n++] = IOVEC_MAKE_STRING("\n");
26,774✔
1151
                }
1152

1153
                log_do_context(iovec, iovec_len, &n);
3,816✔
1154

1155
                const struct msghdr msghdr = {
3,816✔
1156
                        .msg_iov = iovec,
1157
                        .msg_iovlen = n,
1158
                };
1159

1160
                if (sendmsg(journal_fd, &msghdr, MSG_NOSIGNAL) >= 0)
3,816✔
1161
                        return -ERRNO_VALUE(error);
3,813✔
1162
        }
1163

1164
        for (size_t i = 0; i < n_input_iovec; i++)
236✔
1165
                if (memory_startswith(input_iovec[i].iov_base, input_iovec[i].iov_len, "MESSAGE=")) {
236✔
1166
                        char *m;
59✔
1167

1168
                        m = strndupa_safe((char*) input_iovec[i].iov_base + STRLEN("MESSAGE="),
59✔
1169
                                          input_iovec[i].iov_len - STRLEN("MESSAGE="));
1170

1171
                        return log_dispatch_internal(level, error, file, line, func, NULL, NULL, NULL, NULL, m);
59✔
1172
                }
1173

1174
        /* Couldn't find MESSAGE=. */
UNCOV
1175
        return -ERRNO_VALUE(error);
×
1176
}
1177

1178
int log_set_target_from_string(const char *e) {
13,622✔
1179
        LogTarget t;
13,622✔
1180

1181
        t = log_target_from_string(e);
13,622✔
1182
        if (t < 0)
13,622✔
1183
                return t;
1184

1185
        log_set_target(t);
13,622✔
1186
        return 0;
13,622✔
1187
}
1188

1189
int log_set_max_level_from_string(const char *e) {
33,097✔
1190
        int r;
88,703✔
1191

1192
        for (;;) {
88,703✔
1193
                _cleanup_free_ char *word = NULL, *prefix = NULL;
88,703✔
1194
                LogTarget target;
88,703✔
1195
                const char *colon;
88,703✔
1196

1197
                r = extract_first_word(&e, &word, ",", 0);
88,703✔
1198
                if (r < 0)
88,703✔
1199
                        return r;
1200
                if (r == 0)
88,703✔
1201
                        break;
1202

1203
                colon = strchr(word, ':');
55,606✔
1204
                if (!colon) {
55,606✔
1205
                        r = log_level_from_string(word);
33,097✔
1206
                        if (r < 0)
33,097✔
1207
                                return r;
1208

1209
                        log_set_max_level(r);
33,097✔
1210
                        continue;
33,097✔
1211
                }
1212

1213
                prefix = strndup(word, colon - word);
22,509✔
1214
                if (!prefix)
22,509✔
1215
                        return -ENOMEM;
1216

1217
                target = log_target_from_string(prefix);
22,509✔
1218
                if (target < 0)
22,509✔
1219
                        return target;
1220

1221
                if (target >= _LOG_TARGET_SINGLE_MAX)
22,509✔
1222
                        return -EINVAL;
1223

1224
                r = log_level_from_string(colon + 1);
22,509✔
1225
                if (r < 0)
22,509✔
1226
                        return r;
1227

1228
                log_target_max_level[target] = r;
22,509✔
1229
        }
1230

1231
        return 0;
33,097✔
1232
}
1233

1234
int log_max_levels_to_string(int level, char **ret) {
4,978✔
1235
        _cleanup_free_ char *s = NULL;
4,978✔
1236
        int r;
4,978✔
1237

1238
        assert(ret);
4,978✔
1239

1240
        r = log_level_to_string_alloc(level, &s);
4,978✔
1241
        if (r < 0)
4,978✔
1242
                return r;
1243

1244
        for (LogTarget target = 0; target < _LOG_TARGET_SINGLE_MAX; target++) {
24,890✔
1245
                _cleanup_free_ char *l = NULL;
4,978✔
1246

1247
                if (log_target_max_level[target] == INT_MAX)
19,912✔
1248
                        continue;
14,934✔
1249

1250
                r = log_level_to_string_alloc(log_target_max_level[target], &l);
4,978✔
1251
                if (r < 0)
4,978✔
1252
                        return r;
1253

1254
                r = strextendf_with_separator(&s, ",", "%s:%s", log_target_to_string(target), l);
4,978✔
1255
                if (r < 0)
4,978✔
1256
                        return r;
1257
        }
1258

1259
        *ret = TAKE_PTR(s);
4,978✔
1260
        return 0;
4,978✔
1261
}
1262

1263
static int log_set_ratelimit_kmsg_from_string(const char *e) {
9,638✔
1264
        int r;
9,638✔
1265

1266
        r = parse_boolean(e);
9,638✔
1267
        if (r < 0)
9,638✔
1268
                return r;
1269

1270
        ratelimit_kmsg = r;
9,638✔
1271
        return 0;
9,638✔
1272
}
1273

1274
static int parse_proc_cmdline_item(const char *key, const char *value, void *data) {
341,559✔
1275

1276
        /*
1277
         * The systemd.log_xyz= settings are parsed by all tools, and
1278
         * so is "debug".
1279
         *
1280
         * However, "quiet" is only parsed by PID 1, and only turns of
1281
         * status output to /dev/console, but does not alter the log
1282
         * level.
1283
         */
1284

1285
        if (streq(key, "debug") && !value)
341,559✔
UNCOV
1286
                log_set_max_level(LOG_DEBUG);
×
1287

1288
        else if (proc_cmdline_key_streq(key, "systemd.log_target")) {
341,559✔
1289

UNCOV
1290
                if (proc_cmdline_value_missing(key, value))
×
1291
                        return 0;
1292

1293
                if (log_set_target_from_string(value) < 0)
×
UNCOV
1294
                        log_warning("Failed to parse log target '%s', ignoring.", value);
×
1295

1296
        } else if (proc_cmdline_key_streq(key, "systemd.log_level")) {
341,559✔
1297

1298
                if (proc_cmdline_value_missing(key, value))
9,638✔
1299
                        return 0;
1300

1301
                if (log_set_max_level_from_string(value) < 0)
9,638✔
1302
                        log_warning("Failed to parse log level setting '%s', ignoring.", value);
×
1303

1304
        } else if (proc_cmdline_key_streq(key, "systemd.log_color")) {
331,921✔
1305

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

1309
        } else if (proc_cmdline_key_streq(key, "systemd.log_location")) {
331,921✔
1310

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

1314
        } else if (proc_cmdline_key_streq(key, "systemd.log_tid")) {
331,921✔
1315

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

1319
        } else if (proc_cmdline_key_streq(key, "systemd.log_time")) {
331,921✔
1320

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

1324
        } else if (proc_cmdline_key_streq(key, "systemd.log_ratelimit_kmsg")) {
331,921✔
1325

1326
                if (log_set_ratelimit_kmsg_from_string(value ?: "1") < 0)
9,638✔
UNCOV
1327
                        log_warning("Failed to parse log ratelimit kmsg boolean '%s', ignoring.", value);
×
1328
        }
1329

1330
        return 0;
1331
}
1332

1333
static bool should_parse_proc_cmdline(void) {
85,052✔
1334
        /* PID1 always reads the kernel command line. */
1335
        if (getpid_cached() == 1)
85,052✔
1336
                return true;
1337

1338
        /* Otherwise, parse the command line if invoked directly by systemd. */
1339
        return invoked_by_systemd();
84,799✔
1340
}
1341

1342
void log_parse_environment_variables(void) {
87,830✔
1343
        const char *e;
87,830✔
1344
        int r;
87,830✔
1345

1346
        e = getenv("SYSTEMD_LOG_TARGET");
87,830✔
1347
        if (e && log_set_target_from_string(e) < 0)
87,830✔
UNCOV
1348
                log_warning("Failed to parse log target '%s', ignoring.", e);
×
1349

1350
        e = getenv("SYSTEMD_LOG_LEVEL");
87,830✔
1351
        if (e) {
87,830✔
1352
                r = log_set_max_level_from_string(e);
9,577✔
1353
                if (r < 0)
9,577✔
UNCOV
1354
                        log_warning_errno(r, "Failed to parse log level '%s', ignoring: %m", e);
×
1355
        } else {
1356
                /* If no explicit log level is specified then let's see if this is a debug invocation, and if
1357
                 * so raise the log level to debug too. Note that this is not symmetric: just because
1358
                 * DEBUG_INVOCATION is explicitly set to 0 we won't lower the log level below debug. This
1359
                 * follows the logic that debug logging is an opt-in thing anyway, and if there's any reason
1360
                 * to enable it we should not disable it here automatically. */
1361
                r = getenv_bool("DEBUG_INVOCATION");
78,253✔
1362
                if (r < 0 && r != -ENXIO)
78,253✔
UNCOV
1363
                        log_warning_errno(r, "Failed to parse $DEBUG_INVOCATION value, ignoring: %m");
×
1364
                else if (r > 0)
78,253✔
UNCOV
1365
                        log_set_max_level(LOG_DEBUG);
×
1366
        }
1367

1368
        e = getenv("SYSTEMD_LOG_COLOR");
87,830✔
1369
        if (e && log_show_color_from_string(e) < 0)
87,830✔
UNCOV
1370
                log_warning("Failed to parse log color '%s', ignoring.", e);
×
1371

1372
        e = getenv("SYSTEMD_LOG_LOCATION");
87,830✔
1373
        if (e && log_show_location_from_string(e) < 0)
87,830✔
UNCOV
1374
                log_warning("Failed to parse log location '%s', ignoring.", e);
×
1375

1376
        e = getenv("SYSTEMD_LOG_TIME");
87,830✔
1377
        if (e && log_show_time_from_string(e) < 0)
87,830✔
UNCOV
1378
                log_warning("Failed to parse log time '%s', ignoring.", e);
×
1379

1380
        e = getenv("SYSTEMD_LOG_TID");
87,830✔
1381
        if (e && log_show_tid_from_string(e) < 0)
87,830✔
UNCOV
1382
                log_warning("Failed to parse log tid '%s', ignoring.", e);
×
1383

1384
        e = getenv("SYSTEMD_LOG_RATELIMIT_KMSG");
87,830✔
1385
        if (e && log_set_ratelimit_kmsg_from_string(e) < 0)
87,830✔
UNCOV
1386
                log_warning("Failed to parse log ratelimit kmsg boolean '%s', ignoring.", e);
×
1387
}
87,830✔
1388

1389
void log_parse_environment(void) {
85,052✔
1390
        /* Do not call from library code. */
1391

1392
        if (should_parse_proc_cmdline())
85,052✔
1393
                (void) proc_cmdline_parse(parse_proc_cmdline_item, NULL, PROC_CMDLINE_STRIP_RD_PREFIX);
9,714✔
1394

1395
        log_parse_environment_variables();
85,052✔
1396
}
85,052✔
1397

1398
LogTarget log_get_target(void) {
27,430✔
1399
        return log_target;
27,430✔
1400
}
1401

1402
void log_settle_target(void) {
22,973✔
1403

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

1410
        LogTarget t = log_get_target();
22,973✔
1411

1412
        if (t != LOG_TARGET_AUTO)
22,973✔
1413
                return;
1414

1415
        t = getpid_cached() == 1 || stderr_is_journal() ? (prohibit_ipc ? LOG_TARGET_KMSG : LOG_TARGET_JOURNAL_OR_KMSG)
30,735✔
1416
                                                        : LOG_TARGET_CONSOLE;
20,394✔
1417
        log_set_target(t);
10,341✔
1418
}
1419

1420
int log_get_max_level(void) {
20,282,310✔
1421
        return log_max_level;
20,282,310✔
1422
}
1423

1424
int log_get_target_max_level(LogTarget target) {
16✔
1425
        assert(target >= 0);
16✔
1426
        assert(target < _LOG_TARGET_SINGLE_MAX);
16✔
1427
        return log_target_max_level[target];
16✔
1428
}
1429

1430
void log_show_color(bool b) {
73,276✔
1431
        show_color = b;
73,276✔
1432
}
73,276✔
1433

1434
bool log_get_show_color(void) {
290,747✔
1435
        return show_color > 0; /* Defaults to false. */
290,747✔
1436
}
1437

UNCOV
1438
void log_show_location(bool b) {
×
UNCOV
1439
        show_location = b;
×
UNCOV
1440
}
×
1441

1442
bool log_get_show_location(void) {
18✔
1443
        return show_location;
18✔
1444
}
1445

1446
void log_show_time(bool b) {
1✔
1447
        show_time = b;
1✔
1448
}
1✔
1449

1450
bool log_get_show_time(void) {
18✔
1451
        return show_time;
18✔
1452
}
1453

1454
void log_show_tid(bool b) {
1✔
1455
        show_tid = b;
1✔
1456
}
1✔
1457

UNCOV
1458
bool log_get_show_tid(void) {
×
1459
        return show_tid;
×
1460
}
1461

1462
int log_show_color_from_string(const char *e) {
×
1463
        int r;
×
1464

UNCOV
1465
        r = parse_boolean(e);
×
1466
        if (r < 0)
×
1467
                return r;
1468

UNCOV
1469
        log_show_color(r);
×
1470
        return 0;
×
1471
}
1472

1473
int log_show_location_from_string(const char *e) {
×
1474
        int r;
×
1475

UNCOV
1476
        r = parse_boolean(e);
×
1477
        if (r < 0)
×
1478
                return r;
1479

UNCOV
1480
        log_show_location(r);
×
1481
        return 0;
×
1482
}
1483

1484
int log_show_time_from_string(const char *e) {
×
1485
        int r;
×
1486

UNCOV
1487
        r = parse_boolean(e);
×
1488
        if (r < 0)
×
1489
                return r;
1490

UNCOV
1491
        log_show_time(r);
×
UNCOV
1492
        return 0;
×
1493
}
1494

UNCOV
1495
int log_show_tid_from_string(const char *e) {
×
UNCOV
1496
        int r;
×
1497

UNCOV
1498
        r = parse_boolean(e);
×
UNCOV
1499
        if (r < 0)
×
1500
                return r;
1501

UNCOV
1502
        log_show_tid(r);
×
UNCOV
1503
        return 0;
×
1504
}
1505

1506
bool log_on_console(void) {
112,821✔
1507
        if (IN_SET(log_target, LOG_TARGET_CONSOLE,
112,821✔
1508
                               LOG_TARGET_CONSOLE_PREFIXED))
1509
                return true;
1510

1511
        return syslog_fd < 0 && kmsg_fd < 0 && journal_fd < 0;
150,538✔
1512
}
1513

1514
static const char *const log_target_table[_LOG_TARGET_MAX] = {
1515
        [LOG_TARGET_CONSOLE]          = "console",
1516
        [LOG_TARGET_CONSOLE_PREFIXED] = "console-prefixed",
1517
        [LOG_TARGET_KMSG]             = "kmsg",
1518
        [LOG_TARGET_JOURNAL]          = "journal",
1519
        [LOG_TARGET_JOURNAL_OR_KMSG]  = "journal-or-kmsg",
1520
        [LOG_TARGET_SYSLOG]           = "syslog",
1521
        [LOG_TARGET_SYSLOG_OR_KMSG]   = "syslog-or-kmsg",
1522
        [LOG_TARGET_AUTO]             = "auto",
1523
        [LOG_TARGET_NULL]             = "null",
1524
};
1525

1526
DEFINE_STRING_TABLE_LOOKUP(log_target, LogTarget);
46,207✔
1527

1528
void log_received_signal(int level, const struct signalfd_siginfo *si) {
8,533✔
1529
        assert(si);
8,533✔
1530

1531
        if (si_code_from_process(si->ssi_code) && pid_is_valid(si->ssi_pid)) {
8,792✔
1532
                _cleanup_free_ char *p = NULL;
259✔
1533

1534
                (void) pid_get_comm(si->ssi_pid, &p);
259✔
1535

1536
                log_full(level,
259✔
1537
                         "Received SIG%s from PID %"PRIu32" (%s).",
1538
                         signal_to_string(si->ssi_signo),
1539
                         si->ssi_pid, strna(p));
1540
        } else
1541
                log_full(level,
8,274✔
1542
                         "Received SIG%s.",
1543
                         signal_to_string(si->ssi_signo));
1544
}
8,533✔
1545

1546
void set_log_syntax_callback(log_syntax_callback_t cb, void *userdata) {
1,042✔
1547
        assert(!log_syntax_callback || !cb);
1,042✔
1548
        assert(!log_syntax_callback_userdata || !userdata);
1,042✔
1549

1550
        log_syntax_callback = cb;
1,042✔
1551
        log_syntax_callback_userdata = userdata;
1,042✔
1552
}
1,042✔
1553

1554
int log_syntax_internal(
32,533✔
1555
                const char *unit,
1556
                int level,
1557
                const char *config_file,
1558
                unsigned config_line,
1559
                int error,
1560
                const char *file,
1561
                int line,
1562
                const char *func,
1563
                const char *format, ...) {
1564

1565
        PROTECT_ERRNO;
32,533✔
1566

1567
        if (log_syntax_callback)
32,533✔
1568
                log_syntax_callback(unit, level, log_syntax_callback_userdata);
1,518✔
1569

1570
        if (_likely_(LOG_PRI(level) > log_max_level) ||
32,533✔
1571
            log_target == LOG_TARGET_NULL)
32,533✔
1572
                return -ERRNO_VALUE(error);
30✔
1573

1574
        char buffer[LINE_MAX];
32,503✔
1575
        va_list ap;
32,503✔
1576
        const char *unit_fmt = NULL;
32,503✔
1577

1578
        errno = ERRNO_VALUE(error);
32,503✔
1579

1580
        va_start(ap, format);
32,503✔
1581
        (void) vsnprintf(buffer, sizeof buffer, format, ap);
32,503✔
1582
        va_end(ap);
32,503✔
1583

1584
        if (unit)
32,503✔
1585
                unit_fmt = getpid_cached() == 1 ? "UNIT=%s" : "USER_UNIT=%s";
24,362✔
1586

1587
        if (config_file) {
32,503✔
1588
                if (config_line > 0)
32,493✔
1589
                        return log_struct_internal(
25,665✔
1590
                                        level,
1591
                                        error,
1592
                                        file, line, func,
1593
                                        LOG_MESSAGE_ID(SD_MESSAGE_INVALID_CONFIGURATION_STR),
25,665✔
1594
                                        LOG_ITEM("CONFIG_FILE=%s", config_file),
25,665✔
1595
                                        LOG_ITEM("CONFIG_LINE=%u", config_line),
25,665✔
1596
                                        LOG_MESSAGE("%s:%u: %s", config_file, config_line, buffer),
25,665✔
1597
                                        unit_fmt, unit,
1598
                                        NULL);
1599
                else
1600
                        return log_struct_internal(
6,828✔
1601
                                        level,
1602
                                        error,
1603
                                        file, line, func,
1604
                                        LOG_MESSAGE_ID(SD_MESSAGE_INVALID_CONFIGURATION_STR),
6,828✔
1605
                                        LOG_ITEM("CONFIG_FILE=%s", config_file),
6,828✔
1606
                                        LOG_MESSAGE("%s: %s", config_file, buffer),
6,828✔
1607
                                        unit_fmt, unit,
1608
                                        NULL);
1609
        } else if (unit)
10✔
UNCOV
1610
                return log_struct_internal(
×
1611
                                level,
1612
                                error,
1613
                                file, line, func,
UNCOV
1614
                                LOG_MESSAGE_ID(SD_MESSAGE_INVALID_CONFIGURATION_STR),
×
UNCOV
1615
                                LOG_MESSAGE("%s: %s", unit, buffer),
×
1616
                                unit_fmt, unit,
1617
                                NULL);
1618
        else
1619
                return log_struct_internal(
10✔
1620
                                level,
1621
                                error,
1622
                                file, line, func,
1623
                                LOG_MESSAGE_ID(SD_MESSAGE_INVALID_CONFIGURATION_STR),
10✔
1624
                                LOG_MESSAGE("%s", buffer),
10✔
1625
                                NULL);
1626
}
1627

1628
int log_syntax_invalid_utf8_internal(
9✔
1629
                const char *unit,
1630
                int level,
1631
                const char *config_file,
1632
                unsigned config_line,
1633
                const char *file,
1634
                int line,
1635
                const char *func,
1636
                const char *rvalue) {
1637

UNCOV
1638
        PROTECT_ERRNO;
×
1639
        _cleanup_free_ char *p = NULL;
9✔
1640

1641
        if (rvalue)
9✔
1642
                p = utf8_escape_invalid(rvalue);
9✔
1643

1644
        return log_syntax_internal(unit, level, config_file, config_line,
9✔
1645
                                   SYNTHETIC_ERRNO(EINVAL), file, line, func,
1646
                                   "String is not UTF-8 clean, ignoring assignment: %s", strna(p));
1647
}
1648

1649
int log_syntax_parse_error_internal(
135✔
1650
                const char *unit,
1651
                const char *config_file,
1652
                unsigned config_line,
1653
                int error,
1654
                bool critical,
1655
                const char *file,
1656
                int line,
1657
                const char *func,
1658
                const char *lvalue,
1659
                const char *rvalue) {
1660

UNCOV
1661
        PROTECT_ERRNO;
×
1662
        _cleanup_free_ char *escaped = NULL;
135✔
1663

1664
        /* OOM is always handled as critical. */
1665
        if (ERRNO_VALUE(error) == ENOMEM)
135✔
UNCOV
1666
                return log_oom_internal(LOG_ERR, file, line, func);
×
1667

1668
        if (rvalue && !utf8_is_valid(rvalue)) {
270✔
UNCOV
1669
                escaped = utf8_escape_invalid(rvalue);
×
UNCOV
1670
                if (!escaped)
×
1671
                        rvalue = "(oom)";
1672
                else
UNCOV
1673
                        rvalue = " (escaped)";
×
1674
        }
1675

1676
        log_syntax_internal(unit, critical ? LOG_ERR : LOG_WARNING, config_file, config_line, error,
675✔
1677
                            file, line, func,
1678
                            "Failed to parse %s=%s%s%s%s%s",
1679
                            strna(lvalue), strempty(escaped), strempty(rvalue),
1680
                            critical ? "" : ", ignoring",
1681
                            error == 0 ? "." : ": ",
1682
                            error == 0 ? "" : STRERROR(error));
135✔
1683

1684
        return critical ? -ERRNO_VALUE(error) : 0;
135✔
1685
}
1686

1687
void log_set_upgrade_syslog_to_journal(bool b) {
289✔
1688
        upgrade_syslog_to_journal = b;
289✔
1689

1690
        /* Make the change effective immediately */
1691
        if (b) {
289✔
1692
                if (log_target == LOG_TARGET_SYSLOG)
289✔
UNCOV
1693
                        log_target = LOG_TARGET_JOURNAL;
×
1694
                else if (log_target == LOG_TARGET_SYSLOG_OR_KMSG)
289✔
UNCOV
1695
                        log_target = LOG_TARGET_JOURNAL_OR_KMSG;
×
1696
        }
1697
}
289✔
1698

1699
void log_set_always_reopen_console(bool b) {
13,160✔
1700
        always_reopen_console = b;
13,160✔
1701
}
13,160✔
1702

1703
void log_set_open_when_needed(bool b) {
35,577✔
1704
        open_when_needed = b;
35,577✔
1705
}
35,577✔
1706

1707
void log_set_prohibit_ipc(bool b) {
51,877✔
1708
        prohibit_ipc = b;
51,877✔
1709
}
51,877✔
1710

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

1715
        return getpid_cached() == 1 ? LOG_EMERG : LOG_ERR;
×
1716
}
1717

1718
int log_dup_console(void) {
118✔
1719
        int copy;
118✔
1720

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

1724
        if (console_fd < 0 || console_fd >= 3)
118✔
1725
                return 0;
1726

1727
        copy = fcntl(console_fd, F_DUPFD_CLOEXEC, 3);
1✔
1728
        if (copy < 0)
1✔
UNCOV
1729
                return -errno;
×
1730

1731
        console_fd = copy;
1✔
1732
        return 0;
1✔
1733
}
1734

1735
void log_setup(void) {
84,151✔
1736
        log_set_target(LOG_TARGET_AUTO);
84,151✔
1737
        log_parse_environment();
84,151✔
1738
        (void) log_open();
84,151✔
1739
        if (log_on_console() && show_color < 0)
84,151✔
1740
                log_show_color(true);
73,151✔
1741
}
84,151✔
1742

1743
const char* _log_set_prefix(const char *prefix, bool force) {
3,735,784✔
1744
        const char *old = log_prefix;
3,735,784✔
1745

1746
        if (prefix || force)
3,735,784✔
1747
                log_prefix = prefix;
3,733,858✔
1748

1749
        return old;
3,735,784✔
1750
}
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