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

systemd / systemd / 15057632786

15 May 2025 09:01PM UTC coverage: 72.267% (+0.02%) from 72.244%
15057632786

push

github

bluca
man: document how to hook stuff into system wakeup

Fixes: #6364

298523 of 413084 relevant lines covered (72.27%)

738132.88 hits per line

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

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

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

17
#include "sd-messages.h"
18

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

48
#define SNDBUF_SIZE (8*1024*1024)
49
#define IOVEC_MAX 256U
50

51
static log_syntax_callback_t log_syntax_callback = NULL;
52
static void *log_syntax_callback_userdata = NULL;
53

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

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

71
static bool syslog_is_stream = false;
72

73
static int show_color = -1; /* tristate */
74
static bool show_location = false;
75
static bool show_time = false;
76
static bool show_tid = false;
77

78
static bool upgrade_syslog_to_journal = false;
79
static bool always_reopen_console = false;
80
static bool open_when_needed = false;
81
static bool prohibit_ipc = false;
82

83
static thread_local const char *log_prefix = NULL;
84

85
#if LOG_MESSAGE_VERIFICATION || defined(__COVERITY__)
86
bool _log_message_dummy = false; /* Always false */
87
#endif
88

89
/* An assert to use in logging functions that does not call recursively
90
 * into our logging functions (since that might lead to a loop). */
91
#define assert_raw(expr)                                                \
92
        do {                                                            \
93
                if (_unlikely_(!(expr))) {                              \
94
                        fputs(#expr "\n", stderr);                      \
95
                        abort();                                        \
96
                }                                                       \
97
        } while (false)
98

99
static void log_close_console(void) {
347,316✔
100
        /* See comment in log_close_journal() */
101
        (void) safe_close_above_stdio(TAKE_FD(console_fd));
347,316✔
102
        console_fd_is_tty = -1;
347,316✔
103
}
347,316✔
104

105
static int log_open_console(void) {
89,516✔
106

107
        if (!always_reopen_console) {
89,516✔
108
                console_fd = STDERR_FILENO;
70,424✔
109
                console_fd_is_tty = -1;
70,424✔
110
                return 0;
70,424✔
111
        }
112

113
        if (console_fd < 3) {
19,092✔
114
                int fd;
16,821✔
115

116
                fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
16,821✔
117
                if (fd < 0)
16,821✔
118
                        return fd;
119

120
                console_fd = fd_move_above_stdio(fd);
14,911✔
121
                console_fd_is_tty = true;
14,911✔
122
        }
123

124
        return 0;
125
}
126

127
static void log_close_kmsg(void) {
180,566✔
128
        /* See comment in log_close_journal() */
129
        (void) safe_close(TAKE_FD(kmsg_fd));
180,566✔
130
}
180,566✔
131

132
static int log_open_kmsg(void) {
16,367✔
133

134
        if (kmsg_fd >= 0)
16,367✔
135
                return 0;
136

137
        kmsg_fd = open("/dev/kmsg", O_WRONLY|O_NOCTTY|O_CLOEXEC);
14,706✔
138
        if (kmsg_fd < 0)
14,706✔
139
                return -errno;
6,719✔
140

141
        kmsg_fd = fd_move_above_stdio(kmsg_fd);
7,987✔
142
        return 0;
7,987✔
143
}
144

145
static void log_close_syslog(void) {
436,828✔
146
        /* See comment in log_close_journal() */
147
        (void) safe_close(TAKE_FD(syslog_fd));
436,828✔
148
}
436,828✔
149

150
static int create_log_socket(int type) {
157,078✔
151
        struct timeval tv;
157,078✔
152
        int fd;
157,078✔
153

154
        fd = socket(AF_UNIX, type|SOCK_CLOEXEC, 0);
157,078✔
155
        if (fd < 0)
157,078✔
156
                return -errno;
×
157

158
        fd = fd_move_above_stdio(fd);
157,078✔
159
        (void) fd_inc_sndbuf(fd, SNDBUF_SIZE);
157,078✔
160

161
        /* We need a blocking fd here since we'd otherwise lose messages way too early. However, let's not hang forever
162
         * in the unlikely case of a deadlock. */
163
        if (getpid_cached() == 1)
157,078✔
164
                timeval_store(&tv, 10 * USEC_PER_MSEC);
335✔
165
        else
166
                timeval_store(&tv, 10 * USEC_PER_SEC);
156,743✔
167
        (void) setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
157,078✔
168

169
        return fd;
157,078✔
170
}
171

172
static int log_open_syslog(void) {
2✔
173
        int r;
2✔
174

175
        if (syslog_fd >= 0)
2✔
176
                return 0;
177

178
        syslog_fd = create_log_socket(SOCK_DGRAM);
2✔
179
        if (syslog_fd < 0) {
2✔
180
                r = syslog_fd;
×
181
                goto fail;
×
182
        }
183

184
        r = connect_unix_path(syslog_fd, AT_FDCWD, "/dev/log");
2✔
185
        if (r < 0) {
2✔
186
                safe_close(syslog_fd);
×
187

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

196
                r = connect_unix_path(syslog_fd, AT_FDCWD, "/dev/log");
×
197
                if (r < 0)
×
198
                        goto fail;
×
199

200
                syslog_is_stream = true;
×
201
        } else
202
                syslog_is_stream = false;
2✔
203

204
        return 0;
205

206
fail:
×
207
        log_close_syslog();
×
208
        return r;
×
209
}
210

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

219
static int log_open_journal(void) {
164,842✔
220
        int r;
164,842✔
221

222
        if (journal_fd >= 0)
164,842✔
223
                return 0;
224

225
        journal_fd = create_log_socket(SOCK_DGRAM);
157,076✔
226
        if (journal_fd < 0) {
157,076✔
227
                r = journal_fd;
×
228
                goto fail;
×
229
        }
230

231
        r = connect_unix_path(journal_fd, AT_FDCWD, "/run/systemd/journal/socket");
157,076✔
232
        if (r < 0)
157,076✔
233
                goto fail;
53✔
234

235
        return 0;
236

237
fail:
53✔
238
        log_close_journal();
53✔
239
        return r;
53✔
240
}
241

242
bool stderr_is_journal(void) {
248,445✔
243
        _cleanup_free_ char *w = NULL;
248,445✔
244
        const char *e;
248,445✔
245
        uint64_t dev, ino;
248,445✔
246
        struct stat st;
248,445✔
247

248
        e = getenv("JOURNAL_STREAM");
248,445✔
249
        if (!e)
248,445✔
250
                return false;
251

252
        if (extract_first_word(&e, &w, ":", EXTRACT_DONT_COALESCE_SEPARATORS) <= 0)
16,879✔
253
                return false;
254
        if (!e)
16,879✔
255
                return false;
256

257
        if (safe_atou64(w, &dev) < 0)
16,879✔
258
                return false;
259
        if (safe_atou64(e, &ino) < 0)
16,879✔
260
                return false;
261

262
        if (fstat(STDERR_FILENO, &st) < 0)
16,879✔
263
                return false;
264

265
        return st.st_dev == dev && st.st_ino == ino;
17,671✔
266
}
267

268
int log_open(void) {
256,264✔
269
        int r;
256,264✔
270

271
        /* Do not call from library code. */
272

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

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

283
        if (log_target == LOG_TARGET_NULL) {
256,264✔
284
                log_close_journal();
1✔
285
                log_close_syslog();
1✔
286
                log_close_console();
1✔
287
                return 0;
288
        }
289

290
        if (getpid_cached() == 1 ||
501,235✔
291
            stderr_is_journal() ||
244,972✔
292
            IN_SET(log_target,
232,150✔
293
                   LOG_TARGET_KMSG,
294
                   LOG_TARGET_JOURNAL,
295
                   LOG_TARGET_JOURNAL_OR_KMSG,
296
                   LOG_TARGET_SYSLOG,
297
                   LOG_TARGET_SYSLOG_OR_KMSG)) {
298

299
                if (!prohibit_ipc) {
175,128✔
300
                        if (IN_SET(log_target,
171,106✔
301
                                   LOG_TARGET_AUTO,
302
                                   LOG_TARGET_JOURNAL_OR_KMSG,
303
                                   LOG_TARGET_JOURNAL)) {
304

305
                                r = log_open_journal();
157,271✔
306
                                if (r >= 0) {
157,271✔
307
                                        log_close_syslog();
157,231✔
308
                                        log_close_console();
157,231✔
309
                                        return r;
310
                                }
311
                        }
312

313
                        if (IN_SET(log_target,
13,875✔
314
                                   LOG_TARGET_SYSLOG_OR_KMSG,
315
                                   LOG_TARGET_SYSLOG)) {
316

317
                                r = log_open_syslog();
2✔
318
                                if (r >= 0) {
2✔
319
                                        log_close_journal();
2✔
320
                                        log_close_console();
2✔
321
                                        return r;
322
                                }
323
                        }
324
                }
325

326
                if (IN_SET(log_target, LOG_TARGET_AUTO,
17,895✔
327
                                       LOG_TARGET_JOURNAL_OR_KMSG,
328
                                       LOG_TARGET_SYSLOG_OR_KMSG,
329
                                       LOG_TARGET_KMSG)) {
330
                        r = log_open_kmsg();
16,233✔
331
                        if (r >= 0) {
16,233✔
332
                                log_close_journal();
9,515✔
333
                                log_close_syslog();
9,515✔
334
                                log_close_console();
9,515✔
335
                                return r;
336
                        }
337
                }
338
        }
339

340
        log_close_journal();
89,515✔
341
        log_close_syslog();
89,515✔
342

343
        return log_open_console();
89,515✔
344
}
345

346
void log_set_target(LogTarget target) {
107,447✔
347
        assert(target >= 0);
107,447✔
348
        assert(target < _LOG_TARGET_MAX);
107,447✔
349

350
        if (upgrade_syslog_to_journal) {
107,447✔
351
                if (target == LOG_TARGET_SYSLOG)
312✔
352
                        target = LOG_TARGET_JOURNAL;
353
                else if (target == LOG_TARGET_SYSLOG_OR_KMSG)
312✔
354
                        target = LOG_TARGET_JOURNAL_OR_KMSG;
×
355
        }
356

357
        log_target = target;
107,447✔
358
}
107,447✔
359

360
void log_set_target_and_open(LogTarget target) {
281✔
361
        log_set_target(target);
281✔
362
        log_open();
281✔
363
}
281✔
364

365
void log_close(void) {
180,566✔
366
        /* Do not call from library code. */
367

368
        log_close_journal();
180,566✔
369
        log_close_syslog();
180,566✔
370
        log_close_kmsg();
180,566✔
371
        log_close_console();
180,566✔
372
}
180,566✔
373

374
void log_forget_fds(void) {
11,548✔
375
        /* Do not call from library code. */
376

377
        console_fd = kmsg_fd = syslog_fd = journal_fd = -EBADF;
11,548✔
378
        console_fd_is_tty = -1;
11,548✔
379
}
11,548✔
380

381
int log_set_max_level(int level) {
699,322✔
382
        assert(level == LOG_NULL || log_level_is_valid(level));
699,322✔
383

384
        int old = log_max_level;
699,322✔
385
        log_max_level = level;
699,322✔
386

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

395
        /* Ensure that our own LOG_NULL define maps sanely to the log mask */
396
        assert_cc(LOG_UPTO(LOG_NULL) == 0);
699,322✔
397

398
        return old;
699,322✔
399
}
400

401
void log_set_facility(int facility) {
246✔
402
        log_facility = facility;
246✔
403
}
246✔
404

405
static bool check_console_fd_is_tty(void) {
160,237✔
406
        if (console_fd < 0)
160,237✔
407
                return false;
408

409
        if (console_fd_is_tty < 0)
160,237✔
410
                console_fd_is_tty = isatty_safe(console_fd);
11,291✔
411

412
        return console_fd_is_tty;
160,237✔
413
}
414

415
static int write_to_console(
244,332✔
416
                int level,
417
                int error,
418
                const char *file,
419
                int line,
420
                const char *func,
421
                const char *buffer) {
422

423
        static int dumb = -1;
244,332✔
424

425
        char location[256],
244,332✔
426
             header_time[FORMAT_TIMESTAMP_MAX],
427
             prefix[1 + DECIMAL_STR_MAX(int) + 2],
428
             tid_string[3 + DECIMAL_STR_MAX(pid_t) + 1];
429
        struct iovec iovec[11];
244,332✔
430
        const char *on = NULL, *off = NULL;
244,332✔
431
        size_t n = 0;
244,332✔
432

433
        if (console_fd < 0)
244,332✔
434
                return 0;
244,332✔
435

436
        if (dumb < 0)
237,022✔
437
                dumb = getenv_terminal_is_dumb();
12,228✔
438

439
        if (LOG_PRI(level) > log_target_max_level[LOG_TARGET_CONSOLE])
237,022✔
440
                return 0;
441

442
        if (log_target == LOG_TARGET_CONSOLE_PREFIXED) {
160,237✔
443
                xsprintf(prefix, "<%i>", level);
396✔
444
                iovec[n++] = IOVEC_MAKE_STRING(prefix);
396✔
445
        }
446

447
        if (show_time &&
160,237✔
448
            format_timestamp(header_time, sizeof(header_time), now(CLOCK_REALTIME))) {
×
449
                iovec[n++] = IOVEC_MAKE_STRING(header_time);
×
450
                iovec[n++] = IOVEC_MAKE_STRING(" ");
×
451
        }
452

453
        if (show_tid) {
160,237✔
454
                xsprintf(tid_string, "(" PID_FMT ") ", gettid());
×
455
                iovec[n++] = IOVEC_MAKE_STRING(tid_string);
×
456
        }
457

458
        if (log_get_show_color())
160,237✔
459
                get_log_colors(LOG_PRI(level), &on, &off, NULL);
147,131✔
460

461
        if (show_location) {
160,237✔
462
                const char *lon = "", *loff = "";
×
463
                if (log_get_show_color()) {
×
464
                        lon = ansi_highlight_yellow4();
×
465
                        loff = ansi_normal();
×
466
                }
467

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

472
        if (on)
160,237✔
473
                iovec[n++] = IOVEC_MAKE_STRING(on);
137,389✔
474
        if (log_prefix) {
160,237✔
475
                iovec[n++] = IOVEC_MAKE_STRING(log_prefix);
7,060✔
476
                iovec[n++] = IOVEC_MAKE_STRING(": ");
7,060✔
477
        }
478
        iovec[n++] = IOVEC_MAKE_STRING(buffer);
160,237✔
479
        if (off)
160,237✔
480
                iovec[n++] = IOVEC_MAKE_STRING(off);
137,389✔
481

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

489
        if (writev(console_fd, iovec, n) < 0) {
160,237✔
490

491
                if (errno == EIO && getpid_cached() == 1) {
84✔
492

493
                        /* If somebody tried to kick us from our console tty (via vhangup() or suchlike), try
494
                         * to reconnect. */
495

496
                        log_close_console();
1✔
497
                        (void) log_open_console();
1✔
498
                        if (console_fd < 0)
1✔
499
                                return 0;
500

501
                        if (writev(console_fd, iovec, n) < 0)
1✔
502
                                return -errno;
×
503
                } else
504
                        return -errno;
83✔
505
        }
506

507
        return 1;
508
}
509

510
static int write_to_syslog(
180✔
511
                int level,
512
                int error,
513
                const char *file,
514
                int line,
515
                const char *func,
516
                const char *buffer) {
517

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

524
        if (syslog_fd < 0)
180✔
525
                return 0;
180✔
526

527
        if (LOG_PRI(level) > log_target_max_level[LOG_TARGET_SYSLOG])
180✔
528
                return 0;
529

530
        xsprintf(header_priority, "<%i>", level);
180✔
531

532
        r = localtime_or_gmtime_usec(now(CLOCK_REALTIME), /* utc= */ false, &tm);
180✔
533
        if (r < 0)
180✔
534
                return r;
535

536
        if (strftime(header_time, sizeof(header_time), "%h %e %T ", &tm) <= 0)
180✔
537
                return -EINVAL;
538

539
        xsprintf(header_pid, "["PID_FMT"]: ", getpid_cached());
180✔
540

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

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

559
        for (;;) {
180✔
560
                ssize_t n;
180✔
561

562
                n = sendmsg(syslog_fd, &msghdr, MSG_NOSIGNAL);
180✔
563
                if (n < 0)
180✔
564
                        return -errno;
×
565

566
                if (!syslog_is_stream)
180✔
567
                        break;
568

569
                if (iovec_increment(iovec, ELEMENTSOF(iovec), n))
×
570
                        break;
571
        }
572

573
        return 1;
574
}
575

576
static int write_to_kmsg(
211,511✔
577
                int level,
578
                int error,
579
                const char *file,
580
                int line,
581
                const char *func,
582
                const char *buffer) {
583

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

593
        char header_priority[2 + DECIMAL_STR_MAX(int) + 1],
211,511✔
594
             header_pid[4 + DECIMAL_STR_MAX(pid_t) + 1];
595

596
        if (kmsg_fd < 0)
211,511✔
597
                return 0;
211,511✔
598

599
        if (LOG_PRI(level) > log_target_max_level[LOG_TARGET_KMSG])
40,684✔
600
                return 0;
601

602
        if (ratelimit_kmsg && !ratelimit_below(&ratelimit)) {
40,684✔
603
                if (ratelimit_num_dropped(&ratelimit) > 1)
×
604
                        return 0;
605

606
                buffer = "Too many messages being logged to kmsg, ignoring";
607
        }
608

609
        xsprintf(header_priority, "<%i>", level);
40,684✔
610
        xsprintf(header_pid, "["PID_FMT"]: ", getpid_cached());
40,684✔
611

612
        const struct iovec iovec[] = {
325,472✔
613
                IOVEC_MAKE_STRING(header_priority),
40,684✔
614
                IOVEC_MAKE_STRING(program_invocation_short_name),
40,684✔
615
                IOVEC_MAKE_STRING(header_pid),
40,684✔
616
                IOVEC_MAKE_STRING(strempty(log_prefix)),
62,143✔
617
                IOVEC_MAKE_STRING(log_prefix ? ": " : ""),
62,143✔
618
                IOVEC_MAKE_STRING(buffer),
40,684✔
619
                IOVEC_MAKE_STRING("\n"),
40,684✔
620
        };
621

622
        if (writev(kmsg_fd, iovec, ELEMENTSOF(iovec)) < 0)
40,684✔
623
                return -errno;
×
624

625
        return 1;
626
}
627

628
static int log_do_header(
4,875,457✔
629
                char *header,
630
                size_t size,
631
                int level,
632
                int error,
633
                const char *file, int line, const char *func,
634
                const char *object_field, const char *object,
635
                const char *extra_field, const char *extra) {
636
        int r;
4,875,457✔
637

638
        error = IS_SYNTHETIC_ERRNO(error) ? 0 : ERRNO_VALUE(error);
4,875,457✔
639

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

675
        return 0;
4,875,457✔
676
}
677

678
static void log_do_context(struct iovec *iovec, size_t iovec_len, size_t *n) {
4,875,457✔
679
        assert(iovec);
4,875,457✔
680
        assert(n);
4,875,457✔
681

682
        LIST_FOREACH(ll, c, log_context_head()) {
6,873,345✔
683
                STRV_FOREACH(s, c->fields) {
18,598,548✔
684
                        if (*n + 2 >= iovec_len)
16,470,250✔
685
                                return;
×
686

687
                        iovec[(*n)++] = IOVEC_MAKE_STRING(*s);
16,470,250✔
688
                        iovec[(*n)++] = IOVEC_MAKE_STRING("\n");
16,470,250✔
689
                }
690

691
                for (size_t i = 0; i < c->n_input_iovec; i++) {
2,131,909✔
692
                        if (*n + 2 >= iovec_len)
3,611✔
693
                                return;
×
694

695
                        iovec[(*n)++] = c->input_iovec[i];
3,611✔
696
                        iovec[(*n)++] = IOVEC_MAKE_STRING("\n");
3,611✔
697
                }
698

699
                if (c->key && c->value) {
2,128,298✔
700
                        if (*n + 3 >= iovec_len)
285,332✔
701
                                return;
130,410✔
702

703
                        iovec[(*n)++] = IOVEC_MAKE_STRING(c->key);
154,922✔
704
                        iovec[(*n)++] = IOVEC_MAKE_STRING(c->value);
154,922✔
705
                        iovec[(*n)++] = IOVEC_MAKE_STRING("\n");
154,922✔
706
                }
707
        }
708
}
709

710
static int write_to_journal(
5,074,915✔
711
                int level,
712
                int error,
713
                const char *file,
714
                int line,
715
                const char *func,
716
                const char *object_field,
717
                const char *object,
718
                const char *extra_field,
719
                const char *extra,
720
                const char *buffer) {
721

722
        char header[LINE_MAX];
5,074,915✔
723
        size_t n = 0, iovec_len;
5,074,915✔
724
        struct iovec *iovec;
5,074,915✔
725

726
        if (journal_fd < 0)
5,074,915✔
727
                return 0;
5,074,915✔
728

729
        if (LOG_PRI(level) > log_target_max_level[LOG_TARGET_JOURNAL])
4,815,143✔
730
                return 0;
731

732
        iovec_len = MIN(6 + log_context_num_fields() * 3, IOVEC_MAX);
4,815,143✔
733
        iovec = newa(struct iovec, iovec_len);
4,815,143✔
734

735
        log_do_header(header, sizeof(header), level, error, file, line, func, object_field, object, extra_field, extra);
4,815,143✔
736

737
        iovec[n++] = IOVEC_MAKE_STRING(header);
4,815,143✔
738
        iovec[n++] = IOVEC_MAKE_STRING("MESSAGE=");
4,815,143✔
739
        if (log_prefix) {
4,815,143✔
740
                iovec[n++] = IOVEC_MAKE_STRING(log_prefix);
1,792,073✔
741
                iovec[n++] = IOVEC_MAKE_STRING(": ");
1,792,073✔
742
        }
743
        iovec[n++] = IOVEC_MAKE_STRING(buffer);
4,815,143✔
744
        iovec[n++] = IOVEC_MAKE_STRING("\n");
4,815,143✔
745

746
        log_do_context(iovec, iovec_len, &n);
4,815,143✔
747

748
        const struct msghdr msghdr = {
4,815,143✔
749
                .msg_iov = iovec,
750
                .msg_iovlen = n,
751
        };
752

753
        if (sendmsg(journal_fd, &msghdr, MSG_NOSIGNAL) < 0)
4,815,143✔
754
                return -errno;
184✔
755

756
        return 1;
757
}
758

759
int log_dispatch_internal(
5,090,787✔
760
                int level,
761
                int error,
762
                const char *file,
763
                int line,
764
                const char *func,
765
                const char *object_field,
766
                const char *object,
767
                const char *extra_field,
768
                const char *extra,
769
                char *buffer) {
770

771
        assert_raw(buffer);
5,090,787✔
772

773
        if (log_target == LOG_TARGET_NULL)
5,090,787✔
774
                return -ERRNO_VALUE(error);
10✔
775

776
        /* Patch in LOG_DAEMON facility if necessary */
777
        if (LOG_FAC(level) == 0)
5,090,777✔
778
                level |= log_facility;
5,082,476✔
779

780
        if (open_when_needed)
5,090,777✔
781
                (void) log_open();
140,703✔
782

783
        do {
5,145,511✔
784
                char *e;
5,145,511✔
785
                int k = 0;
5,145,511✔
786

787
                buffer += strspn(buffer, NEWLINE);
5,145,511✔
788

789
                if (buffer[0] == 0)
5,145,511✔
790
                        break;
791

792
                if ((e = strpbrk(buffer, NEWLINE)))
5,100,155✔
793
                        *(e++) = 0;
54,734✔
794

795
                if (IN_SET(log_target, LOG_TARGET_AUTO,
5,100,155✔
796
                                       LOG_TARGET_JOURNAL_OR_KMSG,
797
                                       LOG_TARGET_JOURNAL)) {
798

799
                        k = write_to_journal(level, error, file, line, func, object_field, object, extra_field, extra, buffer);
5,074,915✔
800
                        if (k < 0 && k != -EAGAIN)
5,074,915✔
801
                                log_close_journal();
4✔
802
                }
803

804
                if (IN_SET(log_target, LOG_TARGET_SYSLOG_OR_KMSG,
5,100,155✔
805
                                       LOG_TARGET_SYSLOG)) {
806

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

812
                if (k <= 0 &&
5,100,155✔
813
                    IN_SET(log_target, LOG_TARGET_AUTO,
285,016✔
814
                                       LOG_TARGET_SYSLOG_OR_KMSG,
815
                                       LOG_TARGET_JOURNAL_OR_KMSG,
816
                                       LOG_TARGET_KMSG)) {
817

818
                        if (k < 0)
211,511✔
819
                                log_open_kmsg();
134✔
820

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

828
                if (k <= 0)
285,016✔
829
                        (void) write_to_console(level, error, file, line, func, buffer);
244,332✔
830

831
                buffer = e;
5,100,155✔
832
        } while (buffer);
5,100,155✔
833

834
        if (open_when_needed)
5,090,777✔
835
                log_close();
140,703✔
836

837
        return -ERRNO_VALUE(error);
5,090,777✔
838
}
839

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

848
        PROTECT_ERRNO;
6✔
849

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

852
        if (_likely_(LOG_PRI(level) > log_max_level))
6✔
853
                return -ERRNO_VALUE(error);
×
854

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

858
int log_internalv(
3,373,399✔
859
                int level,
860
                int error,
861
                const char *file,
862
                int line,
863
                const char *func,
864
                const char *format,
865
                va_list ap) {
866

867
        if (_likely_(LOG_PRI(level) > log_max_level))
3,373,399✔
868
                return -ERRNO_VALUE(error);
3,373,399✔
869

870
        /* Make sure that %m maps to the specified error (or "Success"). */
871
        char buffer[LINE_MAX];
3,373,175✔
872
        LOCAL_ERRNO(ERRNO_VALUE(error));
3,373,175✔
873

874
        (void) vsnprintf(buffer, sizeof buffer, format, ap);
3,373,175✔
875

876
        return log_dispatch_internal(level, error, file, line, func, NULL, NULL, NULL, NULL, buffer);
3,373,175✔
877
}
878

879
int log_internal(
3,371,463✔
880
                int level,
881
                int error,
882
                const char *file,
883
                int line,
884
                const char *func,
885
                const char *format, ...) {
886

887
        va_list ap;
3,371,463✔
888
        int r;
3,371,463✔
889

890
        va_start(ap, format);
3,371,463✔
891
        r = log_internalv(level, error, file, line, func, format, ap);
3,371,463✔
892
        va_end(ap);
3,371,463✔
893

894
        return r;
3,371,463✔
895
}
896

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

910
        char *buffer, *b;
1,761,858✔
911

912
        if (_likely_(LOG_PRI(level) > log_max_level))
1,761,858✔
913
                return -ERRNO_VALUE(error);
1,761,858✔
914

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

918
        LOG_SET_PREFIX(object);
3,418,880✔
919

920
        b = buffer = newa(char, LINE_MAX);
1,709,440✔
921
        (void) vsnprintf(b, LINE_MAX, format, ap);
1,709,440✔
922

923
        return log_dispatch_internal(level, error, file, line, func,
1,709,440✔
924
                                     object_field, object, extra_field, extra, buffer);
925
}
926

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

939
        va_list ap;
1,757,537✔
940
        int r;
1,757,537✔
941

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

946
        return r;
1,757,537✔
947
}
948

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

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

962
        static const char nl = '\n';
59,021✔
963

964
        while (format && *n + 1 < iovec_len) {
328,844✔
965
                va_list aq;
269,823✔
966
                char *m;
269,823✔
967
                int r;
269,823✔
968

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

973
                errno = ERRNO_VALUE(error);
269,823✔
974

975
                va_copy(aq, ap);
269,823✔
976
                r = vasprintf(&m, format, aq);
269,823✔
977
                va_end(aq);
269,823✔
978
                if (r < 0)
269,823✔
979
                        return -EINVAL;
×
980

981
                /* Now, jump enough ahead, so that we point to
982
                 * the next format string */
983
                VA_FORMAT_ADVANCE(format, ap);
871,247✔
984

985
                iovec[(*n)++] = IOVEC_MAKE_STRING(m);
269,823✔
986
                if (newline_separator)
269,823✔
987
                        iovec[(*n)++] = IOVEC_MAKE((char *)&nl, 1);
268,301✔
988

989
                format = va_arg(ap, char *);
269,823✔
990
        }
991
        return 0;
992
}
993

994
int log_struct_internal(
66,673✔
995
                int level,
996
                int error,
997
                const char *file,
998
                int line,
999
                const char *func,
1000
                const char *format, ...) {
1001

1002
        char buf[LINE_MAX];
66,673✔
1003
        bool found = false;
66,673✔
1004
        PROTECT_ERRNO;
66,673✔
1005
        va_list ap;
66,673✔
1006

1007
        if (_likely_(LOG_PRI(level) > log_max_level) ||
66,673✔
1008
            log_target == LOG_TARGET_NULL)
66,673✔
1009
                return -ERRNO_VALUE(error);
50✔
1010

1011
        if (LOG_FAC(level) == 0)
66,623✔
1012
                level |= log_facility;
66,623✔
1013

1014
        if (IN_SET(log_target,
66,623✔
1015
                   LOG_TARGET_AUTO,
1016
                   LOG_TARGET_JOURNAL_OR_KMSG,
1017
                   LOG_TARGET_JOURNAL)) {
1018

1019
                if (open_when_needed)
64,523✔
1020
                        log_open_journal();
7,571✔
1021

1022
                if (journal_fd >= 0) {
64,523✔
1023
                        char header[LINE_MAX];
58,863✔
1024
                        struct iovec *iovec;
58,863✔
1025
                        size_t n = 0, m, iovec_len;
58,863✔
1026
                        int r;
58,863✔
1027
                        bool fallback = false;
58,863✔
1028

1029
                        iovec_len = MIN(17 + log_context_num_fields() * 3, IOVEC_MAX);
58,863✔
1030
                        iovec = newa(struct iovec, iovec_len);
58,863✔
1031

1032
                        /* If the journal is available do structured logging.
1033
                         * Do not report the errno if it is synthetic. */
1034
                        log_do_header(header, sizeof(header), level, error, file, line, func, NULL, NULL, NULL, NULL);
58,863✔
1035
                        iovec[n++] = IOVEC_MAKE_STRING(header);
58,863✔
1036

1037
                        va_start(ap, format);
58,863✔
1038
                        DISABLE_WARNING_FORMAT_NONLITERAL;
58,863✔
1039
                        r = log_format_iovec(iovec, iovec_len, &n, true, error, format, ap);
58,863✔
1040
                        REENABLE_WARNING;
58,863✔
1041
                        m = n;
58,863✔
1042
                        if (r < 0)
58,863✔
1043
                                fallback = true;
1044
                        else {
1045
                                log_do_context(iovec, iovec_len, &n);
58,863✔
1046

1047
                                const struct msghdr msghdr = {
58,863✔
1048
                                        .msg_iov = iovec,
1049
                                        .msg_iovlen = n,
1050
                                };
1051

1052
                                (void) sendmsg(journal_fd, &msghdr, MSG_NOSIGNAL);
58,863✔
1053
                        }
1054

1055
                        va_end(ap);
58,863✔
1056
                        for (size_t i = 1; i < m; i += 2)
327,164✔
1057
                                free(iovec[i].iov_base);
268,301✔
1058

1059
                        if (!fallback) {
58,863✔
1060
                                if (open_when_needed)
58,863✔
1061
                                        log_close();
7,558✔
1062

1063
                                return -ERRNO_VALUE(error);
58,863✔
1064
                        }
1065
                }
1066
        }
1067

1068
        /* Fallback if journal logging is not available or didn't work. */
1069

1070
        va_start(ap, format);
7,760✔
1071
        while (format) {
21,740✔
1072
                va_list aq;
21,740✔
1073

1074
                errno = ERRNO_VALUE(error);
21,740✔
1075

1076
                va_copy(aq, ap);
21,740✔
1077
                DISABLE_WARNING_FORMAT_NONLITERAL;
21,740✔
1078
                (void) vsnprintf(buf, sizeof buf, format, aq);
21,740✔
1079
                REENABLE_WARNING;
21,740✔
1080
                va_end(aq);
21,740✔
1081

1082
                if (startswith(buf, "MESSAGE=")) {
21,740✔
1083
                        found = true;
7,760✔
1084
                        break;
7,760✔
1085
                }
1086

1087
                VA_FORMAT_ADVANCE(format, ap);
37,840✔
1088

1089
                format = va_arg(ap, char *);
13,980✔
1090
        }
1091
        va_end(ap);
7,760✔
1092

1093
        if (!found) {
7,760✔
1094
                if (open_when_needed)
×
1095
                        log_close();
×
1096

1097
                return -ERRNO_VALUE(error);
×
1098
        }
1099

1100
        return log_dispatch_internal(level, error, file, line, func, NULL, NULL, NULL, NULL, buf + 8);
7,760✔
1101
}
1102

1103
int log_struct_iovec_internal(
1,479✔
1104
                int level,
1105
                int error,
1106
                const char *file,
1107
                int line,
1108
                const char *func,
1109
                const struct iovec input_iovec[],
1110
                size_t n_input_iovec) {
1111

1112
        PROTECT_ERRNO;
1,479✔
1113

1114
        if (_likely_(LOG_PRI(level) > log_max_level) ||
1,479✔
1115
            log_target == LOG_TARGET_NULL)
1,479✔
1116
                return -ERRNO_VALUE(error);
×
1117

1118
        if (LOG_FAC(level) == 0)
1,479✔
1119
                level |= log_facility;
1,479✔
1120

1121
        if (IN_SET(log_target, LOG_TARGET_AUTO,
1,479✔
1122
                               LOG_TARGET_JOURNAL_OR_KMSG,
1123
                               LOG_TARGET_JOURNAL) &&
1,479✔
1124
            journal_fd >= 0) {
1,479✔
1125

1126
                char header[LINE_MAX];
1,451✔
1127
                struct iovec *iovec;
1,451✔
1128
                size_t n = 0, iovec_len;
1,451✔
1129

1130
                iovec_len = MIN(1 + n_input_iovec * 2 + log_context_num_fields() * 3, IOVEC_MAX);
1,451✔
1131
                iovec = newa(struct iovec, iovec_len);
1,451✔
1132

1133
                log_do_header(header, sizeof(header), level, error, file, line, func, NULL, NULL, NULL, NULL);
1,451✔
1134

1135
                iovec[n++] = IOVEC_MAKE_STRING(header);
1,451✔
1136
                for (size_t i = 0; i < n_input_iovec; i++) {
11,558✔
1137
                        iovec[n++] = input_iovec[i];
10,107✔
1138
                        iovec[n++] = IOVEC_MAKE_STRING("\n");
10,107✔
1139
                }
1140

1141
                log_do_context(iovec, iovec_len, &n);
1,451✔
1142

1143
                const struct msghdr msghdr = {
1,451✔
1144
                        .msg_iov = iovec,
1145
                        .msg_iovlen = n,
1146
                };
1147

1148
                if (sendmsg(journal_fd, &msghdr, MSG_NOSIGNAL) >= 0)
1,451✔
1149
                        return -ERRNO_VALUE(error);
1,451✔
1150
        }
1151

1152
        for (size_t i = 0; i < n_input_iovec; i++)
112✔
1153
                if (memory_startswith(input_iovec[i].iov_base, input_iovec[i].iov_len, "MESSAGE=")) {
112✔
1154
                        char *m;
28✔
1155

1156
                        m = strndupa_safe((char*) input_iovec[i].iov_base + STRLEN("MESSAGE="),
28✔
1157
                                          input_iovec[i].iov_len - STRLEN("MESSAGE="));
1158

1159
                        return log_dispatch_internal(level, error, file, line, func, NULL, NULL, NULL, NULL, m);
28✔
1160
                }
1161

1162
        /* Couldn't find MESSAGE=. */
1163
        return -ERRNO_VALUE(error);
×
1164
}
1165

1166
int log_set_target_from_string(const char *e) {
12,163✔
1167
        LogTarget t;
12,163✔
1168

1169
        t = log_target_from_string(e);
12,163✔
1170
        if (t < 0)
12,163✔
1171
                return t;
1172

1173
        log_set_target(t);
12,163✔
1174
        return 0;
12,163✔
1175
}
1176

1177
int log_set_max_level_from_string(const char *e) {
25,111✔
1178
        int r;
68,792✔
1179

1180
        for (;;) {
68,792✔
1181
                _cleanup_free_ char *word = NULL, *prefix = NULL;
68,792✔
1182
                LogTarget target;
68,792✔
1183
                const char *colon;
68,792✔
1184

1185
                r = extract_first_word(&e, &word, ",", 0);
68,792✔
1186
                if (r < 0)
68,792✔
1187
                        return r;
1188
                if (r == 0)
68,792✔
1189
                        break;
1190

1191
                colon = strchr(word, ':');
43,681✔
1192
                if (!colon) {
43,681✔
1193
                        r = log_level_from_string(word);
25,111✔
1194
                        if (r < 0)
25,111✔
1195
                                return r;
1196

1197
                        log_set_max_level(r);
25,111✔
1198
                        continue;
25,111✔
1199
                }
1200

1201
                prefix = strndup(word, colon - word);
18,570✔
1202
                if (!prefix)
18,570✔
1203
                        return -ENOMEM;
1204

1205
                target = log_target_from_string(prefix);
18,570✔
1206
                if (target < 0)
18,570✔
1207
                        return target;
1208

1209
                if (target >= _LOG_TARGET_SINGLE_MAX)
18,570✔
1210
                        return -EINVAL;
1211

1212
                r = log_level_from_string(colon + 1);
18,570✔
1213
                if (r < 0)
18,570✔
1214
                        return r;
1215

1216
                log_target_max_level[target] = r;
18,570✔
1217
        }
1218

1219
        return 0;
25,111✔
1220
}
1221

1222
int log_max_levels_to_string(int level, char **ret) {
2,222✔
1223
        _cleanup_free_ char *s = NULL;
2,222✔
1224
        int r;
2,222✔
1225

1226
        assert(ret);
2,222✔
1227

1228
        r = log_level_to_string_alloc(level, &s);
2,222✔
1229
        if (r < 0)
2,222✔
1230
                return r;
1231

1232
        for (LogTarget target = 0; target < _LOG_TARGET_SINGLE_MAX; target++) {
11,110✔
1233
                _cleanup_free_ char *l = NULL;
2,222✔
1234

1235
                if (log_target_max_level[target] == INT_MAX)
8,888✔
1236
                        continue;
6,666✔
1237

1238
                r = log_level_to_string_alloc(log_target_max_level[target], &l);
2,222✔
1239
                if (r < 0)
2,222✔
1240
                        return r;
1241

1242
                r = strextendf_with_separator(&s, ",", "%s:%s", log_target_to_string(target), l);
2,222✔
1243
                if (r < 0)
2,222✔
1244
                        return r;
1245
        }
1246

1247
        *ret = TAKE_PTR(s);
2,222✔
1248
        return 0;
2,222✔
1249
}
1250

1251
static int log_set_ratelimit_kmsg_from_string(const char *e) {
7,022✔
1252
        int r;
7,022✔
1253

1254
        r = parse_boolean(e);
7,022✔
1255
        if (r < 0)
7,022✔
1256
                return r;
1257

1258
        ratelimit_kmsg = r;
7,022✔
1259
        return 0;
7,022✔
1260
}
1261

1262
static int parse_proc_cmdline_item(const char *key, const char *value, void *data) {
251,174✔
1263

1264
        /*
1265
         * The systemd.log_xyz= settings are parsed by all tools, and
1266
         * so is "debug".
1267
         *
1268
         * However, "quiet" is only parsed by PID 1, and only turns of
1269
         * status output to /dev/console, but does not alter the log
1270
         * level.
1271
         */
1272

1273
        if (streq(key, "debug") && !value)
251,174✔
1274
                log_set_max_level(LOG_DEBUG);
×
1275

1276
        else if (proc_cmdline_key_streq(key, "systemd.log_target")) {
251,174✔
1277

1278
                if (proc_cmdline_value_missing(key, value))
×
1279
                        return 0;
1280

1281
                if (log_set_target_from_string(value) < 0)
×
1282
                        log_warning("Failed to parse log target '%s', ignoring.", value);
×
1283

1284
        } else if (proc_cmdline_key_streq(key, "systemd.log_level")) {
251,174✔
1285

1286
                if (proc_cmdline_value_missing(key, value))
7,022✔
1287
                        return 0;
1288

1289
                if (log_set_max_level_from_string(value) < 0)
7,022✔
1290
                        log_warning("Failed to parse log level setting '%s', ignoring.", value);
×
1291

1292
        } else if (proc_cmdline_key_streq(key, "systemd.log_color")) {
244,152✔
1293

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

1297
        } else if (proc_cmdline_key_streq(key, "systemd.log_location")) {
244,152✔
1298

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

1302
        } else if (proc_cmdline_key_streq(key, "systemd.log_tid")) {
244,152✔
1303

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

1307
        } else if (proc_cmdline_key_streq(key, "systemd.log_time")) {
244,152✔
1308

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

1312
        } else if (proc_cmdline_key_streq(key, "systemd.log_ratelimit_kmsg")) {
244,152✔
1313

1314
                if (log_set_ratelimit_kmsg_from_string(value ?: "1") < 0)
7,022✔
1315
                        log_warning("Failed to parse log ratelimit kmsg boolean '%s', ignoring.", value);
×
1316
        }
1317

1318
        return 0;
1319
}
1320

1321
static bool should_parse_proc_cmdline(void) {
90,467✔
1322
        /* PID1 always reads the kernel command line. */
1323
        if (getpid_cached() == 1)
90,467✔
1324
                return true;
1325

1326
        /* Otherwise, parse the command line if invoked directly by systemd. */
1327
        return invoked_by_systemd();
90,278✔
1328
}
1329

1330
void log_parse_environment_variables(void) {
92,468✔
1331
        const char *e;
92,468✔
1332
        int r;
92,468✔
1333

1334
        e = getenv("SYSTEMD_LOG_TARGET");
92,468✔
1335
        if (e && log_set_target_from_string(e) < 0)
92,468✔
1336
                log_warning("Failed to parse log target '%s', ignoring.", e);
×
1337

1338
        e = getenv("SYSTEMD_LOG_LEVEL");
92,468✔
1339
        if (e) {
92,468✔
1340
                r = log_set_max_level_from_string(e);
6,541✔
1341
                if (r < 0)
6,541✔
1342
                        log_warning_errno(r, "Failed to parse log level '%s', ignoring: %m", e);
×
1343
        } else {
1344
                /* If no explicit log level is specified then let's see if this is a debug invocation, and if
1345
                 * so raise the log level to debug too. Note that this is not symmetric: just because
1346
                 * DEBUG_INVOCATION is explicitly set to 0 we won't lower the log level below debug. This
1347
                 * follows the logic that debug logging is an opt-in thing anyway, and if there's any reason
1348
                 * to enable it we should not disable it here automatically. */
1349
                r = getenv_bool("DEBUG_INVOCATION");
85,927✔
1350
                if (r < 0 && r != -ENXIO)
85,927✔
1351
                        log_warning_errno(r, "Failed to parse $DEBUG_INVOCATION value, ignoring: %m");
×
1352
                else if (r > 0)
85,927✔
1353
                        log_set_max_level(LOG_DEBUG);
×
1354
        }
1355

1356
        e = getenv("SYSTEMD_LOG_COLOR");
92,468✔
1357
        if (e && log_show_color_from_string(e) < 0)
92,468✔
1358
                log_warning("Failed to parse log color '%s', ignoring.", e);
×
1359

1360
        e = getenv("SYSTEMD_LOG_LOCATION");
92,468✔
1361
        if (e && log_show_location_from_string(e) < 0)
92,468✔
1362
                log_warning("Failed to parse log location '%s', ignoring.", e);
×
1363

1364
        e = getenv("SYSTEMD_LOG_TIME");
92,468✔
1365
        if (e && log_show_time_from_string(e) < 0)
92,468✔
1366
                log_warning("Failed to parse log time '%s', ignoring.", e);
×
1367

1368
        e = getenv("SYSTEMD_LOG_TID");
92,468✔
1369
        if (e && log_show_tid_from_string(e) < 0)
92,468✔
1370
                log_warning("Failed to parse log tid '%s', ignoring.", e);
×
1371

1372
        e = getenv("SYSTEMD_LOG_RATELIMIT_KMSG");
92,468✔
1373
        if (e && log_set_ratelimit_kmsg_from_string(e) < 0)
92,468✔
1374
                log_warning("Failed to parse log ratelimit kmsg boolean '%s', ignoring.", e);
×
1375
}
92,468✔
1376

1377
void log_parse_environment(void) {
90,467✔
1378
        /* Do not call from library code. */
1379

1380
        if (should_parse_proc_cmdline())
90,467✔
1381
                (void) proc_cmdline_parse(parse_proc_cmdline_item, NULL, PROC_CMDLINE_STRIP_RD_PREFIX);
7,095✔
1382

1383
        log_parse_environment_variables();
90,467✔
1384
}
90,467✔
1385

1386
LogTarget log_get_target(void) {
16,268✔
1387
        return log_target;
16,268✔
1388
}
1389

1390
void log_settle_target(void) {
14,309✔
1391

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

1398
        LogTarget t = log_get_target();
14,309✔
1399

1400
        if (t != LOG_TARGET_AUTO)
14,309✔
1401
                return;
1402

1403
        t = getpid_cached() == 1 || stderr_is_journal() ? (prohibit_ipc ? LOG_TARGET_KMSG : LOG_TARGET_JOURNAL_OR_KMSG)
10,024✔
1404
                                                        : LOG_TARGET_CONSOLE;
6,639✔
1405
        log_set_target(t);
3,385✔
1406
}
1407

1408
int log_get_max_level(void) {
13,701,676✔
1409
        return log_max_level;
13,701,676✔
1410
}
1411

1412
int log_get_target_max_level(LogTarget target) {
4✔
1413
        assert(target >= 0);
4✔
1414
        assert(target < _LOG_TARGET_SINGLE_MAX);
4✔
1415
        return log_target_max_level[target];
4✔
1416
}
1417

1418
void log_show_color(bool b) {
81,701✔
1419
        show_color = b;
81,701✔
1420
}
81,701✔
1421

1422
bool log_get_show_color(void) {
190,022✔
1423
        return show_color > 0; /* Defaults to false. */
190,022✔
1424
}
1425

1426
void log_show_location(bool b) {
×
1427
        show_location = b;
×
1428
}
×
1429

1430
bool log_get_show_location(void) {
14✔
1431
        return show_location;
14✔
1432
}
1433

1434
void log_show_time(bool b) {
1✔
1435
        show_time = b;
1✔
1436
}
1✔
1437

1438
bool log_get_show_time(void) {
14✔
1439
        return show_time;
14✔
1440
}
1441

1442
void log_show_tid(bool b) {
1✔
1443
        show_tid = b;
1✔
1444
}
1✔
1445

1446
bool log_get_show_tid(void) {
×
1447
        return show_tid;
×
1448
}
1449

1450
int log_show_color_from_string(const char *e) {
×
1451
        int r;
×
1452

1453
        r = parse_boolean(e);
×
1454
        if (r < 0)
×
1455
                return r;
1456

1457
        log_show_color(r);
×
1458
        return 0;
×
1459
}
1460

1461
int log_show_location_from_string(const char *e) {
×
1462
        int r;
×
1463

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

1468
        log_show_location(r);
×
1469
        return 0;
×
1470
}
1471

1472
int log_show_time_from_string(const char *e) {
×
1473
        int r;
×
1474

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

1479
        log_show_time(r);
×
1480
        return 0;
×
1481
}
1482

1483
int log_show_tid_from_string(const char *e) {
×
1484
        int r;
×
1485

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

1490
        log_show_tid(r);
×
1491
        return 0;
×
1492
}
1493

1494
bool log_on_console(void) {
106,218✔
1495
        if (IN_SET(log_target, LOG_TARGET_CONSOLE,
106,218✔
1496
                               LOG_TARGET_CONSOLE_PREFIXED))
1497
                return true;
1498

1499
        return syslog_fd < 0 && kmsg_fd < 0 && journal_fd < 0;
129,311✔
1500
}
1501

1502
static const char *const log_target_table[_LOG_TARGET_MAX] = {
1503
        [LOG_TARGET_CONSOLE]          = "console",
1504
        [LOG_TARGET_CONSOLE_PREFIXED] = "console-prefixed",
1505
        [LOG_TARGET_KMSG]             = "kmsg",
1506
        [LOG_TARGET_JOURNAL]          = "journal",
1507
        [LOG_TARGET_JOURNAL_OR_KMSG]  = "journal-or-kmsg",
1508
        [LOG_TARGET_SYSLOG]           = "syslog",
1509
        [LOG_TARGET_SYSLOG_OR_KMSG]   = "syslog-or-kmsg",
1510
        [LOG_TARGET_AUTO]             = "auto",
1511
        [LOG_TARGET_NULL]             = "null",
1512
};
1513

1514
DEFINE_STRING_TABLE_LOOKUP(log_target, LogTarget);
35,296✔
1515

1516
void log_received_signal(int level, const struct signalfd_siginfo *si) {
3,610✔
1517
        assert(si);
3,610✔
1518

1519
        if (pid_is_valid(si->ssi_pid)) {
3,610✔
1520
                _cleanup_free_ char *p = NULL;
3,610✔
1521

1522
                (void) pid_get_comm(si->ssi_pid, &p);
3,610✔
1523

1524
                log_full(level,
4,336✔
1525
                         "Received SIG%s from PID %"PRIu32" (%s).",
1526
                         signal_to_string(si->ssi_signo),
1527
                         si->ssi_pid, strna(p));
1528
        } else
1529
                log_full(level,
×
1530
                         "Received SIG%s.",
1531
                         signal_to_string(si->ssi_signo));
1532
}
3,610✔
1533

1534
void set_log_syntax_callback(log_syntax_callback_t cb, void *userdata) {
858✔
1535
        assert(!log_syntax_callback || !cb);
858✔
1536
        assert(!log_syntax_callback_userdata || !userdata);
858✔
1537

1538
        log_syntax_callback = cb;
858✔
1539
        log_syntax_callback_userdata = userdata;
858✔
1540
}
858✔
1541

1542
int log_syntax_internal(
11,490✔
1543
                const char *unit,
1544
                int level,
1545
                const char *config_file,
1546
                unsigned config_line,
1547
                int error,
1548
                const char *file,
1549
                int line,
1550
                const char *func,
1551
                const char *format, ...) {
1552

1553
        PROTECT_ERRNO;
11,490✔
1554

1555
        if (log_syntax_callback)
11,490✔
1556
                log_syntax_callback(unit, level, log_syntax_callback_userdata);
846✔
1557

1558
        if (_likely_(LOG_PRI(level) > log_max_level) ||
11,490✔
1559
            log_target == LOG_TARGET_NULL)
11,490✔
1560
                return -ERRNO_VALUE(error);
30✔
1561

1562
        char buffer[LINE_MAX];
11,460✔
1563
        va_list ap;
11,460✔
1564
        const char *unit_fmt = NULL;
11,460✔
1565

1566
        errno = ERRNO_VALUE(error);
11,460✔
1567

1568
        va_start(ap, format);
11,460✔
1569
        (void) vsnprintf(buffer, sizeof buffer, format, ap);
11,460✔
1570
        va_end(ap);
11,460✔
1571

1572
        if (unit)
11,460✔
1573
                unit_fmt = getpid_cached() == 1 ? "UNIT=%s" : "USER_UNIT=%s";
4,883✔
1574

1575
        if (config_file) {
11,460✔
1576
                if (config_line > 0)
11,450✔
1577
                        return log_struct_internal(
5,929✔
1578
                                        level,
1579
                                        error,
1580
                                        file, line, func,
1581
                                        LOG_MESSAGE_ID(SD_MESSAGE_INVALID_CONFIGURATION_STR),
5,929✔
1582
                                        LOG_ITEM("CONFIG_FILE=%s", config_file),
5,929✔
1583
                                        LOG_ITEM("CONFIG_LINE=%u", config_line),
5,929✔
1584
                                        LOG_MESSAGE("%s:%u: %s", config_file, config_line, buffer),
5,929✔
1585
                                        unit_fmt, unit,
1586
                                        NULL);
1587
                else
1588
                        return log_struct_internal(
5,521✔
1589
                                        level,
1590
                                        error,
1591
                                        file, line, func,
1592
                                        LOG_MESSAGE_ID(SD_MESSAGE_INVALID_CONFIGURATION_STR),
5,521✔
1593
                                        LOG_ITEM("CONFIG_FILE=%s", config_file),
5,521✔
1594
                                        LOG_MESSAGE("%s: %s", config_file, buffer),
5,521✔
1595
                                        unit_fmt, unit,
1596
                                        NULL);
1597
        } else if (unit)
10✔
1598
                return log_struct_internal(
×
1599
                                level,
1600
                                error,
1601
                                file, line, func,
1602
                                LOG_MESSAGE_ID(SD_MESSAGE_INVALID_CONFIGURATION_STR),
×
1603
                                LOG_MESSAGE("%s: %s", unit, buffer),
×
1604
                                unit_fmt, unit,
1605
                                NULL);
1606
        else
1607
                return log_struct_internal(
10✔
1608
                                level,
1609
                                error,
1610
                                file, line, func,
1611
                                LOG_MESSAGE_ID(SD_MESSAGE_INVALID_CONFIGURATION_STR),
10✔
1612
                                LOG_MESSAGE("%s", buffer),
10✔
1613
                                NULL);
1614
}
1615

1616
int log_syntax_invalid_utf8_internal(
1✔
1617
                const char *unit,
1618
                int level,
1619
                const char *config_file,
1620
                unsigned config_line,
1621
                const char *file,
1622
                int line,
1623
                const char *func,
1624
                const char *rvalue) {
1625

1626
        PROTECT_ERRNO;
×
1627
        _cleanup_free_ char *p = NULL;
1✔
1628

1629
        if (rvalue)
1✔
1630
                p = utf8_escape_invalid(rvalue);
1✔
1631

1632
        return log_syntax_internal(unit, level, config_file, config_line,
1✔
1633
                                   SYNTHETIC_ERRNO(EINVAL), file, line, func,
1634
                                   "String is not UTF-8 clean, ignoring assignment: %s", strna(p));
1635
}
1636

1637
int log_syntax_parse_error_internal(
110✔
1638
                const char *unit,
1639
                const char *config_file,
1640
                unsigned config_line,
1641
                int error,
1642
                bool critical,
1643
                const char *file,
1644
                int line,
1645
                const char *func,
1646
                const char *lvalue,
1647
                const char *rvalue) {
1648

1649
        PROTECT_ERRNO;
×
1650
        _cleanup_free_ char *escaped = NULL;
110✔
1651

1652
        /* OOM is always handled as critical. */
1653
        if (ERRNO_VALUE(error) == ENOMEM)
110✔
1654
                return log_oom_internal(LOG_ERR, file, line, func);
×
1655

1656
        if (rvalue && !utf8_is_valid(rvalue)) {
220✔
1657
                escaped = utf8_escape_invalid(rvalue);
×
1658
                if (!escaped)
×
1659
                        rvalue = "(oom)";
1660
                else
1661
                        rvalue = " (escaped)";
×
1662
        }
1663

1664
        log_syntax_internal(unit, critical ? LOG_ERR : LOG_WARNING, config_file, config_line, error,
550✔
1665
                            file, line, func,
1666
                            "Failed to parse %s=%s%s%s%s%s",
1667
                            strna(lvalue), strempty(escaped), strempty(rvalue),
1668
                            critical ? "" : ", ignoring",
1669
                            error == 0 ? "." : ": ",
1670
                            error == 0 ? "" : STRERROR(error));
110✔
1671

1672
        return critical ? -ERRNO_VALUE(error) : 0;
110✔
1673
}
1674

1675
void log_set_upgrade_syslog_to_journal(bool b) {
236✔
1676
        upgrade_syslog_to_journal = b;
236✔
1677

1678
        /* Make the change effective immediately */
1679
        if (b) {
236✔
1680
                if (log_target == LOG_TARGET_SYSLOG)
236✔
1681
                        log_target = LOG_TARGET_JOURNAL;
×
1682
                else if (log_target == LOG_TARGET_SYSLOG_OR_KMSG)
236✔
1683
                        log_target = LOG_TARGET_JOURNAL_OR_KMSG;
×
1684
        }
1685
}
236✔
1686

1687
void log_set_always_reopen_console(bool b) {
11,784✔
1688
        always_reopen_console = b;
11,784✔
1689
}
11,784✔
1690

1691
void log_set_open_when_needed(bool b) {
18,576✔
1692
        open_when_needed = b;
18,576✔
1693
}
18,576✔
1694

1695
void log_set_prohibit_ipc(bool b) {
34,068✔
1696
        prohibit_ipc = b;
34,068✔
1697
}
34,068✔
1698

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

1703
        return getpid_cached() == 1 ? LOG_EMERG : LOG_ERR;
×
1704
}
1705

1706
int log_dup_console(void) {
99✔
1707
        int copy;
99✔
1708

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

1712
        if (console_fd < 0 || console_fd >= 3)
99✔
1713
                return 0;
1714

1715
        copy = fcntl(console_fd, F_DUPFD_CLOEXEC, 3);
1✔
1716
        if (copy < 0)
1✔
1717
                return -errno;
×
1718

1719
        console_fd = copy;
1✔
1720
        return 0;
1✔
1721
}
1722

1723
void log_setup(void) {
89,653✔
1724
        log_set_target(LOG_TARGET_AUTO);
89,653✔
1725
        log_parse_environment();
89,653✔
1726
        (void) log_open();
89,653✔
1727
        if (log_on_console() && show_color < 0)
89,653✔
1728
                log_show_color(true);
81,598✔
1729
}
89,653✔
1730

1731
const char* _log_set_prefix(const char *prefix, bool force) {
3,442,578✔
1732
        const char *old = log_prefix;
3,442,578✔
1733

1734
        if (prefix || force)
3,442,578✔
1735
                log_prefix = prefix;
3,440,699✔
1736

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

© 2026 Coveralls, Inc